hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9430550d891ef9d922a420e8912800b1f4480008
4,747
cpp
C++
data_structure/data_structure_median.cpp
LuisMBaezCo/cpp-algorithm-snippets
9736f97437cf52b3c8cdf6bfe00de919448d2e50
[ "MIT" ]
7
2020-12-11T00:24:42.000Z
2022-03-14T05:59:35.000Z
data_structure/data_structure_median.cpp
LuisMBaezCo/algorithms-template
6290ee91eb2dd67e6e367887a815a7aac065fe3a
[ "MIT" ]
15
2021-02-04T23:12:46.000Z
2022-03-17T01:07:12.000Z
data_structure/data_structure_median.cpp
LuisMBaezCo/cpp-algorithm-snippets
9736f97437cf52b3c8cdf6bfe00de919448d2e50
[ "MIT" ]
null
null
null
namespace data_structure { template<typename T> T get_min(multiset<T> &st) { assert(!st.empty()); return *st.begin(); } template<typename T> T get_max(multiset<T> &st) { assert(!st.empty()); return *st.rbegin(); } template<typename T> T erase_min(multiset<T> &st) { assert(!st.empty()); T to_return = get_min(st); st.erase(st.begin()); return to_return; } template<typename T> T erase_max(multiset<T> &st) { assert(!st.empty()); T to_return = get_max(st); st.erase(--st.end()); return to_return; } /** * Description: calculates the median of a data set, supporting add and erase operations * Time: * add: O(log2(n)) * erase: O(log2(n)) * get_median: O(log2(n)) * Verification: t.ly/P4wn */ template<typename T> struct Median { int n; multiset<T> left; multiset<T> right; Median() : n(0) {} bool add(const T &value) { int left_size = (int) left.size(); int right_size = (int) right.size(); n++; if(left_size==0 && right_size==0) { right.insert(value); return true; } else if(left_size == 0 && right_size==1) { T right_current = get_min(right); if(value > right_current) { erase_min(right); right.insert(value); left.insert(right_current); } else if(value <= right_current) { left.insert(value); } return true; } else if(left_size == right_size) { T left_current = get_max(left); if(value >= left_current) { right.insert(value); } else if(value < left_current) { erase_max(left); left.insert(value); right.insert(left_current); } return true; } else if(left_size+1 == right_size) { T left_current = get_max(left); T right_current = get_min(right); if(value <= left_current) { left.insert(value); } else if(value > left_current && value > right_current) { erase_min(right); left.insert(right_current); right.insert(value); } else if(value > left_current && value <= right_current) { left.insert(value); } return true; } n--; return false; } bool erase(const int &value) { int left_size = (int) left.size(); int right_size = (int) right.size(); n--; if(left_size>0 && right_size>0) { T left_current = get_max(left); T right_current = get_min(right); if(value <= left_current) { auto it = left.find(value); if(it != left.end()) { left.erase(it); left_size = (int) left.size(); if(abs(right_size - left_size) > 1) { erase_min(right); left.insert(right_current); } return true; } } else if(value > left_current && value > right_current) { auto it = right.find(value); if(it != left.end()) { right.erase(it); right_size = (int) right.size(); if(left_size - right_size > 0) { erase_max(left); right.insert(left_current); } return true; } } else if(value > left_current && value <= right_current) { auto it = right.find(value); if(it != left.end()) { right.erase(it); right_size = (int) right.size(); if(left_size - right_size > 0) { erase_max(left); right.insert(left_current); } return true; } } } else if(left_size==0 && right_size>0) { auto it = right.find(value); if(it != left.end()) { right.erase(it); return true; } } n++; return false; } int get_median() { int answer; if(n & 1) { // k is odd answer = get_min(right); // answer for k odd: min(right) } else { // k is even answer = min(get_max(left), get_min(right)); // answer for k even: min(max(left), min(right)) } return answer; } int size() { return n; } bool empty() {return n==0;} }; } using data_structure::Median;
31.646667
105
0.470402
LuisMBaezCo
9430a004b6c45165eb5abdfbf68ec4abdd050dab
895
hpp
C++
Source/Hyper/include/Hyper/Lexer.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
13
2021-08-08T19:17:22.000Z
2022-02-17T10:52:07.000Z
Source/Hyper/include/Hyper/Lexer.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
null
null
null
Source/Hyper/include/Hyper/Lexer.hpp
SkillerRaptor/HyperLang
c7bcabf90462247e388861b4255fe61e74c32fca
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020-2021, SkillerRaptor <skillerraptor@protonmail.com> * * SPDX-License-Identifier: MIT */ #pragma once #include "Hyper/Token.hpp" #include <string> namespace Hyper { class Diagnostics; class Lexer { public: Lexer(Diagnostics &diagnostics, std::string text); Token next_token(); private: void advance() noexcept; char peek() const noexcept; void skip_whitespace() noexcept; bool has_reached_end() const noexcept; Token scan_comment() noexcept; Token scan_block_comment() noexcept; std::string scan_string(); std::string scan_integer_literal(); std::string scan_identifier(); Token::Type scan_keyword(std::string_view identifier) const noexcept; private: Diagnostics &m_diagnostics; std::string m_text; char m_current_char = '\0'; size_t m_index = 0; size_t m_line = 1; size_t m_column = 0; }; } // namespace Hyper
17.54902
72
0.713966
SkillerRaptor
94378968473e84908b44b3b69d2b7fdd6b469493
25,640
cpp
C++
sparse_blas/parsy/symbolic/supernode_detection.cpp
leila68/sympiler
8a7a5a6403f7b261332bd14d27c019a84dbd672a
[ "MIT" ]
30
2018-01-19T08:42:46.000Z
2022-01-25T12:02:24.000Z
sparse_blas/parsy/symbolic/supernode_detection.cpp
leila68/sympiler
8a7a5a6403f7b261332bd14d27c019a84dbd672a
[ "MIT" ]
1
2019-01-05T20:36:42.000Z
2021-04-22T15:17:53.000Z
sparse_blas/parsy/symbolic/supernode_detection.cpp
leila68/sympiler
8a7a5a6403f7b261332bd14d27c019a84dbd672a
[ "MIT" ]
13
2017-11-14T17:12:47.000Z
2022-01-16T11:11:16.000Z
// // Created by kazem on 04/30/21. // #include "symbolic/supernode_detection.h" #include "common/SparseUtils.h" namespace sym_lib { namespace parsy { void subtree(int j, int k, int *Ap, int *Ai, int *Anz, int *SuperMap, int *Sparent, int mark, int sorted, int k1, int *Flag, int *Ls, int *Lpi2) { int p, pend, i, si; p = Ap[j]; //pend = (Anz == NULL) ? (Ap [j+1]) : (p + Anz [j]) ; pend = (Ap[j + 1]); for (; p < pend; p++) { i = Ai[p]; if (i < k1) { /* (i,k) is an entry in the upper triangular part of A or A*F'. * symmetric case: A(i,k) is nonzero (j=k). * unsymmetric case: A(i,j) and F(j,k) are both nonzero. * * Column i is in supernode si = SuperMap [i]. Follow path from si * to root of supernodal etree, stopping at the first flagged * supernode. The root of the row subtree is supernode SuperMap[k], * which is flagged already. This traversal will stop there, or it * might stop earlier if supernodes have been flagged by previous * calls to this routine for the same k. */ for (si = SuperMap[i]; Flag[si] < mark; si = Sparent[si]) { ASSERT(si <= SuperMap[k]); Ls[Lpi2[si]++] = k; Flag[si] = mark; } } else if (sorted) { break; } } } int super_node_detection(int for_whom, CSC *A, CSC *F, int *Parent, int *orig_or_extra, BCSC *L, int *nrelax, double *zrelax, int *Sparent, int status) { double zrelax0, zrelax1, zrelax2; size_t xxsize, ssize, xsize, *Lpi, nsuper; int *Wi, *Wj, *Super, *Snz, *Ap, *Ai, *Flag, *Head, *Ls, *Lpx, *Fnz, *Anz, *SuperMap, *Merged, *Nscol, *Zeros, *Fp, *Fj, *ColCount, *Lsuper, *Iwork, *Lpi2; int d, n, j, k, s, mark, parent, p, pend, k1, k2, packed, nscol, nsrow, ndrow1, ndrow2, stype, sparent, plast, slast, csize, maxcsize, ss, nscol0, nscol1, ns, nfsuper, newzeros, totzeros, merge, snext, esize, maxesize, nrelax0, nrelax1, nrelax2, Asorted; size_t w; int ok = TRUE, find_xsize; const char *env_use_gpu; const char *env_max_bytes; size_t max_bytes; const char *env_max_fraction; double max_fraction; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ /* RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_PATTERN, FALSE) ;*/ stype = A->stype; if (stype < 0) { /* invalid symmetry; symmetric lower form not supported */ // ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE); } if (stype == 0) { /* F must be present in the unsymmetric case */ // RETURN_IF_NULL (F, FALSE) ; } /* if (L->is_super) { *//* L must be a simplicial symbolic factor *//* // ERROR (CHOLMOD_INVALID, "L must be symbolic on input") ; return (FALSE) ; }*/ //Common->status = CHOLMOD_OK ; status = TRUE; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ n = A->nrow; /* w = 5*n */ w = mult_size_t(n, 4, &ok); if (!ok) { //ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE); } //CHOLMOD(allocate_work) (n, w, 0, Common) ; /* if (Common->status < CHOLMOD_OK) { *//* out of memory *//* return (FALSE) ; }*/ // ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* allocate GPU workspace */ /* ---------------------------------------------------------------------- */ L->useGPU = 0; /* only used for Cholesky factorization, not QR */ /* GPU module is not installed */ //Common->useGPU = 0 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* A is now either A or triu(A(p,p)) for the symmetric case. It is either * A or A(p,f) for the unsymmetric case (both in column form). It can be * either packed or unpacked, and either sorted or unsorted. Entries in * the lower triangular part may be present if A is symmetric, but these * are ignored. */ Ap = A->p; Ai = A->i; Anz = A->nz; if (stype != 0) { /* F not accessed */ Fp = NULL; Fj = NULL; Fnz = NULL; packed = TRUE; } else { /* F = A(:,f) or A(p,f) in packed row form, either sorted or unsorted */ Fp = F->p; Fj = F->i; Fnz = F->nz; packed = F->packed; } ColCount = L->ColCount; /* nrelax0 = Common->nrelax [0] ; nrelax1 = Common->nrelax [1] ; nrelax2 = Common->nrelax [2] ; zrelax0 = Common->zrelax [0] ; zrelax1 = Common->zrelax [1] ; zrelax2 = Common->zrelax [2] ;*/ nrelax0 = nrelax[0]; nrelax1 = nrelax[1]; nrelax2 = nrelax[2]; zrelax0 = zrelax[0]; zrelax1 = zrelax[1]; zrelax2 = zrelax[2]; /*zrelax0 = IS_NAN (zrelax0) ? 0 : zrelax0 ; zrelax1 = IS_NAN (zrelax1) ? 0 : zrelax1 ; zrelax2 = IS_NAN (zrelax2) ? 0 : zrelax2 ;*/ // ASSERT (CHOLMOD(dump_parent) (Parent, n, "Parent", Common)) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ /* Sparent, Snz, and Merged could be allocated later, of size nfsuper */ //Iwork = Common->Iwork ; Iwork = new int[w](); Wi = Iwork; /* size n (i/l/l). Lpi2 is i/l/l */ Wj = Iwork + n; /* size n (i/l/l). Zeros is i/l/l */ // Sparent = Iwork + 2*((size_t) n) ; /* size nfsuper <= n [ */ Snz = Iwork + 2 * ((size_t) n); /* size nfsuper <= n [ */ Merged = Iwork + 3 * ((size_t) n); /* size nfsuper <= n [ */ Flag = new int[n]();//Common->Flag ; /* size n */ Head = new int[n + 1]();//Common->Head ; /* size n+1 */ /* ---------------------------------------------------------------------- */ /* find the fundamental supernodes */ /* ---------------------------------------------------------------------- */ /* count the number of children of each node, using Wi [ */ for (j = 0; j < n; j++) { Wi[j] = 0; } for (j = 0; j < n; j++) { parent = Parent[j]; if (parent != EMPTY) { Wi[parent]++; } } Super = Head; /* use Head [0..nfsuper] as workspace for Super list ( */ /* column 0 always starts a new supernode */ nfsuper = (n == 0) ? 0 : 1; /* number of fundamental supernodes */ Super[0] = 0; int *mergeable = new int[n](); for (j = 1; j < n; j++) { /* check if j starts new supernode, or in the same supernode as j-1 */ if (Parent[j - 1] != j /* parent of j-1 is not j */ || (ColCount[j - 1] != ColCount[j] + 1) /* j-1 not subset of j*/ || Wi[j] > 1 /* j has more than one child */ || orig_or_extra[j] == 1 || orig_or_extra[j - 1] == 1 ) { /* j is the leading node of a supernode */ Super[nfsuper++] = j; if (orig_or_extra[j] == 1 || orig_or_extra[j - 1] == 1) { // single col supernode mergeable[nfsuper - 1] = 1; } } } Super[nfsuper] = n; /* contents of Wi no longer needed for child count ] */ Nscol = Wi; /* use Wi as size-nfsuper workspace for Nscol [ */ /* ---------------------------------------------------------------------- */ /* find the mapping of fundamental nodes to supernodes */ /* ---------------------------------------------------------------------- */ SuperMap = Wj; /* use Wj as workspace for SuperMap [ */ /* SuperMap [k] = s if column k is contained in supernode s */ for (s = 0; s < nfsuper; s++) { for (k = Super[s]; k < Super[s + 1]; k++) { SuperMap[k] = s; } } /* ---------------------------------------------------------------------- */ /* construct the fundamental supernodal etree */ /* ---------------------------------------------------------------------- */ for (s = 0; s < nfsuper; s++) { j = Super[s + 1] - 1; /* last node in supernode s */ parent = Parent[j]; /* parent of last node */ Sparent[s] = (parent == EMPTY) ? EMPTY : SuperMap[parent]; // PRINT1 (("Sparent ["ID"] = "ID"\n", s, Sparent [s])) ; } /* contents of Wj no longer needed as workspace for SuperMap ] * SuperMap will be recomputed below, for the relaxed supernodes. */ Zeros = Wj; /* use Wj for Zeros, workspace of size nfsuper [ */ /* ---------------------------------------------------------------------- */ /* relaxed amalgamation */ /* ---------------------------------------------------------------------- */ for (s = 0; s < nfsuper; s++) { Merged[s] = EMPTY; /* s not merged into another */ Nscol[s] = Super[s + 1] - Super[s]; /* # of columns in s */ Zeros[s] = 0; /* # of zero entries in s */ ASSERT(s <= Super[s]); Snz[s] = ColCount[Super[s]]; /* # of entries in leading col of s */ // PRINT2 (("lnz ["ID"] "ID"\n", s, Snz [s])) ; } for (s = nfsuper - 2; s >= 0; s--) { /* if (s==971) printf("here");*/ double lnz1; /* should supernodes s and s+1 merge into a new node s? */ // PRINT1 (("\n========= Check relax of s "ID" and s+1 "ID"\n", s, s+1)) ; ss = Sparent[s]; if (ss == EMPTY) { // PRINT1 (("s "ID" is a root, no merge with s+1 = "ID"\n", s, s+1)) ; continue; } if (mergeable[s] || mergeable[s + 1]) { continue; } /* find the current parent of s (perform path compression as needed) */ for (ss = Sparent[s]; Merged[ss] != EMPTY; ss = Merged[ss]); sparent = ss; // PRINT2 (("Current sparent of s "ID" is "ID"\n", s, sparent)) ; /* ss is the current parent of s */ for (ss = Sparent[s]; Merged[ss] != EMPTY; ss = snext) { snext = Merged[ss]; // PRINT2 (("ss "ID" is dead, merged into snext "ID"\n", ss, snext)) ; Merged[ss] = sparent; } /* if s+1 is not the current parent of s, do not merge */ if (sparent != s + 1) { continue; } nscol0 = Nscol[s]; /* # of columns in s */ nscol1 = Nscol[s + 1]; /* # of columns in s+1 */ ns = nscol0 + nscol1; //PRINT2 (("ns "ID" nscol0 "ID" nscol1 "ID"\n", ns, nscol0, nscol1)) ; totzeros = Zeros[s + 1]; /* current # of zeros in s+1 */ lnz1 = (double) (Snz[s + 1]); /* # entries in leading column of s+1 */ /* determine if supernodes s and s+1 should merge */ if (ns <= nrelax0) { // PRINT2 (("ns is tiny ("ID"), so go ahead and merge\n", ns)) ; merge = TRUE; } else { /* use double to avoid integer overflow */ double lnz0 = Snz[s]; /* # entries in leading column of s */ double xnewzeros = nscol0 * (lnz1 + nscol0 - lnz0); /* use int for the final update of Zeros [s] below */ newzeros = nscol0 * (Snz[s + 1] + nscol0 - Snz[s]); ASSERT(newzeros == xnewzeros); // PRINT2 (("lnz0 %g lnz1 %g xnewzeros %g\n", lnz0, lnz1, xnewzeros)) ; if (xnewzeros == 0) { /* no new zeros, so go ahead and merge */ // PRINT2 (("no new fillin, so go ahead and merge\n")) ; merge = TRUE; } else { /* # of zeros if merged */ double xtotzeros = ((double) totzeros) + xnewzeros; /* xtotsize: total size of merged supernode, if merged: */ double xns = (double) ns; double xtotsize = (xns * (xns + 1) / 2) + xns * (lnz1 - nscol1); double z = xtotzeros / xtotsize; int totsize; totsize = (ns * (ns + 1) / 2) + ns * (Snz[s + 1] - nscol1); /* use int for the final update of Zeros [s] below */ totzeros += newzeros; /* do not merge if supernode would become too big * (int overflow). Continue computing; not (yet) an error. */ /* fl.pt. compare, but no NaN's can occur here */ merge = ((ns <= nrelax1 && z < zrelax0) || (ns <= nrelax2 && z < zrelax1) || (z < zrelax2)) && (xtotsize < Int_max / sizeof(double)); } } if (merge) { // PRINT1 (("Merge node s ("ID") and s+1 ("ID")\n", s, s+1)) ; Zeros[s] = totzeros; Merged[s + 1] = s; Snz[s] = nscol0 + Snz[s + 1]; Nscol[s] += Nscol[s + 1]; } } /* contents of Wj no longer needed for Zeros ] */ /* contents of Wi no longer needed for Nscol ] */ /* contents of Sparent no longer needed (recomputed below) */ /* ---------------------------------------------------------------------- */ /* construct the relaxed supernode list */ /* ---------------------------------------------------------------------- */ nsuper = 0; for (s = 0; s < nfsuper; s++) { if (Merged[s] == EMPTY) { // PRINT1 (("live supernode: "ID" snz "ID"\n", s, Snz [s])) ; Super[nsuper] = Super[s]; Snz[nsuper] = Snz[s]; nsuper++; } } Super[nsuper] = n; // PRINT1 (("Fundamental supernodes: "ID" relaxed "ID"\n", nfsuper, nsuper)) ; /* Merged no longer needed ] */ /* ---------------------------------------------------------------------- */ /* find the mapping of relaxed nodes to supernodes */ /* ---------------------------------------------------------------------- */ /* use Wj as workspace for SuperMap { */ // SuperMap ==> col2Sup /* SuperMap [k] = s if column k is contained in supernode s */ for (s = 0; s < nsuper; s++) { for (k = Super[s]; k < Super[s + 1]; k++) { SuperMap[k] = s; } } #if 0 printf("number of SN is %d: ", nsuper); for (int i = 0; i < n; ++i) { printf("%d ", SuperMap[i]); } printf("-----\n"); #endif /* ---------------------------------------------------------------------- */ /* construct the relaxed supernodal etree */ /* ---------------------------------------------------------------------- */ for (s = 0; s < nsuper; s++) { j = Super[s + 1] - 1; /* last node in supernode s */ parent = Parent[j]; /* parent of last node */ Sparent[s] = (parent == EMPTY) ? EMPTY : SuperMap[parent]; // PRINT1 (("new Sparent ["ID"] = "ID"\n", s, Sparent [s])) ; } /* ---------------------------------------------------------------------- */ /* determine the size of L->s and L->x */ /* ---------------------------------------------------------------------- */ #if 1 int mm = 0; for (int i = 0; i < nsuper; ++i) { mm += (Super[i + 1] - Super[i]); } assert(mm == n); #endif ssize = 0; xsize = 0; xxsize = 0; /*find_xsize = for_whom == CHOLMOD_ANALYZE_FOR_CHOLESKY || for_whom == CHOLMOD_ANALYZE_FOR_SPQRGPU ;*/ find_xsize = TRUE; //TODO for (s = 0; s < nsuper; s++) { nscol = Super[s + 1] - Super[s]; nsrow = Snz[s]; ASSERT(nscol > 0); ssize += nsrow; if (find_xsize) { xsize += nscol * nsrow; /* also compute xsize in double to guard against int overflow */ xxsize += ((double) nscol) * ((double) nsrow); } if (ssize < 0) { /* int overflow, clear workspace and return. QR factorization will not use xxsize, so that error is ignored. For Cholesky factorization, however, memory of space xxsize will be allocated, so this is a failure. Both QR and Cholesky fail if ssize overflows. */ // ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; // FREE_WORKSPACE ; return (FALSE); } ASSERT(ssize > 0); // ASSERT (IMPLIES (find_xsize, xsize > 0)) ; } xsize = MAX(1, xsize); ssize = MAX(1, ssize); // PRINT1 (("ix sizes: "ID" "ID" nsuper "ID"\n", ssize, xsize, nsuper)) ; /* ---------------------------------------------------------------------- */ /* allocate L (all except real part L->x) */ /* ---------------------------------------------------------------------- */ L->ssize = ssize; L->xsize = xsize; L->nsuper = nsuper; allocateLC(L, true); //CHOLMOD(change_factor) (CHOLMOD_PATTERN, TRUE, TRUE, TRUE, TRUE, L, Common); /* if (Common->status < CHOLMOD_OK) { *//* out of memory; L is still a valid simplicial symbolic factor *//* // FREE_WORKSPACE ; return (FALSE) ; }*/ //DEBUG (CHOLMOD(dump_factor) (L, "L to symbolic super", Common)) ; //ASSERT (L->is_ll && L->xtype == CHOLMOD_PATTERN && L->is_super) ; Lpi = L->pi; Lpx = L->px; Ls = L->s; Ls[0] = 0; /* flag for cholmod_check_factor; supernodes are defined */ Lsuper = L->super; /* copy the list of relaxed supernodes into the final list in L */ for (s = 0; s <= nsuper; s++) { Lsuper[s] = Super[s]; } /* Head no longer needed as workspace for fundamental Super list ) */ Super = Lsuper; /* Super is now the list of relaxed supernodes */ /* ---------------------------------------------------------------------- */ /* construct column pointers of relaxed supernodal pattern (L->pi) */ /* ---------------------------------------------------------------------- */ p = 0; for (s = 0; s < nsuper; s++) { Lpi[s] = p; p += Snz[s]; // PRINT1 (("Snz ["ID"] = "ID", Super ["ID"] = "ID"\n", // s, Snz [s], s, Super[s])) ; } Lpi[nsuper] = p; ASSERT((int) (L->ssize) == MAX(1, p)); /* ---------------------------------------------------------------------- */ /* construct pointers for supernodal values (L->px) */ /* ---------------------------------------------------------------------- */ /*if( for_whom == CHOLMOD_ANALYZE_FOR_CHOLESKY || for_whom == CHOLMOD_ANALYZE_FOR_SPQRGPU)*/ /* if (TRUE) { Lpx [0] = 0 ; p = 0 ; for (s = 0 ; s < nsuper ; s++) { nscol = Super [s+1] - Super [s] ; *//* number of columns in s *//* nsrow = Snz [s] ; *//* # of rows, incl triangular part*//* Lpx [s] = p ; *//* pointer to numerical part of s *//* p += nscol * nsrow ; } Lpx [s] = p ; ASSERT ((int) (L->xsize) == MAX (1,p)) ; } else { *//* L->px is not needed for non-GPU accelerated QR factorization (it may * lead to int overflow, anyway, if xsize caused int overflow above). * Use a magic number to tell cholmod_check_factor to ignore Lpx. *//* Lpx [0] = 123456 ; }*/ /* Snz no longer needed ] */ /* ---------------------------------------------------------------------- */ /* symbolic analysis to construct the relaxed supernodal pattern (L->s) */ /* ---------------------------------------------------------------------- */ //Lpi2 = Wi ; /* copy Lpi into Lpi2, using Wi as workspace for Lpi2 [ */ Lpi2 = new int[n + 1](); for (s = 0; s < nsuper; s++) { Lpi2[s] = Lpi[s]; } Asorted = A->sorted; mark = EMPTY; for (s = 0; s < nsuper; s++) { /* sth supernode is in columns k1 to k2-1. * compute nonzero pattern of L (k1:k2-1,:). */ /* place rows k1 to k2-1 in leading column of supernode s */ k1 = Super[s]; k2 = Super[s + 1]; // PRINT1 (("=========>>> Supernode "ID" k1 "ID" k2-1 "ID"\n", // s, k1, k2-1)) ; for (k = k1; k < k2; k++) { Ls[Lpi2[s]++] = k; } /* compute nonzero pattern each row k1 to k2-1 */ for (k = k1; k < k2; k++) { /* compute row k of L. In the symmetric case, the pattern of L(k,:) * is the set of nodes reachable in the supernodal etree from any * row i in the nonzero pattern of A(0:k,k). In the unsymmetric * case, the pattern of the kth column of A*A' is the set union * of all columns A(0:k,j) for each nonzero F(j,k). */ /* clear the Flag array and mark the current supernode */ /* mark = CHOLMOD(clear_flag) (Common) ; */ // CHOLMOD_CLEAR_FLAG (Common) ; //mark = Common->mark ; /*#define CHOLMOD_CLEAR_FLAG(Common) \ 1131 { \ 1132: Common->mark++ ; \ 1133: if (Common->mark <= 0) \ 1134 { \ 1135: Common->mark = EMPTY ; \ 1136 CHOLMOD (clear_flag) (Common) ; \ 1137 } \*/ mark++; if (mark <= 0) { for (int i = 0; i < n; i++) { Flag[i] = EMPTY; } mark = 0; } Flag[s] = mark; ASSERT(s == SuperMap[k]); /* traverse the row subtree for each nonzero in A or AA' */ if (stype != 0) { subtree(k, k, Ap, Ai, Anz, SuperMap, Sparent, mark, Asorted, k1, Flag, Ls, Lpi2); } else { /* for each j nonzero in F (:,k) do */ p = Fp[k]; pend = (packed) ? (Fp[k + 1]) : (p + Fnz[k]); for (; p < pend; p++) { subtree(Fj[p], k, Ap, Ai, Anz, SuperMap, Sparent, mark, Asorted, k1, Flag, Ls, Lpi2); } } } } #if 0 for (s = 0 ; s < nsuper ; s++) { // PRINT1 (("Lpi2[s] "ID" Lpi[s+1] "ID"\n", Lpi2 [s], Lpi [s+1])) ; ASSERT (Lpi2 [s] == Lpi [s+1]) ; // CHOLMOD(dump_super) (s, Super, Lpi, Ls, NULL, NULL, 0, Common) ; } #endif /* contents of Wi no longer needed for Lpi2 ] */ /* Sparent no longer needed ] */ /* ---------------------------------------------------------------------- */ /* determine the largest update matrix (L->maxcsize) */ /* ---------------------------------------------------------------------- */ /* maxcsize could be determined before L->s is allocated and defined, which * would mean that all memory requirements for both the symbolic and numeric * factorizations could be computed using O(nnz(A)+O(n)) space. However, it * would require a lot of extra work. The analysis phase, above, would need * to be duplicated, but with Ls not kept; instead, the algorithm would keep * track of the current s and slast for each supernode d, and update them * when a new row index appears in supernode d. An alternative would be to * do this computation only if the allocation of L->s failed, in which case * the following code would be skipped. * * The csize for a supernode is the size of its largest contribution to * a subsequent ancestor supernode. For example, suppose the rows of #'s * in the figure below correspond to the columns of a subsequent supernode, * and the dots are the entries in that ancestore. * * c * c c * c c c * x x x * x x x * # # # . * # # # . . * * * * . . * * * * . . * * * * . . * . . * * Then for this update, the csize is 3-by-2, or 6, because there are 3 * rows of *'s which is the number of rows in the update, and there are * 2 rows of #'s, which is the number columns in the update. The csize * of a supernode is the largest such contribution for any ancestor * supernode. maxcsize, for the whole matrix, has a rough upper bound of * the maximum size of any supernode. This bound is loose, because the * the contribution must be less than the size of the ancestor supernodal * that it's updating. maxcsize of a completely dense matrix, with one * supernode, is zero. * * maxesize is the column dimension for the workspace E needed for the * solve. E is of size nrhs-by-maxesize, where the nrhs is the number of * columns in the right-hand-side. The maxesize is the largest esize of * any supernode. The esize of a supernode is the number of row indices * it contains, excluding the column indices of the supernode itself. * For the following example, esize is 4: * * c * c c * c c c * x x x * x x x * x x x * x x x * * maxesize can be no bigger than n. */ maxcsize = 1; maxesize = 1; /* Do not need to guard csize against int overflow since xsize is OK. */ /*if (for_whom == CHOLMOD_ANALYZE_FOR_CHOLESKY || for_whom == CHOLMOD_ANALYZE_FOR_SPQRGPU)*/ if (TRUE) { /* this is not needed for non-GPU accelerated QR factorization */ for (d = 0; d < nsuper; d++) { nscol = Super[d + 1] - Super[d]; p = Lpi[d] + nscol; plast = p; pend = Lpi[d + 1]; esize = pend - p; maxesize = MAX(maxesize, esize); slast = (p == pend) ? (EMPTY) : (SuperMap[Ls[p]]); for (; p <= pend; p++) { s = (p == pend) ? (EMPTY) : (SuperMap[Ls[p]]); if (s != slast) { /* row i is the start of a new supernode */ ndrow1 = p - plast; ndrow2 = pend - plast; csize = ndrow2 * ndrow1; // PRINT1 (("Supernode "ID" ancestor "ID" C: "ID"-by-"ID // " csize "ID"\n", d, slast, ndrow1, ndrow2, csize)) ; maxcsize = MAX(maxcsize, csize); plast = p; slast = s; } } } // PRINT1 (("max csize "ID"\n", maxcsize)) ; } /* Wj no longer needed for SuperMap } */ L->maxcsize = maxcsize; L->maxesize = maxesize; L->is_super = TRUE; // ASSERT (L->xtype == CHOLMOD_PATTERN && L->is_ll) ; /* ---------------------------------------------------------------------- */ /* supernodal symbolic factorization is complete */ /* ---------------------------------------------------------------------- */ delete[]Iwork; delete[]Flag; delete[]Head; delete[]mergeable; delete[]Lpi2; // FREE_WORKSPACE ; return (TRUE); } } }
34.095745
111
0.483658
leila68
943e45a1f8fdf919a2a2ea691996bef0550a144d
3,404
cpp
C++
src/elona/lua_env/mod_manifest.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/mod_manifest.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/mod_manifest.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#include "mod_manifest.hpp" #include "../hcl.hpp" namespace elona { namespace lua { namespace { std::string _read_mod_name(const hcl::Value& value, const fs::path& path) { std::string result; // TODO: Clean up, as with lua::ConfigTable const hcl::Value* object = value.find("name"); if (object && object->is<std::string>()) { result = object->as<std::string>(); } else { throw std::runtime_error( filepathutil::to_utf8_path(path) + ": Missing \"name\" in mod manifest"); } return result; } semver::Version _read_mod_version(const hcl::Value& value, const fs::path& path) { // TODO: Clean up, as with lua::ConfigTable const hcl::Value* object = value.find("version"); if (!object) { return semver::Version{}; } if (object->is<std::string>()) { if (const auto result = semver::Version::parse(object->as<std::string>())) { return result.right(); } else { throw std::runtime_error{result.left()}; } } else { throw std::runtime_error( filepathutil::to_utf8_path(path) + ": Missing \"name\" in mod manifest"); } } ModManifest::Dependencies _read_dependencies( const hcl::Value& value, const fs::path& path) { ModManifest::Dependencies result; const hcl::Value* object = value.find("dependencies"); if (object) { if (object->is<hcl::Object>()) { const auto& dependencies = object->as<hcl::Object>(); for (const auto& kvp : dependencies) { hcl::Value mod; hcl::Value version; std::tie(mod, version) = kvp; if (mod.is<std::string>() && version.is<std::string>()) { if (const auto req = semver::VersionRequirement::parse( version.as<std::string>())) { result.emplace(mod.as<std::string>(), req.right()); } else { throw std::runtime_error( filepathutil::to_utf8_path(path) + ": " + req.left()); } } else { throw std::runtime_error( filepathutil::to_utf8_path(path) + ": \"dependencies\" field must be an object."); } } } else { throw std::runtime_error( filepathutil::to_utf8_path(path) + ": \"dependencies\" field must be an object."); } } return result; } } // namespace ModManifest ModManifest::load(const fs::path& path) { auto parsed = hclutil::load(path); const auto& value = hclutil::skip_sections( parsed, {"mod"}, filepathutil::to_utf8_path(path)); const auto mod_name = _read_mod_name(value, path); const auto version = _read_mod_version(value, path); const auto mod_path = path.parent_path(); const auto dependencies = _read_dependencies(value, path); return ModManifest{mod_name, version, mod_path, dependencies}; } } // namespace lua } // namespace elona
24.846715
80
0.509107
XrosFade
943eb38924d56e97cf8e36a1b8c19ebdda38d25c
508
cpp
C++
src/mafu/src/LAF.cpp
metaphaseaudio/audio_file_utility
93c6a5a6cedd379b24712bc1bf4a818f3be4c88d
[ "MIT" ]
null
null
null
src/mafu/src/LAF.cpp
metaphaseaudio/audio_file_utility
93c6a5a6cedd379b24712bc1bf4a818f3be4c88d
[ "MIT" ]
null
null
null
src/mafu/src/LAF.cpp
metaphaseaudio/audio_file_utility
93c6a5a6cedd379b24712bc1bf4a818f3be4c88d
[ "MIT" ]
null
null
null
// // Created by Matt on 8/9/2021. // #include <file_viewer/LAF.h> #include <meta/gooey/WaveformComponent.h> LAF::LAF() : meta::MetaLookAndFeel() { setColour(meta::WaveformComponent::ColourIds::backgroundColourId, juce::Colours::transparentBlack); setColour(meta::WaveformComponent::ColourIds::foregroundColourId, juce::Colours::greenyellow); } int LAF::getTabButtonBestWidth(juce::TabBarButton& button, int tabDepth) { return LookAndFeel_V2::getTabButtonBestWidth(button, tabDepth); }
23.090909
103
0.748031
metaphaseaudio
9441a748af77c007a3535f0e3443780e854f1067
23,324
cpp
C++
unit/analyses/variable-sensitivity/value_expression_evaluation/assume.cpp
fanhy2114/cbmc-1
04c83673aaa9888e19a71c62fa5e0c0ffa9de27a
[ "BSD-4-Clause" ]
412
2016-04-02T01:14:27.000Z
2022-03-27T09:24:09.000Z
unit/analyses/variable-sensitivity/value_expression_evaluation/assume.cpp
fanhy2114/cbmc-1
04c83673aaa9888e19a71c62fa5e0c0ffa9de27a
[ "BSD-4-Clause" ]
4,671
2016-02-25T13:52:16.000Z
2022-03-31T22:14:46.000Z
unit/analyses/variable-sensitivity/value_expression_evaluation/assume.cpp
fanhy2114/cbmc-1
04c83673aaa9888e19a71c62fa5e0c0ffa9de27a
[ "BSD-4-Clause" ]
266
2016-02-23T12:48:00.000Z
2022-03-22T18:15:51.000Z
/*******************************************************************\ Module: Unit tests for abstract_environmentt::assume Author: Jez Higgins, jez@jezuk.co.uk \*******************************************************************/ #include <analyses/variable-sensitivity/variable_sensitivity_object_factory.h> #include <analyses/variable-sensitivity/variable_sensitivity_test_helpers.h> #include <testing-utils/use_catch.h> #include <util/arith_tools.h> #include <util/bitvector_types.h> #include <util/symbol_table.h> exprt binary_expression( dstringt const &exprId, const abstract_object_pointert &op1, const abstract_object_pointert &op2, abstract_environmentt &environment, namespacet &ns) { auto op1_sym = symbol_exprt("op1", op1->type()); auto op2_sym = symbol_exprt("op2", op2->type()); environment.assign(op1_sym, op1, ns); environment.assign(op2_sym, op2, ns); return binary_relation_exprt(op1_sym, exprId, op2_sym); } static void ASSUME_TRUE( abstract_environmentt &env, const exprt &expr, const namespacet &ns); static void ASSUME_FALSE( abstract_environmentt &env, const exprt &expr, const namespacet &ns); static void ASSUME_NIL(abstract_environmentt &env, const exprt &expr, const namespacet &ns); std::vector<std::string> split(std::string const &s, std::string const &delimiter); std::vector<exprt> numbersToExprs(std::vector<std::string> const &numbers); class assume_testert { public: void operator()(bool is_true, std::vector<std::string> const &tests) { for(auto test : tests) { if(is_test(test, "==")) test_fn(ID_equal, is_true, test, "=="); else if(is_test(test, "!=")) test_fn(ID_notequal, is_true, test, "!="); else if(is_test(test, "<=")) test_fn(ID_le, is_true, test, "<="); else if(is_test(test, ">=")) test_fn(ID_ge, is_true, test, ">="); else if(is_test(test, "<")) test_fn(ID_lt, is_true, test, "<"); else if(is_test(test, ">")) test_fn(ID_gt, is_true, test, ">"); else FAIL("Unknown test: " + test); } } bool is_test(std::string const &test, std::string const &delimiter) { return test.find(delimiter) != std::string::npos; } void test_fn( dstringt const &exprId, bool is_true, std::string const &test, std::string const &delimiter) { WHEN(test) { auto operands = split(test, delimiter); REQUIRE(operands.size() == 2); auto op1 = build_op(operands[0]); auto op2 = build_op(operands[1]); auto test_expr = binary_expression(exprId, op1, op2, environment, ns); if(is_true) ASSUME_TRUE(environment, test_expr, ns); else ASSUME_FALSE(environment, test_expr, ns); } } assume_testert(abstract_environmentt &env, namespacet &n) : environment(env), ns(n) { } private: abstract_object_pointert build_op(std::string const &optext) { auto stripped = std::string{}; for(auto i : optext) if(i != ' ') stripped.push_back(i); switch(stripped[0]) { case '{': return build_value_set(stripped); case '[': return build_interval(stripped); default: return build_constant(stripped); } } abstract_object_pointert build_value_set(std::string const &optext) { auto numbers = split(optext.substr(1, optext.size() - 2), ","); auto exprs = numbersToExprs(numbers); REQUIRE(exprs.size() > 0); return make_value_set(exprs, environment, ns); } abstract_object_pointert build_interval(std::string const &optext) { auto numbers = split(optext.substr(1, optext.size() - 2), ","); auto exprs = numbersToExprs(numbers); REQUIRE(exprs.size() == 2); return make_interval(exprs[0], exprs[1], environment, ns); } abstract_object_pointert build_constant(std::string const &optext) { auto expr = numbersToExprs({optext})[0]; return make_constant(expr, environment, ns); } const typet type = signedbv_typet(32); abstract_environmentt &environment; namespacet &ns; }; SCENARIO( "assume value expressions", "[core][analyses][variable-sensitivity][constant_abstract_value][value_set_" "abstract_object][interval_abstract_value][assume]") { auto config = vsd_configt::constant_domain(); config.context_tracking.data_dependency_context = false; config.context_tracking.last_write_context = false; auto object_factory = variable_sensitivity_object_factoryt::configured_with(config); abstract_environmentt environment{object_factory}; environment.make_top(); symbol_tablet symbol_table; namespacet ns(symbol_table); assume_testert assumeTester(environment, ns); GIVEN("true or false") { WHEN("true") { ASSUME_TRUE(environment, true_exprt(), ns); } WHEN("false") { ASSUME_FALSE(environment, false_exprt(), ns); } WHEN("!true") { ASSUME_FALSE(environment, not_exprt(true_exprt()), ns); } WHEN("!false") { ASSUME_TRUE(environment, not_exprt(false_exprt()), ns); } auto type = signedbv_typet(32); auto val1 = from_integer(1, type); auto val2 = from_integer(2, type); auto val3 = from_integer(3, type); auto val4 = from_integer(4, type); auto val5 = from_integer(5, type); auto constant1 = make_constant(val1, environment, ns); auto constant3 = make_constant(val3, environment, ns); auto interval12 = make_interval(val1, val2, environment, ns); WHEN("1 == 1") { auto is_equal = binary_expression(ID_equal, constant1, constant1, environment, ns); ASSUME_TRUE(environment, is_equal, ns); } WHEN("!(1 == 1)") { auto is_equal = binary_expression(ID_equal, constant1, constant1, environment, ns); ASSUME_FALSE(environment, not_exprt(is_equal), ns); } WHEN("[1,2] == 1") { auto is_equal = binary_expression(ID_equal, interval12, constant1, environment, ns); ASSUME_TRUE(environment, is_equal, ns); } WHEN("!([1,2] == 1)") { auto is_equal = binary_expression(ID_equal, interval12, constant1, environment, ns); ASSUME_FALSE(environment, not_exprt(is_equal), ns); } WHEN("1 != 3") { auto is_not_equal = binary_expression(ID_notequal, constant1, constant3, environment, ns); ASSUME_TRUE(environment, is_not_equal, ns); } WHEN("!(1 != 3)") { auto is_not_equal = binary_expression(ID_notequal, constant1, constant3, environment, ns); ASSUME_FALSE(environment, not_exprt(is_not_equal), ns); } WHEN("[1,2] != 3") { auto is_not_equal = binary_expression(ID_notequal, interval12, constant3, environment, ns); ASSUME_TRUE(environment, is_not_equal, ns); } WHEN("!([1,2] != 3)") { auto is_not_equal = binary_expression(ID_notequal, interval12, constant3, environment, ns); ASSUME_FALSE(environment, not_exprt(is_not_equal), ns); } WHEN("1 <= 3") { auto is_le = binary_expression(ID_le, constant1, constant3, environment, ns); ASSUME_TRUE(environment, is_le, ns); } WHEN("!(1 <= 3)") { auto is_le = binary_expression(ID_le, constant1, constant3, environment, ns); ASSUME_FALSE(environment, not_exprt(is_le), ns); } WHEN("[1,2] <= 3") { auto is_le = binary_expression(ID_le, interval12, constant3, environment, ns); ASSUME_TRUE(environment, is_le, ns); } WHEN("!([1,2] <= 3)") { auto is_le = binary_expression(ID_le, interval12, constant3, environment, ns); ASSUME_FALSE(environment, not_exprt(is_le), ns); } WHEN("3 > 1") { auto is_le = binary_expression(ID_gt, constant3, constant1, environment, ns); ASSUME_TRUE(environment, is_le, ns); } WHEN("!(3 > 1)") { auto is_le = binary_expression(ID_gt, constant3, constant1, environment, ns); ASSUME_FALSE(environment, not_exprt(is_le), ns); } WHEN("3 > [1,2]") { auto is_le = binary_expression(ID_gt, constant3, interval12, environment, ns); ASSUME_TRUE(environment, is_le, ns); } WHEN("!(3 > [1,2])") { auto is_le = binary_expression(ID_gt, constant3, interval12, environment, ns); ASSUME_FALSE(environment, not_exprt(is_le), ns); } } GIVEN("expected equality") { assumeTester( true, {"2 == 2", "[1, 1] == 1", "[1, 1] == [1, 1]", "[1, 1] == { 1 }", "[1, 2] == 1", "[1, 2] == [1, 1]", "[1, 2] == { 1 }", "[1, 2] == 2", "[1, 2] == [2, 2]", "[1, 2] == [1, 2]", "[1, 2] == {1, 2}", "[1, 3] == 2", "[1, 3] == [2, 2]", "[1, 3] == { 2 }", "{ 1 } == 1", "{ 1, 2 } == 1", "{ 1, 2 } == [ 1, 1 ]", "{ 1, 2 } == [ 1, 2 ]", "{ 1, 2 } == [ 1, 3 ]", "{ 1, 2 } == [ 2, 5 ]", "{ 1, 2 } == { 1 }", "{ 1, 2 } == { 2 }", "{ 1, 2 } == { 1, 2 }", "{ 1, 2 } == { 1, 3 }", "{ 1, 2 } == { 2, 5 }"}); } GIVEN("expected not equality") { assumeTester( false, {"1 == 2", "[2, 3] == 1", "[2, 3] == [1, 1]", "{ 2, 3 } == 1", "{ 1, 2, 3 } == [ 6, 10 ]", "{ 2, 3 } == { 4, 5 }"}); } GIVEN("expected inequality") { assumeTester( true, {"1 != 2", "[2, 3] != 1", "[2, 3] != [1, 1]", "{ 2, 3 } != 1", "{ 1, 2, 3 } != [ 6, 10 ]", "{ 2, 3 } != { 4, 5 }"}); } GIVEN("expected not inequality") { assumeTester( false, {"2 != 2", "[1, 1] != 1", "[1, 1] != [1, 1]", "[1, 1] != { 1 }", "[1, 2] != 1", "[1, 2] != [1, 1]", "[1, 2] != { 1 }", "[1, 2] != 2", "[1, 2] != [2, 2]", "[1, 2] != [1, 2]", "[1, 2] != {1, 2}", "[1, 3] != 2", "[1, 3] != [2, 2]", "[1, 3] != { 2 }", "{ 1 } != 1", "{ 1, 2 } != 1", "{ 1, 2 } != [ 1, 1 ]", "{ 1, 2 } != [ 1, 2 ]", "{ 1, 2 } != [ 1, 3 ]", "{ 1, 2 } != [ 2, 5 ]", "{ 1, 2 } != { 1 }", "{ 1, 2 } != { 2 }", "{ 1, 2 } != { 1, 2 }", "{ 1, 2 } != { 1, 3 }", "{ 1, 2 } != { 2, 5 }"}); } GIVEN("expected less than or equal to") { assumeTester( true, { "1 <= 1", "1 <= 2", "1 <= [1, 2]", "2 <= [1, 2]", "1 <= [0, 2]", "1 <= { 0, 1 }", "1 <= { 1 }", "[1, 2] <= 1", "[1, 2] <= 2", "[1, 2] <= 5", "[1, 5] <= [1, 2]", "[1, 5] <= [1, 5]", "[1, 5] <= [1, 7]", "[1, 5] <= [0, 7]", "[1, 5] <= [0, 3]", "[1, 5] <= { 1, 2 }", "[1, 5] <= { 1, 5 }", "[1, 5] <= { 1, 7 }", "[1, 5] <= { 0, 7 }", "[1, 5] <= { 0, 3 }", "[1, 5] <= { 0, 1 }", "{ 1, 2 } <= 1", "{ 1, 2 } <= 2", "{ 1, 2 } <= 5", "{ 1, 5 } <= [1, 2]", "{ 1, 5 } <= [1, 5]", "{ 1, 5 } <= [1, 7]", "{ 1, 5 } <= [0, 7]", "{ 1, 5 } <= [0, 3]", "{ 1, 5 } <= { 1, 2 }", "{ 1, 5 } <= { 1, 5 }", "{ 1, 5 } <= { 1, 7 }", "{ 1, 5 } <= { 0, 7 }", "{ 1, 5 } <= { 0, 3 }", "{ 1, 5 } <= { 0, 1 }", }); } GIVEN("expected not less than or equal to") { assumeTester( false, {"2 <= 1", "[2, 3] <= 1", "[2, 3] <= [0, 1]", "[2, 3] <= { 0, 1 }", "{ 2, 3, 4 } <= 1", "{ 2, 4 } <= [0, 1]", "{ 2, 4 } <= { 0, 1 }"}); } GIVEN("expected less than") { assumeTester( true, {"1 < 2", "1 < [1, 2]", "1 < [0, 2]", "1 < { 1, 2 }", "1 < { 0, 2 }", "[1, 2] < 2", "[1, 2] < 5", "[1, 5] < [1, 2]", "[1, 5] < [1, 5]", "[1, 5] < [1, 7]", "[1, 5] < [0, 7]", "[1, 5] < [0, 3]", "[1, 5] < { 1, 2 }", "[1, 5] < { 1, 5 }", "[1, 5] < { 1, 7 }", "[1, 5] < { 0, 7 }", "[1, 5] < { 0, 3 }", "{ 1, 2 } < 2", "{ 1, 2 } < 5", "{ 1, 5 } < [1, 2]", "{ 1, 5 } < [1, 5]", "{ 1, 5 } < [1, 7]", "{ 1, 5 } < [0, 7]", "{ 1, 5 } < [0, 3]", "{ 1, 5 } < { 1, 2 }", "{ 1, 5 } < { 1, 5 }", "{ 1, 5 } < { 1, 7 }", "{ 1, 5 } < { 0, 7 }", "{ 1, 5 } < { 0, 3 }"}); } GIVEN("expected not less than") { assumeTester( false, {"2 < 1", "2 < 2", "[2, 3] < 1", "[2, 3] < 2", "[2, 3] < [0, 1]", "[2, 3] < [0, 2]", "[2, 3] < { 0, 1 }", "[2, 3] < { 0, 2 }", "{ 2, 3, 4 } < 1", "{ 2, 3, 4 } < 2", "{ 2, 4 } < [0, 1]", "{ 2, 4 } < [0, 2]", "{ 2, 4 } < { 0, 1 }", "{ 2, 4 } < { 0, 2 }"}); } GIVEN("expected greater than or equal to") { assumeTester( true, { "1 >= 1", "1 >= 0", "1 >= [1, 2]", "2 >= [1, 2]", "1 >= [0, 2]", "1 >= { 0, 1 }", "1 >= { 1 }", "[1, 2] >= 0", "[1, 2] >= 1", "[1, 2] >= 2", "[1, 5] >= [1, 2]", "[1, 5] >= [1, 5]", "[1, 5] >= [1, 7]", "[1, 5] >= [0, 7]", "[1, 5] >= [0, 3]", "[1, 5] >= { 1, 2 }", "[1, 5] >= { 1, 5 }", "[1, 5] >= { 1, 7 }", "[1, 5] >= { 0, 7 }", "[1, 5] >= { 0, 3 }", "[1, 5] >= { 0, 1 }", "{ 1, 2 } >= 0", "{ 1, 2 } >= 1", "{ 1, 2 } >= 2", "{ 1, 5 } >= [1, 2]", "{ 1, 5 } >= [1, 5]", "{ 1, 5 } >= [1, 7]", "{ 1, 5 } >= [0, 7]", "{ 1, 5 } >= [0, 3]", "{ 1, 5 } >= { 1, 2 }", "{ 1, 5 } >= { 1, 5 }", "{ 1, 5 } >= { 1, 7 }", "{ 1, 5 } >= { 0, 7 }", "{ 1, 5 } >= { 0, 3 }", "{ 1, 5 } >= { 0, 1 }", }); } GIVEN("expected not greater than or equal") { assumeTester( false, {"1 >= 2", "1 >= [2, 3]", "[0, 1] >= 2", "[0, 1] >= [2 ,3]", "[0, 1] >= { 2, 3 }", "{ 0, 1, 2 } >= 3", "{ 0, 1 } >= [2, 3]", "{ 0, 1 } >= { 2, 3 }"}); } GIVEN("expected greater than") { assumeTester( true, { "1 > 0", "2 > [1, 2]", "1 > [0, 2]", "1 > { 0, 1 }", "1 > { 0 }", "[1, 2] > 0", "[1, 2] > 1", "[1, 5] > [1, 2]", "[1, 5] > [1, 5]", "[1, 5] > [1, 7]", "[1, 5] > [0, 7]", "[1, 5] > [0, 3]", "[1, 5] > { 1, 2 }", "[1, 5] > { 1, 5 }", "[1, 5] > { 1, 7 }", "[1, 5] > { 0, 7 }", "[1, 5] > { 0, 3 }", "[1, 5] > { 0, 1 }", "{ 1, 2 } > 0", "{ 1, 2 } > 1", "{ 1, 5 } > [1, 2]", "{ 1, 5 } > [1, 5]", "{ 1, 5 } > [1, 7]", "{ 1, 5 } > [0, 7]", "{ 1, 5 } > [0, 3]", "{ 1, 5 } > { 1, 2 }", "{ 1, 5 } > { 1, 5 }", "{ 1, 5 } > { 1, 7 }", "{ 1, 5 } > { 0, 7 }", "{ 1, 5 } > { 0, 3 }", "{ 1, 5 } > { 0, 1 }", }); } GIVEN("expected not greater than") { assumeTester( false, {"1 > 1", "1 > 2", "1 > [1, 3]", "1 > [2, 3]", "[0, 1] > 1", "[0, 1] > 2", "[0, 1] > [1 ,3]", "[0, 1] > [2 ,3]", "[0, 1] > { 1, 3 }", "[0, 1] > { 2, 3 }", "{ 0, 1, 2 } > 2", "{ 0, 1, 2 } > 3", "{ 0, 1 } > [1, 3]", "{ 0, 1 } > [2, 3]", "{ 0, 1 } > { 1, 3 }", "{ 0, 1 } > { 2, 3 }"}); } GIVEN("and expressions") { auto type = signedbv_typet(32); auto val1 = from_integer(1, type); auto val2 = from_integer(2, type); auto val3 = from_integer(3, type); auto val4 = from_integer(4, type); auto val5 = from_integer(5, type); auto v12 = make_value_set({val1, val2}, environment, ns); auto v23 = make_value_set({val2, val3}, environment, ns); auto v34 = make_value_set({val3, val4}, environment, ns); auto v45 = make_value_set({val4, val5}, environment, ns); auto c1_sym = symbol_exprt("c1", v12->type()); auto c2_sym = symbol_exprt("c2", v23->type()); auto c3_sym = symbol_exprt("c3", v23->type()); auto c4_sym = symbol_exprt("c4", v23->type()); environment.assign(c1_sym, v12, ns); environment.assign(c2_sym, v23, ns); environment.assign(c3_sym, v34, ns); environment.assign(c4_sym, v45, ns); WHEN("{ 1, 2 } == { 2, 3 } && { 3, 4 } == { 4, 5 }") { auto lhs_expr = equal_exprt(c1_sym, c2_sym); auto rhs_expr = equal_exprt(c3_sym, c4_sym); auto and_expr = and_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, and_expr, ns); } WHEN("{ 1, 2 } == { 2, 3 } && { 3, 4 } == { 4, 5 } && { 1, 2 } != { 3, 4 }") { auto expr0 = equal_exprt(c1_sym, c2_sym); auto expr1 = equal_exprt(c3_sym, c4_sym); auto expr2 = notequal_exprt(c1_sym, c4_sym); auto and_expr = and_exprt(expr0, expr1, expr2); ASSUME_TRUE(environment, and_expr, ns); } WHEN( "{ 1, 2 } == { 2, 3 } && { 3, 4 } == { 4, 5 } && !({ 1, 2 } == { 3, 4 })") { auto expr0 = equal_exprt(c1_sym, c2_sym); auto expr1 = equal_exprt(c3_sym, c4_sym); auto expr2 = not_exprt(equal_exprt(c1_sym, c4_sym)); auto and_expr = and_exprt(expr0, expr1, expr2); ASSUME_TRUE(environment, and_expr, ns); } WHEN("unknown == { 2, 3 } && { 3, 4 } == { 4, 5 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(unknown, c2_sym); auto rhs_expr = equal_exprt(c3_sym, c4_sym); auto and_expr = and_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, and_expr, ns); } WHEN("{ 3, 4 } == { 4, 5 } && unknown == { 2, 3 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(c3_sym, c4_sym); auto rhs_expr = equal_exprt(unknown, c2_sym); auto and_expr = and_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, and_expr, ns); } WHEN("unknown == { 2, 3 } && mystery == { 1, 2 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(unknown, c2_sym); auto mystery = symbol_exprt("mystery", v23->type()); auto rhs_expr = equal_exprt(mystery, c1_sym); auto and_expr = and_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, and_expr, ns); } WHEN("unknown == { 2, 3 } && { 3, 4 } == { 1, 2 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(unknown, c2_sym); auto rhs_expr = equal_exprt(c3_sym, c1_sym); auto and_expr = and_exprt(lhs_expr, rhs_expr); ASSUME_FALSE(environment, and_expr, ns); } WHEN("{ 1, 2 } == { 4, 5 } && { 3, 4 } == { 1, 2 }") { auto expr0 = equal_exprt(c1_sym, c4_sym); auto expr1 = equal_exprt(c3_sym, c1_sym); auto and_expr = and_exprt(expr0, expr1); ASSUME_FALSE(environment, and_expr, ns); } } GIVEN("or expressions") { auto type = signedbv_typet(32); auto val1 = from_integer(1, type); auto val2 = from_integer(2, type); auto val3 = from_integer(3, type); auto val4 = from_integer(4, type); auto val5 = from_integer(5, type); auto v12 = make_value_set({val1, val2}, environment, ns); auto v23 = make_value_set({val2, val3}, environment, ns); auto v34 = make_value_set({val3, val4}, environment, ns); auto v45 = make_value_set({val4, val5}, environment, ns); auto c1_sym = symbol_exprt("c1", v12->type()); auto c2_sym = symbol_exprt("c2", v23->type()); auto c3_sym = symbol_exprt("c3", v23->type()); auto c4_sym = symbol_exprt("c4", v23->type()); environment.assign(c1_sym, v12, ns); environment.assign(c2_sym, v23, ns); environment.assign(c3_sym, v34, ns); environment.assign(c4_sym, v45, ns); WHEN("{ 1, 2 } == { 2, 3 } || { 3, 4 } == { 4, 5 }") { auto lhs_expr = equal_exprt(c1_sym, c2_sym); auto rhs_expr = equal_exprt(c3_sym, c4_sym); auto or_expr = or_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, or_expr, ns); } WHEN("{ 1, 2 } == { 2, 3 } || { 3, 4 } == { 4, 5 } || { 1, 2 } != { 3, 4 }") { auto expr0 = equal_exprt(c1_sym, c2_sym); auto expr1 = equal_exprt(c3_sym, c4_sym); auto expr2 = notequal_exprt(c1_sym, c4_sym); auto or_expr = or_exprt(expr0, expr1, expr2); ASSUME_TRUE(environment, or_expr, ns); } WHEN("{ 1, 2 } == { 2, 3 } && { 3, 4 } != { 4, 5 }") { auto expr0 = equal_exprt(c1_sym, c2_sym); auto expr1 = notequal_exprt(c3_sym, c4_sym); auto or_expr = or_exprt(expr0, expr1); ASSUME_TRUE(environment, or_expr, ns); } WHEN("unknown == { 2, 3 } || { 3, 4 } == { 4, 5 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(unknown, c2_sym); auto rhs_expr = equal_exprt(c3_sym, c4_sym); auto or_expr = or_exprt(lhs_expr, rhs_expr); ASSUME_TRUE(environment, or_expr, ns); } WHEN("unknown == { 2, 3 } || { 3, 4 } != { 4, 5 }") { auto unknown = symbol_exprt("unknown", v23->type()); auto lhs_expr = equal_exprt(unknown, c2_sym); auto rhs_expr = notequal_exprt(c3_sym, c4_sym); auto or_expr = or_exprt(lhs_expr, rhs_expr); ASSUME_NIL(environment, or_expr, ns); } WHEN("{ 1, 2 } == { 4, 5 } || { 3, 4 } == { 1, 2 }") { auto expr0 = equal_exprt(c1_sym, c4_sym); auto expr1 = equal_exprt(c3_sym, c1_sym); auto or_expr = or_exprt(expr0, expr1); ASSUME_FALSE(environment, or_expr, ns); } } } void ASSUME_TRUE( abstract_environmentt &env, const exprt &expr, const namespacet &ns) { THEN("assume is true") { auto assumption = env.do_assume(expr, ns); REQUIRE(assumption.id() != ID_nil); REQUIRE(assumption.type().id() == ID_bool); REQUIRE(assumption.is_true()); } } void ASSUME_FALSE( abstract_environmentt &env, const exprt &expr, const namespacet &ns) { THEN("assume is false") { auto assumption = env.do_assume(expr, ns); REQUIRE(assumption.id() != ID_nil); REQUIRE(assumption.type().id() == ID_bool); REQUIRE(assumption.is_false()); } } void ASSUME_NIL( abstract_environmentt &env, const exprt &expr, const namespacet &ns) { THEN("assume is nil") { auto assumption = env.do_assume(expr, ns); REQUIRE(assumption.id() == ID_nil); } } std::vector<std::string> split(std::string const &s, std::string const &delimiter) { std::vector<std::string> tokens; size_t pos = 0; size_t end = 0; while(end != s.size()) { end = s.find(delimiter, pos); end = (end != std::string::npos) ? end : s.size(); tokens.push_back(s.substr(pos, end - pos)); pos = end + delimiter.size(); } return tokens; } std::vector<exprt> numbersToExprs(std::vector<std::string> const &numbers) { auto type = signedbv_typet(32); auto exprs = std::vector<exprt>{}; for(auto number : numbers) { auto n = std::stoi(number); exprs.push_back(from_integer(n, type)); } return exprs; }
27.215869
80
0.484222
fanhy2114
9443f790a574b949ab7746181e2ea1eb2942fbb5
4,007
cpp
C++
source/utils/utils.cpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
4
2021-02-06T09:13:54.000Z
2021-12-14T20:09:23.000Z
source/utils/utils.cpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
null
null
null
source/utils/utils.cpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
1
2021-12-30T15:49:42.000Z
2021-12-30T15:49:42.000Z
#include "utils.hpp" // #include "b0RemoteApi.h" // #include "common.hpp" #include <cmath> // função que calcula a integral de linha do polinomio de terceiro grau // aproximação por serie de Taylor double poly3Length(const double coef[], const double l){ const double NumPoints = 1000.0; //dlambda double integral = 0.0, Dx, Dy; double a0,a1,a2,a3,b0,b1,b2,b3; a0 = coef[0]; a1 = coef[1]; a2 = coef[2]; a3 = coef[3]; b0 = coef[4]; b1 = coef[5]; b2 = coef[6]; b3 = coef[7]; double dlambda = 1.0/NumPoints; for(double lambda = 0.0; lambda < l; lambda += dlambda){ Dx = a1 + 2.0*a2*lambda + 3.0*a3*lambda*lambda; Dy = b1 + 2.0*b2*lambda + 3.0*b3*lambda*lambda; integral += sqrt(Dx*Dx + Dy*Dy) * dlambda; } return integral; } double curvature(const double coef[], const double l){ double Dx = coef[1] + 2*coef[2]*l + 3*coef[3]*l*l; double Dy = coef[5] + 2*coef[6]*l + 3*coef[7]*l*l; double DDx = 2*coef[2] + 6*coef[3]*l; double DDy = 2*coef[6] + 6*coef[7]*l; double kappa = (DDy*Dx - DDx*Dy)/pow( Dx*Dx + Dy*Dy, 3.0/2.0); return fabs(kappa); } void poly3(const double coef[], const double l, float &x, float &y, float &th){ double l2 = l*l; double l3 = l2*l; x = coef[0] + coef[1]*l + coef[2]*l2 + coef[3]*l3; y = coef[4] + coef[5]*l + coef[6]*l2 + coef[7]*l3; th= atan2f64(coef[5] + 2*coef[6]*l + 3*coef[7]*l2, coef[1] + 2*coef[2]*l + 3*coef[3]*l2); } void pathGenerator(const double coef[],const uint32_t numPoints, float x[], float y[], float th[]){ double l = 0, step_l = 1.0/numPoints; for(int i = 0; i < numPoints; i++) { poly3(coef,l,x[i], y[i], th[i]); l += step_l; } } void pathComputing(float xi, float yi, float thi, float xf, float yf, float thf, double coef[]){ const double delta = 0.001; double dx = xf - xi; double dy = yf - yi; double *a0,*a1,*a2,*a3,*b0,*b1,*b2,*b3; a0 = &coef[0]; a1 = &coef[1]; a2 = &coef[2]; a3 = &coef[3]; b0 = &coef[4]; b1 = &coef[5]; b2 = &coef[6]; b3 = &coef[7]; bool thi_test = ((M_PI_2 - delta) < thi) && (thi < (M_PI_2 + delta)); bool thf_test = ((M_PI_2 - delta) < thf) && (thf < (M_PI_2 + delta)); if(thi_test && thf_test){ // # caso especial 1 *b1 = dy; //#coef. livre *b2 = 0; //#coef. livre *a0 = xi; *a1 = 0; *a2 = 3*dx; *a3 = -2*dx; *b0 = yi; *b3 = dy - (*b1) - (*b2); } else if(thi_test){ // #caso especial 2 double alpha_f = tanf64(thf); *a3 = -dx/2.0; //#coef. livre *b3 = 0; //#coef. livre (qualquer valor aqui) *a0 = xi; *a1 = 0; *a2 = dx - (*a3); *b0 = yi; *b1 = 2*(dy - alpha_f*dx) - alpha_f*(*a3) + (*b3); *b2 = (2*alpha_f*dx - dy) + alpha_f*(*a3) - 2*(*b3); } else if(thf_test){ // #caso especial 3 double alpha_i = tanf64(thi); *a1 = 3*dx/2.0; //#coef. livre *b2 = 0; //#coef. livre (qualquer valor aqui) *a0 = xi; *a2 = 3*dx - 2*(*a1); *a3 = (*a1) - 2*dx; *b0 = yi; *b1 = alpha_i*(*a1); *b3 = dy - alpha_i*(*a1) - (*b2); } else{ // #caso geral double alpha_i = tanf64(thi); double alpha_f = tanf64(thf); *a1 = dx; //#coef. livre *a2 = 0; //#coef. livre *a0 = xi; *a3 = dx - (*a1) - (*a2); *b0 = yi; *b1 = alpha_i*(*a1); *b2 = 3*(dy - alpha_f*dx) + 2*(alpha_f - alpha_i)*(*a1) + alpha_f*(*a2); *b3 = 3*alpha_f*dx - 2*dy - (2*alpha_f - alpha_i)*(*a1) - alpha_f*(*a2); } } void pioneer_model(float v, float w, float &w_right, float &w_left) { const static float b = 0.331; //wheel axis distance [m] const static float r = 0.09751; //wheel radius [m] w_right = (1.0/r)*v + (b/(2.0*r))*w; w_left = (1.0/r)*v - (b/(2.0*r))*w; }
32.577236
99
0.499875
Gabriellgpc
9443fabf944b8309fd43c8ee190a352dae6d1ce1
306
cpp
C++
connectionraii.cpp
yuminc1234/web-server
78135002609038708c4a1028de7041b24c4e3d8e
[ "MIT" ]
null
null
null
connectionraii.cpp
yuminc1234/web-server
78135002609038708c4a1028de7041b24c4e3d8e
[ "MIT" ]
null
null
null
connectionraii.cpp
yuminc1234/web-server
78135002609038708c4a1028de7041b24c4e3d8e
[ "MIT" ]
null
null
null
#include "connectionraii.h" ConnectionRAII::ConnectionRAII(MYSQL **mysql, ConnectionPool *conn_pool) { *mysql = conn_pool->get_connection(); mysql_RAII = *mysql; conn_pool_RAII = conn_pool; } ConnectionRAII::~ConnectionRAII() { conn_pool_RAII->release_connection(mysql_RAII); }
23.538462
75
0.715686
yuminc1234
94481db32f8322c73dda454123c927d51f884b87
351
cpp
C++
lib/Gen/IRCodeGenFunction.cpp
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
lib/Gen/IRCodeGenFunction.cpp
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
lib/Gen/IRCodeGenFunction.cpp
StoneLang/Stone
baf74e460b2c7e03a17d4ec1682b0d5beb3ad6a1
[ "MIT" ]
null
null
null
#include "stone/Gen/IRCodeGenFunction.h" #include "stone/Gen/IRCodeGenModule.h" using namespace stone; IRCodeGenFunction::IRCodeGenFunction(IRCodeGenModule &irCodeGenModule, llvm::Function *llvmFun) : irCodeGenModule(irCodeGenModule), llvmFunction(llvmFunction) {} IRCodeGenFunction::~IRCodeGenFunction() {}
35.1
70
0.723647
StoneLang
944a473f17644f0088321185563102bae145f496
2,146
cpp
C++
Source/Services/Common/xbox_live_context_api.cpp
natiskan/xbox-live-api
9e7e51e0863b5983c2aa334a7b0db579b3bdf1de
[ "MIT" ]
118
2019-05-13T22:56:02.000Z
2022-03-16T06:12:39.000Z
Source/Services/Common/xbox_live_context_api.cpp
aspavlov/xbox-live-api
4bec6f92347d0ad6c85463b601821333de631e3a
[ "MIT" ]
31
2019-05-07T13:09:28.000Z
2022-01-26T10:02:59.000Z
Source/Services/Common/xbox_live_context_api.cpp
aspavlov/xbox-live-api
4bec6f92347d0ad6c85463b601821333de631e3a
[ "MIT" ]
48
2019-05-28T23:55:31.000Z
2021-12-22T03:47:56.000Z
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "xbox_live_context_internal.h" #include "xbox_live_app_config_internal.h" using namespace xbox::services; STDAPI XblContextCreateHandle( _In_ XblUserHandle user, _Out_ XblContextHandle* context ) XBL_NOEXCEPT try { RETURN_HR_INVALIDARGUMENT_IF(user == nullptr || context == nullptr); auto globalState{ GlobalState::Get() }; if (!globalState) { return E_XBL_NOT_INITIALIZED; } auto wrapUserResult{ User::WrapHandle(user) }; RETURN_HR_IF_FAILED(wrapUserResult.Hresult()); auto xboxLiveContext = XblContext::Make(wrapUserResult.ExtractPayload()); HRESULT hr = xboxLiveContext->Initialize(globalState->RTAManager()); if (SUCCEEDED(hr)) { xboxLiveContext->AddRef(); *context = xboxLiveContext.get(); } return hr; } CATCH_RETURN() STDAPI XblContextDuplicateHandle( _In_ XblContextHandle handle, _Out_ XblContextHandle* duplicatedHandle ) XBL_NOEXCEPT try { RETURN_HR_INVALIDARGUMENT_IF(handle == nullptr || duplicatedHandle == nullptr); handle->AddRef(); *duplicatedHandle = handle; return S_OK; } CATCH_RETURN() STDAPI_(void) XblContextCloseHandle( _In_ XblContextHandle handle ) XBL_NOEXCEPT try { if (handle) { handle->DecRef(); } } CATCH_RETURN_WITH(;) STDAPI XblContextGetUser( _In_ XblContextHandle context, _Out_ XblUserHandle* user ) XBL_NOEXCEPT try { RETURN_HR_INVALIDARGUMENT_IF(user == nullptr || context == nullptr); return XalUserDuplicateHandle(context->User().Handle(), user); } CATCH_RETURN() STDAPI XblContextGetXboxUserId( _In_ XblContextHandle context, _Out_ uint64_t* xuid ) XBL_NOEXCEPT try { RETURN_HR_INVALIDARGUMENT_IF(context == nullptr || xuid == nullptr); *xuid = context->Xuid(); return S_OK; } CATCH_RETURN() void XblSetApiType( _In_ XblApiType apiType ) XBL_NOEXCEPT { auto state = GlobalState::Get(); if (state) { state->ApiType = apiType; } }
21.897959
101
0.70876
natiskan
944aae92a4d11cc4fb164fc8543f7698584a2cbd
14,000
hpp
C++
src/poutreImageProcessingLowLevelMorphology/include/poutreImageProcessingEroDilLine.hpp
ThomasRetornaz/poutre
21717ce1da24515dd208f711d6e7c38095ba8ecf
[ "BSL-1.0" ]
null
null
null
src/poutreImageProcessingLowLevelMorphology/include/poutreImageProcessingEroDilLine.hpp
ThomasRetornaz/poutre
21717ce1da24515dd208f711d6e7c38095ba8ecf
[ "BSL-1.0" ]
null
null
null
src/poutreImageProcessingLowLevelMorphology/include/poutreImageProcessingEroDilLine.hpp
ThomasRetornaz/poutre
21717ce1da24515dd208f711d6e7c38095ba8ecf
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright (c) 2015 - Thomas Retornaz // // thomas.retornaz@mines-paris.org // // Distributed under the Boost Software License, Version 1.0. // // See accompanying file LICENSE.txt or copy at // // http://www.boost.org/LICENSE_1_0.txt // //============================================================================== #ifndef POUTRE_IMAGEPROCESSING_ERO_DIL_LINE_HPP__ #define POUTRE_IMAGEPROCESSING_ERO_DIL_LINE_HPP__ /** * @file poutreImageProcessingEroDil.hpp * @author Thomas Retornaz * @brief Define erosion/dilatation using line se * * */ #include <poutreBase/poutreContainerView.hpp> #include <poutreImageProcessingCore/include/poutreImageProcessingContainerCopieConvert.hpp> #include <poutreImageProcessingCore/poutreImageProcessingCore.hpp> #include <poutreImageProcessingCore/poutreImageProcessingInterface.hpp> #include <poutreImageProcessingCore/poutreImageProcessingInterfaceCopieConvert.hpp> #include <poutreImageProcessingCore/poutreImageProcessingType.hpp> #include <poutreImageProcessingPixelOperation/include/poutreImageProcessingArith.hpp> #include <poutreImageProcessingSE/poutreImageProcessingSENeighborList.hpp> #include <algorithm> #include <numeric> namespace poutre { /** * @addtogroup image_processing_mm_group Image Processing Morphology * @ingroup image_processing_group *@{ */ /** * @addtogroup image_processing_erodil_group Image Processing Erosion Dilatation *functions * @ingroup image_processing_mm_group *@{ */ // stolen from pylene todo propagate __restrict everywhere template<class T, class BinaryFunction> void running_max_min_1d(T *__restrict f, T *__restrict g, T *__restrict h, ptrdiff_t n, ptrdiff_t k, BinaryFunction func, bool use_extension = true) { if( n == 0 ) return; const ptrdiff_t alpha = 2 * k + 1; const ptrdiff_t size = n + 2 * k; // Forward pass // Compute g[x] = Max f(y), y ∈ [α * ⌊x / α⌋ : x] { ptrdiff_t chunk_start = use_extension ? -k : 0; ptrdiff_t rem = use_extension ? size : n; for( ; rem > 0; chunk_start += alpha, rem -= alpha ) { ptrdiff_t chunk_size = std::min(rem, alpha); std::partial_sum(f + chunk_start, f + chunk_start + chunk_size, g + chunk_start, func); } } // Backward pass // Compute h[x] = Max f(y) y ∈ [x : α * (⌊x/α⌋+1)) { ptrdiff_t chunk_start = use_extension ? -k : 0; ptrdiff_t rem = use_extension ? size : n; for( ; rem > 0; chunk_start += alpha, rem -= alpha ) { ptrdiff_t chunk_size = std::min(alpha, rem); std::partial_sum(std::make_reverse_iterator(f + chunk_start + chunk_size), std::make_reverse_iterator(f + chunk_start), std::make_reverse_iterator(h + chunk_start + chunk_size), func); } } // Compute local maximum out[x] = Max f(y) y ∈ [x-k:x+k] // out[x] = Max (Max f[x-k:b), Max f[b:x+k]) with b = α.⌈(x-k)/α⌉ = α.⌊(x+k)/α⌋ // = Max( h[x-k], g[x+k] ) { for( ptrdiff_t i = 0; i < n; ++i ) f[i] = func(h[i - k], g[i + k]); } } template<typename T1, typename T2, ptrdiff_t Rank, template<typename, ptrdiff_t> class View1, template<typename, ptrdiff_t> class View2> struct t_DilateXOpLineDispatcher { // generic case not supported yet // static_assert(false, "To be implemented for generic views"); }; template<typename T> struct t_DilateXOpLineDispatcher<T, T, 1, array_view, array_view> { void operator()(const array_view<T, 1> &i_vin, ptrdiff_t k, array_view<T, 1> &o_vout) { POUTRE_ASSERTCHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); auto ibd = i_vin.bound(); auto obd = o_vout.bound(); scoord n = ibd[0]; if( n == 0 ) return; if( k <= 0 ) { std::memcpy((void *)o_vout.data(), (void *)i_vin.data(), sizeof(T) * i_vin.size()); return; } using lineView = T *; lineView rawLineIn = i_vin.data(); lineView rawLineOut = o_vout.data(); // need auxilary buffer using tmpBuffer = std::vector<T, xs::aligned_allocator<T, SIMD_IDEAL_MAX_ALIGN_BYTES>>; // alignement not // required tmpBuffer f(n + 2 * k), g(n + 2 * k), h(n + 2 * k); std::fill_n(f.begin(), f.size(), std::numeric_limits<T>::lowest()); std::memcpy(f.data() + k, rawLineIn, n * sizeof(T)); auto sup = [](auto x, auto y) { return std::max(x, y); }; running_max_min_1d(f.data() + k, g.data() + k, h.data() + k, n, k, sup); } }; template<typename T> struct t_DilateXOpLineDispatcher<T, T, 2, array_view, array_view> { void operator()(const array_view<T, 2> &i_vin, ptrdiff_t k, array_view<T, 2> &o_vout) { POUTRE_ASSERTCHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); auto ibd = i_vin.bound(); auto obd = o_vout.bound(); auto istride = i_vin.stride(); auto ostride = o_vout.stride(); scoord ysize = ibd[0]; scoord xsize = ibd[1]; POUTRE_ASSERTCHECK(ibd == obd, "bound not compatible"); POUTRE_ASSERTCHECK(istride == ostride, "stride not compatible"); if( xsize == 0 || ysize == 0 ) return; if( k <= 0 ) { t_Copy(i_vin, o_vout); } using lineView = T *; ptrdiff_t n = xsize; // need auxilary buffer using tmpBuffer = std::vector<T, xs::aligned_allocator<T, SIMD_IDEAL_MAX_ALIGN_BYTES>>; // alignement not // required tmpBuffer f(n + 2 * k), g(n + 2 * k), h(n + 2 * k); for( scoord y = 0; y < ysize; y++ ) { lineView bufInputCurrentLine = i_vin.data() + y * xsize; lineView bufOuputCurrentLine = o_vout.data() + y * xsize; std::fill_n(f.begin(), f.size(), std::numeric_limits<T>::lowest()); std::memcpy(f.data() + k, bufInputCurrentLine, n * sizeof(T)); auto sup = [](auto x, auto y) { return std::max(x, y); }; running_max_min_1d(f.data() + k, g.data() + k, h.data() + k, n, k, sup); std::memcpy(bufOuputCurrentLine, f.data() + k, n * sizeof(T)); } } }; template<typename T1, typename T2, ptrdiff_t Rank, template<typename, ptrdiff_t> class View1, template<typename, ptrdiff_t> class View2> struct t_ErodeXOpLineDispatcher { // generic case not supported yet // static_assert(false, "To be implemented for generic views"); }; template<typename T> struct t_ErodeXOpLineDispatcher<T, T, 1, array_view, array_view> { void operator()(const array_view<T, 1> &i_vin, ptrdiff_t k, array_view<T, 1> &o_vout) { POUTRE_ASSERTCHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); auto ibd = i_vin.bound(); auto obd = o_vout.bound(); scoord n = ibd[0]; if( n == 0 ) return; if( k <= 0 ) { std::memcpy((void *)o_vout.data(), (void *)i_vin.data(), sizeof(T) * i_vin.size()); return; } using lineView = T *; lineView rawLineIn = i_vin.data(); lineView rawLineOut = o_vout.data(); // need auxilary buffer using tmpBuffer = std::vector<T, xs::aligned_allocator<T, SIMD_IDEAL_MAX_ALIGN_BYTES>>; // alignement not // required tmpBuffer f(n + 2 * k), g(n + 2 * k), h(n + 2 * k); std::fill_n(f.begin(), f.size(), std::numeric_limits<T>::max()); std::memcpy(f.data() + k, rawLineIn, n * sizeof(T)); auto inf = [](auto x, auto y) { return std::min(x, y); }; running_max_min_1d(f.data() + k, g.data() + k, h.data() + k, n, k, inf); } }; template<typename T> struct t_ErodeXOpLineDispatcher<T, T, 2, array_view, array_view> { void operator()(const array_view<T, 2> &i_vin, ptrdiff_t k, array_view<T, 2> &o_vout) { POUTRE_ASSERTCHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); auto ibd = i_vin.bound(); auto obd = o_vout.bound(); auto istride = i_vin.stride(); auto ostride = o_vout.stride(); scoord ysize = ibd[0]; scoord xsize = ibd[1]; POUTRE_ASSERTCHECK(ibd == obd, "bound not compatible"); POUTRE_ASSERTCHECK(istride == ostride, "stride not compatible"); if( xsize == 0 || ysize == 0 ) return; if( k <= 0 ) { t_Copy(i_vin, o_vout); } using lineView = T *; ptrdiff_t n = xsize; // need auxilary buffer using tmpBuffer = std::vector<T, xs::aligned_allocator<T, SIMD_IDEAL_MAX_ALIGN_BYTES>>; // alignement not // required tmpBuffer f(n + 2 * k), g(n + 2 * k), h(n + 2 * k); for( scoord y = 0; y < ysize; y++ ) { lineView bufInputCurrentLine = i_vin.data() + y * xsize; lineView bufOuputCurrentLine = o_vout.data() + y * xsize; std::fill_n(f.begin(), f.size(), std::numeric_limits<T>::max()); std::memcpy(f.data() + k, bufInputCurrentLine, n * sizeof(T)); auto inf = [](auto x, auto y) { return std::min(x, y); }; running_max_min_1d(f.data() + k, g.data() + k, h.data() + k, n, k, inf); std::memcpy(bufOuputCurrentLine, f.data() + k, n * sizeof(T)); } } }; template<typename TIn, typename TOut, ptrdiff_t Rank, template<typename, ptrdiff_t> class ViewIn, template<typename, ptrdiff_t> class ViewOut> void t_DilateX(const ViewIn<TIn, Rank> &i_vin, ptrdiff_t k, ViewOut<TOut, Rank> &o_vout) { POUTRE_CHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); t_DilateXOpLineDispatcher<TIn, TOut, Rank, ViewIn, ViewOut> dispatcher; dispatcher(i_vin, k, o_vout); } template<typename TIn, typename TOut, ptrdiff_t Rank> void t_DilateX(const DenseImage<TIn, Rank> &i_vin, ptrdiff_t k, DenseImage<TOut, Rank> &o_vout) { POUTRE_ENTERING("t_DilateX"); AssertSizesCompatible(i_vin, o_vout, "t_DilateX incompatible size"); AssertAsTypesCompatible(i_vin, o_vout, "t_DilateX incompatible types"); auto viewIn = view(const_cast<DenseImage<TIn, Rank> &>(i_vin)); auto viewOut = view(o_vout); t_DilateX(viewIn, k, viewOut); } template<typename TIn, typename TOut, ptrdiff_t Rank, template<typename, ptrdiff_t> class ViewIn, template<typename, ptrdiff_t> class ViewOut> void t_DilateY(const ViewIn<TIn, Rank> &i_vin, ptrdiff_t k, ViewOut<TOut, Rank> &o_vout) { POUTRE_ENTERING("t_DilateY"); POUTRE_CHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); } template<typename TIn, typename TOut, ptrdiff_t Rank> void t_DilateY(const DenseImage<TIn, Rank> &i_vin, ptrdiff_t k, DenseImage<TOut, Rank> &o_vout) { AssertSizesCompatible(i_vin, o_vout, "t_DilateY incompatible size"); AssertAsTypesCompatible(i_vin, o_vout, "t_DilateY incompatible types"); auto viewIn = view(const_cast<DenseImage<TIn, Rank> &>(i_vin)); auto viewOut = view(o_vout); t_DilateY(viewIn, k, viewOut); } template<typename TIn, typename TOut, ptrdiff_t Rank, template<typename, ptrdiff_t> class ViewIn, template<typename, ptrdiff_t> class ViewOut> void t_ErodeX(const ViewIn<TIn, Rank> &i_vin, ptrdiff_t k, ViewOut<TOut, Rank> &o_vout) { POUTRE_ENTERING("t_ErodeX"); POUTRE_CHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); t_ErodeXOpLineDispatcher<TIn, TOut, Rank, ViewIn, ViewOut> dispatcher; dispatcher(i_vin, k, o_vout); } template<typename TIn, typename TOut, ptrdiff_t Rank> void t_ErodeX(const DenseImage<TIn, Rank> &i_vin, ptrdiff_t k, DenseImage<TOut, Rank> &o_vout) { AssertSizesCompatible(i_vin, o_vout, "t_ErodeX incompatible size"); AssertAsTypesCompatible(i_vin, o_vout, "t_ErodeX incompatible types"); auto viewIn = view(const_cast<DenseImage<TIn, Rank> &>(i_vin)); auto viewOut = view(o_vout); t_ErodeX(viewIn, k, viewOut); } template<typename TIn, typename TOut, ptrdiff_t Rank, template<typename, ptrdiff_t> class ViewIn, template<typename, ptrdiff_t> class ViewOut> void t_ErodeY(const ViewIn<TIn, Rank> &i_vin, ptrdiff_t k, ViewOut<TOut, Rank> &o_vout) { POUTRE_ENTERING("t_ErodeY"); POUTRE_CHECK(i_vin.size() == o_vout.size(), "Incompatible views size"); } template<typename TIn, typename TOut, ptrdiff_t Rank> void t_ErodeY(const DenseImage<TIn, Rank> &i_vin, ptrdiff_t k, DenseImage<TOut, Rank> &o_vout) { // AssertSizesCompatible(i_vin, o_vout, "t_ErodeY incompatible size"); AssertAsTypesCompatible(i_vin, o_vout, "t_ErodeY incompatible types"); auto viewIn = view(const_cast<DenseImage<TIn, Rank> &>(i_vin)); auto viewOut = view(o_vout); t_ErodeX(viewIn, k, viewOut); } //! @} doxygroup: image_processing_erodil_group //! @} doxygroup: image_processing_group } // namespace poutre #endif // POUTRE_IMAGEPROCESSING_ERO_DIL_LINE_HPP__
39.325843
111
0.583286
ThomasRetornaz
94596cd37fdc3129ab05483520b67dc919149781
3,243
cpp
C++
triple_temperature_uno/message_reader.cpp
Scottz0r/TripleTemperature
58492e3c40c0ae86ada6868971c7f9809d69bcc8
[ "MIT" ]
null
null
null
triple_temperature_uno/message_reader.cpp
Scottz0r/TripleTemperature
58492e3c40c0ae86ada6868971c7f9809d69bcc8
[ "MIT" ]
null
null
null
triple_temperature_uno/message_reader.cpp
Scottz0r/TripleTemperature
58492e3c40c0ae86ada6868971c7f9809d69bcc8
[ "MIT" ]
null
null
null
#include "message_reader.h" #include <Arduino.h> static constexpr auto REQUEST_MESSAGE_ID = 4; // TODO: Should probably have this in one place for all messages. static constexpr auto REQUEST_MESSAGE_SIZE = 3; namespace scottz0r { namespace temperature { MessageReader::MessageReader(time_type receive_timeout) : m_receive_timeout(receive_timeout), m_buffer_index(0), m_start_receive(0), m_state(State::Start) { } bool MessageReader::process(int c) { // Message timeout from previous collect. Reset collection state and assume this is a new message. if (m_state == State::Collect) { time_type elapsed = millis() - m_start_receive; if (elapsed >= m_receive_timeout) { m_state = State::Start; } } if (m_state == State::Done || m_state == State::Start) { m_buffer_index = 0; m_state = State::Collect; m_start_receive = millis(); // When starting to collect, if the first byte is not the correct message identifier, do not go to // collection state. This means that following bytes could trigger a collect if it contains the start // byte. if (c != REQUEST_MESSAGE_ID) { return false; } } // Assert buffer collection state before adding byte. if (m_buffer_index < buffer_size) { m_buffer[m_buffer_index] = (uint8_t)c; ++m_buffer_index; } else { // Buffer overflow. Restart collection. m_state = State::Start; return false; } if (m_buffer_index == REQUEST_MESSAGE_SIZE) { m_state = State::Done; return true; } return false; } void MessageReader::reset() { m_buffer_index = 0; m_state = State::Start; } bool MessageReader::get_data(RequestType &dest) { if (m_state != State::Done) { return false; } return decode_request_message(dest); } bool MessageReader::decode_request_message(RequestType &dest) { // Set output parameter to a default state. dest = RequestType::_Unknown; // Assert buffer size is expected size. if (m_buffer_index != REQUEST_MESSAGE_SIZE) { return false; } // Assert this really is a request message type. if (m_buffer[0] != REQUEST_MESSAGE_ID) { return false; } // Checksum. Return false if checksums do not match. Do not attempt to decode data if checksum is bad. uint8_t checksum = 0; checksum ^= m_buffer[0]; checksum ^= m_buffer[1]; if (checksum != m_buffer[2]) { return false; } // Assert message enumeration type is within bounds. if (m_buffer[1] >= static_cast<uint8_t>(RequestType::_Unknown)) { return false; } dest = static_cast<RequestType>(m_buffer[1]); return true; } } // namespace temperature } // namespace scottz0r
26.581967
113
0.565834
Scottz0r
9459f3c27c3372662f06f88e02aa77c5fdb11bf1
2,101
cpp
C++
lib/resources/ResourceShader.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
1
2016-11-15T09:04:12.000Z
2016-11-15T09:04:12.000Z
lib/resources/ResourceShader.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
lib/resources/ResourceShader.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 maldicion069 * * Authors: Cristian Rodríguez Bernal <ccrisrober@gmail.com> * * This file is part of MonkeyBrushPlusPlus * <https://github.com/maldicion069/monkeybrushplusplus> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3.0 as published * by the Free Software Foundation. * * 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "ResourceShader.hpp" namespace mb { std::unordered_map<std::string, std::string> ResourceShader::_files; void ResourceShader::add(const std::string& key, const std::string& value) { ResourceShader::_files[key] = value; } const std::string& ResourceShader::get(const std::string& key) { return ResourceShader::_files[key]; } bool ResourceShader::exist(const std::string& key) { return ResourceShader::_files.find(key) != ResourceShader::_files.end(); } void ResourceShader::remove(const std::string& key) { ResourceShader::_files.erase(key); } void ResourceShader::clear() { ResourceShader::_files.clear(); } void ResourceShader::loadShader(const std::string& alias, const std::string& filePath) { std::ifstream file(filePath); if (!file.is_open()) { throw "File " + std::string(filePath) + " undefined"; } std::stringstream buffer; buffer << file.rdbuf(); const std::string& src = buffer.str(); ResourceShader::loadShaderFromText(alias, src); } void ResourceShader::loadShaderFromText(const std::string& alias, const std::string& shaderSource) { ResourceShader::add(alias, shaderSource); } }
31.358209
100
0.709186
maldicion069
945abe0605d9f07c69a0ed2725b7f6916a8774ac
2,272
cpp
C++
0001-0100/0084.cpp
YKR/LeetCode2019
e4c6346eae5c7b85ba53249c46051700a73dd95e
[ "MIT" ]
null
null
null
0001-0100/0084.cpp
YKR/LeetCode2019
e4c6346eae5c7b85ba53249c46051700a73dd95e
[ "MIT" ]
null
null
null
0001-0100/0084.cpp
YKR/LeetCode2019
e4c6346eae5c7b85ba53249c46051700a73dd95e
[ "MIT" ]
null
null
null
class Solution { public: int largestRectangleAreaWithUnionFind(vector<int>& heights) { if (heights.empty()) return 0; int ans = 0; int order[heights.size()], uf[heights.size()], ufsize[heights.size()]; for (int i = 0; i < heights.size(); ++i) order[i] = uf[i] = i, ufsize[i] = 1; auto orderCompare = [&heights](int a, int b) -> bool { return heights[a] > heights[b]; }; sort(order, order + heights.size(), orderCompare); function<int (int index)> unionFind; unionFind = [&uf, &unionFind](int index) -> int { if (uf[index] == index) return index; return uf[index] = unionFind(uf[index]); }; bool searched[heights.size()]; memset(searched, 0, sizeof(searched)); for (int i = 0; i < heights.size(); ++i) { if (order[i] + 1 < heights.size() && searched[order[i] + 1]) { ufsize[unionFind(order[i] + 1)] += ufsize[unionFind(order[i])]; uf[unionFind(order[i])] = unionFind(order[i] + 1); } if (order[i] - 1 >= 0 && searched[order[i] - 1]) { ufsize[unionFind(order[i] - 1)] += ufsize[unionFind(order[i])]; uf[unionFind(order[i])] = unionFind(order[i] - 1); } ans = max(ans, heights[order[i]] * ufsize[unionFind(order[i])]); searched[order[i]] = true; } return ans; } int largestRectangleArea(vector<int>& heights) { //return largestRectangleAreaWithUnionFind(heights); heights.push_back(0); int ans = 0; vector<int> heightStack; for (int i = 0 ; i < heights.size(); ++i) { while (!heightStack.empty() && heights[heightStack.back()] >= heights[i]) { int rangeHeightIndex = heightStack.back(); heightStack.pop_back(); int beginIndex = heightStack.empty() ? 0 : heightStack.back() + 1; ans = max(ans, (i - beginIndex) * heights[rangeHeightIndex]); } heightStack.push_back(i); } return ans; } };
39.859649
86
0.493838
YKR
9464968677d24215fe3815ec1b7a7b311f3e5198
1,717
hpp
C++
include/Zen/Enterprise/I_ResourceLocation.hpp
indie-zen/zen-enterprise
e8155dc1349b32a5996202edbeee80a168b20a2d
[ "MIT" ]
1
2018-01-28T22:50:54.000Z
2018-01-28T22:50:54.000Z
include/Zen/Enterprise/I_ResourceLocation.hpp
indie-zen/zen-enterprise
e8155dc1349b32a5996202edbeee80a168b20a2d
[ "MIT" ]
null
null
null
include/Zen/Enterprise/I_ResourceLocation.hpp
indie-zen/zen-enterprise
e8155dc1349b32a5996202edbeee80a168b20a2d
[ "MIT" ]
null
null
null
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Zen Enterprise Framework // // Copyright (C) 2001 - 2016 Raymond A. Richards //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #ifndef ZEN_ENTERPRISE_I_RESOURCE_LOCATION_HPP_INCLUDED #define ZEN_ENTERPRISE_I_RESOURCE_LOCATION_HPP_INCLUDED #include "Configuration.hpp" #include <memory> #include <boost/noncopyable.hpp> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace Enterprise { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ ; /// @brief Resource Location /// /// class ENTERPRISE_DLL_LINK I_ResourceLocation : boost::noncopyable { /// @name Types /// @{ public: /// @} /// @name I_ResourceLocation interface. /// @{ public: /// Get the location as a string. virtual const std::string& toString() const = 0; /// Operators virtual bool operator==(const I_ResourceLocation& _otherLocation) const = 0; virtual bool operator!=(const I_ResourceLocation& _otherLocation) const = 0; /// @} /// @name Events /// @{ public: /// @} /// @name 'Structors /// @{ protected: I_ResourceLocation() = default; virtual ~I_ResourceLocation() = default; /// @} }; // interface I_ResourceLocation //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace Enterprise } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #endif // ZEN_ENTERPRISE_I_RESOURCE_LOCATION_HPP_INCLUDED
27.253968
81
0.455446
indie-zen
94665efc0a06464d0402447828a935bc462b04db
8,686
cpp
C++
imgproc/png.cpp
melowntech/libimgproc
2dc035d12b0d0128f0f97274d2efa62de924b257
[ "BSD-2-Clause" ]
4
2017-06-23T19:16:00.000Z
2019-03-11T08:10:56.000Z
externals/browser/externals/browser/externals/libimgproc/imgproc/png.cpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
null
null
null
externals/browser/externals/browser/externals/libimgproc/imgproc/png.cpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
1
2018-03-16T18:24:48.000Z
2018-03-16T18:24:48.000Z
/** * Copyright (c) 2017 Melown Technologies SE * * 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. * * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <cstdio> #include <memory> #include <algorithm> #include <system_error> #include <png.h> #include "dbglog/dbglog.hpp" #include "utility/binaryio.hpp" #include "png.hpp" #include "error.hpp" namespace fs = boost::filesystem; namespace bin = utility::binaryio; namespace imgproc { namespace png { namespace { extern "C" { void imgproc_PngWrite(::png_structp png, ::png_bytep data, ::png_size_t length) { auto &out(*static_cast<SerializedPng*>(::png_get_io_ptr(png))); out.insert(out.end(), data, data + length); } void imgproc_PngFlush(::png_structp) {} } // extern "C" class PngWriter { public: PngWriter(SerializedPng &out) : png_(::png_create_write_struct (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr)) , info_() { if (!png_) { LOGTHROW(err1, Error) << "Unable to initialize PNG writer."; } info_ = ::png_create_info_struct(png_); ::png_set_write_fn(png_ , &out , &imgproc_PngWrite , imgproc_PngFlush); } PngWriter(FILE *out) : png_(::png_create_write_struct (PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr)) , info_() { if (!png_) { LOGTHROW(err1, Error) << "Unable to initialize PNG writer."; } info_ = ::png_create_info_struct(png_); ::png_init_io(png_, out); } ~PngWriter() { png_destroy_write_struct(&png_, &info_); } ::png_structp png() { return png_; } ::png_infop info() { return info_; } private: ::png_structp png_; ::png_infop info_; }; template <typename PixelType, typename ConstView> void writeView(PngWriter &writer, const ConstView &view , int compressionLevel, int type) { ::png_set_IHDR(writer.png(), writer.info() , png_uint_32(view.width()), png_uint_32(view.height()) , 8, type, PNG_INTERLACE_NONE , PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); if ((compressionLevel >= 0) && (compressionLevel <= 9)) { ::png_set_compression_level(writer.png(), compressionLevel); } ::png_write_info(writer.png(), writer.info()); std::vector<PixelType> row(view.width()); // copy row by row for(int y(0), ey(int(view.height())); y != ey; ++y) { std::copy(view.row_begin(y), view.row_end(y), row.begin()); ::png_write_row(writer.png() , reinterpret_cast< ::png_bytep>(&row.front())); } ::png_write_end(writer.png(), writer.info()); } template <typename PixelType, typename ConstView> SerializedPng serializeView(const ConstView &view, int compressionLevel , int type) { SerializedPng out; PngWriter writer(out); writeView<PixelType>(writer, view, compressionLevel, type); return out; } template <typename PixelType, typename ConstView> void writeViewToFile(const fs::path &path, const ConstView &view , int compressionLevel, int type) { struct FileHolder { FileHolder(const fs::path &path) : path(path), f(std::fopen(path.string().c_str(), "w")) {} ~FileHolder() { if (!f) { return; } if (std::fclose(f)) { std::system_error e(errno, std::system_category()); LOG(warn3) << "Cannot close PNG file " << path << ": <" << e.code() << ", " << e.what() << ">."; } } const fs::path path; std::FILE *f; }; FileHolder fh(path); if (!fh.f) { std::system_error e(errno, std::system_category()); LOG(err3) << "Cannot create PNG file " << path << ": <" << e.code() << ", " << e.what() << ">."; throw e; } PngWriter writer(fh.f); writeView<PixelType>(writer, view, compressionLevel, type); } } // namespace SerializedPng serialize(const boost::gil::gray8_image_t &image , int compressionLevel) { return serializeView<boost::gil::gray8_pixel_t> (boost::gil::const_view(image), compressionLevel, PNG_COLOR_TYPE_GRAY); } void write(const fs::path &file , const boost::gil::gray8_image_t &image , int compressionLevel) { return writeViewToFile<boost::gil::gray8_pixel_t> (file, boost::gil::const_view(image) , compressionLevel, PNG_COLOR_TYPE_GRAY); } SerializedPng serialize(const boost::gil::rgb8_image_t &image , int compressionLevel) { return serializeView<boost::gil::rgb8_pixel_t> (boost::gil::const_view(image), compressionLevel, PNG_COLOR_TYPE_RGB); } void write(const fs::path &file , const boost::gil::rgb8_image_t &image , int compressionLevel) { return writeViewToFile<boost::gil::rgb8_pixel_t> (file, boost::gil::const_view(image) , compressionLevel, PNG_COLOR_TYPE_RGB); } SerializedPng serialize(const boost::gil::rgba8_image_t &image , int compressionLevel) { return serializeView<boost::gil::rgba8_pixel_t> (boost::gil::const_view(image), compressionLevel, PNG_COLOR_TYPE_RGBA); } SerializedPng serialize(const void *data, std::size_t length , const math::Size2 &size, RawFormat format , int compressionLevel) { auto checkLength([&](int components) { if ((math::area(size) * components) != int(length)) { LOGTHROW(err1, Error) << "Cannot serialize raw data to PNG: wrong lenght " << length << "; should be " << (math::area(size) * components) << "."; } }); switch (format) { case RawFormat::gray: checkLength(1); return serializeView<boost::gil::gray8_pixel_t> (boost::gil::interleaved_view (size.width, size.height , static_cast<const boost::gil::gray8_pixel_t*>(data) , size.width) , compressionLevel, PNG_COLOR_TYPE_GRAY); case RawFormat::rgb: checkLength(3); return serializeView<boost::gil::rgb8_pixel_t> (boost::gil::interleaved_view (size.width, size.height , static_cast<const boost::gil::rgb8_pixel_t*>(data) , 3 * size.width) , compressionLevel, PNG_COLOR_TYPE_RGB); case RawFormat::rgba: checkLength(4); return serializeView<boost::gil::rgba8_pixel_t> (boost::gil::interleaved_view (size.width, size.height , static_cast<const boost::gil::rgba8_pixel_t*>(data) , 4 * size.width) , compressionLevel, PNG_COLOR_TYPE_RGBA); } LOGTHROW(err1, Error) << "Unsupported raw format <" << static_cast<int>(format) << "> for PNG serialization."; throw; } void write(const fs::path &file , const boost::gil::rgba8_image_t &image , int compressionLevel) { return writeViewToFile<boost::gil::rgba8_pixel_t> (file, boost::gil::const_view(image) , compressionLevel, PNG_COLOR_TYPE_RGBA); } } } // namespace imgproc::png
31.585455
79
0.612019
melowntech
9468612075105945699d30c48d8a2379589096c3
2,079
cpp
C++
solved_problems/602B.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
1
2021-01-27T16:37:31.000Z
2021-01-27T16:37:31.000Z
solved_problems/602B.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
null
null
null
solved_problems/602B.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
null
null
null
/*When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it? You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1. A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1. Find the length of the longest almost constant range. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000). Output Print a single number — the maximum length of an almost constant range of the given sequence. Examples Input Copy 5 1 2 3 3 2 Output Copy 4 Input Copy 11 5 4 5 5 6 7 8 8 8 7 6 Output Copy 5 Note In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4. In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10]. */ #include <bits/stdc++.h> using namespace std; int a[1000050], num, ans; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> num; a[num]++; a[num + 1]++; a[num - 1] = 0; a[num + 2] = 0; ans = max(ans, a[num]); ans = max(ans, a[num + 1]); // cout<<ans<<endl; } cout << ans << "\n"; }
27
81
0.659933
archit-1997
946a6cfcd9d1e801e37c60e467b19b8c81849873
1,958
cpp
C++
src/Generator.cpp
egan105/6837FinalProject
60afe2412cf606989c294192b7d6ea817bbc7ddb
[ "MIT" ]
2
2016-03-28T12:57:18.000Z
2016-03-28T12:57:19.000Z
src/Generator.cpp
egan105/6837FinalProject
60afe2412cf606989c294192b7d6ea817bbc7ddb
[ "MIT" ]
null
null
null
src/Generator.cpp
egan105/6837FinalProject
60afe2412cf606989c294192b7d6ea817bbc7ddb
[ "MIT" ]
null
null
null
#include "Generator.h" #include <iostream> using namespace std; #include <math.h> #include <stdio.h> #include <stdlib.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif float get_rand(float x, float y) { if (x == 0) { x = 1995; } if (y == 0) { y = 1995; } srand(RAND_SEED * x * y); return (float)rand()/ RAND_MAX; } static float get_smooth_value(int x, int y) { float corner_pnts = (get_rand(x-1, y-1) + get_rand(x+1, y-1) + get_rand(x-1, y+1) + get_rand(x+1, y+1))/16; float adjacent_pnts = (get_rand(x, y-1) + get_rand(x, y+1) + get_rand(x-1, y) + get_rand(x+1, y))/8; float current_pnt = get_rand(x, y)/4; return current_pnt + adjacent_pnts + corner_pnts; } static double cosine_interpolate(double x, double y, double mu) { double mu2; mu2 = (1-cos(mu*M_PI))/2; return (x*(1-mu2)+y*mu2); } static float interpolation(float x, float y) { int x_int = (int) floor(x); float x_mod = x - x_int; int y_int = (int) floor(y); float y_mod = y - y_int; float point_1 = get_smooth_value(x_int, y_int); float point_2 = get_smooth_value(x_int + 1, y_int); float point_3 = get_smooth_value(x_int, y_int + 1); float point_4 = get_smooth_value(x_int + 1, y_int + 1); float i1 = (float) cosine_interpolate(point_1, point_2, x_mod); float i2 = (float) cosine_interpolate(point_3, point_4, x_mod); return (float) cosine_interpolate(i1,i2, y_mod); } float brownian(float x, float y, int octaves, float frequency) { float gain = .99f; float lacularity = 2.0f; float height = 0; float amps = gain; for (int i=0; i < octaves; i++) { height += interpolation(x*frequency, y*frequency) * amps; frequency *= lacularity; amps *= gain; } return height; } float generate_y(float x, float z) { return ((brownian(x, z, 5, 1.0f/300.0f) * 100) - 200); }
24.17284
67
0.609295
egan105
20e17886de24af029f986479655e722db63a0169
2,527
hpp
C++
include/lxgui/impl/gui_sfml_atlas.hpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
50
2015-01-15T10:00:31.000Z
2022-02-04T20:45:25.000Z
include/lxgui/impl/gui_sfml_atlas.hpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
88
2020-03-15T17:40:04.000Z
2022-03-15T08:21:44.000Z
include/lxgui/impl/gui_sfml_atlas.hpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
19
2017-03-11T04:32:01.000Z
2022-01-12T22:47:12.000Z
#ifndef LXGUI_GUI_SFML_ATLAS_HPP #define LXGUI_GUI_SFML_ATLAS_HPP #include <lxgui/utils.hpp> #include <lxgui/gui_material.hpp> #include <lxgui/gui_atlas.hpp> #include <SFML/Graphics/Texture.hpp> namespace lxgui { namespace gui { namespace sfml { class renderer; /// A single texture holding multiple materials for efficient rendering /** This is an abstract class that must be implemented * and created by the corresponding gui::renderer. */ class atlas_page final : public gui::atlas_page { public : /// Constructor. explicit atlas_page(const gui::renderer& mRenderer, material::filter mFilter); protected : /// Adds a new material to this page, at the provided location /** \param mMat The material to add * \param mLocation The position at which to insert this material * \return A new material pointing to inside this page */ std::shared_ptr<gui::material> add_material_(const gui::material& mMat, const bounds2f& mLocation) override; /// Return the width of this page (in pixels). /** \return The width of this page (in pixels) */ float get_width() const override; /// Return the height of this page (in pixels). /** \return The height of this page (in pixels) */ float get_height() const override; private : sf::Texture mTexture_; }; /// A class that holds rendering data /** This implementation can contain either a plain color * or a real sf::Texture. It is also used by the * gui::sfml::render_target class to store the output data. */ class atlas final : public gui::atlas { public : /// Constructor for textures. /** \param mRenderer The renderer with witch to create this atlas * \param mFilter Use texture filtering or not (see set_filter()) */ explicit atlas(const renderer& mRenderer, material::filter mFilter); atlas(const atlas& tex) = delete; atlas(atlas&& tex) = delete; atlas& operator = (const atlas& tex) = delete; atlas& operator = (atlas&& tex) = delete; protected : /// Create a new page in this atlas. /** \return The new page, added at the back of the page list */ std::unique_ptr<gui::atlas_page> create_page_() const override; }; } } } #endif
30.083333
87
0.610605
cschreib
20e1cddeb44e7d97abac56b71bce59db4471044b
1,567
hpp
C++
hpx/util/apex.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
hpx/util/apex.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
hpx/util/apex.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/hpx_fwd.hpp> #ifdef HPX_HAVE_APEX #include <apex.hpp> #endif #ifdef HPX_HAVE_APEX extern bool use_ittnotify_api; #endif namespace hpx { namespace util { #ifdef HPX_HAVE_APEX inline void apex_init() { if (use_ittnotify_api) { apex::init(); apex::set_node_id(hpx::get_locality_id()); } } inline void apex_finalize() { if (use_ittnotify_api) apex::finalize(); } struct apex_wrapper { apex_wrapper(char const* const name) : name_(name) { if (use_ittnotify_api) apex::start(name_); } ~apex_wrapper() { if (use_ittnotify_api) apex::stop(name_); } char const* const name_; }; struct apex_wrapper_init { apex_wrapper_init(int argc, char **argv) { apex::init(argc, argv); } ~apex_wrapper_init() { apex::finalize(); } }; #else inline void apex_init() {} inline void apex_finalize() {} struct apex_wrapper { apex_wrapper(char const* const name) {} ~apex_wrapper() {} }; struct apex_wrapper_init { apex_wrapper_init(int argc, char **argv) {} ~apex_wrapper_init() {} }; #endif }}
19.5875
80
0.553925
kempj
20e4d45250f3668fb3d85a8e1c12ab21af027b8e
2,661
cpp
C++
mayhem/submissions/accepted/answer_jacob.cpp
csecutsc/utscode2
469367528cc5697e0c5c0ccee28420591335d899
[ "Unlicense" ]
4
2018-09-30T15:06:49.000Z
2020-12-09T06:50:25.000Z
mayhem/submissions/accepted/answer_jacob.cpp
csecutsc/utscode2
469367528cc5697e0c5c0ccee28420591335d899
[ "Unlicense" ]
null
null
null
mayhem/submissions/accepted/answer_jacob.cpp
csecutsc/utscode2
469367528cc5697e0c5c0ccee28420591335d899
[ "Unlicense" ]
1
2021-06-17T04:10:51.000Z
2021-06-17T04:10:51.000Z
#define DEBUG 0 #include <algorithm> #include <functional> #include <numeric> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <complex> #include <cstdlib> #include <ctime> #include <cstring> #include <cassert> #include <string> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <sstream> using namespace std; #define LL long long #define LD long double #define PR pair<int,int> #define Fox(i,n) for (i=0; i<n; i++) #define Fox1(i,n) for (i=1; i<=n; i++) #define FoxI(i,a,b) for (i=a; i<=b; i++) #define FoxR(i,n) for (i=(n)-1; i>=0; i--) #define FoxR1(i,n) for (i=n; i>0; i--) #define FoxRI(i,a,b) for (i=b; i>=a; i--) #define Foxen(i,s) for (i=s.begin(); i!=s.end(); i++) #define Min(a,b) a=min(a,b) #define Max(a,b) a=max(a,b) #define Sz(s) int((s).size()) #define All(s) (s).begin(),(s).end() #define Fill(s,v) memset(s,v,sizeof(s)) #define pb push_back #define mp make_pair #define x first #define y second template<typename T> T Abs(T x) { return(x<0 ? -x : x); } template<typename T> T Sqr(T x) { return(x*x); } string plural(string s) { return(Sz(s) && s[Sz(s)-1]=='x' ? s+"en" : s+"s"); } const int INF = (int)1e9; const LD EPS = 1e-12; const LD PI = acos(-1.0); #if DEBUG #define GETCHAR getchar #else #define GETCHAR getchar_unlocked #endif bool Read(int &x) { char c,r=0,n=0; x=0; for(;;) { c=GETCHAR(); if ((c<0) && (!r)) return(0); if ((c=='-') && (!r)) n=1; else if ((c>='0') && (c<='9')) x=x*10+c-'0',r=1; else if (r) break; } if (n) x=-x; return(1); } int R,C; char G[2001][2001]; vector<PR> con[2001][2001]; queue<PR> Q; int main() { if (DEBUG) freopen("in.txt","r",stdin); int i,j,p,x,y,z,x2,y2,ans=0; Read(R),Read(C); Fox(i,R) scanf("%s",&G[i]); Fox(i,R) { p=-1; Fox(j,C) if (G[i][j]=='x') if (p<0) p=j; else { con[i][j].pb(mp(i,p)); con[i][p].pb(mp(i,j)); } } Fox(i,C) { p=-1; Fox(j,R) if (G[j][i]=='x') if (p<0) p=j; else { con[j][i].pb(mp(p,i)); con[p][i].pb(mp(j,i)); } } Fox(i,R) Fox(j,C) if (G[i][j]=='x') { ans--; Q.push(mp(i,j)),G[i][j]='.'; while (!Q.empty()) { y=Q.front().x; x=Q.front().y; Q.pop(); ans++; Fox(z,Sz(con[y][x])) { y2=con[y][x][z].x; x2=con[y][x][z].y; if (G[y2][x2]=='x') Q.push(mp(y2,x2)),G[y2][x2]='.'; } } } printf("%d\n",ans); return(0); }
18.102041
78
0.503946
csecutsc
20e6e5767ee53577c54da21a9b0badce55f2a1a5
552
cpp
C++
kactl/stress-tests/number-theory/ModLog.cpp
prince776/CodeBook
874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b
[ "CC0-1.0" ]
17
2021-01-25T12:07:17.000Z
2022-02-26T17:20:31.000Z
kactl/stress-tests/number-theory/ModLog.cpp
NavneelSinghal/CodeBook
ff60ace9107dd19ef8ba81e175003f567d2a9070
[ "CC0-1.0" ]
null
null
null
kactl/stress-tests/number-theory/ModLog.cpp
NavneelSinghal/CodeBook
ff60ace9107dd19ef8ba81e175003f567d2a9070
[ "CC0-1.0" ]
4
2021-02-28T11:13:44.000Z
2021-11-20T12:56:20.000Z
#include "../utilities/template.h" #include "../../content/number-theory/ModLog.h" int main() { const int lim = 100; rep(m,1,lim) { rep(a,0,lim) { vector<ll> ans(m, -1); ll b = a % m; rep(x,1,max(m,2)) { if (ans[b] == -1) ans[b] = x; b = b * a % m; } rep(b,0,m) { ll res = modLog(a, b, m); if (ans[b] != res) { cerr << "FAIL" << endl; cerr << "Expected log(" << a << ", " << b << ", " << m << ") = " << ans[b] << ", found " << res << endl; return 1; } } } } cout<<"Tests passed!"<<endl; }
20.444444
109
0.434783
prince776
20e770343290e9d981b4c99a2a289333e88fc035
293
cpp
C++
Src/Context.cpp
PipeRift/rift-core
82e1e287808e78b752fd76f3bee74bfb926859d1
[ "MIT" ]
6
2021-01-22T21:18:12.000Z
2022-02-25T19:16:32.000Z
Src/Context.cpp
PipeRift/rift-core
82e1e287808e78b752fd76f3bee74bfb926859d1
[ "MIT" ]
null
null
null
Src/Context.cpp
PipeRift/rift-core
82e1e287808e78b752fd76f3bee74bfb926859d1
[ "MIT" ]
null
null
null
// Copyright 2015-2021 Piperift - All rights reserved #include "Context.h" namespace Rift { TOwnPtr<Context> globalInstance; TOwnPtr<Context>& GetContextInstance() { return globalInstance; } void ShutdownContext() { if (globalInstance) { globalInstance.Delete(); } } }
12.208333
53
0.699659
PipeRift
20e843efaed4355965f1c13989cd648f30327cc5
79,963
cpp
C++
examples/Vulkan/ExampleUI/VulkanExampleUI.cpp
senthuran-ukr/Native_SDK
2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf
[ "MIT" ]
null
null
null
examples/Vulkan/ExampleUI/VulkanExampleUI.cpp
senthuran-ukr/Native_SDK
2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf
[ "MIT" ]
null
null
null
examples/Vulkan/ExampleUI/VulkanExampleUI.cpp
senthuran-ukr/Native_SDK
2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf
[ "MIT" ]
null
null
null
/*!********************************************************************************************************************* \File VulkanExampleUI.cpp \Title ExampleUI \Author PowerVR by Imagination, Developer Technology Team \Copyright Copyright (c) Imagination Technologies Limited. \brief Demonstrates how to efficiently render UI and sprites using UIRenderer ***********************************************************************************************************************/ #include "PVRShell/PVRShell.h" #include "PVRVk/ApiObjectsVk.h" #include "PVRUtils/PVRUtilsVk.h" enum { NullQuadPix = 4, VirtualWidth = 640, VirtualHeight = 480, UiDisplayTime = 5, // Display each page for 5 seconds UiDisplayTimeInMs = UiDisplayTime * 1000, NumClocks = 22 }; static const float LowerContainerHeight = .3f; namespace Sprites { enum Enum { Clockface, Hand, Battery, Web, Newmail, Network, Calendar, WeatherSunCloudBig, WeatherSunCloud, WeatherRain, WeatherStorm, ContainerCorner, ContainerVertical, ContainerHorizontal, ContainerFiller, VerticalBar, Text1, Text2, TextLorem, TextWeather, TextFriday, TextSaturday, TextSunday, TextMonday, ClockfaceSmall, HandSmall, WindowBottom, WindowBottomCorner, WindowSide, WindowTop, WindowTopLeft, WindowTopRight, Count, None = 0xFFFF }; } // Ancillary textures namespace Ancillary { enum Enum { Topbar = Sprites::Count, Background = Sprites::Count + 1, Count = 2 }; } const pvr::StringHash SpritesFileNames[Sprites::Count + Ancillary::Count] = { "clock-face.pvr", // Clockface "hand.pvr", // Hand "battery.pvr", // Battery "internet-web-browser.pvr", // Web "mail-message-new.pvr", // Newmail "network-wireless.pvr", // Network "office-calendar.pvr", // Calendar "weather-sun-cloud-big.pvr", // Weather_SUNCLOUD_BIG "weather-sun-cloud.pvr", // Weather_SUNCLOUD "weather-rain.pvr", // Weather_RAIN "weather-storm.pvr", // Weather_STORM "container-corner.pvr", // Container_CORNER "container-vertical.pvr", // Container_VERT "container-horizontal.pvr", // Container_HORI "container-filler.pvr", // container_FILLER "vertical-bar.pvr", "text1.pvr", // Text1 "text2.pvr", // Text2 "loremipsum.pvr", "text-weather.pvr", // Text_WEATHER "text-fri.pvr", // Fri "text-sat.pvr", // Sat "text-sun.pvr", // Sun "text-mon.pvr", // Mon "clock-face-small.pvr", // ClockfaceSmall "hand-small.pvr", // Hand_SMALL "window-bottom.pvr", // Window_BOTTOM "window-bottomcorner.pvr", // Window_BOTTOMCORNER "window-side.pvr", // Window_SIDE "window-top.pvr", // Window_TOP "window-topleft.pvr", // Window_TOPLEFT "window-topright.pvr", // Window_TOPRIGHT "topbar.pvr", // Topbar "background.pvr", // Background }; // Displayed pages namespace DisplayPage { enum Enum { Clocks, Weather, Window, Count, Default = Clocks }; } // Display option. Toggled with keyboard. namespace DisplayOption { enum Enum { UI, Count, Default = UI }; } // Display _state namespace DisplayState { enum Enum { Element, Transition, Default = Element }; } const char* const FragShaderFileName = "ColShader.fsh.spv"; // ColorShader const char* const VertShaderFileName = "ColShader.vsh.spv"; // ColorShader // Group shader programs and their uniform locations together struct SpriteDesc { pvrvk::ImageView imageView; uint32_t uiWidth; uint32_t uiHeight; uint32_t uiSrcX; uint32_t uiSrcY; bool bHasAlpha; void release() { imageView.reset(); } }; struct Vertex { glm::vec4 vVert; }; struct SpriteClock { pvr::ui::PixelGroup group; // root group pvr::ui::PixelGroup hand; // hand group contains hand sprite pvr::ui::Image clock; // clock sprite glm::vec2 scale; }; struct SpriteContainer { pvr::ui::PixelGroup group; pvrvk::Rect2Df size; }; struct PageClock { pvr::ui::MatrixGroup group[(uint8_t)pvrvk::FrameworkCaps::MaxSwapChains]; // root group void update(uint32_t swapchain, float frameTime, const glm::mat4& trans); std::vector<SpriteClock> clocks; SpriteContainer container; glm::mat4 _projMtx; }; struct PageWeather { pvr::ui::MatrixGroup group[(uint8_t)pvrvk::FrameworkCaps::MaxSwapChains]; void update(uint32_t swapchain, const glm::mat4& transMtx); glm::mat4 _projMtx; SpriteContainer containerTop, containerBottom; }; struct PageWindow { pvr::ui::MatrixGroup group[(uint8_t)pvrvk::FrameworkCaps::MaxSwapChains]; pvr::utils::StructuredBufferView renderQuadUboBufferView; pvrvk::Buffer renderQuadUboBuffer; pvrvk::DescriptorSet renderQuadUboDesc[4]; void update(glm::mat4& proj, uint32_t swapchain, float width, float height, const glm::mat4& trans); pvrvk::Rect2D renderArea; }; /*!********************************************************************************************************************* \brief Update the clock page \param screenWidth Screen width \param screenHeight Screen height \param frameTime Current frame \param trans Transformation matrix ***********************************************************************************************************************/ void PageClock::update(uint32_t swapchain, float frameTime, const glm::mat4& trans) { // to do render the container static float handRotate = 0.0f; handRotate -= frameTime * 0.001f; const float clockHandScale(.22f); uint32_t i = 0; // right groups glm::vec2 clockOrigin(container.size.getOffset().getX() + container.size.getExtent().getWidth(), container.size.getOffset().getY() + container.size.getExtent().getHeight()); const glm::vec2 smallClockDim(clocks[0].group->getDimensions() * clocks[0].scale); glm::vec2 clockOffset(0, 0); uint32_t clockIndex = 1; for (; i < clocks.size() / 2; i += 2) { // the first two small clock (left & right) at the top closer. if (i < 2) { clocks[i].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i].group->setAnchor(pvr::ui::Anchor::TopRight, clockOrigin); clocks[i].group->setPixelOffset(-smallClockDim.x * 2, 0); ++clockIndex; clocks[i + 1].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i + 1].group->setAnchor(pvr::ui::Anchor::TopLeft, glm::vec2(container.size.getOffset().getX(), clockOrigin.y)); clocks[i + 1].group->setPixelOffset(smallClockDim.x * 2, 0); ++clockIndex; continue; } clocks[i].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i].group->setAnchor(pvr::ui::Anchor::TopRight, clockOrigin); clocks[i].group->setPixelOffset(0, clockOffset.y); ++clockIndex; clocks[i + 1].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i + 1].group->setAnchor(pvr::ui::Anchor::TopRight, clockOrigin); clocks[i + 1].group->setPixelOffset(-smallClockDim.x, clockOffset.y); clockOffset.y -= smallClockDim.y; ++clockIndex; } // left group clockOrigin = glm::vec2(container.size.getOffset().getX(), container.size.getOffset().getY() + container.size.getExtent().getHeight()); clockOffset.y = 0; for (; i < clocks.size() - 1; i += 2) { clocks[i].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i].group->setAnchor(pvr::ui::Anchor::TopLeft, clockOrigin); clocks[i].group->setPixelOffset(0, clockOffset.y); ++clockIndex; clocks[i + 1].hand->setRotation(handRotate + clockIndex)->setScale(glm::vec2(clockHandScale)); clocks[i + 1].group->setAnchor(pvr::ui::Anchor::TopLeft, clockOrigin); clocks[i + 1].group->setPixelOffset(smallClockDim.x, clockOffset.y); clockOffset.y -= smallClockDim.y; ++clockIndex; } // render the center clocks clocks[i].hand->setRotation(handRotate); clocks[i].group->setAnchor(pvr::ui::Anchor::Center, glm::vec2(0))->setPixelOffset(0, 30); group[swapchain]->setScaleRotateTranslate(trans); // _transform the entire group group[swapchain]->commitUpdates(); } /*!********************************************************************************************************************* \brief Update the window page \param screenWidth Screen width \param screenHeight Screen height \param trans Transformation matrix ***********************************************************************************************************************/ void PageWindow::update(glm::mat4& proj, uint32_t swapchain, float width, float height, const glm::mat4& trans) { glm::vec2 offset(width * .5f, height * .5f); // center it on the screen // offset the render area center to aligned with the center of the screen offset -= glm::vec2(renderArea.getExtent().getWidth(), renderArea.getExtent().getHeight()) * glm::vec2(.5f, .5f); glm::mat4 worldTrans = glm::translate(glm::vec3(offset, 0.0f)) * trans; group[swapchain]->setScaleRotateTranslate(worldTrans); group[swapchain]->commitUpdates(); // update the render quad ubo glm::mat4 scale = glm::scale(glm::vec3(glm::vec2(renderArea.getExtent().getWidth(), renderArea.getExtent().getHeight()) / glm::vec2(width, height), 1.f)); glm::mat4x4 mvp = proj * worldTrans * scale; renderQuadUboBufferView.getElement(0, 0, swapchain).setValue(mvp); // if the memory property flags used by the buffers' device memory do not contain e_HOST_COHERENT_BIT then we must flush the memory if (static_cast<uint32_t>(renderQuadUboBuffer->getDeviceMemory()->getMemoryFlags() & pvrvk::MemoryPropertyFlags::e_HOST_COHERENT_BIT) == 0) { renderQuadUboBuffer->getDeviceMemory()->flushRange(renderQuadUboBufferView.getDynamicSliceOffset(swapchain), renderQuadUboBufferView.getDynamicSliceSize()); } } /*!********************************************************************************************************************* \brief Update the weather page \param screenWidth Screen width \param screenHeight Screen height \param transMtx Transformation matrix ***********************************************************************************************************************/ void PageWeather::update(uint32_t swapchain, const glm::mat4& transMtx) { group[swapchain]->setScaleRotateTranslate(transMtx); group[swapchain]->commitUpdates(); } class VulkanExampleUI; /*!********************************************************************************************************************* ** Constants ***********************************************************************************************************************/ const char* const DisplayOpts[DisplayOption::Count] = { "Displaying Interface", // Ui }; #ifdef DISPLAY_SPRITE_ALPHA const char* const SpriteShaderDefines[] = { "DISPLAY_SPRITE_ALPHA", }; #else const char** const SpriteShaderDefines = NULL; #endif static const uint32_t DimDefault = 0xABCD; static const uint32_t DimCentre = 0xABCE; static const float ByteToFloat = 1.0f / 255.0f; static const char* const TextLoremIpsum = "Stencil Clipped text: \n\nLorem ipsum dolor sit amet, consectetuer adipiscing elit.\nDonec molestie. " "Sed aliquam sem ut arcu.\nPhasellus sollicitudin. Vestibulum condimentum facilisis nulla.\nIn " "hac habitasse platea dictumst. Nulla nonummy. Cras quis libero.\nCras venenatis. Aliquam posuere " "lobortis pede. Nullam fringilla urna id leo.\nPraesent aliquet pretium erat. Praesent non odio. " "Pellentesque a magna a\nmauris vulputate lacinia. Aenean viverra. Class aptent taciti sociosqu " "ad litora\ntorquent per conubia nostra, per inceptos hymenaeos. Aliquam\nlacus. Mauris magna eros, " "semper a, tempor et, rutrum et, tortor."; class Area { private: int32_t x; int32_t y; int32_t w; int32_t h; int32_t size; bool isFilled; Area* right; Area* left; private: void setSize(int32_t iWidth, int32_t iHeight); public: Area(int32_t iWidth, int32_t iHeight); Area(); Area* insert(int32_t iWidth, int32_t iHeight); bool deleteArea(); int32_t getX() const; int32_t getY() const; }; class SpriteCompare { public: bool operator()(const SpriteDesc& pSpriteDescA, const SpriteDesc& pSpriteDescB) { uint32_t uiASize = pSpriteDescA.uiWidth * pSpriteDescA.uiHeight; uint32_t uiBSize = pSpriteDescB.uiWidth * pSpriteDescB.uiHeight; return (uiASize > uiBSize); } }; struct DeviceResources { pvrvk::Instance instance; pvrvk::DebugReportCallback debugCallbacks[2]; pvrvk::Surface surface; pvrvk::Device device; pvrvk::Queue queue; pvr::utils::vma::Allocator vmaAllocator; pvrvk::Swapchain swapchain; pvrvk::CommandPool commandPool; pvrvk::DescriptorPool descriptorPool; pvrvk::Semaphore semaphoreImageAcquired[static_cast<uint32_t>(pvrvk::FrameworkCaps::MaxSwapChains)]; pvrvk::Fence perFrameAcquireFence[static_cast<uint32_t>(pvrvk::FrameworkCaps::MaxSwapChains)]; pvrvk::Semaphore semaphorePresent[static_cast<uint32_t>(pvrvk::FrameworkCaps::MaxSwapChains)]; pvrvk::Fence perFrameCommandBufferFence[static_cast<uint32_t>(pvrvk::FrameworkCaps::MaxSwapChains)]; pvrvk::GraphicsPipeline renderQuadPipe; pvrvk::GraphicsPipeline renderWindowTextPipe; // Shader handles pvrvk::ShaderModule vertexShader; pvrvk::ShaderModule fragmentShader; pvrvk::DescriptorSetLayout texLayout; pvrvk::DescriptorSetLayout uboLayoutVert; pvrvk::DescriptorSetLayout uboLayoutFrag; pvrvk::Sampler samplerNearest; pvrvk::Sampler samplerBilinear; // UIRenderer used to display text pvr::ui::UIRenderer uiRenderer; PageClock pageClock; PageWeather pageWeather; PageWindow pageWindow; SpriteContainer containerTop; pvrvk::Buffer quadVbo; pvr::Multi<pvrvk::Framebuffer> onScreenFramebuffer; pvr::Multi<pvrvk::ImageView> depthStencil; pvr::Multi<pvrvk::CommandBuffer> commandBuffer; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferTitleDesc; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferBaseUI; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferClockPage; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferWeatherpage; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferWindow; pvr::Multi<pvrvk::SecondaryCommandBuffer> commandBufferRenderUI; SpriteDesc spritesDesc[Sprites::Count + Ancillary::Count]; pvr::ui::Text textLorem; pvr::ui::Image sprites[Sprites::Count + Ancillary::Count]; pvr::ui::PixelGroup groupBaseUI; pvrvk::PipelineCache pipelineCache; ~DeviceResources() { if (device.isValid()) { device->waitIdle(); uint32_t l = swapchain->getSwapchainLength(); for (uint32_t i = 0; i < l; ++i) { if (perFrameAcquireFence[i].isValid()) perFrameAcquireFence[i]->wait(); if (perFrameCommandBufferFence[i].isValid()) perFrameCommandBufferFence[i]->wait(); } } } }; class VulkanExampleUI : public pvr::Shell { private: enum { MaxSwapChains = 8 }; std::unique_ptr<DeviceResources> _deviceResources; uint32_t _frameId; // Transforms float _wndRotate; glm::mat4 _transform; glm::mat4 _projMtx; // Display options int32_t _displayOption; DisplayState::Enum _state; float _transitionPerc; DisplayPage::Enum _currentPage; DisplayPage::Enum _lastPage; int32_t _cycleDir; uint64_t _currTime; // Time float _wndRotPerc; uint64_t _prevTransTime; uint64_t _prevTime; bool _swipe; glm::vec2 _screenScale; uint32_t _numSwapchain; void createFullScreenQuad(pvrvk::CommandBuffer& uploadCmd) { uint32_t width = getWidth(); uint32_t height = getHeight(); Vertex vVerts[4] = { { glm::vec4(0, height, 0, 1) }, // top left { glm::vec4(0, 0, 0, 1) }, // bottom left { glm::vec4(width, height, 0, 1) }, // top right { glm::vec4(width, 0, 0, 1) } // bottom right }; _deviceResources->quadVbo = pvr::utils::createBuffer(_deviceResources->device, sizeof(vVerts), pvrvk::BufferUsageFlags::e_VERTEX_BUFFER_BIT | pvrvk::BufferUsageFlags::e_TRANSFER_DST_BIT, pvrvk::MemoryPropertyFlags::e_DEVICE_LOCAL_BIT, pvrvk::MemoryPropertyFlags::e_DEVICE_LOCAL_BIT, &_deviceResources->vmaAllocator, pvr::utils::vma::AllocationCreateFlags::e_MAPPED_BIT); bool isBufferHostVisible = (_deviceResources->quadVbo->getDeviceMemory()->getMemoryFlags() & pvrvk::MemoryPropertyFlags::e_HOST_VISIBLE_BIT) != 0; if (isBufferHostVisible) { pvr::utils::updateHostVisibleBuffer(_deviceResources->quadVbo, &vVerts[0], 0, static_cast<uint32_t>(sizeof(vVerts[0]) * 4), true); } else { pvr::utils::updateBufferUsingStagingBuffer( _deviceResources->device, _deviceResources->quadVbo, uploadCmd, &vVerts[0], 0, static_cast<uint32_t>(sizeof(vVerts[0]) * 4), &_deviceResources->vmaAllocator); } } void updateTitleAndDesc(DisplayOption::Enum _displayOption) { switch (_displayOption) { case DisplayOption::UI: _deviceResources->uiRenderer.getDefaultDescription()->setText("Displaying Interface"); _deviceResources->uiRenderer.getDefaultDescription()->commitUpdates(); break; default: break; } for (uint32_t i = 0; i < _numSwapchain; ++i) { _deviceResources->commandBufferTitleDesc[i]->begin(_deviceResources->onScreenFramebuffer[i], 0); _deviceResources->uiRenderer.beginRendering(_deviceResources->commandBufferTitleDesc[i]); _deviceResources->uiRenderer.getDefaultTitle()->render(); _deviceResources->uiRenderer.getDefaultDescription()->render(); _deviceResources->uiRenderer.getSdkLogo()->render(); _deviceResources->uiRenderer.endRendering(); _deviceResources->commandBufferTitleDesc[i]->end(); } } private: void drawScreenAlignedQuad(const pvrvk::GraphicsPipeline& pipe, pvrvk::DescriptorSet& ubo, pvrvk::CommandBufferBase commandBuffer); void renderUI(uint32_t swapchain); void renderPage(DisplayPage::Enum Page, const glm::mat4& mTransform, uint32_t swapchain); void createPipelines(); void createBaseUI(); void createPageWeather(); void createPageWindow(); void swipeLeft(); void swipeRight(); void eventMappedInput(pvr::SimplifiedInput action); float getVirtualWidth() { return static_cast<float>(isRotated() ? this->getHeight() : this->getWidth()); } float getVirtualHeight() { return static_cast<float>(isRotated() ? this->getWidth() : this->getHeight()); } float toDeviceX(float fVal) { return ((fVal / VirtualWidth) * getVirtualWidth()); } float toDeviceY(float fVal) { return ((fVal / VirtualHeight) * getVirtualHeight()); } inline bool isRotated() { return this->isScreenRotated(); } void createSamplersAndDescriptorSet(); void createSpriteContainer(pvrvk::Rect2Df const& rect, uint32_t numSubContainer, float lowerContainerHeight, SpriteContainer& outContainer); void createPageClock(); void createClockSprite(SpriteClock& outClock, Sprites::Enum sprite); void recordSecondaryCommandBuffers(uint32_t swapchain); void loadSprites(pvrvk::CommandBuffer& uploadCmd); public: VulkanExampleUI(); virtual pvr::Result initApplication(); virtual pvr::Result initView(); virtual pvr::Result releaseView(); virtual pvr::Result quitApplication(); virtual pvr::Result renderFrame(); }; /*!********************************************************************************************************************* \brief Constructor ***********************************************************************************************************************/ VulkanExampleUI::VulkanExampleUI() : _wndRotate(0.0f), _displayOption(DisplayOption::Default), _state(DisplayState::Default), _transitionPerc(0.0f), _currentPage(DisplayPage::Default), _lastPage(DisplayPage::Default), _cycleDir(1), _wndRotPerc(0.0f), _prevTransTime(0), _prevTime(0) {} /*!******************************************************************************************************************** \brief Create Window page ***********************************************************************************************************************/ void VulkanExampleUI::createPageWindow() { // create the window page _deviceResources->textLorem = _deviceResources->uiRenderer.createText(TextLoremIpsum); _deviceResources->textLorem->setScale(glm::vec2(.5f)); _deviceResources->textLorem->setColor(0.0f, 0.0f, 0.0f, 1.0f); _deviceResources->textLorem->setAnchor(pvr::ui::Anchor::BottomLeft, glm::vec2(-1.0f, -1.0f)); _deviceResources->pageWindow.renderArea = pvrvk::Rect2D(0, 0, 390, 250); _deviceResources->pageWindow.renderArea.setOffset(pvrvk::Offset2D(static_cast<int32_t>(_deviceResources->pageWindow.renderArea.getOffset().getX() * _screenScale.x), static_cast<int32_t>(_deviceResources->pageWindow.renderArea.getOffset().getY() * _screenScale.y))); _deviceResources->pageWindow.renderArea.setExtent(pvrvk::Extent2D(static_cast<uint32_t>(_deviceResources->pageWindow.renderArea.getExtent().getWidth() * _screenScale.x), static_cast<uint32_t>(_deviceResources->pageWindow.renderArea.getExtent().getHeight() * _screenScale.y))); for (uint32_t i = 0; i < _numSwapchain; ++i) { _deviceResources->pageWindow.group[i] = _deviceResources->uiRenderer.createMatrixGroup(); _deviceResources->pageWindow.group[i]->setViewProjection(_projMtx); _deviceResources->pageWindow.group[i]->add(_deviceResources->textLorem); _deviceResources->pageWindow.group[i]->commitUpdates(); } } /*!********************************************************************************************************************* \brief Create sprite container \param[in] rect Container rectangle \param[in] numSubContainer Number of lower sub containers \param[in] lowerContainerHeight lower container height \param[out] outContainer Returned Sprite container ***********************************************************************************************************************/ void VulkanExampleUI::createSpriteContainer(pvrvk::Rect2Df const& rect, uint32_t numSubContainer, float lowerContainerHeight, SpriteContainer& outContainer) { outContainer.size = rect; outContainer.group = _deviceResources->uiRenderer.createPixelGroup(); // calculate the border of the container const float borderX = _deviceResources->sprites[Sprites::ContainerHorizontal]->getWidth() / _deviceResources->uiRenderer.getRenderingDimX() * 2.f; const float borderY = _deviceResources->sprites[Sprites::ContainerCorner]->getHeight() / _deviceResources->uiRenderer.getRenderingDimY() * 2.f; pvrvk::Rect2Df rectVerticleLeft(rect.getOffset().getX(), rect.getOffset().getY() + borderY, borderX, rect.getExtent().getHeight() - borderY * 2); pvrvk::Rect2Df rectVerticleRight( rect.getOffset().getX() + rect.getExtent().getWidth(), rect.getOffset().getY() + borderY, rect.getExtent().getWidth(), rect.getExtent().getHeight() - borderY * 2); pvrvk::Rect2Df rectTopHorizontal(rect.getOffset().getX() + borderX, rect.getOffset().getY() + rect.getExtent().getHeight() - borderY, rect.getExtent().getWidth() - borderX * 2, rect.getExtent().getHeight()); pvrvk::Rect2Df rectBottomHorizontal(rect.getOffset().getX() + borderX, rect.getOffset().getY(), rect.getExtent().getWidth() - borderX * 2, rect.getOffset().getY() + borderY); // align the sprites to lower left so they will be aligned with their group _deviceResources->sprites[Sprites::ContainerCorner]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.0f); _deviceResources->sprites[Sprites::ContainerVertical]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.0f); _deviceResources->sprites[Sprites::ContainerHorizontal]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.f, -1.f); // add the filler { pvr::ui::PixelGroup filler = _deviceResources->uiRenderer.createPixelGroup(); filler->add(_deviceResources->sprites[Sprites::ContainerFiller]); _deviceResources->sprites[Sprites::ContainerFiller]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.f, -1.f); filler->setAnchor(pvr::ui::Anchor::BottomLeft, rect.getOffset().getX() + borderX, rect.getOffset().getY() + borderY); filler->setScale(glm::vec2(.5f * (rect.getExtent().getWidth() - borderX * 2 /*minus the left and right borders*/) * _deviceResources->uiRenderer.getRenderingDimX() / _deviceResources->sprites[Sprites::ContainerFiller]->getWidth(), .501f * (rect.getExtent().getHeight() - borderY * 2 /*minus Top and Bottom borders*/) * _deviceResources->uiRenderer.getRenderingDimY() / _deviceResources->sprites[Sprites::ContainerFiller]->getHeight())); outContainer.group->add(filler); outContainer.group->setSize(glm::vec2(_deviceResources->uiRenderer.getRenderingDimX(), _deviceResources->uiRenderer.getRenderingDimY())); } // Top Left Corner { pvr::ui::PixelGroup newGroup = _deviceResources->uiRenderer.createPixelGroup(); // place the center at the newGroup->add(_deviceResources->sprites[Sprites::ContainerCorner]); newGroup->setAnchor(pvr::ui::Anchor::BottomRight, rectTopHorizontal.getOffset().getX(), rectTopHorizontal.getOffset().getY()); outContainer.group->add(newGroup); } // Top Right Corner { pvr::ui::PixelGroup newGroup = _deviceResources->uiRenderer.createPixelGroup(); newGroup->add(_deviceResources->sprites[Sprites::ContainerCorner]); // flip the x coordinate by negative scale newGroup->setAnchor(pvr::ui::Anchor::BottomRight, rectTopHorizontal.getOffset().getX() + rectTopHorizontal.getExtent().getWidth(), rectTopHorizontal.getOffset().getY()) ->setScale(glm::vec2(-1.f, 1.0f)); outContainer.group->add(newGroup); } // bottom left Corner { pvr::ui::PixelGroup newGroup = _deviceResources->uiRenderer.createPixelGroup(); newGroup->add(_deviceResources->sprites[Sprites::ContainerCorner]); // flip the y coordinates newGroup->setAnchor(pvr::ui::Anchor::BottomRight, rectBottomHorizontal.getOffset().getX(), rectBottomHorizontal.getExtent().getHeight())->setScale(glm::vec2(1.f, -1.0f)); outContainer.group->add(newGroup); } // Bottom right Corner { pvr::ui::PixelGroup newGroup = _deviceResources->uiRenderer.createPixelGroup(); newGroup->add(_deviceResources->sprites[Sprites::ContainerCorner]); // flip the x and y coordinates newGroup ->setAnchor( pvr::ui::Anchor::BottomRight, rectBottomHorizontal.getOffset().getX() + rectBottomHorizontal.getExtent().getWidth(), rectBottomHorizontal.getExtent().getHeight()) ->setScale(glm::vec2(-1.f, -1.0f)); outContainer.group->add(newGroup); } // Horizontal Up { // calculate the width of the sprite float width = (rectTopHorizontal.getExtent().getWidth() * .5f * _deviceResources->uiRenderer.getRenderingDimX() / _deviceResources->sprites[Sprites::ContainerVertical]->getWidth()); pvr::ui::PixelGroup horizontal = _deviceResources->uiRenderer.createPixelGroup(); horizontal->add(_deviceResources->sprites[Sprites::ContainerVertical]); horizontal->setAnchor(pvr::ui::Anchor::BottomLeft, rectTopHorizontal.getOffset().getX(), rectTopHorizontal.getOffset().getY()); horizontal->setScale(glm::vec2(width, 1.f)); outContainer.group->add(horizontal); } // Horizontal Down { // calculate the width of the sprite float width = (rectBottomHorizontal.getExtent().getWidth() * .5f * _deviceResources->uiRenderer.getRenderingDimX() / _deviceResources->sprites[Sprites::ContainerVertical]->getWidth()); pvr::ui::PixelGroup horizontal = _deviceResources->uiRenderer.createPixelGroup(); horizontal->add(_deviceResources->sprites[Sprites::ContainerVertical]); horizontal->setAnchor(pvr::ui::Anchor::TopLeft, rectBottomHorizontal.getOffset().getX(), rectBottomHorizontal.getOffset().getY()); horizontal->setScale(glm::vec2(width, -1.f)); outContainer.group->add(horizontal); } // Vertical Left { // calculate the height of the sprite float height = (rectVerticleLeft.getExtent().getHeight() * .501f * _deviceResources->uiRenderer.getRenderingDimY() / _deviceResources->sprites[Sprites::ContainerHorizontal]->getHeight()); pvr::ui::PixelGroup verticle = _deviceResources->uiRenderer.createPixelGroup(); verticle->add(_deviceResources->sprites[Sprites::ContainerHorizontal]); verticle->setScale(glm::vec2(1, height))->setAnchor(pvr::ui::Anchor::BottomLeft, rectVerticleLeft.getOffset().getX(), rectVerticleLeft.getOffset().getY())->setPixelOffset(0, 0); outContainer.group->add(verticle); } // Vertical Right { // calculate the height of the sprite float height = (rectVerticleRight.getExtent().getHeight() * .501f * _deviceResources->uiRenderer.getRenderingDimY() / _deviceResources->sprites[Sprites::ContainerHorizontal]->getHeight()); pvr::ui::PixelGroup vertical = _deviceResources->uiRenderer.createPixelGroup(); vertical->add(_deviceResources->sprites[Sprites::ContainerHorizontal]); vertical->setScale(glm::vec2(-1, height))->setAnchor(pvr::ui::Anchor::BottomLeft, rectVerticleRight.getOffset().getX(), rectVerticleRight.getOffset().getY()); outContainer.group->add(vertical); } float width = 1.f / _deviceResources->uiRenderer.getRenderingDimX() * _deviceResources->sprites[Sprites::ContainerHorizontal]->getWidth(); float height = (outContainer.size.getExtent().getHeight() - outContainer.size.getOffset().getY()) * .5f; // calculate the each container size float containerWidth = rect.getExtent().getWidth() / numSubContainer; float borderWidth = 1.f / _deviceResources->uiRenderer.getRenderingDimX() * _deviceResources->sprites[Sprites::VerticalBar]->getWidth(); pvrvk::Rect2Df subRect(rect.getOffset().getX(), rect.getOffset().getY(), rect.getOffset().getX() + containerWidth, rect.getOffset().getY() + lowerContainerHeight); height = .5f * (subRect.getExtent().getHeight() - subRect.getOffset().getY()) * _deviceResources->uiRenderer.getRenderingDimY() / _deviceResources->sprites[Sprites::VerticalBar]->getHeight(); // create the lower containers // Horizontal Split { // half it here because the scaling happen at the center width = (rect.getExtent().getWidth() * .5f * _deviceResources->uiRenderer.getRenderingDimX() / _deviceResources->sprites[Sprites::VerticalBar]->getHeight()); width -= .25; // reduce the width by quarter of a pixel so they fit well between the container pvr::ui::PixelGroup horizontal = _deviceResources->uiRenderer.createPixelGroup(); horizontal->add(_deviceResources->sprites[Sprites::VerticalBar]); horizontal->setScale(glm::vec2(1.f, width)) ->setAnchor(pvr::ui::Anchor::BottomLeft, rect.getOffset().getX() + (2 / _deviceResources->uiRenderer.getRenderingDimX()) /*offset it by 2 pixel*/, subRect.getExtent().getHeight()); horizontal->setRotation(glm::pi<float>() * -.5f); // rotate y 90 degree outContainer.group->add(horizontal); } for (uint32_t i = 0; i < numSubContainer - 1; ++i) { pvr::ui::PixelGroup groupVertical = _deviceResources->uiRenderer.createPixelGroup(); _deviceResources->sprites[Sprites::VerticalBar]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.f, -1.f); groupVertical->add(_deviceResources->sprites[Sprites::VerticalBar]); groupVertical->setAnchor(pvr::ui::Anchor::BottomLeft, subRect.getExtent().getWidth(), subRect.getOffset().getY())->setScale(glm::vec2(1, height)); outContainer.group->add(groupVertical); subRect.setOffset(pvrvk::Offset2Df(subRect.getOffset().getX() + containerWidth - borderWidth, subRect.getOffset().getY())); subRect.setExtent(pvrvk::Extent2Df(subRect.getExtent().getWidth() + containerWidth, subRect.getExtent().getHeight())); } _deviceResources->containerTop = outContainer; } /*!********************************************************************************************************************* \brief Code in initApplication() will be called by PVRShell once per run, before the rendering context is created. Used to initialize variables that are not Dependant on it (e.g. external modules, loading meshes, etc.) If the rendering context is lost, InitApplication() will not be called again. \return Return pvr::Result::Success if no error occurred ***********************************************************************************************************************/ pvr::Result VulkanExampleUI::initApplication() { setStencilBitsPerPixel(8); // initialise current and previous times to avoid saturating the variable used for rotating the window text _currTime = this->getTime(); _prevTime = this->getTime(); _frameId = 0; return pvr::Result::Success; } /*!********************************************************************************************************************* \brief create the weather page ***********************************************************************************************************************/ void VulkanExampleUI::createPageWeather() { // background pvr::ui::PixelGroup backGround = _deviceResources->uiRenderer.createPixelGroup(); backGround->add(_deviceResources->sprites[Ancillary::Background]); // create the weather page std::vector<pvr::ui::Sprite> groupsList; SpriteContainer container; createSpriteContainer(_deviceResources->pageClock.container.size, 4, LowerContainerHeight, container); _deviceResources->pageWeather.containerTop = container; groupsList.push_back(container.group); pvr::ui::PixelGroup group = _deviceResources->uiRenderer.createPixelGroup(); // align the sprite with its parent group _deviceResources->sprites[Sprites::TextWeather]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.f); group->setScale(_screenScale); group->add(_deviceResources->sprites[Sprites::TextWeather]); const glm::vec2& containerHalfSize = glm::vec2(_deviceResources->pageWeather.containerTop.size.getExtent().getWidth(), _deviceResources->pageWeather.containerTop.size.getExtent().getHeight()) * .5f; group ->setAnchor(pvr::ui::Anchor::CenterLeft, _deviceResources->pageWeather.containerTop.size.getOffset().getX(), _deviceResources->pageWeather.containerTop.size.getOffset().getY() + (_deviceResources->pageWeather.containerTop.size.getExtent().getHeight() / 2.0f)) ->setPixelOffset(10, 40); groupsList.push_back(group); // add the Weather group = _deviceResources->uiRenderer.createPixelGroup(); group->add(_deviceResources->sprites[Sprites::WeatherSunCloudBig]); // align the sprite with its parent group _deviceResources->sprites[Sprites::WeatherSunCloudBig]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.f); group ->setAnchor(pvr::ui::Anchor::Center, _deviceResources->pageWeather.containerTop.size.getOffset().getX() + containerHalfSize.x, _deviceResources->pageWeather.containerTop.size.getOffset().getY() + containerHalfSize.y) ->setPixelOffset(0, 40); group->setScale(_screenScale); groupsList.push_back(group); // create the bottom 4 groups const Sprites::Enum sprites[] = { Sprites::WeatherSunCloud, Sprites::TextFriday, Sprites::WeatherSunCloud, Sprites::TextSaturday, Sprites::WeatherRain, Sprites::TextSunday, Sprites::WeatherStorm, Sprites::TextMonday }; const float width = _deviceResources->pageWeather.containerTop.size.getExtent().getWidth() / 4.f; float tempOffsetX = _deviceResources->pageWeather.containerTop.size.getOffset().getX() + (width * .5f); ; for (uint32_t i = 0; i < 8; i += 2) { Sprites::Enum weather = sprites[i]; Sprites::Enum text = sprites[i + 1]; group = _deviceResources->uiRenderer.createPixelGroup(); // align the sprite with its parent group this->_deviceResources->sprites[weather]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.f); group->add(this->_deviceResources->sprites[weather]); group->setAnchor(pvr::ui::Anchor::BottomCenter, tempOffsetX, _deviceResources->pageWeather.containerTop.size.getOffset().getY()); group->setScale(_screenScale); groupsList.push_back(group); // add the text group = _deviceResources->uiRenderer.createPixelGroup(); // align the text with its parent group this->_deviceResources->sprites[text]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.0f, -1.f); group->add(this->_deviceResources->sprites[text]); group->setAnchor(pvr::ui::Anchor::TopCenter, tempOffsetX, _deviceResources->pageWeather.containerTop.size.getOffset().getY() + LowerContainerHeight)->setPixelOffset(0, -5); group->setScale(_screenScale); groupsList.push_back(group); tempOffsetX = tempOffsetX + width; } for (uint32_t i = 0; i < _numSwapchain; ++i) { _deviceResources->pageWeather.group[i] = _deviceResources->uiRenderer.createMatrixGroup(); _deviceResources->pageWeather.group[i]->add(groupsList.data(), static_cast<uint32_t>(groupsList.size())); _deviceResources->pageWeather.group[i]->setViewProjection(_projMtx); _deviceResources->pageWeather.group[i]->commitUpdates(); } } /*!********************************************************************************************************************* \brief Create clock sprite \param outClock Returned clock \param sprite Clock Sprite to create ***********************************************************************************************************************/ void VulkanExampleUI::createClockSprite(SpriteClock& outClock, Sprites::Enum sprite) { // create a group of clock and hand so they can be transformed outClock.group = _deviceResources->uiRenderer.createPixelGroup(); outClock.clock = _deviceResources->sprites[sprite]; outClock.hand = _deviceResources->uiRenderer.createPixelGroup(); outClock.hand->add(_deviceResources->sprites[Sprites::Hand]); outClock.group->add(outClock.clock); outClock.group->add(outClock.hand); // set the size of the parent group outClock.group->setSize(outClock.clock->getDimensions()); // center the clock's to the center of the parent group outClock.clock->setAnchor(pvr::ui::Anchor::Center, 0.0f, 0.0f); // center the hand group so that it can be rotated at the center of the clock outClock.hand->setSize(_deviceResources->sprites[Sprites::Hand]->getDimensions())->setAnchor(pvr::ui::Anchor::BottomCenter, .0f, .0f); // center the clock hand bottom center and offset it by few pixel so they can be rotated at that point _deviceResources->sprites[Sprites::Hand]->setAnchor(pvr::ui::Anchor::BottomCenter, glm::vec2(0.0f, -1.f))->setPixelOffset(0, -10); } /*!********************************************************************************************************************* \brief Create clock page ***********************************************************************************************************************/ void VulkanExampleUI::createPageClock() { SpriteContainer container; const uint32_t numClocksInColumn = 5; float containerHeight = _deviceResources->sprites[Sprites::ClockfaceSmall]->getDimensions().y * numClocksInColumn / getHeight(); containerHeight += LowerContainerHeight * .5f; // add the lower container height as well float containerWidth = _deviceResources->sprites[Sprites::ClockfaceSmall]->getDimensions().x * 4; containerWidth += _deviceResources->sprites[Sprites::Clockface]->getDimensions().x; containerWidth /= getWidth(); pvrvk::Rect2Df containerRect(-containerWidth, -containerHeight, containerWidth * 2.f, containerHeight * 2.f); createSpriteContainer(containerRect, 2, LowerContainerHeight, container); _deviceResources->pageClock.container = container; pvr::ui::Sprite groupSprites[NumClocks + 3]; uint32_t i = 0; for (; i < NumClocks; ++i) { SpriteClock clock; createClockSprite(clock, Sprites::ClockfaceSmall); clock.group->setScale(_screenScale); clock.scale = _screenScale; // add the clock group in to page group groupSprites[i] = clock.group; _deviceResources->pageClock.clocks.push_back(clock); // add the clock } // add the center clock // group the hands SpriteClock clockCenter; createClockSprite(clockCenter, Sprites::Clockface); clockCenter.group->setScale(_screenScale); groupSprites[i++] = clockCenter.group; _deviceResources->pageClock.clocks.push_back(clockCenter); _deviceResources->sprites[Sprites::Text1] ->setAnchor( pvr::ui::Anchor::BottomLeft, glm::vec2(_deviceResources->pageClock.container.size.getOffset().getX(), _deviceResources->pageClock.container.size.getOffset().getY())) ->setPixelOffset(0, 10); _deviceResources->sprites[Sprites::Text1]->setScale(_screenScale); groupSprites[i++] = _deviceResources->sprites[Sprites::Text1]; _deviceResources->sprites[Sprites::Text2] ->setAnchor(pvr::ui::Anchor::BottomRight, glm::vec2(_deviceResources->pageClock.container.size.getExtent().getWidth() + _deviceResources->pageClock.container.size.getOffset().getX() - 0.05f, _deviceResources->pageClock.container.size.getOffset().getY())) ->setPixelOffset(0, 10); _deviceResources->sprites[Sprites::Text2]->setScale(_screenScale); groupSprites[i++] = _deviceResources->sprites[Sprites::Text2]; for (uint32_t i = 0; i < _numSwapchain; ++i) { _deviceResources->pageClock.group[i] = _deviceResources->uiRenderer.createMatrixGroup(); pvr::ui::MatrixGroup groupBorder = _deviceResources->uiRenderer.createMatrixGroup(); groupBorder->add(_deviceResources->sprites[Sprites::ContainerVertical]); groupBorder->setScaleRotateTranslate(glm::translate(glm::vec3(0.0f, -0.45f, 0.0f)) * glm::scale(glm::vec3(.65f, .055f, .2f))); _deviceResources->pageClock.group[i]->add(_deviceResources->containerTop.group); _deviceResources->pageClock.group[i]->add(groupSprites, ARRAY_SIZE(groupSprites)); _deviceResources->pageClock.group[i]->setViewProjection(_projMtx); _deviceResources->pageClock.group[i]->commitUpdates(); } } /*!********************************************************************************************************************* \brief Create base UI ***********************************************************************************************************************/ void VulkanExampleUI::createBaseUI() { // build the render base UI float offset = 0.f; int32_t offsetPixel = 10; // battery sprite _deviceResources->sprites[Sprites::Battery]->setAnchor(pvr::ui::Anchor::TopRight, glm::vec2(1.f, 1.0f)); offset -= _deviceResources->sprites[Sprites::Battery]->getDimensions().x + offsetPixel; // web sprite _deviceResources->sprites[Sprites::Web]->setAnchor(pvr::ui::Anchor::TopRight, glm::vec2(1.f, 1.0))->setPixelOffset(offset, 0.f); offset -= _deviceResources->sprites[Sprites::Web]->getDimensions().x + offsetPixel; // new mail sprite _deviceResources->sprites[Sprites::Newmail]->setAnchor(pvr::ui::Anchor::TopRight, glm::vec2(1.f, 1.0f))->setPixelOffset(offset, 0.f); offset -= _deviceResources->sprites[Sprites::Newmail]->getDimensions().x + offsetPixel; ; // network sprite _deviceResources->sprites[Sprites::Network]->setAnchor(pvr::ui::Anchor::TopRight, glm::vec2(1.f, 1.0f))->setPixelOffset(offset, 0.f); _deviceResources->groupBaseUI = _deviceResources->uiRenderer.createPixelGroup(); pvr::ui::PixelGroup horizontalTopBarGrop = _deviceResources->uiRenderer.createPixelGroup(); _deviceResources->sprites[Ancillary::Topbar]->setAnchor(pvr::ui::Anchor::BottomLeft, -1.f, -1.f); horizontalTopBarGrop->add(_deviceResources->sprites[Ancillary::Topbar]); horizontalTopBarGrop->setAnchor(pvr::ui::Anchor::TopLeft, -1.f, 1.f); horizontalTopBarGrop->setScale(glm::vec2(_deviceResources->uiRenderer.getRenderingDimX() * .5f, 1.0f)); _deviceResources->groupBaseUI->add(_deviceResources->sprites[Ancillary::Background]) ->add(horizontalTopBarGrop) ->add(_deviceResources->sprites[Sprites::Battery]) ->add(_deviceResources->sprites[Sprites::Web]) ->add(_deviceResources->sprites[Sprites::Newmail]) ->add(_deviceResources->sprites[Sprites::Network]); glm::vec2 scale = glm::vec2(_deviceResources->sprites[Ancillary::Background]->getWidth(), _deviceResources->sprites[Ancillary::Background]->getHeight()); scale = 2.5f / scale; scale *= glm::vec2(getWidth(), getHeight()); _deviceResources->sprites[Ancillary::Background]->setAnchor(pvr::ui::Anchor::TopLeft, -1.f, 1.f)->setScale(scale); _deviceResources->groupBaseUI->setSize(glm::vec2(_deviceResources->uiRenderer.getRenderingDimX(), _deviceResources->uiRenderer.getRenderingDimY())) ->setAnchor(pvr::ui::Anchor::TopRight, glm::vec2(1.0f, 1.0f)); _deviceResources->groupBaseUI->commitUpdates(); // update once here } /*!********************************************************************************************************************* \brief Code in initView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are Dependant on the rendering context (e.g. textures, vertex buffers, etc.) \return Return true if no error occurred ***********************************************************************************************************************/ pvr::Result VulkanExampleUI::initView() { _deviceResources = std::unique_ptr<DeviceResources>(new DeviceResources()); // Create instance and retrieve compatible physical devices _deviceResources->instance = pvr::utils::createInstance(this->getApplicationName()); if (_deviceResources->instance->getNumPhysicalDevices() == 0) { setExitMessage("Unable not find a compatible Vulkan physical device."); return pvr::Result::UnknownError; } // Create the surface _deviceResources->surface = pvr::utils::createSurface(_deviceResources->instance, _deviceResources->instance->getPhysicalDevice(0), this->getWindow(), this->getDisplay()); // Add Debug Report Callbacks // Add a Debug Report Callback for logging messages for events of all supported types. _deviceResources->debugCallbacks[0] = pvr::utils::createDebugReportCallback(_deviceResources->instance); // Add a second Debug Report Callback for throwing exceptions for Error events. _deviceResources->debugCallbacks[1] = pvr::utils::createDebugReportCallback(_deviceResources->instance, pvrvk::DebugReportFlagsEXT::e_ERROR_BIT_EXT, pvr::utils::throwOnErrorDebugReportCallback); // Create the logical device pvr::utils::QueuePopulateInfo queueInfo = { pvrvk::QueueFlags::e_GRAPHICS_BIT, _deviceResources->surface }; pvr::utils::QueueAccessInfo queueAccessInfo; _deviceResources->device = pvr::utils::createDeviceAndQueues(_deviceResources->instance->getPhysicalDevice(0), &queueInfo, 1, &queueAccessInfo); // get the queue _deviceResources->queue = _deviceResources->device->getQueue(queueAccessInfo.familyId, queueAccessInfo.queueId); _deviceResources->vmaAllocator = pvr::utils::vma::createAllocator(pvr::utils::vma::AllocatorCreateInfo(_deviceResources->device)); pvrvk::SurfaceCapabilitiesKHR surfaceCapabilities = _deviceResources->instance->getPhysicalDevice(0)->getSurfaceCapabilities(_deviceResources->surface); // validate the supported swapchain image usage pvrvk::ImageUsageFlags swapchainImageUsage = pvrvk::ImageUsageFlags::e_COLOR_ATTACHMENT_BIT; if (pvr::utils::isImageUsageSupportedBySurface(surfaceCapabilities, pvrvk::ImageUsageFlags::e_TRANSFER_SRC_BIT)) { swapchainImageUsage |= pvrvk::ImageUsageFlags::e_TRANSFER_SRC_BIT; } // Create the swapchain and depthstencil attachments pvr::utils::createSwapchainAndDepthStencilImageAndViews(_deviceResources->device, _deviceResources->surface, getDisplayAttributes(), _deviceResources->swapchain, _deviceResources->depthStencil, swapchainImageUsage, pvrvk::ImageUsageFlags::e_DEPTH_STENCIL_ATTACHMENT_BIT | pvrvk::ImageUsageFlags::e_TRANSIENT_ATTACHMENT_BIT, &_deviceResources->vmaAllocator); _numSwapchain = _deviceResources->swapchain->getSwapchainLength(); pvr::utils::createOnscreenFramebufferAndRenderpass(_deviceResources->swapchain, &_deviceResources->depthStencil[0], _deviceResources->onScreenFramebuffer); // Create the commandpool _deviceResources->commandPool = _deviceResources->device->createCommandPool(pvrvk::CommandPoolCreateInfo(queueAccessInfo.familyId, pvrvk::CommandPoolCreateFlags::e_RESET_COMMAND_BUFFER_BIT)); _deviceResources->descriptorPool = _deviceResources->device->createDescriptorPool(pvrvk::DescriptorPoolCreateInfo() .addDescriptorInfo(pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 16) .addDescriptorInfo(pvrvk::DescriptorType::e_UNIFORM_BUFFER, 16) .addDescriptorInfo(pvrvk::DescriptorType::e_UNIFORM_BUFFER_DYNAMIC, 16)); for (uint32_t i = 0; i < _numSwapchain; ++i) { _deviceResources->commandBuffer[i] = _deviceResources->commandPool->allocateCommandBuffer(); _deviceResources->commandBufferTitleDesc[i] = _deviceResources->commandPool->allocateSecondaryCommandBuffer(); } // Initialize _deviceResources->uiRenderer _deviceResources->uiRenderer.init(getWidth(), getHeight(), isFullScreen(), _deviceResources->onScreenFramebuffer[0]->getRenderPass(), 0, getBackBufferColorspace() == pvr::ColorSpace::sRGB, _deviceResources->commandPool, _deviceResources->queue, true, true, true, 1024); _screenScale = glm::vec2(glm::min(_deviceResources->uiRenderer.getRenderingDim().x / getWidth(), _deviceResources->uiRenderer.getRenderingDim().y / getHeight())); _prevTransTime = this->getTime(); // Load the sprites _deviceResources->commandBuffer[0]->begin(pvrvk::CommandBufferUsageFlags::e_ONE_TIME_SUBMIT_BIT); loadSprites(_deviceResources->commandBuffer[0]); createFullScreenQuad(_deviceResources->commandBuffer[0]); _deviceResources->commandBuffer[0]->end(); // Submit all the image uploads pvrvk::SubmitInfo submitInfo; submitInfo.commandBuffers = &_deviceResources->commandBuffer[0]; submitInfo.numCommandBuffers = 1; _deviceResources->queue->submit(&submitInfo, 1); _deviceResources->queue->waitIdle(); _deviceResources->commandBuffer[0]->reset(pvrvk::CommandBufferResetFlags::e_RELEASE_RESOURCES_BIT); // Create the pipeline cache _deviceResources->pipelineCache = _deviceResources->device->createPipelineCache(); // Load the shaders createPipelines(); createSamplersAndDescriptorSet(); if (isScreenRotated()) { _projMtx = pvr::math::ortho(pvr::Api::Vulkan, 0.f, static_cast<float>(_deviceResources->swapchain->getDimension().getHeight()), 0.f, static_cast<float>(_deviceResources->swapchain->getDimension().getWidth()), 0.0f); } else { _projMtx = pvr::math::ortho(pvr::Api::Vulkan, 0.f, static_cast<float>(_deviceResources->swapchain->getDimension().getWidth()), 0.f, static_cast<float>(_deviceResources->swapchain->getDimension().getHeight()), 0.0f); } _swipe = false; // set the default title _deviceResources->uiRenderer.getDefaultTitle()->setText("ExampleUI"); _deviceResources->uiRenderer.getDefaultTitle()->commitUpdates(); // create the UI groups createBaseUI(); createPageClock(); createPageWeather(); createPageWindow(); for (uint32_t i = 0; i < _numSwapchain; ++i) { recordSecondaryCommandBuffers(i); _deviceResources->semaphorePresent[i] = _deviceResources->device->createSemaphore(); _deviceResources->semaphoreImageAcquired[i] = _deviceResources->device->createSemaphore(); _deviceResources->perFrameCommandBufferFence[i] = _deviceResources->device->createFence(pvrvk::FenceCreateFlags::e_SIGNALED_BIT); _deviceResources->perFrameAcquireFence[i] = _deviceResources->device->createFence(pvrvk::FenceCreateFlags::e_SIGNALED_BIT); } updateTitleAndDesc((DisplayOption::Enum)_displayOption); return pvr::Result::Success; } /*!********************************************************************************************************************* \brief Loads the sprites \return Return true if no error occurred ***********************************************************************************************************************/ void VulkanExampleUI::loadSprites(pvrvk::CommandBuffer& uploadCmd) { pvrvk::SamplerCreateInfo samplerInfo; samplerInfo.minFilter = pvrvk::Filter::e_NEAREST; samplerInfo.magFilter = pvrvk::Filter::e_NEAREST; samplerInfo.mipMapMode = pvrvk::SamplerMipmapMode::e_NEAREST; samplerInfo.wrapModeU = pvrvk::SamplerAddressMode::e_CLAMP_TO_EDGE; samplerInfo.wrapModeV = pvrvk::SamplerAddressMode::e_CLAMP_TO_EDGE; samplerInfo.wrapModeW = pvrvk::SamplerAddressMode::e_CLAMP_TO_EDGE; pvrvk::Sampler samplerNearest = _deviceResources->device->createSampler(samplerInfo); pvr::Texture tex; // Load sprites and add to sprite array for (uint32_t i = 0; i < Sprites::Count + Ancillary::Count; i++) { // Copy some useful data out of the texture header. _deviceResources->spritesDesc[i].uiWidth = tex.getWidth(); _deviceResources->spritesDesc[i].uiHeight = tex.getHeight(); _deviceResources->spritesDesc[i].imageView = pvr::utils::loadAndUploadImageAndView(_deviceResources->device, SpritesFileNames[i].c_str(), true, uploadCmd, *this, pvrvk::ImageUsageFlags::e_SAMPLED_BIT, pvrvk::ImageLayout::e_SHADER_READ_ONLY_OPTIMAL, &tex, &_deviceResources->vmaAllocator, &_deviceResources->vmaAllocator); const uint8_t* pixelString = tex.getPixelFormat().getPixelTypeChar(); if (tex.getPixelFormat().getPixelTypeId() == (uint64_t)pvr::CompressedPixelFormat::PVRTCI_2bpp_RGBA || tex.getPixelFormat().getPixelTypeId() == (uint64_t)pvr::CompressedPixelFormat::PVRTCI_4bpp_RGBA || pixelString[0] == 'a' || pixelString[1] == 'a' || pixelString[2] == 'a' || pixelString[3] == 'a') { _deviceResources->spritesDesc[i].bHasAlpha = true; } else { _deviceResources->spritesDesc[i].bHasAlpha = false; } _deviceResources->sprites[i] = _deviceResources->uiRenderer.createImage(_deviceResources->spritesDesc[i].imageView, samplerNearest); } } /*!********************************************************************************************************************* \brief Create nearest and bilinear sampler, and descriptor set \return Return true if no error occurred ***********************************************************************************************************************/ void VulkanExampleUI::createSamplersAndDescriptorSet() { // create the samplers. pvrvk::SamplerCreateInfo samplerInfo; // create bilinear sampler samplerInfo.minFilter = pvrvk::Filter::e_LINEAR; samplerInfo.magFilter = pvrvk::Filter::e_LINEAR; _deviceResources->samplerBilinear = _deviceResources->device->createSampler(samplerInfo); // create point sampler samplerInfo.minFilter = pvrvk::Filter::e_NEAREST; samplerInfo.magFilter = pvrvk::Filter::e_NEAREST; _deviceResources->samplerNearest = _deviceResources->device->createSampler(samplerInfo); pvrvk::WriteDescriptorSet writeDescSets[pvrvk::FrameworkCaps::MaxSwapChains]; pvrvk::DescriptorSetLayoutCreateInfo descSetLayoutInfo; descSetLayoutInfo.setBinding(0, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT); // set up the page window ubo auto& ubo = _deviceResources->pageWindow.renderQuadUboBufferView; pvr::utils::StructuredMemoryDescription desc; desc.addElement("MVP", pvr::GpuDatatypes::mat4x4); ubo.initDynamic(desc, _numSwapchain, pvr::BufferUsageFlags::UniformBuffer, static_cast<uint32_t>(_deviceResources->device->getPhysicalDevice()->getProperties().getLimits().getMinUniformBufferOffsetAlignment())); _deviceResources->pageWindow.renderQuadUboBuffer = pvr::utils::createBuffer(_deviceResources->device, ubo.getSize(), pvrvk::BufferUsageFlags::e_UNIFORM_BUFFER_BIT, pvrvk::MemoryPropertyFlags::e_HOST_VISIBLE_BIT, pvrvk::MemoryPropertyFlags::e_DEVICE_LOCAL_BIT | pvrvk::MemoryPropertyFlags::e_HOST_VISIBLE_BIT | pvrvk::MemoryPropertyFlags::e_HOST_COHERENT_BIT, &_deviceResources->vmaAllocator, pvr::utils::vma::AllocationCreateFlags::e_MAPPED_BIT); ubo.pointToMappedMemory(_deviceResources->pageWindow.renderQuadUboBuffer->getDeviceMemory()->getMappedData()); for (uint32_t i = 0; i < _numSwapchain; ++i) { pvrvk::DescriptorSet& uboDesc = _deviceResources->pageWindow.renderQuadUboDesc[i]; uboDesc = _deviceResources->descriptorPool->allocateDescriptorSet(_deviceResources->renderQuadPipe->getPipelineLayout()->getDescriptorSetLayout(0)); writeDescSets[i] .set(pvrvk::DescriptorType::e_UNIFORM_BUFFER, uboDesc, 0) .setBufferInfo(0, pvrvk::DescriptorBufferInfo(_deviceResources->pageWindow.renderQuadUboBuffer, ubo.getDynamicSliceOffset(i), ubo.getDynamicSliceSize())); } _deviceResources->device->updateDescriptorSets(writeDescSets, _numSwapchain, nullptr, 0); } /*!********************************************************************************************************************* \brief create graphics pipelines. \return Return true if no error occurred ***********************************************************************************************************************/ void VulkanExampleUI::createPipelines() { _deviceResources->texLayout = _deviceResources->device->createDescriptorSetLayout( pvrvk::DescriptorSetLayoutCreateInfo().setBinding(0, pvrvk::DescriptorType::e_COMBINED_IMAGE_SAMPLER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT)); _deviceResources->uboLayoutVert = _deviceResources->device->createDescriptorSetLayout( pvrvk::DescriptorSetLayoutCreateInfo().setBinding(0, pvrvk::DescriptorType::e_UNIFORM_BUFFER, 1, pvrvk::ShaderStageFlags::e_VERTEX_BIT)); _deviceResources->uboLayoutFrag = _deviceResources->device->createDescriptorSetLayout( pvrvk::DescriptorSetLayoutCreateInfo().setBinding(0, pvrvk::DescriptorType::e_UNIFORM_BUFFER, 1, pvrvk::ShaderStageFlags::e_FRAGMENT_BIT)); pvr::Stream::ptr_type vertSource = getAssetStream(VertShaderFileName); pvr::Stream::ptr_type fragSource = getAssetStream(FragShaderFileName); // create the vertex and fragment shaders _deviceResources->vertexShader = _deviceResources->device->createShaderModule(pvrvk::ShaderModuleCreateInfo(vertSource->readToEnd<uint32_t>())); _deviceResources->fragmentShader = _deviceResources->device->createShaderModule(pvrvk::ShaderModuleCreateInfo(fragSource->readToEnd<uint32_t>())); // --- renderquad pipeline { pvrvk::GraphicsPipelineCreateInfo pipeInfo; pvrvk::PipelineColorBlendAttachmentState colorAttachmentBlendState; pipeInfo.pipelineLayout = _deviceResources->device->createPipelineLayout(pvrvk::PipelineLayoutCreateInfo().setDescSetLayout(0, _deviceResources->uboLayoutVert)); pipeInfo.vertexShader = _deviceResources->vertexShader; pipeInfo.fragmentShader = _deviceResources->fragmentShader; pipeInfo.vertexInput.addInputAttribute(pvrvk::VertexInputAttributeDescription(0, 0, pvrvk::Format::e_R32G32B32A32_SFLOAT, 0)); pipeInfo.vertexInput.addInputBinding(pvrvk::VertexInputBindingDescription(0, sizeof(Vertex))); pipeInfo.inputAssembler.setPrimitiveTopology(pvrvk::PrimitiveTopology::e_TRIANGLE_STRIP); pipeInfo.rasterizer.setCullMode(pvrvk::CullModeFlags::e_BACK_BIT); pipeInfo.renderPass = _deviceResources->onScreenFramebuffer[0]->getRenderPass(); //- Set stencil function to always pass, and write 0x1 in to the stencil buffer. //- disable depth write and depth test pvrvk::StencilOpState stencilState; stencilState.setPassOp(pvrvk::StencilOp::e_REPLACE); stencilState.setCompareOp(pvrvk::CompareOp::e_ALWAYS); stencilState.setWriteMask(0xffffffff); stencilState.setReference(1); pipeInfo.depthStencil.setStencilFrontAndBack(stencilState).enableStencilTest(true); pipeInfo.colorBlend.setAttachmentState(0, colorAttachmentBlendState); pipeInfo.depthStencil.setStencilFrontAndBack(stencilState).enableDepthTest(true).enableDepthWrite(false); pipeInfo.depthStencil.setDepthCompareFunc(pvrvk::CompareOp::e_LESS_OR_EQUAL); pvr::utils::populateViewportStateCreateInfo(_deviceResources->onScreenFramebuffer[0], pipeInfo.viewport); _deviceResources->renderQuadPipe = _deviceResources->device->createGraphicsPipeline(pipeInfo, _deviceResources->pipelineCache); } // --- render window text ui pipeline { // copy the create param from the parent pvrvk::GraphicsPipelineCreateInfo pipeInfo = _deviceResources->uiRenderer.getPipeline()->getCreateInfo(); pipeInfo.depthStencil.enableDepthTest(false).enableDepthWrite(false).enableStencilTest(true); // Set stencil compare op to equal and only render when the stencil function passes pvrvk::StencilOpState stencilState; stencilState.setCompareOp(pvrvk::CompareOp::e_EQUAL); stencilState.setCompareMask(0xff); stencilState.setReference(1); pipeInfo.depthStencil.setStencilFrontAndBack(stencilState); pvrvk::PipelineColorBlendAttachmentState colorAttachment; colorAttachment.setBlendEnable(true); colorAttachment.setSrcColorBlendFactor(pvrvk::BlendFactor::e_SRC_ALPHA); colorAttachment.setDstColorBlendFactor(pvrvk::BlendFactor::e_ONE_MINUS_SRC_ALPHA); // Setting the alpha blend factors so that we preserve the contents of the framebuffer (i.e. opaque), to avoid // artifacts on compositors that use the alpha value. Otherwise someone might use a different scheme to actually // have transparency in his winod, if the windowing system/compositor supported it (e.g. Wayland). colorAttachment.setSrcAlphaBlendFactor(pvrvk::BlendFactor::e_ZERO); colorAttachment.setDstAlphaBlendFactor(pvrvk::BlendFactor::e_ONE); pipeInfo.colorBlend.setAttachmentState(0, colorAttachment); pipeInfo.basePipeline = _deviceResources->uiRenderer.getPipeline(); pipeInfo.flags = pvrvk::PipelineCreateFlags::e_DERIVATIVE_BIT; _deviceResources->renderWindowTextPipe = _deviceResources->device->createGraphicsPipeline(pipeInfo, _deviceResources->pipelineCache); } } /*!********************************************************************************************************************* \brief Renders a 2D quad with the given parameters. DstRect is the rectangle to be rendered in world coordinates. SrcRect is the rectangle to be cropped from the texture in pixel coordinates. NOTE: This is not an optimized function and should not be called repeatedly to draw quads to the screen at render time. ***********************************************************************************************************************/ void VulkanExampleUI::drawScreenAlignedQuad(const pvrvk::GraphicsPipeline& pipe, pvrvk::DescriptorSet& ubo, pvrvk::CommandBufferBase commandBuffer) { commandBuffer->bindDescriptorSet(pvrvk::PipelineBindPoint::e_GRAPHICS, pipe->getPipelineLayout(), 0, ubo); commandBuffer->bindVertexBuffer(_deviceResources->quadVbo, 0, 0); commandBuffer->draw(0, 4, 0, 1); } /*!********************************************************************************************************************* \return Return Result::Success if no error occurred \brief Code in releaseView() will be called by Shell when the application quits or before a change in the rendering context. ***********************************************************************************************************************/ pvr::Result VulkanExampleUI::releaseView() { _deviceResources.reset(); return pvr::Result::Success; } /*!********************************************************************************************************************* \brief Code in quitApplication() will be called by PVRShell once per run, just before exiting the program. If the rendering context is lost, quitApplication() will not be called. \return Return pvr::Result::Success if no error occurred ***********************************************************************************************************************/ pvr::Result VulkanExampleUI::quitApplication() { return pvr::Result::Success; } /*!********************************************************************************************************************* \brief Render the page \param page Page to render \param mTransform Transformation matrix ***********************************************************************************************************************/ void VulkanExampleUI::renderPage(DisplayPage::Enum page, const glm::mat4& mTransform, uint32_t swapchain) { switch (page) { case DisplayPage::Clocks: _deviceResources->pageClock.update(swapchain, float(getFrameTime()), mTransform); _deviceResources->commandBuffer[swapchain]->executeCommands(_deviceResources->commandBufferClockPage[swapchain]); break; case DisplayPage::Weather: _deviceResources->pageWeather.update(swapchain, mTransform); _deviceResources->commandBuffer[swapchain]->executeCommands(_deviceResources->commandBufferWeatherpage[swapchain]); break; case DisplayPage::Window: _deviceResources->pageWindow.update(_projMtx, swapchain, _deviceResources->uiRenderer.getRenderingDimX(), _deviceResources->uiRenderer.getRenderingDimY(), mTransform); _deviceResources->commandBuffer[swapchain]->executeCommands(_deviceResources->commandBufferWindow[swapchain]); break; default: break; } } /*!********************************************************************************************************************* \brief Renders the default interface. ***********************************************************************************************************************/ void VulkanExampleUI::renderUI(uint32_t swapchain) { pvrvk::ClearValue clearValues[] = { pvrvk::ClearValue(.3f, .3f, 0.3f, 1.f), pvrvk::ClearValue::createDefaultDepthStencilClearValue() }; _deviceResources->commandBuffer[swapchain]->beginRenderPass( _deviceResources->onScreenFramebuffer[swapchain], pvrvk::Rect2D(0, 0, getWidth(), getHeight()), false, clearValues, ARRAY_SIZE(clearValues)); // render the baseUI _deviceResources->commandBuffer[swapchain]->executeCommands(_deviceResources->commandBufferBaseUI[swapchain]); if (_state == DisplayState::Element) { // A transformation matrix if (_currentPage == DisplayPage::Window) { glm::mat4 vRot, vCentre, vInv; vRot = glm::rotate(_wndRotate, glm::vec3(0.0f, 0.0f, 1.0f)); vCentre = glm::translate(glm::vec3(-_deviceResources->uiRenderer.getRenderingDim() * .5f, 0.0f)); vInv = glm::inverse(vCentre); const glm::vec2 rotateOrigin = -glm::vec2(_deviceResources->pageWindow.renderArea.getExtent().getWidth(), _deviceResources->pageWindow.renderArea.getExtent().getHeight()) * glm::vec2(.5f); vCentre = glm::translate(glm::vec3(rotateOrigin, 0.0f)); vInv = glm::inverse(vCentre); // align the group center to the center of the rotation, rotate and translate it back. _transform = vInv * vRot * vCentre; } else { _transform = glm::mat4(1.f); } // Just render the single, current page renderPage(_currentPage, _transform, swapchain); } else if (_state == DisplayState::Transition) { //--- Render outward group float fX = pvr::math::quadraticEaseIn(0.f, -_deviceResources->uiRenderer.getRenderingDimX() * _cycleDir, _transitionPerc); _transform = glm::translate(glm::vec3(fX, 0.0f, 0.0f)); // the last page page renderPage(_lastPage, _transform, swapchain); // --- Render inward group fX = pvr::math::quadraticEaseIn(_deviceResources->uiRenderer.getRenderingDimX() * _cycleDir, 0.0f, _transitionPerc); _transform = glm::translate(glm::vec3(fX, 0.0f, 0.0f)); // Render page renderPage(_currentPage, _transform, swapchain); } // record draw title and description commands _deviceResources->commandBuffer[swapchain]->executeCommands(_deviceResources->commandBufferTitleDesc[swapchain]); _deviceResources->commandBuffer[swapchain]->endRenderPass(); } /*!********************************************************************************************************************* \brief Swipe left ***********************************************************************************************************************/ void VulkanExampleUI::swipeLeft() { if (_currentPage == 0) { return; } _swipe = true; _cycleDir = -1; } /*!********************************************************************************************************************* \brief Swipe right ***********************************************************************************************************************/ void VulkanExampleUI::swipeRight() { if (_currentPage == DisplayPage::Count - 1) { return; } _swipe = true; _cycleDir = 1; } /*!********************************************************************************************************************* \return Return pvr::Result::Success if no error occurred \brief Main rendering loop function of the program. The shell will call this function every frame. ***********************************************************************************************************************/ pvr::Result VulkanExampleUI::renderFrame() { // begin recording the command buffer _deviceResources->perFrameAcquireFence[_frameId]->wait(); _deviceResources->perFrameAcquireFence[_frameId]->reset(); _deviceResources->swapchain->acquireNextImage(uint64_t(-1), _deviceResources->semaphoreImageAcquired[_frameId], _deviceResources->perFrameAcquireFence[_frameId]); const uint32_t swapchainIndex = _deviceResources->swapchain->getSwapchainIndex(); _deviceResources->perFrameCommandBufferFence[swapchainIndex]->wait(); _deviceResources->perFrameCommandBufferFence[swapchainIndex]->reset(); _deviceResources->commandBuffer[swapchainIndex]->begin(pvrvk::CommandBufferUsageFlags::e_ONE_TIME_SUBMIT_BIT); _currTime = this->getTime(); float deltaTime = (_currTime - _prevTime) * 0.001f; _prevTime = _currTime; // Update Window rotation _wndRotPerc += (1.0f / UiDisplayTime) * deltaTime; _wndRotate = pvr::math::quadraticEaseOut(0.0f, glm::pi<float>() * 2.f, _wndRotPerc); // Check to see if we should transition to a new page (if we're not already) if ((_currTime - _prevTransTime > UiDisplayTimeInMs && _state != DisplayState::Transition) || _swipe) { // Switch to next page _state = DisplayState::Transition; _transitionPerc = 0.0f; _lastPage = _currentPage; // Cycle pages int32_t nextPage = _currentPage + _cycleDir; if (nextPage >= DisplayPage::Count || nextPage < 0) { _cycleDir *= -1; // Reverse direction nextPage = _currentPage + _cycleDir; // Recalculate } _currentPage = (DisplayPage::Enum)nextPage; _swipe = false; } // Calculate next transition amount if (_state == DisplayState::Transition) { _transitionPerc += 0.01666f; // 60 FPS if (_transitionPerc > 1.f) { _state = DisplayState::Element; _transitionPerc = 1.f; _wndRotate = 0.0f; // Reset Window rotation _wndRotPerc = 0.0f; // Reset Window rotation percentage _prevTransTime = _currTime; // Reset time } } renderUI(swapchainIndex); // record commands to draw the title and description _deviceResources->commandBuffer[swapchainIndex]->end(); // Submit pvrvk::SubmitInfo submitInfo; pvrvk::PipelineStageFlags waitStage = pvrvk::PipelineStageFlags::e_COLOR_ATTACHMENT_OUTPUT_BIT; submitInfo.commandBuffers = &_deviceResources->commandBuffer[swapchainIndex]; submitInfo.numCommandBuffers = 1; submitInfo.waitSemaphores = &_deviceResources->semaphoreImageAcquired[_frameId]; submitInfo.numWaitSemaphores = 1; submitInfo.signalSemaphores = &_deviceResources->semaphorePresent[_frameId]; submitInfo.numSignalSemaphores = 1; submitInfo.waitDestStages = &waitStage; _deviceResources->queue->submit(&submitInfo, 1, _deviceResources->perFrameCommandBufferFence[swapchainIndex]); if (this->shouldTakeScreenshot()) { pvr::utils::takeScreenshot(_deviceResources->swapchain, swapchainIndex, _deviceResources->commandPool, _deviceResources->queue, this->getScreenshotFileName(), &_deviceResources->vmaAllocator, &_deviceResources->vmaAllocator); } // Present pvrvk::PresentInfo presentInfo; presentInfo.imageIndices = &swapchainIndex; presentInfo.numSwapchains = 1; presentInfo.swapchains = &_deviceResources->swapchain; presentInfo.waitSemaphores = &_deviceResources->semaphorePresent[_frameId]; presentInfo.numWaitSemaphores = 1; _frameId = (_frameId + 1) % _deviceResources->swapchain->getSwapchainLength(); _deviceResources->queue->present(presentInfo); return pvr::Result::Success; } /*!********************************************************************************************************************* \brief Record secondary command buffer for drawing textures, clock page, weather page and Window page ***********************************************************************************************************************/ void VulkanExampleUI::recordSecondaryCommandBuffers(uint32_t swapchain) { // record the base ui { _deviceResources->commandBufferBaseUI[swapchain] = _deviceResources->commandPool->allocateSecondaryCommandBuffer(); _deviceResources->uiRenderer.beginRendering(_deviceResources->commandBufferBaseUI[swapchain]); _deviceResources->groupBaseUI->render(); // render the base GUI _deviceResources->uiRenderer.endRendering(); } // record DrawClock commands { _deviceResources->commandBufferClockPage[swapchain] = _deviceResources->commandPool->allocateSecondaryCommandBuffer(); _deviceResources->uiRenderer.beginRendering(_deviceResources->commandBufferClockPage[swapchain], _deviceResources->onScreenFramebuffer[swapchain]); _deviceResources->pageClock.group[swapchain]->render(); _deviceResources->uiRenderer.endRendering(); } // record draw weather commands { _deviceResources->commandBufferWeatherpage[swapchain] = _deviceResources->commandPool->allocateSecondaryCommandBuffer(); _deviceResources->commandBufferWeatherpage[swapchain]->begin(_deviceResources->onScreenFramebuffer[swapchain]); _deviceResources->uiRenderer.beginRendering(_deviceResources->commandBufferWeatherpage[swapchain], _deviceResources->onScreenFramebuffer[swapchain]); _deviceResources->pageWeather.group[swapchain]->render(); _deviceResources->uiRenderer.endRendering(); _deviceResources->commandBufferWeatherpage[swapchain]->end(); } // record draw Window commands { _deviceResources->commandBufferWindow[swapchain] = _deviceResources->commandPool->allocateSecondaryCommandBuffer(); _deviceResources->commandBufferWindow[swapchain]->begin(_deviceResources->onScreenFramebuffer[swapchain], 0); // bind the render quad pipeline _deviceResources->commandBufferWindow[swapchain]->bindPipeline(_deviceResources->renderQuadPipe); // draw a quad only to clear a specific region of the screen drawScreenAlignedQuad(_deviceResources->renderQuadPipe, _deviceResources->pageWindow.renderQuadUboDesc[swapchain], _deviceResources->commandBufferWindow[swapchain]); // bind the renderWindowTextPipe pipeline and render the text _deviceResources->uiRenderer.beginRendering( _deviceResources->commandBufferWindow[swapchain], _deviceResources->renderWindowTextPipe, _deviceResources->onScreenFramebuffer[swapchain]); _deviceResources->pageWindow.group[swapchain]->render(); _deviceResources->uiRenderer.endRendering(); _deviceResources->commandBufferWindow[swapchain]->end(); } } /*!********************************************************************************************************************* \brief Handle input events \param[in] action Input event to handle ***********************************************************************************************************************/ void VulkanExampleUI::eventMappedInput(pvr::SimplifiedInput action) { switch (action) { case pvr::SimplifiedInput::Right: swipeLeft(); break; case pvr::SimplifiedInput::Left: swipeRight(); break; case pvr::SimplifiedInput::ActionClose: // quit the application this->exitShell(); break; default: break; } } /*!********************************************************************************************************************* \brief Constructor \param[in] width Area width \param[in] height Area height ***********************************************************************************************************************/ Area::Area(int32_t width, int32_t height) : x(0), y(0), isFilled(false), right(nullptr), left(nullptr) { setSize(width, height); } /*!********************************************************************************************************************* \brief Constructor ***********************************************************************************************************************/ Area::Area() : x(0), y(0), isFilled(false), right(NULL), left(NULL) { setSize(0, 0); } /*!********************************************************************************************************************* \brief Calculates an area where there's sufficient space or returns NULL if no space could be found. \return Return a pointer to the area added, else NULL if it fails \param width Area width \param height Area height ***********************************************************************************************************************/ Area* Area::insert(int32_t width, int32_t height) { // If this area has branches below it (i.e. is not a leaf) then traverse those. // Check the left branch first. if (left) { Area* tempPtr = NULL; tempPtr = left->insert(width, height); if (tempPtr != NULL) { return tempPtr; } } // Now check right if (right) { return right->insert(width, height); } // Already filled! if (isFilled) { return NULL; } // Too small if (size < width * height || w < width || h < height) { return NULL; } // Just right! if (size == width * height && w == width && h == height) { isFilled = true; return this; } // Too big. Split up. if (size > width * height && w >= width && h >= height) { // Initializes the children, and sets the left child's coordinates as these don't change. left = new Area; right = new Area; left->x = x; left->y = y; // --- Splits the current area depending on the size and position of the placed texture. // Splits vertically if larger free distance across the texture. if ((w - width) > (h - height)) { left->w = width; left->h = h; right->x = x + width; right->y = y; right->w = w - width; right->h = h; } // Splits horizontally if larger or equal free distance downwards. else { left->w = w; left->h = height; right->x = x; right->y = y + height; right->w = w; right->h = h - height; } // Initializes the child members' size attributes. left->size = left->h * left->w; right->size = right->h * right->w; // Inserts the texture into the left child member. return left->insert(width, height); } // Catch all error return. return NULL; } /*!********************************************************************************************************************* \brief Deletes the given area. \return Return true on success ***********************************************************************************************************************/ bool Area::deleteArea() { if (left != NULL) { if (left->left != NULL) { if (!left->deleteArea()) { return false; } if (!right->deleteArea()) { return false; } } } if (right != NULL) { if (right->left != NULL) { if (!left->deleteArea()) { return false; } if (!right->deleteArea()) { return false; } } } delete right; right = NULL; delete left; left = NULL; return true; } /*!********************************************************************************************************************* \brief set the area size \param width Area width \param height Area height ***********************************************************************************************************************/ void Area::setSize(int32_t width, int32_t height) { w = width; h = height; size = width * height; } /*!********************************************************************************************************************* \brief Get the X position of the area. \return Return the area's x position ***********************************************************************************************************************/ inline int32_t Area::getX() const { return x; } /*!********************************************************************************************************************* \brief get the Y position of the area. \return Return the area's y position ***********************************************************************************************************************/ inline int32_t Area::getY() const { return y; } /*!********************************************************************************************************************* \brief This function must be implemented by the user of the shell.The user should return its pvr::Shell object defining the behavior of the application. \return Return The demo supplied by the user ***********************************************************************************************************************/ std::unique_ptr<pvr::Shell> pvr::newDemo() { return std::unique_ptr<pvr::Shell>(new VulkanExampleUI()); }
43.316901
179
0.679577
senthuran-ukr
20e9fcaf4d085261658253d6e7976202270795a7
1,261
cpp
C++
Hackerearth/distrubteTheWeight.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
1
2020-03-06T21:05:14.000Z
2020-03-06T21:05:14.000Z
Hackerearth/distrubteTheWeight.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
2
2020-03-09T05:08:14.000Z
2020-03-09T05:14:09.000Z
Hackerearth/distrubteTheWeight.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; bool part(vector<int> a, int n, int k, long long max_sum){ long long no_part{1}, curr_sum{}; for(int i = 0; i < n; i++){ if(a[i] > max_sum) return false; if(curr_sum+a[i] > max_sum){ curr_sum = 0; no_part++; } if(no_part > k) return false; curr_sum += a[i]; } return no_part <= k; } int calculate (vector<int> a, int k,int n) { long long low = 1, high = 10000000000; int ans{}; while(low <= high){ long long mid = (low + high)/2; if(part(a, n, k, mid)){ ans = mid; high = mid-1; } else low = mid+1; } return ans; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; for(int t_i=0; t_i<T; t_i++) { int A_size,A_i; cin >> A_size; int K; cin >> K; vector<int> A; for(int i_A=0; i_A<A_size; i_A++) { cin >> A_i; A.push_back(A_i); } int out_; out_ = calculate(A, K,A_size); cout << out_ << '\n'; } }
18.544118
58
0.417129
sgpritam
20f61e858c00595e302c2ee13815b796ac82e276
4,336
cpp
C++
Sources/ChronoRage/Foes/FoeCommon.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/ChronoRage/Foes/FoeCommon.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/ChronoRage/Foes/FoeCommon.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FoeCommon.h" #include <Core/Math/Random.h> #include <Modes/GameMode.h> namespace ChronoRage { FoeCommon::FoeCommon(EFoeType type, const Ptr<Universe::World> & pWorld, const Ptr<Player> & pPlayer, GameMode & gameMode) : Foe(type, pWorld, pPlayer, gameMode), _minRange(0.0f), _maxRange(50.0f), _approachPoint(0.0f, 0.0f, 0.0f), _speed(15.0f), _radialSpeed(10.0f), _tolerance(5.0f), _angleWithPlayer(0.0f) {} FoeCommon::~FoeCommon() {} void FoeCommon::initialize(const Core::Vector3f & position) { Foe::initialize(position); _approachPoint.x = Core::frand(_minRange, _maxRange); _approachPoint.y = 0.0f; _approachPoint.z = 0.0f; float angle = Core::frand(0.0f, f_PI_MUL_2); Core::Matrix4f rotationMatrix(Core::ROTATION, angle, Core::Vector3f(0.0f, 1.0f, 0.0f)); _approachPoint = rotationMatrix.apply(_approachPoint); } void FoeCommon::updateActive(double elapsed) { if(!_pPlayer->isDead()) { Core::Vector3f playerPosition = _pPlayer->getPosition(); Core::Vector3f target = _pPlayer->getApproachPoint(_approachPoint); _gameMode.movePointInPlayground(target); Core::Vector3f distance = target - getPosition(); if(!distance.isZero() && distance.getLengthFast() > _tolerance) { Core::Vector3f localTarget(_pNodeFoe->getParentWorldToLocalMatrix().apply(target)); Core::Vector3f localDir(localTarget - _pNodeFoe->getLocalPosition()); Core::Matrix3f mat; mat.setZVec(localDir.getNormalizedSafe(), _pNodeFoe->getUpVector(), _pNodeFoe->getLocalMatrix().getYVector()); Core::Quaternionf q1(_pNodeFoe->getLocalOrient()); Core::Quaternionf q2(mat); double rotTime = elapsed; _angleWithPlayer = 2.0f * Core::L_acosSafe(Core::L_abs(Core::dot(q1, q2))); LM_ASSERT(Core::isValid(_angleWithPlayer)); float maxAngle = float(_radialSpeed * rotTime); float alpha = 1.0; if(_angleWithPlayer != 0.0) alpha = std::min(1.0f, maxAngle / _angleWithPlayer); Core::Quaternionf newOrient(q1, q2, alpha); _pNodeFoe->setLocalOrientation(newOrient); } } Core::Vector3f currentPosition = getPosition(); Core::Vector3f direction = _pNodeFoe->getWorldDirection(); Core::Vector3f newPosition = currentPosition + (direction * _speed * (float)elapsed); _pNodeFoe->setWorldPosition(newPosition); Foe::updateActive(elapsed); } }//namespace ChronoRage
39.063063
123
0.681965
benkaraban
20fb2306cdccf3b572d1f049b473b83c566dc072
22,029
cpp
C++
game_engine_base.cpp
CreativeMetalCat/Top_Down_Shooter_2d
1f8e40080a8118a96d45febc1c01a6caca6143fa
[ "MIT" ]
null
null
null
game_engine_base.cpp
CreativeMetalCat/Top_Down_Shooter_2d
1f8e40080a8118a96d45febc1c01a6caca6143fa
[ "MIT" ]
null
null
null
game_engine_base.cpp
CreativeMetalCat/Top_Down_Shooter_2d
1f8e40080a8118a96d45febc1c01a6caca6143fa
[ "MIT" ]
null
null
null
// game_engine_base.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "game_engine_base.h" #include <WindowRenderingNew.h> #include <WindowRenderingNew.cpp> #include <iostream> #include <fstream> #include <string> #include "Player.h" #include "Drawable.h" #include "Weapon.h" #include "Actor.h" #include "Animation.h" #include "Triggers.h" #define MAX_LOADSTRING 100 #pragma message("All systems Online") enum TextureFillType { WrapModeTile = Gdiplus::WrapMode::WrapModeTile, // 0 WrapModeTileFlipX = Gdiplus::WrapMode::WrapModeTileFlipX, // 1 WrapModeTileFlipY = Gdiplus::WrapMode::WrapModeTileFlipY, // 2 WrapModeTileFlipXY = Gdiplus::WrapMode::WrapModeTileFlipXY, // 3 WrapModeClamp = Gdiplus::WrapMode::WrapModeClamp, // 4 Sprite = 5, //5 Just displays image }; class Func_View_Layer:public Actor { public: int TargetLayer = 0; Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::PointF pt, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); }; Func_View_Layer::Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer) :Actor(image, image_rect, HasCollision,collision, DrawAsSprite, FillType, Layer) { this->TargetLayer = TargetLayer; } Func_View_Layer::Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer) : Actor(image, image_rect, HasCollision, DrawAsSprite, FillType, Layer) { this->TargetLayer = TargetLayer; } Func_View_Layer::Func_View_Layer(int TargetLayer,Gdiplus::Image*image, Gdiplus::PointF pt, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer) : Actor(image, pt, HasCollision,collision, DrawAsSprite, FillType, Layer) { this->TargetLayer = TargetLayer; } bool CheckPlayerCollision(Player*&player, std::vector<Actor*>*&world_actors,OUT Actor*&caller) { if (world_actors->empty()) { return false; } for (UINT i = 0; i < world_actors->size(); i++) { if (player->GetLayer()== world_actors->at(i)->Layer) { if (world_actors->at(i)->HasCollision == true) { if (player->collision.IntersectsWith(world_actors->at(i)->collision)) { if (dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))) { Trigger_Change_Layer*t = dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i)); if (t->type == Trigger_Type::Trigger_Once) { player->SetLayer(t->LayerToChangeTo); dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))->Used = true; } if (t->type == Trigger_Type::Trigget_One_Side_Once) { if (t->enter_dir == player->LastDir) { player->SetLayer(t->LayerToChangeTo); dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))->Used = true; } } if (t->type == Trigger_Type::Trigger_One_Side_Multi) { if (t->enter_dir == player->LastDir) { player->SetLayer(t->LayerToChangeTo); } } /*t->~Trigger_Change_Layer();*/ caller = world_actors->at(i); return true; } else { while (player->collision.IntersectsWith(world_actors->at(i)->collision)) { if (player->LastDir == MoveDirection::DOWN) { player->SetY(player->GetY()-1); player->collision.Y -= 1; } else if (player->LastDir == MoveDirection::UP) { player->SetY(player->GetY() + 1); player->collision.Y += 1; } else if (player->LastDir == MoveDirection::LEFT) { player->SetY(player->GetX() + 1); player->collision.X += 1; } else if (player->LastDir == MoveDirection::RIGHT) { player->SetY(player->GetX() - 1); player->collision.X -= 1; } } caller = world_actors->at(i); return true; } } } } } return false; } bool CheckPlayerCollision(Player*&player, std::vector<Actor*>*&world_actors) { if (world_actors->empty()) { return false; } for (UINT i = 0; i < world_actors->size(); i++) { if (player->GetLayer() == world_actors->at(i)->Layer) { if (world_actors->at(i)->HasCollision == true) { if (player->collision.IntersectsWith(world_actors->at(i)->collision)) { if (dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))) { Trigger_Change_Layer*t = dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i)); if (t->type == Trigger_Type::Trigger_Once) { player->SetLayer(t->LayerToChangeTo); dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))->Used = true; } if (t->type == Trigger_Type::Trigget_One_Side_Once) { if (t->enter_dir == player->LastDir) { player->SetLayer(t->LayerToChangeTo); dynamic_cast<Trigger_Change_Layer*>(world_actors->at(i))->Used = true; } } if (t->type == Trigger_Type::Trigger_One_Side_Multi) { if (t->enter_dir == player->LastDir) { player->SetLayer(t->LayerToChangeTo); } } else { //do } /*t->~Trigger_Change_Layer();*/ return true; } else { while (player->collision.IntersectsWith(world_actors->at(i)->collision)) { if (player->LastDir == MoveDirection::DOWN) { player->SetY(player->GetY() - 1); player->collision.Y -= 1; } else if (player->LastDir == MoveDirection::UP) { player->SetY(player->GetY() + 1); player->collision.Y += 1; } else if (player->LastDir == MoveDirection::LEFT) { player->SetY(player->GetX() + 1); player->collision.X += 1; } else if (player->LastDir == MoveDirection::RIGHT) { player->SetY(player->GetX() - 1); player->collision.X -= 1; } } return true; } } } } } return false; } ////base class for ptojectile data only //class Projectile abstract :public Actor //{ //public: // //}; class GunShot :public Actor { public: bool IsActive = false; int Speed = 0; GunShot(int Speed,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); GunShot(int Speed,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); GunShot(int Speed,Gdiplus::Image*image, Gdiplus::PointF pt, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer); static void CountPhysics(GunShot*&e, int delay, Gdiplus::PointF dest); static std::thread*CreatePhysicThread(GunShot*&e, Gdiplus::PointF dest) { std::thread*res = new std::thread(GunShot::CountPhysics, std::ref(e), e->Speed, dest); return res; } }; GunShot::GunShot(int Speed,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer):Actor(image, image_rect, HasCollision, collision, DrawAsSprite, FillType, Layer) { this->Speed = Speed; } GunShot::GunShot(int Speed,Gdiplus::Image*image, Gdiplus::RectF image_rect, bool HasCollision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer):Actor(image, image_rect, HasCollision, DrawAsSprite, FillType, Layer) { this->Speed = Speed; } GunShot::GunShot(int Speed,Gdiplus::Image*image, Gdiplus::PointF pt, bool HasCollision, Gdiplus::RectF collision, bool DrawAsSprite, Gdiplus::WrapMode FillType, int Layer):Actor(image, pt, HasCollision, collision, DrawAsSprite, FillType, Layer) { this->Speed = Speed; } void GunShot::CountPhysics(GunShot *& e, int delay, Gdiplus::PointF dest) { if (dest.X < 0 || dest.Y < 0) { return; } else { int sx = e->Image_Rect.X; int sy = e->Image_Rect.Y; e->IsActive = true; float multiply = dest.Y / dest.X; while (dest.Y != e->Image_Rect.Y || dest.X != e->Image_Rect.X) { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); e->Image_Rect.X += 1; e->Image_Rect.Y = e->Image_Rect.X*multiply; } /*e->Image_Rect.X = sx; e->Image_Rect.Y = sy;*/ e->IsActive = false; return; } } // Global Variables: HINSTANCE hInst; WindowRendering*window; Player*player; std::vector<Actor*>*world_actors = new std::vector<Actor*>(); GunShot*g; Gdiplus::Point mousecoord(0, 0); int ScreenHeight = 1000; int ScreenWidth = 1000; Gdiplus::RectF PlayerViewArea(0, 0, 0, 0); int PlayerViewRadius = 600; int PlayerSpeed = 2; Gdiplus::Image*anim; //void LoadMap(std::string filename) //{ // using namespace std; // ifstream file; // string line; // file.open(filename.c_str()); // // while (!file.eof()) // { // if (line == "entity") // { // // } // if (line == "actor") // { // // } // } // file.close(); //} void paint(PaintArgs e) { using namespace Gdiplus; Gdiplus::Graphics graphics(e.hdc); graphics.Clear(Color::White); std::vector<Func_View_Layer*>*view_areas = new std::vector<Func_View_Layer*>(); for (UINT i = 0; i < world_actors->size(); i++) { if (dynamic_cast<Func_View_Layer*>(world_actors->at(i)) && world_actors->at(i)->Layer == player->GetLayer()) { view_areas->push_back(dynamic_cast<Func_View_Layer*>(world_actors->at(i))); } if (PlayerViewArea.Contains(world_actors->at(i)->Image_Rect) || PlayerViewArea.IntersectsWith(world_actors->at(i)->Image_Rect)) { if (world_actors->at(i)->Layer == player->GetLayer()) { if (!dynamic_cast<Func_View_Layer*>(world_actors->at(i))) { if (world_actors->at(i)->Visible == true) { if (world_actors->at(i)->DrawAsSprite != true) { if (((world_actors->at(i)->Image_Rect.X + world_actors->at(i)->Image_Rect.Width) < player->GetX() - PlayerViewRadius) && (world_actors->at(i)->Image_Rect.Y + world_actors->at(i)->Image_Rect.Height) < player->GetY()- PlayerViewRadius) { } else if (((world_actors->at(i)->Image_Rect.X + world_actors->at(i)->Image_Rect.Width) > player->GetX() + PlayerViewRadius) && (world_actors->at(i)->Image_Rect.Y + world_actors->at(i)->Image_Rect.Height) > player->GetY() + PlayerViewRadius) { } else { /*RectF draw_rect(world_actors->at(i)->Image_Rect.X, world_actors->at(i)->Image_Rect.Y, world_actors->at(i)->Image_Rect.Width, world_actors->at(i)->Image_Rect.Height); if ((world_actors->at(i)->Image_Rect.X > player->Image_Rect.X) && world_actors->at(i)->Image_Rect.X < (player->Image_Rect.X + PlayerViewRadius)) { if ((world_actors->at(i)->Image_Rect.X + world_actors->at(i)->Image_Rect.Width)>(player->Image_Rect.X+PlayerViewRadius)) { draw_rect.Width = PlayerViewRadius; } } if ((world_actors->at(i)->Image_Rect.Height + world_actors->at(i)->Image_Rect.Y) > (player->Image_Rect.Y + PlayerViewRadius)) { draw_rect.Height = player->Image_Rect.Y + PlayerViewRadius; } if ((world_actors->at(i)->Image_Rect.Width + world_actors->at(i)->Image_Rect.X) > (player->Image_Rect.X + PlayerViewRadius)) { draw_rect.Width = player->Image_Rect.X + PlayerViewRadius; } if (world_actors->at(i)->Image_Rect.X < (player->Image_Rect.X - PlayerViewRadius)) { if ((world_actors->at(i)->Image_Rect.X + world_actors->at(i)->Image_Rect.Width) > player->Image_Rect.X - PlayerViewRadius) { draw_rect.X++; draw_rect.Width--; } } if (world_actors->at(i)->Image_Rect.Y < (player->Image_Rect.Y - PlayerViewRadius)) { if ((world_actors->at(i)->Image_Rect.Y + world_actors->at(i)->Image_Rect.Height) > player->Image_Rect.Y - PlayerViewRadius) { draw_rect.Y++; draw_rect.Height--; } }*/ TextureBrush* brush = new TextureBrush(world_actors->at(i)->image, world_actors->at(i)->FillType); if (world_actors->at(i)->RotateDegree != 0) { brush->RotateTransform(world_actors->at(i)->RotateDegree); } if (world_actors->at(i)->Scale != 1) { brush->ScaleTransform(world_actors->at(i)->Scale, world_actors->at(i)->Scale); } graphics.FillRectangle(brush, world_actors->at(i)->Image_Rect); delete brush; } } else { if (dynamic_cast<AnimatedSprite*>(world_actors->at(i))) { if (dynamic_cast<AnimatedSprite*>(world_actors->at(i))->AnimationIsActive == false) { dynamic_cast<AnimatedSprite*>(world_actors->at(i))->StartAnimThread(); } } graphics.DrawImage(world_actors->at(i)->image, world_actors->at(i)->Image_Rect); } } } } else { if (!world_actors->empty()) { for (UINT u = 0; u < view_areas->size(); u++) { if (view_areas->at(u)->collision.Contains(world_actors->at(i)->Image_Rect) && !dynamic_cast<Func_View_Layer*>(world_actors->at(i))) { if (world_actors->at(i)->Visible = true) { if (world_actors->at(i)->DrawAsSprite != true) { graphics.FillRectangle(new TextureBrush(world_actors->at(i)->image, world_actors->at(i)->FillType), world_actors->at(i)->Image_Rect); } else { graphics.DrawImage(world_actors->at(i)->image, world_actors->at(i)->Image_Rect); } } } } } } } } if (player->image->AnimationIsActive == false) { player->image->StartAnimThread(); } graphics.DrawImage(player->image->image, player->image->Image_Rect); graphics.DrawImage(g->image, g->Image_Rect); view_areas->~vector(); graphics.~Graphics(); } void onkeydown(KeyDownArgs e) { if (e.Key == KeyCodes::eKeyCodes::KEY_DOWN) { int sy = player->image->Image_Rect.Y; player->image->Image_Rect.Y += PlayerSpeed/2; player->collision.Y += PlayerSpeed/2; player->LastDir = MoveDirection::DOWN; CheckPlayerCollision(player, world_actors); if (player->image->Image_Rect.Y != sy) { for (UINT i = 0; i < world_actors->size(); i++) { world_actors->at(i)->Image_Rect.Y -= PlayerSpeed / 2; world_actors->at(i)->collision.Y -= PlayerSpeed / 2; } } } if (e.Key == KeyCodes::eKeyCodes::KEY_RIGHT) { int sx = player->image->Image_Rect.X; player->image->Image_Rect.X += PlayerSpeed/2; player->collision.X += PlayerSpeed/2; player->LastDir = MoveDirection::RIGHT; CheckPlayerCollision(player, world_actors); if (player->image->Image_Rect.X != sx) { for (UINT i = 0; i < world_actors->size(); i++) { world_actors->at(i)->Image_Rect.X -= PlayerSpeed / 2; world_actors->at(i)->collision.X -= PlayerSpeed / 2; } } } if (e.Key == KeyCodes::eKeyCodes::KEY_UP) { int sy = player->image->Image_Rect.Y; player->image->Image_Rect.Y -= PlayerSpeed/2; player->collision.Y -= PlayerSpeed/2; if (player->image->Image_Rect.Y < 0) { player->image->Image_Rect.Y = 0; } player->LastDir = MoveDirection::UP; CheckPlayerCollision(player, world_actors); if (player->image->Image_Rect.Y != sy) { for (UINT i = 0; i < world_actors->size(); i++) { world_actors->at(i)->Image_Rect.Y += PlayerSpeed / 2; world_actors->at(i)->collision.Y += PlayerSpeed / 2; } } } if (e.Key == KeyCodes::eKeyCodes::KEY_LEFT) { int sx = player->image->Image_Rect.X; player->image->Image_Rect.X -= PlayerSpeed/2; player->collision.X -= PlayerSpeed/2; if (player->image->Image_Rect.X < 0) { player->image->Image_Rect.X = 0; } player->LastDir = MoveDirection::LEFT; CheckPlayerCollision(player, world_actors); if (player->image->Image_Rect.X != sx) { for (UINT i = 0; i < world_actors->size(); i++) { world_actors->at(i)->Image_Rect.X += PlayerSpeed / 2; world_actors->at(i)->collision.X += PlayerSpeed / 2; } } } PlayerViewArea.X = player->image->Image_Rect.X - PlayerViewRadius; PlayerViewArea.Y = player->image->Image_Rect.Y - PlayerViewRadius; } void onclick(MouseClickArgs e) { mousecoord.X = e.x; mousecoord.Y = e.y; if (g->IsActive == false) { g->Image_Rect.X = player->GetX(); g->Image_Rect.Y = player->GetY(); GunShot::CreatePhysicThread(g, Gdiplus::PointF(e.x, e.y))->detach(); } } INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { using namespace Gdiplus; Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); anim = new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\image.gif"); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); PlayerViewArea.Height = PlayerViewRadius*2; PlayerViewArea.Width = PlayerViewRadius*2; /*world_actors->push_back(new Actor(new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\Dust2_layout.png"), Gdiplus::RectF(0, 0, 700, 1000), false, true, WrapMode::WrapModeTile, 0));*/ ////world_actors->push_back(new Actor(new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\floor_checkboard_texture.png"), Gdiplus::RectF(300, 0, 200, 200), false, false, WrapMode::WrapModeTile, 1,0,5)); //world_actors->push_back(new Actor(new Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\floor_checkboard_texture.png"), Rect(100, 100, 500, 500), true, false, WrapMode::WrapModeTile)); player = new Player(0,20,true,new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\player_idle.gif"), Gdiplus::RectF(0, 0, 60, 60), Gdiplus::RectF(0,0,50,50)); player->DrawImageAsAnim = true; /*world_actors->push_back(new Trigger_Change_Layer(1, Trigger_Type::Trigget_One_Side_Once, MoveDirection::RIGHT, new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\ground_texture.png"), Gdiplus::RectF(100, 0, 60, 60), true, true, WrapMode::WrapModeTile, 0));*/ /*world_actors->push_back(new Func_View_Layer(1, new Gdiplus::Image(L""), Gdiplus::RectF(50, 300, 100, 100), true, true, WrapMode::WrapModeTile, 0)); world_actors->push_back(new Actor(new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\floor_checkboard_texture.png"), Gdiplus::RectF(200, 200, 500, 500), false, false, WrapMode::WrapModeTile, 1)); world_actors->push_back(new Actor(new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\floor_checkboard_texture.png"), Gdiplus::RectF(50, 300, 60, 60), true, true, WrapMode::WrapModeTile, 0)); world_actors->push_back(new Actor(new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\floor_checkboard_texture.png"), Gdiplus::RectF(50, 100, 60, 60), true, true, WrapMode::WrapModeTile, 0));*/ /*t = new std::thread(PlayImageAnim, std::ref(anim), 20,true); t->detach();*/ world_actors->push_back(new AnimatedSprite(20,true,new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\image.gif"), Gdiplus::RectF(50, 100, 60, 60), true, 0)); g = new GunShot(1, new Gdiplus::Image(L"C:\\Users\\catgu\\source\\repos\\game_engine_base\\Debug\\assets\\models\\gunshot.bmp"), Gdiplus::RectF(0, 0, 10, 10), true, true, WrapMode::WrapModeTile, 0); // TODO: Place code here. using namespace Gdiplus; EventListener*l = new EventListener(); l->OnPaint = paint; l->OnKeyDown = onkeydown; l->OnMouseClick = onclick; window = new WindowRendering(hInstance, 0, L"0", 0, WS_OVERLAPPEDWINDOW, 0, 0, 1000, 1000, MAKEINTRESOURCE(IDC_MYICON), LoadCursor(hInstance, IDC_ARROW), l); if (window->Show()) { HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GAMEENGINEBASE)); MSG msg; // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } GdiplusShutdown(gdiplusToken); return (int)msg.wParam; } else { //Handle Window Errors GdiplusShutdown(gdiplusToken); return 0; } } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
34.856013
306
0.637206
CreativeMetalCat
20fdc532ea429e88fc490179d8411f36e079501f
381
cpp
C++
leetcode/9.palindrome-number.cpp
frankyao47/Algorithm
c4d331facc15bdfc4f5990aa788647b714799206
[ "MIT" ]
1
2016-02-19T04:16:33.000Z
2016-02-19T04:16:33.000Z
leetcode/9.palindrome-number.cpp
frankyao47/Algorithm
c4d331facc15bdfc4f5990aa788647b714799206
[ "MIT" ]
null
null
null
leetcode/9.palindrome-number.cpp
frankyao47/Algorithm
c4d331facc15bdfc4f5990aa788647b714799206
[ "MIT" ]
null
null
null
class Solution { public: bool isPalindrome(int x) { //use long long or handle overflow //only compare half to avoid overflow if(x < 0 || (x != 0 && x % 10 == 0)) return false; int sum = 0; while(sum < x) { sum = sum * 10 + x % 10; x /= 10; } return (x == sum) || (x == sum / 10); } };
25.4
58
0.427822
frankyao47
1f01e76581f8c9af268f4c8e059dfbcc9bb5018c
1,165
cpp
C++
source/Tty.cpp
blastrock/flix
86aff484beaadca1263fadd28eae658f2a641029
[ "BSD-2-Clause-FreeBSD" ]
6
2016-10-09T15:36:23.000Z
2021-08-28T01:56:08.000Z
source/Tty.cpp
blastrock/flix
86aff484beaadca1263fadd28eae658f2a641029
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
source/Tty.cpp
blastrock/flix
86aff484beaadca1263fadd28eae658f2a641029
[ "BSD-2-Clause-FreeBSD" ]
1
2018-08-31T15:40:51.000Z
2018-08-31T15:40:51.000Z
#include "Tty.hpp" #include "Screen.hpp" #include "Util.hpp" #include "Debug.hpp" XLL_LOG_CATEGORY("core/tty"); Tty* Tty::getCurrent() { static Tty* tty = new Tty(); return tty; } void Tty::feedInput(char data) { xDeb("Got input"); auto _ = _mutex.getScoped(); if (data == '\b') { if (!_stdin.empty()) { _stdin.pop_back(); Screen::getInstance().putChar(data); } return; } _stdin.push_back(data); Screen::getInstance().putChar(data); if (data == '\n') _condvar.notify_all(); xDeb("Notified"); } void Tty::print(const char* buf, size_t size) { Screen::getInstance().putString(buf, size); } size_t Tty::readInto(char* buf, size_t size) { if (size == 0) return 0; xDeb("Reading %d bytes from TTY", size); auto _ = _mutex.getScoped(); while (_stdin.empty()) { xDeb("TTY empty, waiting"); _condvar.wait(_mutex); } xDeb("Starting read"); size_t toRead = std::min(size, _stdin.size()); for (char* ptr = buf, * end = buf + toRead; ptr != end; ++ptr) { *ptr = _stdin.front(); _stdin.pop_front(); } xDeb("Read %d bytes", toRead); return toRead; }
16.180556
48
0.593133
blastrock
1f0499f68375c7f21733175904dcf0c8e10e793e
4,890
cpp
C++
src/examples/imgproc/src/gen_images.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/examples/imgproc/src/gen_images.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/examples/imgproc/src/gen_images.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include <random> #include <stdlib.h> #include <string.h> #include <linux/limits.h> using namespace std; void help(char * name) { cout << "Usage : " << name << " n out_dir width height method methodparams..." << std::endl; } void help_rand() { cout << "rand cmd parameters : density" << endl; } void help_rand_square() { cout << "rand_square cmd parameters : none" << endl; } typedef struct { unsigned char r; unsigned char g; unsigned char b; } pix_t; size_t slashpath(char * path) { int path_len = strlen(path); if (path[path_len - 1] != '/') { path[path_len++] = '/'; path[path_len] = '\0'; } return path_len; } size_t write_ppm_header(char * buf, int height, int width) { return sprintf(buf, "P6 %d %d 255\n", width, height); } size_t init_ppm(char ** buf, size_t * buf_size, int height, int width) { unsigned char header_buf[1024]; size_t header_size = write_ppm_header((char *) header_buf, width, height); size_t npix = width * height; size_t pixmap_size = npix * sizeof(pix_t); *buf_size = header_size + pixmap_size; *buf = (char *) malloc(*buf_size); memcpy(*buf, header_buf, header_size); return header_size; } void gen_rand(const char * out_dir, int n, int height, int width, int) { char path[PATH_MAX]; strcpy(path, out_dir); int path_len = slashpath(path); char * img; size_t img_size; size_t header_size = init_ppm(&img, &img_size, height, width); size_t npix = height * width; pix_t * pixmap = (pix_t *) &img[header_size]; std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> dist(0,255); for (int i = 0; i < n; ++i) { for (size_t j = 0; j < npix; ++j) { pixmap[j].r = dist(rng); pixmap[j].g = dist(rng); pixmap[j].b = dist(rng); } sprintf(path + path_len, "img_gen_%d.ppm",i); ofstream os(path); if (!os.is_open()) { cout << "could not open file " << path << " for writing" << endl; } os.write(img, img_size); os.close(); } free(img); } void gen_rand_square(const char * out_dir, int n, int height, int width) { char path[PATH_MAX]; strcpy(path, out_dir); int path_len = slashpath(path); char * img; size_t img_size; size_t header_size = init_ppm(&img, &img_size, height, width); size_t npix = height * width; pix_t * pixmap = (pix_t *) &img[header_size]; std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> x_dist(0,width); std::uniform_int_distribution<std::mt19937::result_type> y_dist(0,height); pix_t white {0,0,0}; pix_t black {255,255,255}; for (int i = 0; i < n; ++i) { size_t square_x1 = x_dist(rng); size_t square_x2 = x_dist(rng); size_t square_y1 = y_dist(rng); size_t square_y2 = y_dist(rng); if (square_x1 > square_x2) { std::swap(square_x1,square_x2); } if (square_y1 > square_y2) { std::swap(square_y1,square_y2); } for (size_t j = 0; j < npix; ++j) { size_t x = j / height; size_t y = j % height; if (x >= square_x1 && x <= square_x2 && y >= square_y1 && y <= square_y2) { pixmap[j] = white; } else { pixmap[j] = black; } } sprintf(path + path_len, "img_gen_%d.ppm",i); ofstream os(path); if (!os.is_open()) { cout << "could not open file " << path << " for writing" << endl; } os.write(img, img_size); os.close(); } free(img); } int main (int argc, char ** argv) { if (argc < 6) { help(argv[0]); return 1; } int n = atoi(argv[1]); char * out_dir = argv[2]; int width = atoi(argv[3]); int height = atoi(argv[4]); char * method = argv[5]; if (strcmp(method, "rand") == 0) { if (argc < 7) { help_rand(); return 1; } int density = atoi(argv[6]); if (density < 0 || density > 100) { cout << "density must be between 0 and 100" << endl; return 1; } gen_rand(out_dir, n, height, width, density); } else if (strcmp(method, "rand_square") == 0) { if (argc < 6) { help_rand_square(); return 1; } gen_rand_square(out_dir, n, height, width); } else { cout << "method " << method << " not recognized" << endl; return 1; } return 0; }
22.534562
96
0.533129
fbaude
1f0ace197aa68370bdf72714b89eb25e2c82d053
1,637
cpp
C++
AtCoder/AtCoder Regular Contest 076/D.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AtCoder/AtCoder Regular Contest 076/D.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AtCoder/AtCoder Regular Contest 076/D.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
/** * author: MaGnsi0 * created: 01/07/2021 19:05:52 **/ #include <bits/stdc++.h> using namespace std; struct edge { int u, v; long long w; bool operator<(edge e) { return (this -> w < e.w); } }; struct DSU { vector<int> parent; vector<int> length; DSU(int N) { parent = vector<int>(N); iota(parent.begin(), parent.end(), 0); length = vector<int>(N, 1); } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } void unite(int x, int y) { int a = find(x); int b = find(y); if (a == b) { return; } if (length[a] < length[b]) { swap(a, b); } length[a] += length[b]; parent[b] = a; } }; int main() { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int n; cin >> n; vector<pair<int, int>> x(n), y(n); for (int i = 0; i < n; ++i) { cin >> x[i].first >> y[i].first; x[i].second = y[i].second = i; } sort(x.begin(), x.end()); sort(y.begin(), y.end()); vector<edge> edges; for (int i = 1; i < n; ++i) { edges.push_back({x[i].second, x[i - 1].second, x[i].first - x[i - 1].first}); edges.push_back({y[i].second, y[i - 1].second, y[i].first - y[i - 1].first}); } sort(edges.begin(), edges.end()); long long res = 0; DSU d(n); for (auto& [u, v, w] : edges) { if (d.find(u) == d.find(v)) { continue; } d.unite(u, v); res += w; } cout << res; }
22.736111
85
0.443494
MaGnsio
1f0ae265ca009ef8d28454ddd87eb1a2dee6b5bd
916
cpp
C++
ActionRPG/Source/ActionRPG/Private/Abilities/RPGAbilityTypes.cpp
crystal-mesh/scill-unreal-examples
da844cbb4b31f3c39f4d3f1c8a68761f27db1add
[ "MIT" ]
1
2021-12-05T15:00:47.000Z
2021-12-05T15:00:47.000Z
ActionRPG/Source/ActionRPG/Private/Abilities/RPGAbilityTypes.cpp
crystal-mesh/scill-unreal-examples
da844cbb4b31f3c39f4d3f1c8a68761f27db1add
[ "MIT" ]
null
null
null
ActionRPG/Source/ActionRPG/Private/Abilities/RPGAbilityTypes.cpp
crystal-mesh/scill-unreal-examples
da844cbb4b31f3c39f4d3f1c8a68761f27db1add
[ "MIT" ]
3
2021-09-24T15:55:23.000Z
2022-02-17T14:17:09.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "Abilities/RPGAbilityTypes.h" #include "Abilities/RPGAbilitySystemComponent.h" #include "AbilitySystemGlobals.h" bool FRPGGameplayEffectContainerSpec::HasValidEffects() const { return TargetGameplayEffectSpecs.Num() > 0; } bool FRPGGameplayEffectContainerSpec::HasValidTargets() const { return TargetData.Num() > 0; } void FRPGGameplayEffectContainerSpec::AddTargets(const TArray<FHitResult>& HitResults, const TArray<AActor*>& TargetActors) { for (const FHitResult& HitResult : HitResults) { FGameplayAbilityTargetData_SingleTargetHit* NewData = new FGameplayAbilityTargetData_SingleTargetHit(HitResult); TargetData.Add(NewData); } if (TargetActors.Num() > 0) { FGameplayAbilityTargetData_ActorArray* NewData = new FGameplayAbilityTargetData_ActorArray(); NewData->TargetActorArray.Append(TargetActors); TargetData.Add(NewData); } }
29.548387
123
0.800218
crystal-mesh
1f0b724e54c0c2c46c4a5d032a98714b8052becb
2,607
cpp
C++
editor/gui/toolbar_dock.cpp
LASTEXILE-CH/Rootex
685b9bb5763bbc35041f3a5f193a43b3156394a6
[ "MIT" ]
1
2021-03-29T09:46:28.000Z
2021-03-29T09:46:28.000Z
editor/gui/toolbar_dock.cpp
LASTEXILE-CH/Rootex
685b9bb5763bbc35041f3a5f193a43b3156394a6
[ "MIT" ]
null
null
null
editor/gui/toolbar_dock.cpp
LASTEXILE-CH/Rootex
685b9bb5763bbc35041f3a5f193a43b3156394a6
[ "MIT" ]
null
null
null
#include "toolbar_dock.h" #include "editor/editor_application.h" #include "framework/scene_loader.h" #include "framework/system.h" #include "editor/editor_system.h" #include "vendor/ImGUI/imgui.h" #include "vendor/ImGUI/imgui_stdlib.h" #include "vendor/ImGUI/imgui_impl_dx11.h" #include "vendor/ImGUI/imgui_impl_win32.h" ToolbarDock::ToolbarDock() { m_FPSRecords.resize(m_FPSRecordsPoolSize, 0.0f); } void ToolbarDock::draw(float deltaMilliseconds) { ZoneScoped; if (m_ToolbarDockSettings.m_IsActive) { if (ImGui::Begin("Toolbar")) { ImGui::Columns(2); if (SceneLoader::GetSingleton()->getCurrentScene()) { ImGui::Text("Play Scene"); ImGui::SameLine(); if (ImGui::ArrowButton("Play Scene", ImGuiDir_Right)) { EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll); OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\" " + SceneLoader::GetSingleton()->getCurrentScene()->getScenePath()); PRINT("Launched Game process"); } } ImGui::NextColumn(); ImGui::Text("Play Game"); ImGui::SameLine(); if (ImGui::ArrowButton("Play Game", ImGuiDir_Right)) { EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll); OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\""); PRINT("Launched Game process"); } ImGui::NextColumn(); #ifdef TRACY_ENABLE ImGui::Text("Profiler"); ImGui::NextColumn(); if (ImGui::Button("Start Tracy " ICON_ROOTEX_EXTERNAL_LINK " ")) { OS::OpenFileInSystemEditor("rootex/vendor/Tracy/Tracy.exe"); } ImGui::NextColumn(); #endif // TRACY_ENABLE ImGui::Columns(1); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth()); ImGui::SliderFloat("##Delta Multiplier", Application::GetSingleton()->getDeltaMultiplierPtr(), -2.0f, 2.0f, ""); if (ImGui::IsItemDeactivatedAfterEdit()) { Application::GetSingleton()->resetDeltaMultiplier(); } if (ImGui::TreeNodeEx("Editor")) { RootexFPSGraph("FPS", m_FPSRecords, EditorApplication::GetSingleton()->getAppFrameTimer().getLastFPS()); ImGui::TreePop(); } if (ImGui::TreeNodeEx("Events")) { for (auto&& [eventType, eventHandlers] : EventManager::GetSingleton()->getRegisteredEvents()) { ImGui::Text((eventType + " (" + std::to_string(eventHandlers.size()) + ")").c_str()); } ImGui::TreePop(); } for (auto& systems : System::GetSystems()) { for (auto& system : systems) { if (ImGui::TreeNodeEx(system->getName().c_str())) { system->draw(); ImGui::TreePop(); } } } } ImGui::End(); } }
26.07
133
0.660146
LASTEXILE-CH
1f0f478237cb03941a46cb6bd1bb2ac596856fae
894
cpp
C++
143-reorder-list/143-reorder-list.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
143-reorder-list/143-reorder-list.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
143-reorder-list/143-reorder-list.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: void reorderList(ListNode* head) { if(!head||!head->next) return; stack<ListNode*> s; ListNode* slow=head,*fast=head; int cnt=0; while(fast&&fast->next){ cnt++; slow=slow->next; fast=fast->next->next; } while(slow){ s.push(slow); slow=slow->next; } slow=head; while(cnt--){ fast=slow->next; slow->next=s.top(); s.top()->next=fast; slow=fast; s.pop(); } slow->next=NULL; } };
24.162162
62
0.46085
SouvikChan
1f1504131ed62230aaf89a0cb6c71a30c380a62b
1,941
hpp
C++
include/Wg/LinkLabel.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
include/Wg/LinkLabel.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
include/Wg/LinkLabel.hpp
iSLC/vaca
c9bc3284c2a1325f7056f455fd5ff1e47e7673bc
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2010 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #pragma once #include "Wg/Base.hpp" #include "Wg/CustomLabel.hpp" namespace Wg { /** A link to Internet (or whatever you want). */ class VACA_DLL LinkLabel : public CustomLabel { enum State { Outside, Inside, Hover }; State m_state; String m_url; Font m_underlineFont; Image *m_image{}; public: struct VACA_DLL Styles { static const Style Default; }; LinkLabel(const String &urlOrText, Widget *parent, const Style &style = Styles::Default); LinkLabel(const String &url, const String &text, Widget *parent, const Style &style = Styles::Default); LinkLabel(const String &url, Image &image, Widget *parent, const Style &style = Styles::Default); ~LinkLabel() override; void setFont(Font font) override; virtual Color getLinkColor(); virtual Color getHoverColor(); Signal1<void, Event &> Click; ///< @see onClick protected: // Events void onPreferredSize(PreferredSizeEvent &ev) override; void onPaint(PaintEvent &ev) override; void onMouseEnter(MouseEvent &ev) override; void onMouseMove(MouseEvent &ev) override; void onMouseLeave(MouseEvent &ev) override; void onMouseDown(MouseEvent &ev) override; void onSetCursor(SetCursorEvent &ev) override; // virtual void onResize(ResizeEvent& ev); void onFocusEnter(FocusEvent &ev) override; void onFocusLeave(FocusEvent &ev) override; void onKeyDown(KeyEvent &ev) override; // New events virtual void onClick(Event &ev); private: void init(const String &text, Image *image = nullptr); void click(); void updateFont(const Font &font); Rect getLinkBounds(Graphics &g); }; } // namespace Wg
21.32967
107
0.683668
iSLC
1f187518a5f869c9acfba6dab6cee431c267f3ac
2,524
cpp
C++
Math/circularPrime.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
22
2021-10-01T20:14:15.000Z
2022-02-22T15:27:20.000Z
Math/circularPrime.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
15
2021-10-01T20:24:55.000Z
2021-10-31T05:55:14.000Z
Math/circularPrime.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
76
2021-10-01T20:01:06.000Z
2022-03-02T16:15:24.000Z
/* problrm statement print total number circular primes below n; The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. */ #include <bits/stdc++.h> using namespace std; int rev (int c,int n) /* it take a number and rotate its digit by one and return that number for eg 123 -> 231 */ { int arr[n]; int cc=c; for(int i=0;i<n;i++) { arr[i]=c%10; // cout<<arr[i]<<" "; c/=10; } //cout<<endl; int a=arr[0]; for(int i=0;i+1<n;i++) { arr[i]=arr[i+1]; } arr[n-1]=a; int p=0; int kx=0; for(int i=0;i<n;i++) { int pp=ceil(arr[i]*pow(10,p)); // cout<<pp<<" "; kx+= pp; // cout<<kx<<endl; p++; } return kx; } /* Driver code */ int main() { int n=1000000; /* take input from user */ int nn=n; n*=10; vector<int> arr; arr.push_back(0); unordered_map<int, int> map; for(int i=1;i<=n;i++) /* fill the array from 1 to n */ { arr.push_back(i); } for(int i=2;i<=n;i++) /* sieve code that mark all non prime number as 1 and store all prime numbers in a hash map*/ { if(arr[i]!=1) { map.insert(make_pair(arr[i],1)); for(int j=i+i;j<=n;j+=i) { arr[j]=1; } } } int count=0; for(int i=1;i<=nn;i++) { if(arr[i]!=1) /* if the number is prime*/ { int flag2=0; int c=arr[i]; int k=0; while(c) /* number of digits in that number =k*/ { k++; c/=10; } int kk=k; c=arr[i]; int cc=c; if(k>1) {int arr1[kk-1]; int p=0; while(k>1) { c= rev(c,kk); /* function that rotate the digits of number by 1*/ if (map.find(c) == map.end()) /* if the new number is not a prime number then it is not a circular prime*/ { flag2=1; break; } k--; } } if(flag2==0) /* if all its rotations are prime then count++ that number */ { count++; } } } cout<<count; return 0; }
19.874016
121
0.410856
Bhannasa
1f196cd287196d655907f4ad1852db139f9cd513
1,936
cpp
C++
CustomEngine/CustomEngine/Logic/States/State_Intro.cpp
kaimelis/LuaGame
7a6220a90c00c539b515f36b563d1542b49c1d1b
[ "MIT" ]
null
null
null
CustomEngine/CustomEngine/Logic/States/State_Intro.cpp
kaimelis/LuaGame
7a6220a90c00c539b515f36b563d1542b49c1d1b
[ "MIT" ]
null
null
null
CustomEngine/CustomEngine/Logic/States/State_Intro.cpp
kaimelis/LuaGame
7a6220a90c00c539b515f36b563d1542b49c1d1b
[ "MIT" ]
1
2020-06-29T07:13:57.000Z
2020-06-29T07:13:57.000Z
#include "State_Intro.hpp" #include "../../Core/StateSystem/StateManager.hpp" State_Intro::State_Intro(StateManager* pStateManager) : BaseState(pStateManager) {} State_Intro::~State_Intro() {} void State_Intro::OnCreate() { _timePassed = 0.0f; sf::Vector2u windowSize = _stateMgr->GetContext()->_wind->GetRenderWindow()->getSize(); _introTexture.loadFromFile("Assets/intro.png"); _introSprite.setTexture(_introTexture); _introSprite.setOrigin(_introTexture.getSize().x / 2.0f,_introTexture.getSize().y / 2.0f); _introSprite.setPosition(windowSize.x / 2.0f, 0); _font.loadFromFile("Assets/arial.ttf"); _text.setFont(_font); _text.setString({ "Press SPACE to continue" }); _text.setCharacterSize(15); sf::FloatRect textRect = _text.getLocalBounds(); _text.setOrigin(textRect.left + textRect.width / 2.0f,textRect.top + textRect.height / 2.0f); _text.setPosition(windowSize.x / 2.0f, windowSize.y / 2.0f); EventManager* evMgr = _stateMgr->GetContext()->_eventManager; evMgr->AddCallback(StateType::Intro, "Intro_Continue", &State_Intro::Continue, this); } void State_Intro::OnDestroy() { EventManager* evMgr = _stateMgr->GetContext()->_eventManager; evMgr->RemoveCallback(StateType::Intro, "Intro_Continue"); } void State_Intro::Update(const sf::Time& pTime) { if (_timePassed < 1.0f ) { // Less than five seconds. _timePassed += pTime.asSeconds(); _introSprite.setPosition( _introSprite.getPosition().x,_introSprite.getPosition().y + (100 * pTime.asSeconds())); } } void State_Intro::Draw() { sf::RenderWindow* window = _stateMgr->GetContext()->_wind->GetRenderWindow(); window->draw(_introSprite); if (_timePassed >= 1.0f) { window->draw(_text); } } void State_Intro::Continue(EventDetails* l_details) { if (_timePassed >= 1.0f) { _stateMgr->SwitchTo(StateType::MainMenu); _stateMgr->Remove(StateType::Intro); } } void State_Intro::Activate() {} void State_Intro::Deactivate() {}
28.057971
94
0.729855
kaimelis
1f1b3405320bb904f05c3de79fa9563663508dcc
1,907
cpp
C++
winprom/ElevColor_dlg.cpp
Frontline-Processing/winprom
621e1422333a9b4e84cd2f507a412e8bb0e68c46
[ "MIT" ]
17
2015-10-23T13:07:06.000Z
2021-08-25T07:06:13.000Z
winprom/ElevColor_dlg.cpp
Frontline-Processing/winprom
621e1422333a9b4e84cd2f507a412e8bb0e68c46
[ "MIT" ]
null
null
null
winprom/ElevColor_dlg.cpp
Frontline-Processing/winprom
621e1422333a9b4e84cd2f507a412e8bb0e68c46
[ "MIT" ]
3
2016-01-27T22:13:40.000Z
2018-05-09T12:56:02.000Z
// WinProm Copyright 2015 Edward Earl // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // ElevColor_dlg.cpp : implementation file // #include "stdafx.h" #include "winprom.h" #include "ElevColor_dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CElevColor_dlg dialog CElevColor_dlg::CElevColor_dlg(Elev_color_intv& eci, CWnd* pParent /*=NULL*/) : CDialog(CElevColor_dlg::IDD, pParent),elev_color_intv(eci) { //{{AFX_DATA_INIT(CElevColor_dlg) m_elev = 0; m_interp = FALSE; //}}AFX_DATA_INIT } void CElevColor_dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CElevColor_dlg) DDX_Text(pDX, IDC_ELEV, m_elev); DDV_MinMaxInt(pDX, m_elev, -16383, 32767); DDX_Check(pDX, IDC_INTERP, m_interp); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CElevColor_dlg, CDialog) //{{AFX_MSG_MAP(CElevColor_dlg) ON_BN_CLICKED(IDC_COLOR, OnColor) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CElevColor_dlg message handlers BOOL CElevColor_dlg::OnInitDialog() { m_interp=elev_color_intv.interp; m_elev=elev_color_intv.elev; m_color=elev_color_intv.color; CDialog::OnInitDialog(); m_color_box.SubclassDlgItem(IDC_COLOR_BOX,this); m_color_box.set_color(m_color); return TRUE; // return TRUE unless you set the focus to a control } void CElevColor_dlg::OnColor() { CColorDialog dlg(m_color); if (dlg.DoModal()!=IDOK) return; m_color=dlg.GetColor(); m_color_box.set_color(m_color); } void CElevColor_dlg::OnOK() { CDialog::OnOK(); elev_color_intv.interp=m_interp!=FALSE; elev_color_intv.elev=m_elev; elev_color_intv.color=m_color; }
22.702381
77
0.686418
Frontline-Processing
1f1d958cd62a80329af3cdf6e99ec95a53ed4cb4
6,701
cpp
C++
src/cmd/domain_commands.cpp
BenjaminFerge/yess
4c8a8fa0c6ba35770140cf9cfa9c7442c7128c38
[ "Apache-2.0" ]
null
null
null
src/cmd/domain_commands.cpp
BenjaminFerge/yess
4c8a8fa0c6ba35770140cf9cfa9c7442c7128c38
[ "Apache-2.0" ]
null
null
null
src/cmd/domain_commands.cpp
BenjaminFerge/yess
4c8a8fa0c6ba35770140cf9cfa9c7442c7128c38
[ "Apache-2.0" ]
null
null
null
#include "domain_commands.hpp" using namespace yess::cmd; Create_stream_req::Create_stream_req(const std::string& type) : type_(type) { } Create_stream::Create_stream(const Action_handler& handler, const Create_stream_req& request) : Domain_command(handler), request_(request) { } Command_result Create_stream::execute() { try { handler_.create_stream(request_.type_); } catch (std::exception /* ex */) { std::string msg = "Unexpected error: cannot create stream"; return Command_result(Command_result::Status::error, msg, nullptr); } return Command_result(Command_result::Status::ok, "OK", nullptr); } std::string Create_stream::usage() { return std::string("create_stream T"); } Domain_command::Domain_command(const yess::Action_handler& handler) : handler_(handler) { } Push_req::Push_req(const int& stream_id, std::string type, std::string payload, const int& version) : stream_id_(stream_id), type_(std::move(type)), payload_(std::move(payload)), version_(version) { } Push::Push(const yess::Action_handler& handler, const Push_req& req) : Domain_command(handler), request_(req) { } Command_result Push::execute() { db::Event e{ -1, request_.stream_id_, request_.type_, request_.payload_, request_.version_, }; try { handler_.push_event(request_.stream_id_, e); } catch (std::runtime_error err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } catch (std::exception /* ex */) { std::string msg = "Unexpected error: cannot push event"; return Command_result(Command_result::Status::error, msg, nullptr); } return Command_result(Command_result::Status::ok, "OK", std::any()); } std::string Push::usage() { return std::string("push SID T JSON VER"); } Create_projection_req::Create_projection_req(std::string data, std::string type) : data(data), type(type) { } Create_projection_req::Create_projection_req(std::string data) : data(data) { } Create_projection::Create_projection(const yess::Action_handler& handler, const Create_projection_req& req) : Domain_command(handler), request_(req) { } Command_result Create_projection::execute() { try { if (!request_.type.empty()) { handler_.create_projection(request_.data, request_.type); } else { handler_.create_projection(request_.data); } } catch (std::runtime_error err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", std::any()); } std::string Create_projection::usage() { return std::string("create_projection JS [T]"); } Get_streams::Get_streams(const yess::Action_handler& handler, const Get_streams_req& req) : Domain_command(handler), request_(req) { } Command_result Get_streams::execute() { std::vector<db::Stream> result; try { if (!request_.type.empty()) { result = handler_.get_streams_by_type(request_.type); } else { result = handler_.get_all_streams(); } } catch (std::runtime_error err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", result); } std::string Get_streams::usage() { return std::string("get_streams [T]"); } Get_projections::Get_projections(const yess::Action_handler& handler, const Get_projections_req& req) : Domain_command(handler), request_(req) { } Command_result Get_projections::execute() { std::vector<db::Projection> result; try { if (!request_.type.empty()) { result = handler_.get_projections_by_type(request_.type); } else { result = handler_.get_all_projections(); } } catch (std::runtime_error err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", result); } std::string Get_projections::usage() { return std::string("get_projections [T]"); } Delete_projection::Delete_projection(const yess::Action_handler& handler, const Delete_projection_req& req) : Domain_command(handler), request_(req) { } Command_result Delete_projection::execute() { try { handler_.delete_projection(request_.id); } catch (std::runtime_error err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", nullptr); } std::string Delete_projection::usage() { return std::string("delete_projection ID"); } Play_req::Play_req(int projection_id, int stream_id, json init) : projection_id(projection_id), stream_id_(stream_id), init(std::move(init)) { } Play_req::Play_req(int projection_id, std::string type, json init) : projection_id(projection_id), type(std::move(type)), init(std::move(init)) { } Play::Play(const yess::Action_handler& handler, const Play_req& req) : Domain_command(handler), request_(req) { } Command_result Play::execute() { json res; try { if (!request_.type.empty()) { res = handler_.play_projection( request_.projection_id, request_.init, request_.type); } else { res = handler_.play_projection( request_.projection_id, request_.init, request_.stream_id_); } } catch (const std::runtime_error& err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", res); } std::string Play::usage() { return std::string("play PID T/SID [I]"); } Delete_stream_req::Delete_stream_req(int id) : id(id) { } Delete_stream::Delete_stream(const yess::Action_handler& handler, const Delete_stream_req& req) : Domain_command(handler), request_(req) { } Command_result Delete_stream::execute() { try { handler_.delete_stream(request_.id); } catch (const std::runtime_error& err) { return Command_result( Command_result::Status::error, err.what(), nullptr); } return Command_result(Command_result::Status::ok, "OK", nullptr); } std::string Delete_stream::usage() { return std::string("delete_stream SID"); }
29.519824
80
0.645874
BenjaminFerge
1f1dd18790d9f263bc7da55fb6eeab50eef62b4c
5,539
cpp
C++
obs-studio/test/win/test.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/test/win/test.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/test/win/test.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
#include <stdio.h> #include <time.h> #include <windows.h> #include <util/base.h> #include <graphics/vec2.h> #include <media-io/audio-resampler.h> #include <obs.h> #include <intrin.h> static const int cx = 800; static const int cy = 600; /* --------------------------------------------------- */ class SourceContext { obs_source_t *source; public: inline SourceContext(obs_source_t *source) : source(source) {} inline ~SourceContext() { obs_source_release(source); } inline operator obs_source_t *() { return source; } }; /* --------------------------------------------------- */ class SceneContext { obs_scene_t *scene; public: inline SceneContext(obs_scene_t *scene) : scene(scene) {} inline ~SceneContext() { obs_scene_release(scene); } inline operator obs_scene_t *() { return scene; } }; /* --------------------------------------------------- */ class DisplayContext { obs_display_t *display; public: inline DisplayContext(obs_display_t *display) : display(display) {} inline ~DisplayContext() { obs_display_destroy(display); } inline operator obs_display_t *() { return display; } }; /* --------------------------------------------------- */ static LRESULT CALLBACK sceneProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CLOSE: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, message, wParam, lParam); } return 0; } static void do_log(int log_level, const char *msg, va_list args, void *param) { char bla[4096]; vsnprintf(bla, 4095, msg, args); OutputDebugStringA(bla); OutputDebugStringA("\n"); if (log_level < LOG_WARNING) __debugbreak(); UNUSED_PARAMETER(param); } static void CreateOBS(HWND hwnd) { RECT rc; GetClientRect(hwnd, &rc); if (!obs_startup("en-US", nullptr, nullptr)) throw "Couldn't create OBS"; struct obs_video_info ovi; ovi.adapter = 0; ovi.base_width = rc.right; ovi.base_height = rc.bottom; ovi.fps_num = 30000; ovi.fps_den = 1001; ovi.graphics_module = DL_OPENGL; ovi.output_format = VIDEO_FORMAT_RGBA; ovi.output_width = rc.right; ovi.output_height = rc.bottom; if (obs_reset_video(&ovi) != 0) throw "Couldn't initialize video"; } static DisplayContext CreateDisplay(HWND hwnd) { RECT rc; GetClientRect(hwnd, &rc); gs_init_data info = {}; info.cx = rc.right; info.cy = rc.bottom; info.format = GS_RGBA; info.zsformat = GS_ZS_NONE; info.window.hwnd = hwnd; return obs_display_create(&info, 0); } static void AddTestItems(obs_scene_t *scene, obs_source_t *source) { obs_sceneitem_t *item = NULL; struct vec2 scale; vec2_set(&scale, 20.0f, 20.0f); item = obs_scene_add(scene, source); obs_sceneitem_set_scale(item, &scale); } static HWND CreateTestWindow(HINSTANCE instance) { WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.lpszClassName = TEXT("bla"); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.hInstance = instance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpfnWndProc = (WNDPROC)sceneProc; if (!RegisterClass(&wc)) return 0; return CreateWindow(TEXT("bla"), TEXT("bla"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 1920 / 2 - cx / 2, 1080 / 2 - cy / 2, cx, cy, NULL, NULL, instance, NULL); } /* --------------------------------------------------- */ static void RenderWindow(void *data, uint32_t cx, uint32_t cy) { obs_render_main_texture(); UNUSED_PARAMETER(data); UNUSED_PARAMETER(cx); UNUSED_PARAMETER(cy); } /* --------------------------------------------------- */ int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, int numCmd) { HWND hwnd = NULL; base_set_log_handler(do_log, nullptr); try { hwnd = CreateTestWindow(instance); if (!hwnd) throw "Couldn't create main window"; /* ------------------------------------------------------ */ /* create OBS */ CreateOBS(hwnd); /* ------------------------------------------------------ */ /* load modules */ obs_load_all_modules(); /* ------------------------------------------------------ */ /* create source */ SourceContext source = obs_source_create( "random", "some randon source", NULL, nullptr); if (!source) throw "Couldn't create random test source"; /* ------------------------------------------------------ */ /* create filter */ SourceContext filter = obs_source_create( "test_filter", "a nice green filter", NULL, nullptr); if (!filter) throw "Couldn't create test filter"; obs_source_filter_add(source, filter); /* ------------------------------------------------------ */ /* create scene and add source to scene (twice) */ SceneContext scene = obs_scene_create("test scene"); if (!scene) throw "Couldn't create scene"; AddTestItems(scene, source); /* ------------------------------------------------------ */ /* set the scene as the primary draw source and go */ obs_set_output_source(0, obs_scene_get_source(scene)); /* ------------------------------------------------------ */ /* create display for output and set the output render callback */ DisplayContext display = CreateDisplay(hwnd); obs_display_add_draw_callback(display, RenderWindow, nullptr); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } catch (char *error) { MessageBoxA(NULL, error, NULL, 0); } obs_shutdown(); blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs()); DestroyWindow(hwnd); UNUSED_PARAMETER(prevInstance); UNUSED_PARAMETER(cmdLine); UNUSED_PARAMETER(numCmd); return 0; }
23.772532
77
0.609135
noelemahcz
1f26852d4de606d926a6ea0e7ebf280848bf99a5
570
cpp
C++
Source/City/CityGameMode.cpp
chozabu/Procedural-Cities
ed74734e9f9e8000659ed43a2a448416a1b2ee77
[ "MIT" ]
577
2017-05-08T12:10:35.000Z
2022-03-30T11:12:14.000Z
Source/City/CityGameMode.cpp
chozabu/Procedural-Cities
ed74734e9f9e8000659ed43a2a448416a1b2ee77
[ "MIT" ]
16
2017-11-02T02:21:49.000Z
2021-08-30T20:45:45.000Z
Source/City/CityGameMode.cpp
chozabu/Procedural-Cities
ed74734e9f9e8000659ed43a2a448416a1b2ee77
[ "MIT" ]
123
2017-07-26T17:54:20.000Z
2022-01-13T09:39:52.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "City.h" #include "CityGameMode.h" //#include "CityHUD.h" #include "CityCharacter.h" ACityGameMode::ACityGameMode() : Super() { // set default pawn class to our Blueprinted character //static ConstructorHelpers::FObjectFinder<UBlueprint> Blueprint(TEXT("Blueprint'/Game/MyCityCharacter.MyCityCharacter'")); //if (Blueprint.Object) { // DefaultPawnClass = (UClass*)Blueprint.Object->GeneratedClass; //} // use our custom HUD class //HUDClass = ACityHUD::StaticClass(); }
28.5
125
0.714035
chozabu
1f2bd116524985f8d4182a4a51783da4b2666839
1,480
hh
C++
include/muensterTPCDetectorMessenger.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
null
null
null
include/muensterTPCDetectorMessenger.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
2
2017-01-24T21:18:46.000Z
2017-01-27T13:24:48.000Z
include/muensterTPCDetectorMessenger.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
4
2017-04-28T12:18:58.000Z
2019-04-10T21:15:00.000Z
#ifndef muensterTPCDetectorMessenger_h #define muensterTPCDetectorMessenger_h 1 #include <G4UImessenger.hh> #include <globals.hh> class muensterTPCDetectorConstruction; class G4UIcommand; class G4UIdirectory; class G4UIcmdWithoutParameter; class G4UIcmdWithAString; class G4UIcmdWithADoubleAndUnit; class G4UIcmdWith3Vector; class G4UIcmdWith3VectorAndUnit; class G4UIcmdWithAnInteger; class G4UIcmdWithADouble; class G4UIcmdWithABool; class G4UIcmdWithoutParameter; class muensterTPCDetectorMessenger: public G4UImessenger { public: muensterTPCDetectorMessenger(muensterTPCDetectorConstruction *pXeDetector); ~muensterTPCDetectorMessenger(); void SetNewValue(G4UIcommand *pUIcommand, G4String hString); private: muensterTPCDetectorConstruction* m_pXeDetector; G4UIdirectory *m_pDetectorDir; G4UIcmdWithADoubleAndUnit *m_pLXeLevelCmd; G4UIcmdWithAString *m_pMaterCmd; G4UIcmdWithAString *m_pLXeMeshMaterialCmd; G4UIcmdWithAString *m_pGXeMeshMaterialCmd; G4UIcmdWithADouble *m_pTeflonReflectivityCmd; G4UIcmdWithADouble *m_pGXeTeflonReflectivityCmd; G4UIcmdWithABool *m_pLXeScintillationCmd; G4UIcmdWithADoubleAndUnit *m_pLXeAbsorbtionLengthCmd; G4UIcmdWithADoubleAndUnit *m_pGXeAbsorbtionLengthCmd; G4UIcmdWithADoubleAndUnit *m_pLXeRayScatterLengthCmd; G4UIcmdWithADouble *m_pLXeRefractionIndexCmd; G4UIcmdWithADouble *m_pGridMeshTransparencyCmd; G4UIcmdWithADouble *m_pLXeMeshTransparencyCmd; G4UIcmdWithADouble *m_pGXeMeshTransparencyCmd; }; #endif
29.019608
76
0.875
l-althueser
1f34c89d4dea3357f30a34591e2eee569e1f10d9
113
cpp
C++
animation.cpp
Wene/WS2812_animations
c461c9b2783380fd3d6931783096304a8db1b39d
[ "MIT" ]
3
2015-09-25T21:27:52.000Z
2022-01-04T04:29:14.000Z
animation.cpp
Wene/WS2812_animations
c461c9b2783380fd3d6931783096304a8db1b39d
[ "MIT" ]
null
null
null
animation.cpp
Wene/WS2812_animations
c461c9b2783380fd3d6931783096304a8db1b39d
[ "MIT" ]
null
null
null
#include "animation.h" Animation::Animation(CRGB *Leds, int iLeds) { iLedCount = iLeds; pLEDS = Leds; }
14.125
43
0.654867
Wene
1f3a30f9092a2b0f77532cbd6a641625c0218609
14,137
cpp
C++
src/dashplayer/dashplayer.cpp
theuerse/ndn-DemoApps
47310e10dbd15bdac9342250a7b84e99d1693b91
[ "MIT" ]
null
null
null
src/dashplayer/dashplayer.cpp
theuerse/ndn-DemoApps
47310e10dbd15bdac9342250a7b84e99d1693b91
[ "MIT" ]
null
null
null
src/dashplayer/dashplayer.cpp
theuerse/ndn-DemoApps
47310e10dbd15bdac9342250a7b84e99d1693b91
[ "MIT" ]
null
null
null
#include "dashplayer.hpp" using namespace player; DashPlayer::DashPlayer(std::string MPD, string adaptionlogic_name, int interest_lifetime, int run_time, double request_rate, std::string logFileName) { this->adaptionlogic_name = adaptionlogic_name; this->interest_lifetime = interest_lifetime; streaming_active = false; mpd_url=MPD; mpd = NULL; base_url = ""; max_buffered_seconds=50; mbuffer = boost::shared_ptr<MultimediaBuffer>(new MultimediaBuffer(max_buffered_seconds)); downloader = boost::shared_ptr<FileDownloader>(new FileDownloader(this->interest_lifetime )); totalConsumedSegments = 0; hasDownloadedAllSegments = false; isStalling=false; requestedRepresentation = NULL; requestedSegmentNr = 0; requestedSegmentURL = NULL; maxRuntimeSeconds = run_time; setMyId (); maxRunTimeReached = false; lastDWRate = 0.0; this->requestRate = request_rate; if(logFileName.empty ()) logFile.open ("dashplayer_trace" + myId + ".txt", ios::out); // keep logfile open until app shutdown else logFile.open (logFileName, ios::out); logFilePrintHeader(); } DashPlayer::~DashPlayer() { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); for(; totalConsumedSegments < alogic->getTotalSegments (); totalConsumedSegments++) { logFile << boost::posix_time::to_simple_string (now) << "\t" << "PI_" << myId << "\t" << totalConsumedSegments << "\t" << -1 << "\t" << 0 << "\t" << 0 << "\t" << 0 << "\t" << "\n"; } logFile.close (); fprintf(stderr, "Player Finished\n"); } void DashPlayer::startStreaming () { //1fetch MPD and parse MPD std::string mpd_path("/tmp/video.mpd"); fprintf(stderr, "Fetching MPD: %s\n", mpd_url.c_str ()); FileDownloader::FileStruct fstruct = downloader->getFile (mpd_url, requestRate); shared_ptr<itec::Buffer> mpd_data = fstruct.buffer; lastDWRate = fstruct.dwrate; if(mpd_data == NULL) { fprintf(stderr, "Error fetching MPD! Exiting..\n"); return; } writeFileToDisk(mpd_data, mpd_path); fprintf(stderr, "parsing...\n"); if(!parseMPD(mpd_path)) return; alogic = AdaptationLogicFactory::Create(adaptionlogic_name, this); alogic->SetAvailableRepresentations (availableRepresentations); //2. start streaming (1. thread) boost::thread downloadThread(&DashPlayer::scheduleDownloadNextSegment, this); //3. start consuming (2. thread) boost::thread playbackThread(&DashPlayer::schedulePlayback, this); //limit run time boost::asio::io_service m_ioService; ndn::Scheduler m_scheduler(m_ioService); if(maxRuntimeSeconds > 0) { m_scheduler.scheduleEvent (ndn::time::seconds(maxRuntimeSeconds), bind(&DashPlayer::stopPlayer, this)); } m_ioService.run (); //wait until threads finished downloadThread.join (); playbackThread.join (); } void DashPlayer::scheduleDownloadNextSegment () { while(!hasDownloadedAllSegments && !maxRunTimeReached) { requestedRepresentation = NULL; requestedSegmentNr = 0; requestedSegmentURL = alogic->GetNextSegment(&requestedSegmentNr, &requestedRepresentation, &hasDownloadedAllSegments); if(requestedSegmentURL == NULL) // IDLE e.g. buffer is full { boost::this_thread::sleep(boost::posix_time::milliseconds(500)); continue; } fprintf(stderr, "downloading segment = %s\n",(base_url+requestedSegmentURL->GetMediaURI()).c_str ()); FileDownloader::FileStruct fstruct = downloader->getFile (base_url+requestedSegmentURL->GetMediaURI(),requestRate); shared_ptr<itec::Buffer> segmentData = fstruct.buffer; if(segmentData->getSize() != 0) { lastDWRate = fstruct.dwrate; while(!mbuffer->addToBuffer (requestedSegmentNr, requestedRepresentation)); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } } } void DashPlayer::schedulePlayback () { boost::posix_time::ptime stallEndTime; boost::posix_time::time_duration stallDuration; player::MultimediaBuffer::BufferRepresentationEntry entry = mbuffer->consumeFromBuffer ();; // did we finish streaming yet? while(! (entry.segmentDuration == 0.0 && hasDownloadedAllSegments == true) ) { if ( entry.segmentDuration > 0.0) { //fprintf(stderr, "Consumed Segment %d, with Rep %s for %f seconds\n",entry.segmentNumber,entry.repId.c_str(), entry.segmentDuration); if (isStalling) { stallEndTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); // we had a freeze/stall, but we can continue playing now stallDuration = (stallEndTime - stallStartTime); isStalling = false; } else stallDuration = boost::posix_time::time_duration(0,0,0,0); logSegmentConsume(entry,stallDuration); totalConsumedSegments++; boost::this_thread::sleep(boost::posix_time::milliseconds(entry.segmentDuration*1000)); //consume the segment } else { if ( isStalling == false) // could not consume, means buffer is empty { isStalling = true; stallStartTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time()); } boost::this_thread::sleep(boost::posix_time::milliseconds(500)); } //check for download abort if(requestedRepresentation != NULL && !hasDownloadedAllSegments && requestedRepresentation->GetDependencyId ().size () > 0) { if(! (alogic->hasMinBufferLevel (requestedRepresentation))) { fprintf(stderr, "canceling: %s", requestedSegmentURL->GetMediaURI ().c_str ()); downloader->cancel (); } } if(maxRunTimeReached) { downloader->cancel (); break; } entry = mbuffer->consumeFromBuffer (); } //consume all remaining segmetns in buffer //just for logging purpose stallDuration = boost::posix_time::time_duration(0,0,0,0); while((entry = mbuffer->consumeFromBuffer ()).segmentDuration > 0.0) { logSegmentConsume(entry,stallDuration); totalConsumedSegments++; } } bool DashPlayer::parseMPD(std::string mpd_path) { dash::IDASHManager *manager; manager = CreateDashManager(); mpd = manager->Open((char*)mpd_path.c_str ()); // We don't need the manager anymore... manager->Delete(); manager = NULL; if (mpd == NULL) { fprintf(stderr, "MPD - Parsing Error. Exiting..\n"); return false; } // we are assuming there is only 1 period, get the first one IPeriod *currentPeriod = mpd->GetPeriods().at(0); // get base URL (we take first always) std::vector<dash::mpd::IBaseUrl*> baseUrls = mpd->GetBaseUrls (); if(baseUrls.size () < 1) { fprintf(stderr, "No BaseUrl detected!\n"); return false; } base_url = baseUrls.at (0)->GetUrl(); if(base_url.substr (0,7).compare ("http://") == 0) base_url = base_url.substr(6,base_url.length ()); //prepend forwarding prefix to base url vector<string> mpd_components; boost::split(mpd_components,mpd_url,boost::is_any_of("/")); if(mpd_components.size () > 1) base_url = "/"+mpd_components.at (1) + base_url; else fprintf(stderr, "Warning MPD url has no components\n"); // Get the adaptation sets, though we are only consider the first one std::vector<IAdaptationSet *> allAdaptationSets = currentPeriod->GetAdaptationSets(); if (allAdaptationSets.size() < 1) { fprintf(stderr, "No adaptation sets found in MPD!\n"); return false; } IAdaptationSet* adaptationSet = allAdaptationSets.at(0); std::vector<IRepresentation*> reps = adaptationSet->GetRepresentation(); if(reps.size () < 1) { fprintf(stderr, "No represntations found in MPD!\n"); return false; } availableRepresentations.clear(); for (IRepresentation* rep : reps) { std::string repId = rep->GetId(); availableRepresentations[repId] = rep; } return true; } void DashPlayer::writeFileToDisk(shared_ptr<itec::Buffer> buf, string file_path) { ofstream outputStream; outputStream.open(file_path, ios::out | ios::binary); outputStream.write(buf->getData(), buf->getSize()); outputStream.close(); } // // Main entry-point // int main(int argc, char** argv) { string appName = boost::filesystem::basename(argv[0]); options_description desc("Programm Options"); desc.add_options () ("name,p", value<string>()->required (), "The name of the interest to be sent (Required)") ("adaptionlogic,a",value<string>()->required(), "The name of the adaption-logic to be used (Required)") ("lifetime,l", value<int>(), "The lifetime of the interest in milliseconds. (Default 1000ms)") ("run-time,t", value<int>(), "Runtime of the Dashplayer in Seconds. If not specified it is unlimited.") ("request-rate,r", value<double>()->required (), "Request Rate in kbits assuming 4kb large data packets.") ("output-file,o", value<string>(), "Name of the dashplayer trace log file."); positional_options_description positionalOptions; variables_map vm; try { store(command_line_parser(argc, argv).options(desc) .positional(positionalOptions).run(), vm); // throws on error notify(vm); //notify if required parameters are not provided. } catch(boost::program_options::required_option& e) { // user forgot to provide a required option cerr << "name ... The name of the interest to be sent (Required)" << endl; cerr << "adaptionlogic ... The name of the adaption-logic to be used (Required, buffer or rate)" << endl; cerr << "lifetime ... The lifetime of the interest in milliseconds. (Default 1000ms)" << endl; cerr << "run-time ... The maximal runtime of the dashplayer in seconds (Default -1 = unlimited)" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer" << endl; cerr << "usage-example: " << "./" << appName << " --name /example/testApp/randomData --adaptionlogic buffer --lifetime 1000 --run-time 300" << endl; cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(boost::program_options::error& e) { // a given parameter is faulty (e.g. given a string, asked for int) cerr << "ERROR: " << e.what() << endl << endl; return -1; } catch(exception& e) { cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << endl; return -1; } int lifetime = 1000; if(vm.count ("lifetime")) { lifetime = vm["lifetime"].as<int>(); } int runtime = -1; if(vm.count ("run-time")) { runtime = vm["run-time"].as<int>(); } std::string outputfile(""); if(vm.count("output-file")) { outputfile = vm["output-file"].as<string>(); } // create new DashPlayer instance with given parameters DashPlayer consumer(vm["name"].as<string>(),vm["adaptionlogic"].as<string>(), lifetime, runtime, vm["request-rate"].as<double>(),outputfile); try { //get MPD and start streaming consumer.startStreaming(); } catch (const exception& e) { // shit happens cerr << "ERROR: " << e.what() << endl; } return 0; } double DashPlayer::GetBufferLevel(std::string repId) { if(repId.compare ("NULL") == 0) return mbuffer->getBufferedSeconds (); else return mbuffer->getBufferedSeconds (repId); } double DashPlayer::GetBufferPercentage(std::string repId) { if(repId.compare ("NULL") == 0) return mbuffer->getBufferedPercentage (); else return mbuffer->getBufferedPercentage (repId); } unsigned int DashPlayer::nextSegmentNrToConsume () { return mbuffer->nextSegmentNrToBeConsumed (); } unsigned int DashPlayer::getHighestBufferedSegmentNr(std::string repId) { return mbuffer->getHighestBufferedSegmentNr (repId); } void DashPlayer::logFilePrintHeader () { logFile << "Time" << "\t" << "Node" << "\t" << "SegmentNumber" << "\t" << "SegmentDuration(sec)" << "\t" << "SegmentRepID" << "\t" << "SegmentBitrate(bit/s)" << "\t" << "StallingTime(msec)" << "\t" << "SegmentDepIds\n"; logFile.flush (); } void DashPlayer::logSegmentConsume(player::MultimediaBuffer::BufferRepresentationEntry &entry, boost::posix_time::time_duration& stallingTime) { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); logFile << boost::posix_time::to_simple_string (now) << "\t" << "PI_" << myId << "\t" << entry.segmentNumber << "\t" << entry.segmentDuration << "\t" << entry.repId << "\t" << entry.bitrate_bit_s << "\t" << stallingTime.total_milliseconds () << "\t"; for(unsigned int i = 0; i < entry.depIds.size (); i++) { if(i == 0) logFile << entry.depIds.at (i); else logFile << "," <<entry.depIds.at (i); } logFile << "\n"; logFile.flush (); } void DashPlayer::setMyId() { myId = "0"; int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); /* I want to get an IPv4 IP address */ ifr.ifr_addr.sa_family = AF_INET; /* I want IP address attached to "eth0" */ strncpy(ifr.ifr_name, "eth0.101", IFNAMSIZ-1); if(ioctl(fd, SIOCGIFADDR, &ifr) != 0) { strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); } close(fd); std::string ip(inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); std::vector<std::string> ip_octets; boost::split(ip_octets, ip, boost::is_any_of(".")); if(ip_octets.size () != 4) { fprintf(stderr, "Invalid IP using default id = 0\n"); return; } int id = boost::lexical_cast<int>(ip_octets.at (3)); if(id < 10) { fprintf(stderr, "Are you deploying this on the PInet? Setting default id = 0\n"); return; } myId = boost::lexical_cast<std::string>(id-10); } void DashPlayer::stopPlayer () { fprintf(stderr, "Stop Player!\n"); maxRunTimeReached = true; } double DashPlayer::GetLastDownloadBitRate() { return lastDWRate; }
28.444668
152
0.654453
theuerse
1f3b95608ad585e2c2d0767b6f56241514e23985
536
hpp
C++
Asciiboard/vendor/ftxui-2.0.0/include/macos/ftxui/component/deprecated.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
1
2022-01-24T23:53:32.000Z
2022-01-24T23:53:32.000Z
Asciiboard/vendor/ftxui-2.0.0/include/macos/ftxui/component/deprecated.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
null
null
null
Asciiboard/vendor/ftxui-2.0.0/include/macos/ftxui/component/deprecated.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
null
null
null
#ifndef FTXUI_COMPONENT_DEPRECATED_HPP #define FTXUI_COMPONENT_DEPRECATED_HPP #include "ftxui/component/component.hpp" namespace ftxui { [[deprecated("use Input with normal std::string instead.")]] Component Input( WideStringRef content, ConstStringRef placeholder, Ref<InputOption> option = {}); } // namespace ftxui #endif /* FTXUI_COMPONENT_DEPRECATED_HPP */ // Copyright 2021 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file.
28.210526
78
0.76306
DanielToby
1f3d271a570bb2d54b4303ec3845e1b27db6e1e4
606
cpp
C++
Sail/src/Sail/entities/systems/render/GUISubmitSystem.cpp
BTH-StoraSpel-DXR/SPLASH
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
12
2019-09-11T15:52:31.000Z
2021-11-14T20:33:35.000Z
Sail/src/Sail/entities/systems/render/GUISubmitSystem.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sail/src/Sail/entities/systems/render/GUISubmitSystem.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
2
2020-10-26T02:35:18.000Z
2020-10-26T02:36:01.000Z
#include "pch.h" #include "GUISubmitSystem.h" #include "Sail/Application.h" #include "Sail/entities/components/Components.h" GUISubmitSystem::GUISubmitSystem() { registerComponent<GUIComponent>(true, false, false); } GUISubmitSystem::~GUISubmitSystem() {} void GUISubmitSystem::submitAll() { Renderer* renderer = Application::getInstance()->getRenderWrapper()->getScreenSpaceRenderer(); for (auto& e : entities) { Renderer::RenderFlag flags = Renderer::MESH_STATIC; Model* model = e->getComponent<GUIComponent>()->getModel(); renderer->submit(model, glm::identity<glm::mat4>(), flags, 0); } }
30.3
95
0.739274
BTH-StoraSpel-DXR
1f3e5620b5416ba9eaa9d490120bede5220672e0
5,911
hpp
C++
shisen_cpp/include/shisen_cpp/consumer/capture_setting_consumer.hpp
threeal/shisen
523dbf72a52058df102df077c73efaa6ef7c3466
[ "MIT" ]
null
null
null
shisen_cpp/include/shisen_cpp/consumer/capture_setting_consumer.hpp
threeal/shisen
523dbf72a52058df102df077c73efaa6ef7c3466
[ "MIT" ]
null
null
null
shisen_cpp/include/shisen_cpp/consumer/capture_setting_consumer.hpp
threeal/shisen
523dbf72a52058df102df077c73efaa6ef7c3466
[ "MIT" ]
null
null
null
// Copyright (c) 2021 ICHIRO ITS // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef SHISEN_CPP__CONSUMER__CAPTURE_SETTING_CONSUMER_HPP_ #define SHISEN_CPP__CONSUMER__CAPTURE_SETTING_CONSUMER_HPP_ #include <rclcpp/rclcpp.hpp> #include <future> #include <memory> #include <string> #include "../node.hpp" namespace shisen_cpp { class CaptureSettingConsumer : public CameraNode { public: using CaptureSettingCallback = std::function<void (const CaptureSetting &)>; struct Options : public virtual CameraNode::Options { }; inline explicit CaptureSettingConsumer( rclcpp::Node::SharedPtr node, const Options & options = Options()); inline virtual void on_capture_setting_changed(const CaptureSetting & capture_setting); inline void request_to_configure_capture_setting( ConfigureCaptureSetting::Request::SharedPtr request, const CaptureSettingCallback & callback = {}); inline void configure_capture_setting( const CaptureSetting & capture_setting, const CaptureSettingCallback & callback = {}); inline void fetch_capture_setting(const CaptureSettingCallback & callback = {}); inline const CaptureSetting & get_capture_setting() const; private: inline void change_capture_setting(const CaptureSetting & capture_setting); rclcpp::Subscription<CaptureSettingMsg>::SharedPtr capture_setting_event_subscription; rclcpp::Client<ConfigureCaptureSetting>::SharedPtr configure_capture_setting_client; CaptureSetting current_capture_setting; }; CaptureSettingConsumer::CaptureSettingConsumer( rclcpp::Node::SharedPtr node, const CaptureSettingConsumer::Options & options) : CameraNode(node, options) { // Initialize the capture setting event subscription { capture_setting_event_subscription = get_node()->create_subscription<CaptureSettingMsg>( get_camera_prefix() + CAPTURE_SETTING_EVENT_SUFFIX, 10, [this](const CaptureSettingMsg::SharedPtr msg) { change_capture_setting((const CaptureSetting &)*msg); }); RCLCPP_INFO_STREAM( get_node()->get_logger(), "Capture setting event subscription initialized on `" << capture_setting_event_subscription->get_topic_name() << "`!"); } // Initialize the configure capture setting client { configure_capture_setting_client = get_node()->create_client<ConfigureCaptureSetting>( get_camera_prefix() + CONFIGURE_CAPTURE_SETTING_SUFFIX); RCLCPP_INFO(get_node()->get_logger(), "Waiting for configure capture setting server..."); if (!configure_capture_setting_client->wait_for_service(std::chrono::seconds(3))) { RCLCPP_ERROR(get_node()->get_logger(), "Configure capture setting server is not ready!"); throw std::runtime_error("configure capture setting server is not ready"); } RCLCPP_INFO_STREAM( get_node()->get_logger(), "Configure capture setting client initialized on `" << configure_capture_setting_client->get_service_name() << "`!"); } // Initial data fetch fetch_capture_setting(); } void CaptureSettingConsumer::on_capture_setting_changed(const CaptureSetting & /*capture_setting*/) { } void CaptureSettingConsumer::request_to_configure_capture_setting( ConfigureCaptureSetting::Request::SharedPtr request, const CaptureSettingCallback & callback) { configure_capture_setting_client->async_send_request( request, [this, callback](rclcpp::Client<ConfigureCaptureSetting>::SharedFuture future) { auto response = future.get(); if (response->capture_setting.size() > 0) { change_capture_setting((const CaptureSetting &)response->capture_setting.front()); // Call callback after future completed if (callback) { callback(get_capture_setting()); } } else { RCLCPP_WARN( get_node()->get_logger(), "Configure capture setting service response is empty!"); } }); } void CaptureSettingConsumer::configure_capture_setting( const CaptureSetting & capture_setting, const CaptureSettingCallback & callback) { auto request = std::make_shared<ConfigureCaptureSetting::Request>(); request->capture_setting.push_back(capture_setting); request_to_configure_capture_setting(request, callback); } void CaptureSettingConsumer::fetch_capture_setting(const CaptureSettingCallback & callback) { request_to_configure_capture_setting( std::make_shared<ConfigureCaptureSetting::Request>(), callback); } const CaptureSetting & CaptureSettingConsumer::get_capture_setting() const { return current_capture_setting; } void CaptureSettingConsumer::change_capture_setting(const CaptureSetting & capture_setting) { current_capture_setting = capture_setting; // Call callback after capture setting changed on_capture_setting_changed(get_capture_setting()); } } // namespace shisen_cpp #endif // SHISEN_CPP__CONSUMER__CAPTURE_SETTING_CONSUMER_HPP_
36.042683
99
0.763999
threeal
1f41267b16cd7e806646e7911ed43ab68a5eaa29
10,905
cpp
C++
src/bindings/Scriptdev2/scripts/northrend/utgarde_keep/utgarde_pinnacle/boss_skadi.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/northrend/utgarde_keep/utgarde_pinnacle/boss_skadi.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/northrend/utgarde_keep/utgarde_pinnacle/boss_skadi.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Skadi SD%Complete: % SDComment: SDAuthor: /// dev FallenAngelX /// SDCategory: Utgarde Pinnacle TODO:: EndScriptData */ #include "precompiled.h" #include "utgarde_pinnacle.h" enum { SAY_AGGRO = -1575019, SAY_DRAKEBREATH_1 = -1575020, SAY_DRAKEBREATH_2 = -1575021, SAY_DRAKEBREATH_3 = -1575022, SAY_DRAKE_HARPOON_1 = -1575023, SAY_DRAKE_HARPOON_2 = -1575024, SAY_KILL_1 = -1575025, SAY_KILL_2 = -1575026, SAY_KILL_3 = -1575027, SAY_DEATH = -1575028, SAY_DRAKE_DEATH = -1575029, EMOTE_HARPOON_RANGE = -1575030, SPELL_CRUSH = 50234, SPELL_CRUSH_H = 59330, SPELL_WHIRLWIND = 50228, SPELL_WHIRLWIND_H = 59322, SPELL_POISONED_SPEAR = 50255, SPELL_POISONED_SPEAR_H = 59331, SPELL_POISONED = 50258, SPELL_POISONED_H = 59334, // casted with base of creature 22515 (World Trigger), so we must make sure // to use the close one by the door leading further in to instance. SPELL_SUMMON_GAUNTLET_MOBS = 48630, // tick every 30 sec SPELL_SUMMON_GAUNTLET_MOBS_H = 59275, // tick every 25 sec SPELL_GAUNTLET_PERIODIC = 47546, // what is this? Unknown use/effect, but probably related SPELL_LAUNCH_HARPOON = 48642, // this spell hit drake to reduce HP (force triggered from 48641) ITEM_HARPOON = 37372, SPELL_SUMMON_HARPOONER_E = 48633, SPELL_SUMMON_HARPOONER_W = 48634, SPELL_SUMMON_WITCH_DOCTOR_E = 48636, SPELL_SUMMON_WITCH_DOCTOR_W = 48635 // ToDo: Find spell summoning warrior }; uint64 goHarpoons[3] = {GO_HARPOON1 ,GO_HARPOON2, GO_HARPOON3}; // has to be replaced by propper spells (summon ymirjar harpooners, uint32 m_uiSkadiAdds[3] = {26692, 26690, 26691}; /*###### ## boss_skadi ######*/ struct MANGOS_DLL_DECL boss_skadiAI : public ScriptedAI { boss_skadiAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } ScriptedInstance* m_pInstance; bool m_bIsRegularMode; bool m_bIsLandPhase; //Land Phase uint32 m_uiCrushTimer; uint32 m_uiPoisonedSpearTimer; uint32 m_uiWirlwhindTimer; //Event Phase uint8 m_uiNextWaveCount; uint32 m_uiIsInHarpoonRangeTimer; uint32 m_uiNextWaveTimer; uint32 m_uiGraufBrathTimer; void Reset() { //Land Phase m_uiCrushTimer = urand(5000, 10000); m_uiPoisonedSpearTimer = urand(5000, 10000); m_uiWirlwhindTimer = urand(5000, 10000); m_bIsLandPhase = false; //Event Phase m_uiGraufBrathTimer = 30000; m_uiNextWaveCount = 0; m_uiIsInHarpoonRangeTimer = urand(5000, 10000); m_uiNextWaveTimer = urand(5000, 10000); } void JustReachedHome() { if (m_pInstance) { m_pInstance->SetData(TYPE_SKADI, NOT_STARTED); m_pInstance->SetData(TYPE_HARPOONLUNCHER, NOT_STARTED); } } void Aggro(Unit* pWho) { DoScriptText(SAY_AGGRO, m_creature); m_creature->SetVisibility(VISIBILITY_OFF); } void KilledUnit(Unit* pVictim) { switch(urand(0, 2)) { case 0: DoScriptText(SAY_KILL_1, m_creature); break; case 1: DoScriptText(SAY_KILL_2, m_creature); break; case 2: DoScriptText(SAY_KILL_3, m_creature); break; } } void JustDied(Unit* pKiller) { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_SKADI, DONE); } void JustSummoned(Creature* pSummoned) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0)) { if (pSummoned->AI()) pSummoned->AI()->AttackStart(pTarget); } } void SendNextWeave() { uint8 waveType = urand(0, 1); for(uint8 i=0; i<(urand(5, 6)); ++i) { switch(waveType) { case 0: DoCast(m_creature, urand(0, 1) ? SPELL_SUMMON_HARPOONER_E: SPELL_SUMMON_HARPOONER_W, false); case 1: DoCast(m_creature, urand(0, 1) ? SPELL_SUMMON_WITCH_DOCTOR_E : SPELL_SUMMON_WITCH_DOCTOR_W, false); } } ++m_uiNextWaveCount; } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if(!m_bIsLandPhase) { if(m_uiNextWaveCount > 4) { if(m_pInstance && m_pInstance->GetData(TYPE_HARPOONLUNCHER) != (m_bIsRegularMode ? DONE : SPECIAL)) { if(m_uiIsInHarpoonRangeTimer < uiDiff) { DoScriptText(EMOTE_HARPOON_RANGE, m_creature); //only 1 from 3 harpoons is aloowe to use at one time if (GameObject* pGo = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(goHarpoons[urand(0,2)]))) pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); m_uiIsInHarpoonRangeTimer = urand(20000, 30000); }else m_uiIsInHarpoonRangeTimer -= uiDiff; } else { DoScriptText(SAY_DRAKE_DEATH, m_creature); m_bIsLandPhase = true; m_creature->SetVisibility(VISIBILITY_ON); if(m_pInstance) { m_pInstance->SetData(TYPE_SKADI, IN_PROGRESS); m_pInstance->SetData(TYPE_HARPOONLUNCHER, 0); } } } if(m_uiNextWaveTimer < uiDiff) { SendNextWeave(); m_uiNextWaveTimer = urand(20000, 30000); }else m_uiNextWaveTimer -= uiDiff; if(m_uiGraufBrathTimer < uiDiff) { switch(urand(0, 2)) { case 0: DoScriptText(SAY_DRAKEBREATH_1, m_creature); break; case 1: DoScriptText(SAY_DRAKEBREATH_2, m_creature); break; case 2: DoScriptText(SAY_DRAKEBREATH_3, m_creature); break; } //breath ID missing if(Unit* pPlayer = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0)) { DoCastSpellIfCan(pPlayer, m_bIsRegularMode ? SPELL_POISONED_SPEAR : SPELL_POISONED_SPEAR_H); pPlayer->CastSpell(pPlayer, m_bIsRegularMode ? SPELL_POISONED : SPELL_POISONED_H, true); } //Spell brath id ? m_uiGraufBrathTimer = urand(10000, 20000); } else m_uiGraufBrathTimer -= uiDiff; } else { if(m_uiPoisonedSpearTimer < uiDiff) { if(Unit* pPlayer = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0)) { DoCastSpellIfCan(pPlayer, m_bIsRegularMode ? SPELL_POISONED_SPEAR : SPELL_POISONED_SPEAR_H); pPlayer->CastSpell(pPlayer, m_bIsRegularMode ? SPELL_POISONED : SPELL_POISONED_H, true); } m_uiPoisonedSpearTimer = urand(5000, 10000); }else m_uiPoisonedSpearTimer -= uiDiff; if(m_uiCrushTimer < uiDiff) { if(m_creature->getVictim()) DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_CRUSH : SPELL_CRUSH_H); m_uiCrushTimer = urand(10000, 15000); }else m_uiCrushTimer -= uiDiff; if(m_uiWirlwhindTimer < uiDiff) { if(m_creature->getVictim()) m_creature->CastSpell(m_creature->getVictim(), m_bIsRegularMode ? SPELL_WHIRLWIND : SPELL_WHIRLWIND_H, false); m_uiWirlwhindTimer = urand(10000, 20000); }else m_uiWirlwhindTimer -= uiDiff; DoMeleeAttackIfReady(); } } }; CreatureAI* GetAI_boss_skadi(Creature* pCreature) { return new boss_skadiAI(pCreature); } bool AreaTrigger_at_skadi(Player* pPlayer, const AreaTriggerEntry* pAt) { if (ScriptedInstance* pInstance = (ScriptedInstance*)pPlayer->GetInstanceData()) { if (pInstance->GetData(TYPE_SKADI) == NOT_STARTED) pInstance->SetData(TYPE_SKADI, SPECIAL); } return false; } bool GOUse_go_skaldi_harpoonluncher(Player* pPlayer, GameObject* pGo) { ScriptedInstance* pInstance = (ScriptedInstance*)pGo->GetInstanceData(); if (!pInstance) return false; if(pPlayer->HasItemCount(ITEM_HARPOON,1)) { pInstance->SetData(TYPE_HARPOONLUNCHER, IN_PROGRESS); pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } return false; } void AddSC_boss_skadi() { Script *newscript; newscript = new Script; newscript->Name = "boss_skadi"; newscript->GetAI = &GetAI_boss_skadi; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "at_skadi"; newscript->pAreaTrigger = &AreaTrigger_at_skadi; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "go_skaldi_harpoonluncher"; newscript->pGOUse = &GOUse_go_skaldi_harpoonluncher; newscript->RegisterSelf(); }
34.078125
131
0.580376
mfooo
1f41f02babce5c8174ea2223f4dc7470452fbaf1
2,289
hpp
C++
src/tests/resources_utils.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
4,537
2015-01-01T03:26:40.000Z
2022-03-31T03:07:00.000Z
src/tests/resources_utils.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
227
2015-01-29T02:21:39.000Z
2022-03-29T13:35:50.000Z
src/tests/resources_utils.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
1,992
2015-01-05T12:29:19.000Z
2022-03-31T03:07:07.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __TESTS_RESOURCES_UTILS_HPP__ #define __TESTS_RESOURCES_UTILS_HPP__ #include <string> #include <ostream> #include <mesos/mesos.hpp> #include <mesos/resources.hpp> #include <stout/try.hpp> namespace mesos { namespace internal { namespace tests { // Returns a copy of the resources that are allocated to the role. // // TODO(bmahler): Consider adding a top-level `AllocatedResources` // that has the invariant that all resources contained within it // have an `AllocationInfo` set. This class could prevent // malformed operations between `Resources` and // `AllocatedResources`, and could clarify interfaces that take // allocated resources (e.g. allocator, sorter, etc). Resources allocatedResources( const Resources& resources, const std::string& role); // Creates a "ports(*)" resource for the given ranges. Resource createPorts(const ::mesos::Value::Ranges& ranges); // Fragments the given range bounds into a number of subranges. // Returns an Error if 'numRanges' is too large. E.g. // // [1-10], 1 -> [1-10] // [1-10], 2 -> [1-1,3-10] // [1-10], 3 -> [1-1,3-3,5-10] // [1-10], 4 -> [1-1,3-3,5-5,7-10] // [1-10], 5 -> [1-1,3-3,5-5,7-7,9-10] // [1-10], 6 -> Error // Try<::mesos::Value::Ranges> fragment( const ::mesos::Value::Range& bounds, size_t numRanges); ::mesos::Value::Range createRange(uint64_t begin, uint64_t end); } // namespace tests { } // namespace internal { } // namespace mesos { #endif // __TESTS_RESOURCES_UTILS_HPP__
33.173913
75
0.715159
zagrev
1f42d68cb36aa146cf4fbbbd3b6d66e8d0e563f5
3,148
hpp
C++
src/util/error.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
src/util/error.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
src/util/error.hpp
ssameerr/pytubes
6b4a839b7503780930b667cf12053089bc66c027
[ "MIT" ]
null
null
null
#pragma once #include <sstream> #include <ostream> #include <type_traits> #include <typeinfo> #include <new> #include <stdexcept> // This is a micro-optimization based on throws being unlikely // Taken from rapidjson source. #ifndef _SS_ERROR_UNLIKELY #if defined(__GNUC__) || defined(__clang__) #define _SS_ERROR_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define _SS_ERROR_UNLIKELY(x) (x) #endif #endif #ifndef _NOEXCEPT #define _NOEXCEPT noexcept #endif #if defined(__clang__) #define NORETURN_A [[noreturn]] #define NORETURN_B #else #define NORETURN_A #define NORETURN_B __attribute__((noreturn)) #endif template<typename... Ts> struct make_void { typedef void type;}; template<typename... Ts> using void_t = typename make_void<Ts...>::type; namespace ss{ using MemoryError = std::bad_alloc; using TypeError = std::bad_cast; using ValueError = std::invalid_argument; using IOError = std::ios_base::failure; using IndexError = std::out_of_range; using OverflowError = std::overflow_error; using ArithmeticError = std::range_error; using RuntimeError = std::runtime_error; class StopIterationExc: public std::exception {}; static StopIterationExc StopIteration; class PyExceptionRaisedExc: public std::exception {}; static PyExceptionRaisedExc PyExceptionRaised; class MissingValue: public std::exception { std::string why; public: MissingValue(std::string why): why(why) {} const char *what() const _NOEXCEPT { return why.c_str(); } }; template<class T, class Enable=void> struct has_ostream_operator : std::false_type {}; template<class T> struct has_ostream_operator<T, void_t<decltype(std::declval<std::ostream&>() << std::declval<T>())> > : std::true_type {}; static_assert(has_ostream_operator<int>::value, "has_ostream_operator failed, int has ostream << defined"); inline void _append_item(std::stringstream &ss){} template<class T> inline typename std::enable_if<has_ostream_operator<T>::value, void>::type _append_item(std::stringstream &ss, T const &first){ ss << first; } template<class T> inline typename std::enable_if<!has_ostream_operator<T>::value, void>::type _append_item(std::stringstream &ss, T const &first){ static_assert(has_ostream_operator<T>::value == false, "enable_if failed"); ss << std::string(first); } template<class T, class ...Args> inline void _append_item(std::stringstream &ss, T first, Args const &... rest) { _append_item(ss, first); _append_item(ss, rest...); } template<class ...Args> inline std::string make_str(Args const &... parts) { std::stringstream ss; _append_item(ss, parts...); return ss.str(); } #define throw_if(Ty, cond, args...) if(_SS_ERROR_UNLIKELY(cond)) { throw_py<Ty>(args);} #define static_throw_if(Ty, cond) if(_SS_ERROR_UNLIKELY(cond)) { throw Ty;} template<class T, class ...Args> NORETURN_A inline void NORETURN_B throw_py(Args const &... args){ throw T(make_str(args...)); } }
28.880734
126
0.683291
ssameerr
1f47ca018e6a97bf2d3b7463d96f15570a49f39d
3,189
cpp
C++
ue5/Blink_game/Blink_win32/winpi.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_win32/winpi.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
ue5/Blink_game/Blink_win32/winpi.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
#include "winpi.h" #include <thread> #include <stdexcept> #include <iostream> #include "WinpiEmulator.h" std::chrono::time_point<std::chrono::system_clock> start_time; int piHiPri(const int pri) { return 0; } void delay(unsigned int howLong) { std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(howLong)); } void delayMicroseconds(unsigned int howLong) { std::this_thread::sleep_for(std::chrono::duration<int, std::micro>(howLong)); } unsigned int millis(void) { return 0; } unsigned int micros(void) { return 0; } Win_pi_emulator& get_emulator() { static Win_pi_emulator winpi_emulator; return winpi_emulator; } int wiringPiFailure(int fatal, const char * message, ...) { throw std::runtime_error(message); } wiringPiNodeStruct * wiringPiFindNode(int pin) { return nullptr; } wiringPiNodeStruct * wiringPiNewNode(int pinBase, int numPins) { return nullptr; } int wiringPiSetup(void) { start_time = std::chrono::system_clock::now(); return 0; } int wiringPiSetupSys(void) { start_time = std::chrono::system_clock::now(); return 0; } int wiringPiSetupGpio(void) { start_time = std::chrono::system_clock::now(); return 0; } int wiringPiSetupPhys(void) { start_time = std::chrono::system_clock::now(); return 0; } void pinModeAlt(int pin, int mode) { } void pinMode(int pin, int mode) { std::cout << "WINPI: Setting pin mode for pin " << pin << " to mode " << mode << std::endl; get_emulator().add_pin(pin, mode == OUTPUT); } void pullUpDnControl(int pin, int pud) { } int digitalRead(int pin) { return get_emulator().get_state(pin); } void digitalWrite(int pin, int value) { std::cout << "WINPI: Setting value " << value << " on pin " << pin << std::endl; get_emulator().set_state(pin, value != 0); } void pwmWrite(int pin, int value) { std::cout << "WINPI: PWM write " << value << " on pin " << pin << std::endl; } int analogRead(int pin) { return 0; } void analogWrite(int pin, int value) { std::cout << "WINPI: Setting analog value " << value << " on pin " << value << std::endl; } int wiringPiSetupPiFace(void) { return 0; } int wiringPiSetupPiFaceForGpioProg(void) { return 0; } int piBoardRev(void) { return 42; } void piBoardId(int * model, int * rev, int * mem, int * maker, int * overVolted) { } int wpiPinToGpio(int wpiPin) { return 0; } int physPinToGpio(int physPin) { return 0; } void setPadDrive(int group, int value) { } int getAlt(int pin) { return 0; } void pwmToneWrite(int pin, int freq) { } void digitalWriteByte(int value) { } unsigned int digitalReadByte(void) { return 0; } void pwmSetMode(int mode) { } void pwmSetRange(unsigned int range) { } void pwmSetClock(int divisor) { } void gpioClockSet(int pin, int freq) { } int waitForInterrupt(int pin, int mS) { return 0; } int wiringPiISR(int pin, int mode, void(*function)(void)) { if(mode == INT_EDGE_BOTH || mode == INT_EDGE_FALLING) { get_emulator().subscribe_falling(pin, function); } if(mode == INT_EDGE_BOTH || mode == INT_EDGE_RISING) { get_emulator().subscribe_rising(pin, function); } return 0; } int piThreadCreate(void *(*fn)(void *)) { return 0; } void piLock(int key) { } void piUnlock(int key) { }
14.695853
92
0.688931
michivo
1f5498b92996628930463e2aea3e5b2286d33026
129
cpp
C++
openjudge/01/02/05.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2020-07-22T16:54:07.000Z
2020-07-22T16:54:07.000Z
openjudge/01/02/05.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2018-05-12T12:53:06.000Z
2018-05-12T12:53:06.000Z
openjudge/01/02/05.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
null
null
null
#include <cstdio> int main() { // printf("%.9f %.9f", float(1.000000001), double(1.000000001)); printf("F E"); return 0; }
14.333333
65
0.589147
TheBadZhang
1f5eb9b1a9186d488d2016004132cee6ea30dd7f
379
cpp
C++
Practica1/ProyectosOGREvc15x86/IG2App/EntidadIG.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica1/ProyectosOGREvc15x86/IG2App/EntidadIG.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica1/ProyectosOGREvc15x86/IG2App/EntidadIG.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
#include "EntidadIG.h" std::vector<EntidadIG*> EntidadIG::appListeners = std::vector<EntidadIG*>(0, nullptr); EntidadIG::EntidadIG(SceneNode* nodo) { mNode = nodo; mSM = mNode->getCreator(); } EntidadIG::~EntidadIG() { } void EntidadIG::sendEvent(EntidadIG* entidad, const OgreBites::KeyboardEvent& evt) { for (EntidadIG* e : appListeners) e->receiveEvent(this, evt); }
22.294118
86
0.71504
nicoFdez
1f5fb7f3d930faeb1dbe6876827617597a0a33ac
922
cpp
C++
systems/OutOfBoundsSystem.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
5
2016-03-15T20:14:10.000Z
2020-10-30T23:56:24.000Z
systems/OutOfBoundsSystem.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
3
2018-12-19T19:12:44.000Z
2020-04-02T13:07:00.000Z
systems/OutOfBoundsSystem.cpp
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
2
2016-04-11T19:29:28.000Z
2021-11-26T20:53:22.000Z
#include "Pos2DComponent.hh" #include "EntityDeletedEvent.hh" #include "TagComponent.hh" #include "OutOfBoundsSystem.hh" OutOfBoundsSystem::OutOfBoundsSystem() : ASystem("OutOfBoundsSystem") {} OutOfBoundsSystem::~OutOfBoundsSystem() {} //----- ----- Methods ----- ----- // bool OutOfBoundsSystem::canProcess(Entity *e) const { if (e->hasComponent("Pos2DComponent")) return (true); return (false); } void OutOfBoundsSystem::processEntity(Entity *e, const float) { Pos2DComponent *pos; if (!(pos = e->getComponent<Pos2DComponent>("Pos2DComponent"))) return ; if ((pos->getX() >= WINDOW_WIDTH + 50 || pos->getX() <= 0 - 50) || (pos->getY() >= WINDOW_HEIGHT + 50 || pos->getY() <= 0 - 50)) { TagComponent *tmp = e->getComponent<TagComponent>("TagComponent"); if (tmp && tmp->hasTag("do_not_delete")) return; this->_world->sendEvent(new EntityDeletedEvent(e, true)); } }
24.918919
70
0.655098
deb0ch
48fb03e7cdaf91128a4436c0fd9cc6c2cb4c0fbc
1,501
cpp
C++
Binary Tree/Traversal_Inorder_MooreTraversal.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Binary Tree/Traversal_Inorder_MooreTraversal.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Binary Tree/Traversal_Inorder_MooreTraversal.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Inorder traversal using Moore Traversal. /*this method doesn't require stack and is non-recursive. Makes a tree a temporarily a threaded binary tree then it reverts it back to its original form*/ #include<iostream> using namespace std; struct Node { int data; Node *left; Node *right; }; //creates node for the tree Node *create(int data) { try{ Node *node=new Node; node->data=data; node->left=NULL; node->right=NULL; return node; } catch(bad_alloc xa) { cout<<"Memory overflow!!"; return NULL; } } //inorder traversal using moore traversal method void mooreTraversal(Node *root) { if(root==NULL) return; Node *pre=NULL; while(root!=NULL) { //if there is no child go to the right child if(root->left==NULL) { cout<<root->data<<" "; root=root->right; } else { //if it has a left child then traverse to the rightmost node of the left child pre=root->left; while(pre->right!=NULL && pre->right!=root) pre=pre->right; //if it doesn't point to its successor then make it point if(pre->right==NULL) { pre->right=root; root=root->left; } //if it is already pointing to the successor then revert it back else { cout<<root->data<<" "; pre->right=NULL; root=root->right; } } } } int main() { Node *root=create(1); root->left=create(2); root->right=create(3); root->left->left=create(4); root->right->right=create(6); root->left->right=create(5); mooreTraversal(root); return 0; }1
17.658824
81
0.651566
susantabiswas
48fc359707a9cad58f8a3587d7a0d666a1ed3281
9,438
cc
C++
src/unix/riku_unix_thread.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
2
2019-03-22T05:01:03.000Z
2020-05-07T11:26:03.000Z
src/unix/riku_unix_thread.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
src/unix/riku_unix_thread.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
#include <riku/core.h> #include <riku/thread.h> #include <errno.h> #include <stdlib.h> #include <limits.h> #include <pthread.h> #if PLATFORM_OSX # include <mach/mach.h> # include <mach/task.h> # include <mach/semaphore.h> # include <TargetConditionals.h> #endif Atomic& Atomic::operator=(i64 value) { #ifdef __ATOMIC_RELAXED __atomic_exchange_n(&this->value, value, __ATOMIC_RELAXED); #else this->value = value; #endif return *this; } Atomic& Atomic::operator=(const Atomic& other) { #ifdef __ATOMIC_RELAXED __atomic_exchange_n(&this->value, other.value, __ATOMIC_RELAXED); #else this->value = other.value; #endif return *this; } Atomic& operator++(Atomic& atomic) { return (atomic += 1); } Atomic& operator--(Atomic& atomic) { return (atomic -= 1); } Atomic operator++(Atomic& atomic, int) { auto result = atomic; atomic += 1; return result; } Atomic operator--(Atomic& atomic, int) { auto result = atomic; atomic -= 1; return result; } Atomic& operator+=(Atomic& atomic, i64 value) { #ifdef __ATOMIC_RELAXED __atomic_add_fetch(&atomic.value, value, __ATOMIC_RELAXED); #else atomic.value += value; #endif return atomic; } Atomic& operator-=(Atomic& atomic, i64 value) { #ifdef __ATOMIC_RELAXED __atomic_sub_fetch(&atomic.value, value, __ATOMIC_RELAXED); #else atomic.value -= value; #endif return atomic; } Atomic& operator^=(Atomic& atomic, i64 value) { #ifdef __ATOMIC_RELAXED __atomic_xor_fetch(&atomic.value, value, __ATOMIC_RELAXED); #else atomic.value ^= value; #endif return atomic; } Atomic& operator|=(Atomic& atomic, i64 value) { #ifdef __ATOMIC_RELAXED __atomic_or_fetch(&atomic.value, value, __ATOMIC_RELAXED); #else atomic.value |= value; #endif return atomic; } Atomic& operator&=(Atomic& atomic, i64 value) { #ifdef __ATOMIC_RELAXED __atomic_and_fetch(&atomic.value, value, __ATOMIC_RELAXED); #else atomic.value &= value; #endif return atomic; } struct Thread::Context : public RefCount { pthread_t handle; Func<void(void)> routine; void stop(void) { #if PLATFORM_ANDROID pthread_kill((pthread_t)handle, SIGUSR1); // pthread_t #elif PLATFORM_UNIX pthread_cancel((pthread_t)handle); // pthread_t #endif handle = 0; } void wait(void) { pthread_join((pthread_t)handle, NULL); } }; static void* Thread_native_routine(void* params) { // Run thread routine Thread::Context* context = (Thread::Context*)params; if (context) { context->routine(); } // Clean up thread context->stop(); // End of thread return NULL; } void Thread::start(const Func<void(void)>& routine) { if (routine) { if (!context) { context = new (memory::allocator) Context(); } context->_incref(); context->routine = routine; pthread_create((pthread_t*)&context->handle, NULL, Thread_native_routine, context); } } void Thread::stop(void) { if (context) { context->stop(); this->~Thread(); } } void Thread::wait(void) { if (context) { context->wait(); } } Thread::~Thread(void) { if (context && context->_decref() <= 0) { context->~Context(); memory::dealloc(context); } } Thread::Thread(const Thread& other) : context(other.context) { if (context) { context->_incref(); } } Thread& Thread::operator=(const Thread& other) { context = other.context; if (context) { context->_incref(); } return *this; } Mutex::Mutex(void) { handle = memory::alloc(sizeof(pthread_mutex_t)); pthread_mutex_init((pthread_mutex_t*)handle, NULL); } Mutex::~Mutex(void) { pthread_mutex_destroy((pthread_mutex_t*)handle); memory::dealloc(handle); } void Mutex::lock(void) { pthread_mutex_lock((pthread_mutex_t*)handle); } bool Mutex::trylock(void) { return pthread_mutex_lock((pthread_mutex_t*)handle) == 0; } void Mutex::unlock(void) { pthread_mutex_unlock((pthread_mutex_t*)handle); } Condition::Condition(void) { handle = memory::alloc(sizeof(pthread_cond_t)); pthread_cond_init((pthread_cond_t*)handle, NULL); } Condition::~Condition(void) { #if defined(__APPLE__) && defined(__MACH__) /* It has been reported that destroying condition variables that have been * signalled but not waited on can sometimes result in application crashes. * See https://codereview.chromium.org/1323293005. */ pthread_mutex_t mutex; struct timespec ts; int err; if (pthread_mutex_init(&mutex, NULL)) { process::abort(); } if (pthread_mutex_lock(&mutex)) { process::abort(); } ts.tv_sec = 0; ts.tv_nsec = 1; err = pthread_cond_timedwait_relative_np((CONDITION_VARIABLE*)handle, &mutex, &ts); if (err != 0 && err != ETIMEDOUT) { process::abort(); } if (pthread_mutex_unlock(&mutex)) { process::abort(); } if (pthread_mutex_destroy(&mutex)) { process::abort(); } #endif /* defined(__APPLE__) && defined(__MACH__) */ if (pthread_cond_destroy((pthread_cond_t*)handle) != 0) { process::abort(); } memory::dealloc(handle); } void Condition::wait(const Mutex& mutex) { if (pthread_cond_wait((pthread_cond_t*)handle, (pthread_mutex_t*)mutex.handle)) { process::abort(); } } bool Condition::wait_timeout(const Mutex& mutex, long nanoseconds) { int r; struct timespec ts; #if defined(__MVS__) struct timeval tv; #endif #if defined(__APPLE__) && defined(__MACH__) ts.tv_sec = timeout / NANOSEC; ts.tv_nsec = timeout % NANOSEC; r = pthread_cond_timedwait_relative_np((pthread_cond_t*)handle, mutex, &ts); #else #if defined(__MVS__) if (gettimeofday(&tv, NULL)) { process::abort(); } timeout += tv.tv_sec * NANOSEC + tv.tv_usec * 1e3; #else //timeout += uv__hrtime(UV_CLOCK_PRECISE); #endif ts.tv_sec = nanoseconds / 1000000000; ts.tv_nsec = nanoseconds % 1000000000; #if defined(__ANDROID_API__) && __ANDROID_API__ < 21 /* * The bionic pthread implementation doesn't support CLOCK_MONOTONIC, * but has this alternative routine instead. */ r = pthread_cond_timedwait_monotonic_np((pthread_cond_t*)handle, (pthread_mutex_t*)mutex.handle, &ts); #else r = pthread_cond_timedwait((pthread_cond_t*)handle, (pthread_mutex_t*)mutex.handle, &ts); #endif /* __ANDROID_API__ */ #endif if (r == 0) { return true; } if (r == ETIMEDOUT) { return false; } process::abort(); return false; /* Satisfy the compiler. */ } void Condition::signal(void) { if (pthread_cond_signal((pthread_cond_t*)handle) != 0) { process::abort(); } } void Condition::broadcast(void) { if (pthread_cond_broadcast((pthread_cond_t*)handle) != 0) { process::abort(); } } #if PLATFORM_UNIX #define USE_CUSTOM_SEMAPHORE 1 #else #define USE_CUSTOM_SEMAPHORE 0 #endif #if USE_CUSTOM_SEMAPHORE struct SemaphoreContext { int count; Mutex mutex; Condition condition; SemaphoreContext(int count) : count(count) {} }; #endif Semaphore::Semaphore(int count) { #if USE_CUSTOM_SEMAPHORE handle = new (memory::allocator) SemaphoreContext(count); #elif PLATFORM_OSX kern_return_t err = semaphore_create(mach_task_self(), (semaphore_t*)&handle, SYNC_POLICY_FIFO, count); if (err != KERN_SUCCESS) { process::abort(); } #endif } Semaphore::~Semaphore(void) { #if USE_CUSTOM_SEMAPHORE ((SemaphoreContext*)handle)->~SemaphoreContext(); memory::dealloc(handle); #elif PLATFORM_OSX if (semaphore_destroy(mach_task_self(), (semaphore_t)handle)) { process::abort(); } #endif } void Semaphore::wait(void) { #if USE_CUSTOM_SEMAPHORE SemaphoreContext* ctx = (SemaphoreContext*)handle; ctx->mutex.lock(); while (ctx->count <= 0) { ctx->condition.wait(ctx->mutex); } ctx->count--; ctx->mutex.unlock(); #elif PLATFORM_OSX int r; do r = semaphore_wait((semaphore_t)handle); while (r == KERN_ABORTED); if (r != KERN_SUCCESS) { process::abort(); } #endif } void Semaphore::post(void) { #if USE_CUSTOM_SEMAPHORE SemaphoreContext* ctx = (SemaphoreContext*)handle; ctx->mutex.lock(); ctx->count++; if (ctx->count == 1) { ctx->condition.signal(); } ctx->mutex.unlock(); #elif PLATFORM_OSX if (semaphore_signal((semaphore_t)handle)) { process::abort(); } #endif } bool Semaphore::trywait(void) { #if USE_CUSTOM_SEMAPHORE SemaphoreContext* ctx = (SemaphoreContext*)handle; if (!ctx->mutex.trylock()) { return false; } if (ctx->count <= 0) { ctx->mutex.unlock(); return false; } ctx->count--; ctx->mutex.unlock(); return 0; #elif PLATFORM_OSX mach_timespec_t interval; kern_return_t err; interval.tv_sec = 0; interval.tv_nsec = 0; err = semaphore_timedwait((semaphore_t)handle, interval); if (err == KERN_SUCCESS) return true; if (err == KERN_OPERATION_TIMED_OUT) return false; process::abort(); return false; /* Satisfy the compiler. */ #endif }
19.182927
107
0.637105
maihd
48febd672eaff92fadac567e9e4e8baa1d95c193
217
cpp
C++
auv_gnc/src/trans_ekf_node.cpp
osu-uwrt/auv_gnc
40dbe4bda0c00fd41ed714cc2ea82f0c319e5e46
[ "BSD-2-Clause" ]
31
2019-08-07T08:04:51.000Z
2022-03-19T10:03:42.000Z
auv_gnc/src/trans_ekf_node.cpp
Chandler-Xu/auv_gnc
9e9efb49fd2a88a76b97c2381bb6138ec7513520
[ "BSD-2-Clause" ]
null
null
null
auv_gnc/src/trans_ekf_node.cpp
Chandler-Xu/auv_gnc
9e9efb49fd2a88a76b97c2381bb6138ec7513520
[ "BSD-2-Clause" ]
11
2019-09-17T14:01:01.000Z
2022-03-16T11:45:33.000Z
#include "auv_gnc/trans_ekf.hpp" #include <ros/ros.h> int main(int argc, char** argv) { ros::init(argc, argv, "trans_ekf"); ros::NodeHandle nh("~"); auv_gnc::TransEKF transEKF(nh); ros::spin(); return 0; }
19.727273
37
0.645161
osu-uwrt
48fec9e4a5f6caeca2df101e56cd6ee97afc3999
1,417
cpp
C++
lib/model/src/initializer.cpp
KaungZawHtet/XMwayLoon
4dd014dc75a209c242bba5d2dc4333af63bcb405
[ "Unlicense" ]
6
2020-03-23T04:20:53.000Z
2020-05-23T00:32:36.000Z
lib/model/src/initializer.cpp
KaungZawHtet/XMwayLoon
4dd014dc75a209c242bba5d2dc4333af63bcb405
[ "Unlicense" ]
null
null
null
lib/model/src/initializer.cpp
KaungZawHtet/XMwayLoon
4dd014dc75a209c242bba5d2dc4333af63bcb405
[ "Unlicense" ]
null
null
null
// // Created by Kaung Zaw Htet on 2020-01-10. // #include <model/db/initializer.h> #include <stdlib.h> #include <dry_comparisons/dry_comparisons.h> namespace fs = std::filesystem; using rollbear::all_of; static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } void Initializer::createDirectory() { if (!fs::exists(directory)) fs::create_directory(directory); } void Initializer::createDatabase() { int rc = sqlite3_open(dbPath.c_str(), &db); if (rc) exit(rc); else Initializer::createTables(); } void Initializer::createTables() { char *zErrMsg = 0; int rc1 = sqlite3_exec(db, sqlCreate_NameProperties.data(), callback, 0, &zErrMsg); int rc2 = sqlite3_exec(db, sqlCreate_CustomTypeName.data(), callback, 0, &zErrMsg); int rc3 = sqlite3_exec(db, sqlCreate_LastRan.data(), callback, 0, &zErrMsg); int rc4 = sqlite3_exec(db, sqlCreate_CustomTypeRecord.data(), callback, 0, &zErrMsg); if(all_of{rc1,rc2,rc3,rc4} !=SQLITE_OK) { exit(0); } else{ int rc4 = sqlite3_exec(db, sqlInsert_NameProperties.data(), callback, 0, &zErrMsg); } sqlite3_close(db); } void Initializer::initialize() { Initializer::createDirectory(); Initializer::createDatabase(); }
23.616667
91
0.652788
KaungZawHtet
5b085b2f5ea8800c8a81bdb5257b67ccf45bac5c
2,172
cpp
C++
src/armnn/memory/BlobLifetimeManager.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/memory/BlobLifetimeManager.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/memory/BlobLifetimeManager.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include "BlobLifetimeManager.hpp" #include "BlobMemoryPool.hpp" #include "arm_compute/runtime/IMemoryGroup.h" #include "boost/assert.hpp" #include <algorithm> namespace armnn { BlobLifetimeManager::BlobLifetimeManager() : m_BlobSizes() { } arm_compute::MappingType BlobLifetimeManager::mapping_type() const { return arm_compute::MappingType::BLOBS; } void BlobLifetimeManager::update_blobs_and_mappings() { using namespace arm_compute; BOOST_ASSERT(are_all_finalized()); BOOST_ASSERT(_active_group); // Sort free blobs requirements in descending order. _free_blobs.sort([](const Blob & ba, const Blob & bb) { return ba.max_size > bb.max_size; }); std::vector<size_t> groupSizes; std::transform(std::begin(_free_blobs), std::end(_free_blobs), std::back_inserter(groupSizes), [](const Blob & b) { return b.max_size; }); // Update blob sizes size_t max_size = std::max(m_BlobSizes.size(), groupSizes.size()); m_BlobSizes.resize(max_size, 0); groupSizes.resize(max_size, 0); std::transform(std::begin(m_BlobSizes), std::end(m_BlobSizes), std::begin(groupSizes), std::begin(m_BlobSizes), [](size_t lhs, size_t rhs) { return std::max(lhs, rhs); }); // Calculate group mappings auto& groupMappings = _active_group->mappings(); unsigned int blobIdx = 0; for(auto& freeBlob : _free_blobs) { for(auto& boundElementId : freeBlob.bound_elements) { BOOST_ASSERT(_active_elements.find(boundElementId) != std::end(_active_elements)); Element& boundElement = _active_elements[boundElementId]; groupMappings[boundElement.handle] = blobIdx; } ++blobIdx; } } std::unique_ptr<arm_compute::IMemoryPool> BlobLifetimeManager::create_pool(arm_compute::IAllocator* allocator) { BOOST_ASSERT(allocator); return std::make_unique<BlobMemoryPool>(allocator, m_BlobSizes); } } // namespace armnn
27.493671
117
0.671731
KevinRodrigues05
5b0adc2285836b350247570a65ea4c98505183ee
1,010
cpp
C++
Source/modules/imogen_dsp/Engine/effects/PreHarmony/NoiseGate.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
109
2020-11-24T05:17:12.000Z
2022-03-25T17:03:16.000Z
Source/modules/imogen_dsp/Engine/effects/PreHarmony/NoiseGate.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
7
2021-02-19T07:22:03.000Z
2022-03-17T17:23:56.000Z
Source/modules/imogen_dsp/Engine/effects/PreHarmony/NoiseGate.cpp
msameen99/imogen
7efd3054a93d91f44f22cc2d6200f550e4aedd4c
[ "MIT" ]
4
2021-04-05T14:11:42.000Z
2021-10-02T15:46:49.000Z
namespace Imogen { template < typename SampleType > NoiseGate< SampleType >::NoiseGate (State& stateToUse) : state (stateToUse) { // static constexpr auto noiseGateAttackMs = 25.0f; // static constexpr auto noiseGateReleaseMs = 100.0f; // static constexpr auto noiseGateFloorRatio = 10.0f; // ratio to one when the noise gate is activated } template < typename SampleType > void NoiseGate< SampleType >::process (AudioBuffer& audio) { if (parameters.noiseGateToggle->get()) { gate.setThreshold (parameters.noiseGateThresh->get()); gate.process (audio); meters.gateRedux->set (static_cast< float > (gate.getAverageGainReduction())); } else { meters.gateRedux->set (0.f); } } template < typename SampleType > void NoiseGate< SampleType >::prepare (double samplerate, int blocksize) { gate.prepare (samplerate, blocksize); } template struct NoiseGate< float >; template struct NoiseGate< double >; } // namespace Imogen
25.897436
110
0.686139
msameen99
5b1189374e67ed1844515ec8f256e82d817027aa
2,065
cpp
C++
TE2502/src/graphics/framebuffer.cpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
TE2502/src/graphics/framebuffer.cpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
TE2502/src/graphics/framebuffer.cpp
ferthu/TE2502
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
[ "MIT" ]
null
null
null
#include <utility> #include "framebuffer.hpp" #include "utilities.hpp" Framebuffer::Framebuffer() { } Framebuffer::Framebuffer(VulkanContext& context) : m_context(&context) { } Framebuffer::~Framebuffer() { destroy(); } Framebuffer::Framebuffer(Framebuffer&& other) { move_from(std::move(other)); } Framebuffer& Framebuffer::operator=(Framebuffer&& other) { if (this != &other) move_from(std::move(other)); return *this; } void Framebuffer::add_attachment(ImageView& image_view) { m_attachments.push_back(image_view.get_view()); } void Framebuffer::create(VkRenderPass render_pass, uint32_t width, uint32_t height) { m_width = width; m_height = height; assert(m_framebuffer == VK_NULL_HANDLE); assert(m_attachments.size()); VkFramebufferCreateInfo framebuffer_info; framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebuffer_info.pNext = nullptr; framebuffer_info.flags = 0; framebuffer_info.renderPass = render_pass; framebuffer_info.attachmentCount = static_cast<uint32_t>(m_attachments.size()); framebuffer_info.pAttachments = m_attachments.data(); framebuffer_info.width = width; framebuffer_info.height = height; framebuffer_info.layers = 1; VK_CHECK(vkCreateFramebuffer(m_context->get_device(), &framebuffer_info, m_context->get_allocation_callbacks(), &m_framebuffer), "Failed to create frame buffer!"); } VkFramebuffer Framebuffer::get_framebuffer() { return m_framebuffer; } uint32_t Framebuffer::get_width() const { return m_width; } uint32_t Framebuffer::get_height() const { return m_height; } void Framebuffer::move_from(Framebuffer&& other) { destroy(); m_context = other.m_context; m_framebuffer = other.m_framebuffer; other.m_framebuffer = VK_NULL_HANDLE; m_width = other.m_width; m_height = other.m_height; m_attachments = std::move(other.m_attachments); } void Framebuffer::destroy() { if (m_framebuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(m_context->get_device(), m_framebuffer, m_context->get_allocation_callbacks()); m_framebuffer = VK_NULL_HANDLE; } }
20.858586
130
0.768523
ferthu
5b17d49df7dc31438b3a083f96383cf5c0b08046
1,768
hpp
C++
graphics/shaders/SlGeneratorInstance.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
graphics/shaders/SlGeneratorInstance.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
graphics/shaders/SlGeneratorInstance.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_GRAPHICS_SHADERS_SL_GENERATOR_INSTANCE_HPP___ #define ___INANITY_GRAPHICS_SHADERS_SL_GENERATOR_INSTANCE_HPP___ #include "ShaderType.hpp" #include "../DataType.hpp" #include <vector> #include <unordered_set> #include <unordered_map> #include <sstream> BEGIN_INANITY_SHADERS class Node; class ValueNode; class AttributeNode; class UniformGroup; class UniformNode; class SamplerNode; class TransformedNode; class InterpolateNode; /// Base class for HLSL11 and GLSL shader generators. class SlGeneratorInstance { protected: /// Root node of shader's source code. ptr<Node> rootNode; /// Type of the shader. ShaderType shaderType; /// Text of the shader in language. std::ostringstream text; /// Registered nodes. std::unordered_set<Node*> registeredNodes; /// Nodes in order of initialization. std::vector<Node*> nodeInits; /// Node indices in order of initialization. std::unordered_map<Node*, int> nodeInitIndices; std::vector<AttributeNode*> attributes; /// Univorm variables by groups. std::vector<std::pair<UniformGroup*, UniformNode*> > uniforms; std::vector<SamplerNode*> samplers; std::vector<TransformedNode*> transformedNodes; std::vector<InterpolateNode*> interpolateNodes; int fragmentTargetsCount; bool dualFragmentTarget; protected: virtual void PrintDataType(DataType dataType) = 0; void RegisterNode(Node* node); /// Print node representation (actually a temporary variable of node). void PrintNode(ValueNode* node); void PrintUniform(UniformNode* uniformNode); /// Helpers to print node init. void PrintNodeInitVar(size_t nodeIndex); void PrintNodeInitBegin(size_t nodeIndex); void PrintNodeInitEnd(); SlGeneratorInstance(ptr<Node> rootNode, ShaderType shaderType); }; END_INANITY_SHADERS #endif
26.787879
71
0.785633
quyse
5b21661b11762395e96a0d6ce6d4abd1778b9a82
1,309
hpp
C++
include/ER_General.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
3
2018-09-13T13:36:50.000Z
2021-10-30T19:35:12.000Z
include/ER_General.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
2
2017-06-06T14:43:45.000Z
2022-03-16T13:01:56.000Z
include/ER_General.hpp
temken/DaMaSCUS
14be6907230e5ef1b93809a6fb5842330497a7a6
[ "MIT" ]
1
2017-06-09T09:48:10.000Z
2017-06-09T09:48:10.000Z
//Contains non-detector-specific functions related with direct detection rates. #ifndef __ER_General_hpp_ #define __ER_General_hpp_ #include <vector> //Analytic //Velocity necessary for a DM particle of mass mChi to recoil a nucleus of mass number A with a given recoil energy. extern double vMinimal(double RecoilEnergy,double mChi,double A); //Maximum recoil energy a DM particle of mass mChi and speed v can cause on a nucleus of mass number A extern double ERMax(double v,double mChi,double A); //Eta-Function: Integral of f(v)/v with lower integration limit v_Min extern double EtaFunctionA(double vMin,double vE); //Direct detection recoil spectrum extern double dRdErA(double ER,double X,double A,double rhoDM,double mChi,double sigma,double vE); //Monte Carlo //Eta function extern std::vector<std::vector<double>> EtaHistogram(std::vector<std::vector<double>> &velocityhistogram); extern std::vector<double> EtaFunctionMC(double vMin,std::vector<std::vector<double>> &etaarray); //Recoil spectrum extern std::vector< std::vector< double > > dRdEHistogram(double X,double A,std::vector<double> rhoDM,double mChi,double sigma,std::vector<std::vector<double>> &etahistogram); extern std::vector<double> dRdEMC(double ER,std::vector<std::vector<double>> &drdehisto); #endif
46.75
177
0.770053
temken
5b2367504def4f2a406822fb6d44d55bdc5e9d0a
433
cpp
C++
src/classwork/03_assign/loops.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-jonsanmigel1
e46a4b98377d10ea989bb656c799d7fcae3d238f
[ "MIT" ]
null
null
null
src/classwork/03_assign/loops.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-jonsanmigel1
e46a4b98377d10ea989bb656c799d7fcae3d238f
[ "MIT" ]
null
null
null
src/classwork/03_assign/loops.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-jonsanmigel1
e46a4b98377d10ea989bb656c799d7fcae3d238f
[ "MIT" ]
null
null
null
/* WITH LOOP OF YOUR CHOICE: Write code for function factorial that accepts an int num and returns the num's factorial factorial(5); 1*2*3*4*5 returns 120 test after fail to pull 1/31 DON'T FORGET TO WRITE TEST CASE. See file loop_test.cpp */ #include "loops.h" #include <iostream> using namespace std; int factorial(int num) { int total = 1; for (int i = 1; i < num + 1; i++) { total = i * total; } return total; }
13.53125
57
0.676674
acc-cosc-1337-spring-2020
5b25370e35d54822876f0dfe7ee22bcf366f2e97
4,072
cpp
C++
test_package/tests/unit/geom/GeometryCollectionTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/GeometryCollectionTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/GeometryCollectionTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
// // Test Suite for geos::geom::GeometryCollection class. #include <tut/tut.hpp> #include <utility.h> #include <memory> namespace tut { // // Test Group // // Common data used by tests struct test_geometry_collection_data { typedef geos::geom::GeometryFactory GeometryFactory; geos::geom::PrecisionModel pm_; GeometryFactory::Ptr factory_; std::unique_ptr<geos::geom::Geometry> empty_gc_; std::unique_ptr<geos::geom::Geometry> readWKT(std::string wkt) { geos::io::WKTReader reader; return std::unique_ptr<geos::geom::Geometry>(reader.read(wkt)); } test_geometry_collection_data() : pm_(1000), factory_(GeometryFactory::create(&pm_, 0)), empty_gc_(factory_->createGeometryCollection()) { } }; typedef test_group<test_geometry_collection_data> group; typedef group::object object; group test_geometry_collection_group("geos::geom::GeometryCollection"); // // Test Cases // // Test of user's constructor to build empty Point template<> template<> void object::test<1> () { using geos::geom::Geometry; std::unique_ptr<Geometry> empty_point(factory_->createPoint()); ensure(empty_point != nullptr); geos::geom::Coordinate coord(1, 2); std::unique_ptr<Geometry> point(factory_->createPoint(coord)); ensure(point != nullptr); std::vector<const Geometry*> geoms{empty_point.get(), point.get()}; std::unique_ptr<Geometry> col(factory_->createGeometryCollection(geoms)); ensure(col != nullptr); ensure(col->getCoordinate() != nullptr); ensure_equals(col->getCoordinate()->x, 1); ensure_equals(col->getCoordinate()->y, 2); } // Test of default constructor template<> template<> void object::test<2> () { using geos::geom::Geometry; geos::geom::PrecisionModel pm; auto gf = GeometryFactory::create(&pm, 1); std::unique_ptr<Geometry> g(gf->createEmptyGeometry()); g->setSRID(0); std::vector<const Geometry*> v = {g.get()}; std::unique_ptr<Geometry> geom_col(gf->createGeometryCollection(v)); ensure_equals(geom_col->getGeometryN(0)->getSRID(), 1); geom_col->setSRID(2); ensure_equals(geom_col->getGeometryN(0)->getSRID(), 2); std::unique_ptr<Geometry> clone(geom_col->clone()); ensure_equals(clone->getGeometryN(0)->getSRID(), 2); } // test getCoordinate() returns nullptr for empty geometry template<> template<> void object::test<3> () { ensure(empty_gc_->getCoordinate() == nullptr); } // test isDimensionStrict for empty GeometryCollection template<> template<> void object::test<4> () { // Empty GeometryCollection passes isDimensionStrict for any input ensure(empty_gc_->isDimensionStrict(geos::geom::Dimension::P)); ensure(empty_gc_->isDimensionStrict(geos::geom::Dimension::L)); ensure(empty_gc_->isDimensionStrict(geos::geom::Dimension::A)); } // test isDimensionStrict for homogeneous GeometryCollections template<> template<> void object::test<5> () { auto point = readWKT("GEOMETRYCOLLECTION(POINT (1 1), POINT(2 2))"); auto line = readWKT("GEOMETRYCOLLECTION(LINESTRING (1 1, 2 2), LINESTRING (3 8, 3 9))"); auto poly = readWKT("GEOMETRYCOLLECTION(POLYGON ((1 1, 2 1, 2 2, 1 1)))"); ensure(point->isDimensionStrict(geos::geom::Dimension::P)); ensure(line->isDimensionStrict(geos::geom::Dimension::L)); ensure(poly->isDimensionStrict(geos::geom::Dimension::A)); ensure(!point->isDimensionStrict(geos::geom::Dimension::L)); ensure(!line->isDimensionStrict(geos::geom::Dimension::A)); ensure(!poly->isDimensionStrict(geos::geom::Dimension::P)); } // test isDimensionStrict for heterogeneous GeometryCollections template<> template<> void object::test<6> () { // Heterogenous GeometryCollection does not pass isDimensionString for any input auto gc = readWKT("GEOMETRYCOLLECTION(POINT (1 1), LINESTRING (1 1, 2 2))"); ensure(!gc->isDimensionStrict(geos::geom::Dimension::P)); ensure(!gc->isDimensionStrict(geos::geom::Dimension::L)); ensure(!gc->isDimensionStrict(geos::geom::Dimension::A)); } } // namespace tut
27.70068
112
0.699902
insaneFactory
5b2be1da8a5ecb962af366952b1eb4715227fb22
11,135
hxx
C++
include/rtkDaubechiesWaveletsConvolutionImageFilter.hxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
167
2015-02-26T08:39:33.000Z
2022-03-31T04:40:35.000Z
include/rtkDaubechiesWaveletsConvolutionImageFilter.hxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
270
2015-02-26T15:34:32.000Z
2022-03-22T09:49:24.000Z
include/rtkDaubechiesWaveletsConvolutionImageFilter.hxx
agravgaard/RTK
419f71cdaf0600fcb54e4faca643121b7832ea96
[ "Apache-2.0", "BSD-3-Clause" ]
117
2015-05-01T14:56:49.000Z
2022-03-11T03:18:26.000Z
/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 rtkDaubechiesWaveletsConvolutionImageFilter_hxx #define rtkDaubechiesWaveletsConvolutionImageFilter_hxx // Includes #include "rtkDaubechiesWaveletsConvolutionImageFilter.h" #include <vector> #include <algorithm> #include <itkImageRegionIterator.h> namespace rtk { template <typename TImage> DaubechiesWaveletsConvolutionImageFilter<TImage>::DaubechiesWaveletsConvolutionImageFilter() { this->SetDeconstruction(); } template <typename TImage> DaubechiesWaveletsConvolutionImageFilter<TImage>::~DaubechiesWaveletsConvolutionImageFilter() = default; template <typename TImage> void DaubechiesWaveletsConvolutionImageFilter<TImage>::SetDeconstruction() { m_Type = Self::Deconstruct; } template <typename TImage> void DaubechiesWaveletsConvolutionImageFilter<TImage>::SetReconstruction() { m_Type = Self::Reconstruct; } template <typename TImage> void DaubechiesWaveletsConvolutionImageFilter<TImage>::PrintSelf(std::ostream & os, itk::Indent i) const { os << i << "DaubechiesWaveletsConvolutionImageFilter { this=" << this << " }" << std::endl; os << i << "m_Order=" << this->GetOrder() << std::endl; os << i << "m_Pass=" << std::endl; for (unsigned int dim = 0; dim < TImage::ImageDimension; dim++) { os << i << i << this->m_Pass[dim] << std::endl; } os << i << "m_Type=" << this->m_Type << std::endl; Superclass::PrintSelf(os, i.GetNextIndent()); } template <typename TImage> typename DaubechiesWaveletsConvolutionImageFilter<TImage>::CoefficientVector DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateCoefficientsLowpassDeconstruct() { CoefficientVector coeff; switch (this->GetOrder()) { case 1: coeff.push_back(1.0 / itk::Math::sqrt2); coeff.push_back(1.0 / itk::Math::sqrt2); break; case 2: coeff.push_back(-0.1830127 / itk::Math::sqrt2); coeff.push_back(0.3169873 / itk::Math::sqrt2); coeff.push_back(1.1830127 / itk::Math::sqrt2); coeff.push_back(0.6830127 / itk::Math::sqrt2); break; case 3: coeff.push_back(0.0498175 / itk::Math::sqrt2); coeff.push_back(-0.12083221 / itk::Math::sqrt2); coeff.push_back(-0.19093442 / itk::Math::sqrt2); coeff.push_back(0.650365 / itk::Math::sqrt2); coeff.push_back(1.14111692 / itk::Math::sqrt2); coeff.push_back(0.47046721 / itk::Math::sqrt2); break; case 4: coeff.push_back(-0.01498699 / itk::Math::sqrt2); coeff.push_back(0.0465036 / itk::Math::sqrt2); coeff.push_back(0.0436163 / itk::Math::sqrt2); coeff.push_back(-0.26450717 / itk::Math::sqrt2); coeff.push_back(-0.03957503 / itk::Math::sqrt2); coeff.push_back(0.8922014 / itk::Math::sqrt2); coeff.push_back(1.01094572 / itk::Math::sqrt2); coeff.push_back(0.32580343 / itk::Math::sqrt2); break; case 5: coeff.push_back(0.00471742793 / itk::Math::sqrt2); coeff.push_back(-0.01779187 / itk::Math::sqrt2); coeff.push_back(-0.00882680 / itk::Math::sqrt2); coeff.push_back(0.10970265 / itk::Math::sqrt2); coeff.push_back(-0.04560113 / itk::Math::sqrt2); coeff.push_back(-0.34265671 / itk::Math::sqrt2); coeff.push_back(0.19576696 / itk::Math::sqrt2); coeff.push_back(1.02432694 / itk::Math::sqrt2); coeff.push_back(0.85394354 / itk::Math::sqrt2); coeff.push_back(0.22641898 / itk::Math::sqrt2); break; case 6: coeff.push_back(-0.00152353381 / itk::Math::sqrt2); coeff.push_back(0.00675606236 / itk::Math::sqrt2); coeff.push_back(0.000783251152 / itk::Math::sqrt2); coeff.push_back(-0.04466375 / itk::Math::sqrt2); coeff.push_back(0.03892321 / itk::Math::sqrt2); coeff.push_back(0.13788809 / itk::Math::sqrt2); coeff.push_back(-0.18351806 / itk::Math::sqrt2); coeff.push_back(-0.31998660 / itk::Math::sqrt2); coeff.push_back(0.44583132 / itk::Math::sqrt2); coeff.push_back(1.06226376 / itk::Math::sqrt2); coeff.push_back(0.69950381 / itk::Math::sqrt2); coeff.push_back(0.15774243 / itk::Math::sqrt2); break; case 7: coeff.push_back(0.000500226853 / itk::Math::sqrt2); coeff.push_back(-0.00254790472 / itk::Math::sqrt2); coeff.push_back(0.000607514995 / itk::Math::sqrt2); coeff.push_back(0.01774979 / itk::Math::sqrt2); coeff.push_back(-0.02343994 / itk::Math::sqrt2); coeff.push_back(-0.05378245 / itk::Math::sqrt2); coeff.push_back(0.11400345 / itk::Math::sqrt2); coeff.push_back(0.1008467 / itk::Math::sqrt2); coeff.push_back(-0.31683501 / itk::Math::sqrt2); coeff.push_back(-0.20351382 / itk::Math::sqrt2); coeff.push_back(0.66437248 / itk::Math::sqrt2); coeff.push_back(1.03114849 / itk::Math::sqrt2); coeff.push_back(0.56079128 / itk::Math::sqrt2); coeff.push_back(0.11009943 / itk::Math::sqrt2); break; default: itkGenericExceptionMacro(<< "In rtkDaubechiesWaveletsConvolutionImageFilter.hxx: Order should be <= 7."); } // end case(Order) return coeff; } template <typename TImage> typename DaubechiesWaveletsConvolutionImageFilter<TImage>::CoefficientVector DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateCoefficientsHighpassDeconstruct() { CoefficientVector coeff = this->GenerateCoefficientsLowpassDeconstruct(); std::reverse(coeff.begin(), coeff.end()); unsigned int it = 0; double factor = -1; for (it = 0; it < coeff.size(); it++) { coeff[it] *= factor; factor *= -1; } return coeff; } template <typename TImage> typename DaubechiesWaveletsConvolutionImageFilter<TImage>::CoefficientVector DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateCoefficientsLowpassReconstruct() { CoefficientVector coeff = this->GenerateCoefficientsLowpassDeconstruct(); std::reverse(coeff.begin(), coeff.end()); return coeff; } template <typename TImage> typename DaubechiesWaveletsConvolutionImageFilter<TImage>::CoefficientVector DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateCoefficientsHighpassReconstruct() { CoefficientVector coeff = this->GenerateCoefficientsHighpassDeconstruct(); std::reverse(coeff.begin(), coeff.end()); return coeff; } template <typename TImage> void DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateOutputInformation() { unsigned int dim = TImage::ImageDimension; std::vector<typename TImage::Pointer> kernelImages; std::vector<typename ConvolutionFilterType::Pointer> convolutionFilters; // Create and connect as many Convolution filters as the number of dimensions for (unsigned int d = 0; d < dim; d++) { // Create the 1-D kernel image typename TImage::SizeType kernelSize; kernelSize.Fill(1); kernelSize[d] = 2 * m_Order; typename TImage::IndexType kernelIndex; kernelIndex.Fill(0); typename TImage::RegionType kernelRegion; kernelRegion.SetSize(kernelSize); kernelRegion.SetIndex(kernelIndex); kernelImages.push_back(TImage::New()); kernelImages[d]->SetRegions(kernelRegion); // Create the convolution filters convolutionFilters.push_back(ConvolutionFilterType::New()); convolutionFilters[d]->SetKernelImage(kernelImages[d]); convolutionFilters[d]->SetOutputRegionModeToValid(); if (d == 0) convolutionFilters[d]->SetInput(this->GetInput()); else convolutionFilters[d]->SetInput(convolutionFilters[d - 1]->GetOutput()); } // Generate output information convolutionFilters[dim - 1]->UpdateOutputInformation(); // Copy it to the output this->GetOutput()->CopyInformation(convolutionFilters[dim - 1]->GetOutput()); } template <typename TImage> void DaubechiesWaveletsConvolutionImageFilter<TImage>::GenerateData() { int dim = TImage::ImageDimension; // Create a vector holding the coefficients along each direction auto * coeffs = new CoefficientVector[dim]; for (int d = 0; d < dim; d++) { if (m_Type == Self::Deconstruct) { switch (m_Pass[d]) { case Self::Low: coeffs[d] = GenerateCoefficientsLowpassDeconstruct(); break; case Self::High: coeffs[d] = GenerateCoefficientsHighpassDeconstruct(); break; default: itkGenericExceptionMacro("In rtkDaubechiesWaveletsConvolutionImageFilter : unknown pass"); } } if (m_Type == Self::Reconstruct) { switch (m_Pass[d]) { case Self::Low: coeffs[d] = GenerateCoefficientsLowpassReconstruct(); break; case Self::High: coeffs[d] = GenerateCoefficientsHighpassReconstruct(); break; default: itkGenericExceptionMacro("In rtkDaubechiesWaveletsConvolutionImageFilter : unknown pass"); } } } std::vector<typename TImage::Pointer> kernelImages; std::vector<typename ConvolutionFilterType::Pointer> convolutionFilters; using KernelIteratorType = itk::ImageRegionIterator<TImage>; // Convolve the input "Dimension" times, each time with a 1-D kernel for (int d = 0; d < dim; d++) { // Create the 1-D kernel image typename TImage::SizeType kernelSize; kernelSize.Fill(1); kernelSize[d] = 2 * m_Order; typename TImage::IndexType kernelIndex; kernelIndex.Fill(0); typename TImage::RegionType kernelRegion; kernelRegion.SetSize(kernelSize); kernelRegion.SetIndex(kernelIndex); kernelImages.push_back(TImage::New()); kernelImages[d]->SetRegions(kernelRegion); kernelImages[d]->Allocate(); KernelIteratorType kernelIt(kernelImages[d], kernelImages[d]->GetLargestPossibleRegion()); int pos = 0; while (!kernelIt.IsAtEnd()) { kernelIt.Set(coeffs[d][pos]); pos++; ++kernelIt; } // Create the convolution filters convolutionFilters.push_back(ConvolutionFilterType::New()); convolutionFilters[d]->SetKernelImage(kernelImages[d]); convolutionFilters[d]->SetOutputRegionModeToValid(); if (d == 0) convolutionFilters[d]->SetInput(this->GetInput()); else convolutionFilters[d]->SetInput(convolutionFilters[d - 1]->GetOutput()); } // Generate output information convolutionFilters[dim - 1]->Update(); this->GraftOutput(convolutionFilters[dim - 1]->GetOutput()); // Clean up delete[] coeffs; } } // end namespace rtk #endif
33.844985
111
0.680467
agravgaard
5b2c7495d5895c5af81f5d367dd6ffc04e55cacf
1,222
cpp
C++
src/threading/event.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
null
null
null
src/threading/event.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
49
2020-08-24T18:09:35.000Z
2022-02-13T22:19:39.000Z
src/threading/event.cpp
tobiasanker/libKitsunemimiCommon
d40d1314db0a6d7e04afded09cb4934e01828ac4
[ "MIT" ]
1
2020-08-29T14:30:41.000Z
2020-08-29T14:30:41.000Z
/** * @file event.cpp * * @author Tobias Anker <tobias.anker@kitsunemimi.moe> * * @copyright MIT License */ #include <libKitsunemimiCommon/threading/event.h> namespace Kitsunemimi { //================================================================================================== // Event //================================================================================================== Event::~Event() {} //================================================================================================== // SleepEvent //================================================================================================== /** * @brief constructor * @param milliSeconds time in milli-seconds, which the event should sleep */ SleepEvent::SleepEvent(const uint64_t milliSeconds) { m_milliSeconds = milliSeconds; } /** * @brief destructor */ SleepEvent::~SleepEvent() {} /** * @brief process sleep-event * @return false, if invalid time was set of zero milliseconds was set, else true */ bool SleepEvent::processEvent() { if(m_milliSeconds == 0) { return false; } std::this_thread::sleep_for(std::chrono::milliseconds(m_milliSeconds)); return true; } }
22.218182
100
0.447627
kitsudaiki
5b2cbca166899dc77ae502507f9c60c1b131c9f7
1,849
hh
C++
src/RealmzGlobalData.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
1
2018-03-20T13:06:16.000Z
2018-03-20T13:06:16.000Z
src/RealmzGlobalData.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
null
null
null
src/RealmzGlobalData.hh
fuzziqersoftware/realmz_dasm
fbfa118de5f232fd7169fbff13d434164a67ee90
[ "MIT" ]
null
null
null
#pragma once #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <phosg/Image.hh> #include <unordered_map> #include <unordered_set> #include <vector> #include <string> #include "ResourceFile.hh" std::unordered_map<int16_t, Image> rsf_picts(ResourceFile& rf); std::unordered_map<int16_t, ResourceFile::DecodedColorIconResource> rsf_cicns(ResourceFile& rf); std::unordered_map<int16_t, std::string> rsf_snds(ResourceFile& rf); std::unordered_map<int16_t, std::pair<std::string, bool>> rsf_texts(ResourceFile& rf); struct TileDefinition { be_uint16_t sound_id; be_uint16_t time_per_move; be_uint16_t solid_type; // 0 = not solid, 1 = solid to 1-box chars, 2 = solid be_uint16_t is_shore; be_uint16_t is_need_boat; // 1 = is boat, 2 = need boat be_uint16_t is_path; be_uint16_t blocks_los; be_uint16_t need_fly_float; be_uint16_t special_type; // 1 = trees, 2 = desert, 3 = shrooms, 4 = swamp, 5 = snow int16_t unknown5; int16_t battle_expansion[9]; int16_t unknown6; } __attribute__((packed)); struct TileSetDefinition { TileDefinition tiles[201]; be_uint16_t base_tile_id; } __attribute__((packed)); TileSetDefinition load_tileset_definition(const std::string& filename); struct RealmzGlobalData { explicit RealmzGlobalData(const std::string& dir); ~RealmzGlobalData() = default; void load_default_tilesets(); std::string dir; ResourceFile global_rsf; ResourceFile portraits_rsf; std::unordered_map<std::string, TileSetDefinition> land_type_to_tileset_definition; }; std::string first_file_that_exists(const std::vector<std::string>& names); int16_t resource_id_for_land_type(const std::string& land_type); Image generate_tileset_definition_legend( const TileSetDefinition& ts, const Image& positive_pattern);
29.822581
97
0.742564
fuzziqersoftware
5b32a584839bc1a7311a032afd2ffcefed58cb6b
1,661
cpp
C++
barnpainting/barnpainting.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
1
2020-12-15T20:25:21.000Z
2020-12-15T20:25:21.000Z
barnpainting/barnpainting.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
barnpainting/barnpainting.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, k; int pc[100005]; vector<int> g[100005]; bool v[100005]; const long long mod = 1000000007; int m[4][100005]; long long dfs(int lc, int f) { if (m[lc][f]) { return m[lc][f]; } if (pc[f]) { if (lc == pc[f]) { return 0; } long long cnt = 1; for (int i = 0; i < g[f].size(); i++) { if (!v[g[f][i]]) { v[g[f][i]] = true; cnt *= (dfs(pc[f], g[f][i]) % mod); cnt %= mod; v[g[f][i]] = false; } } m[lc][f] = cnt; return cnt; } long long cnta = 0; for (int i = 1; i <= 3; i++) { if (i != lc) { long long cnt = 1; for (int j = 0; j < g[f].size(); j++) { if (!v[g[f][j]]) { v[g[f][j]] = true; cnt *= (dfs(i, g[f][j]) % mod); cnt %= mod; v[g[f][j]] = false; } } cnta += cnt; cnta %= mod; } } m[lc][f] = cnta; return cnta; } int main() { freopen("barnpainting.in", "r", stdin); freopen("barnpainting.out", "w", stdout); cin >> n >> k; for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } for (int i = 0; i < k; i++) { int b, c; cin >> b >> c; pc[b] = c; } v[1] = true; cout << dfs(0, 1) << endl; return 0; }
21.025316
51
0.33233
chenhongqiao
5b35eb5efe971e3938591788f0a44bfb7b1e1148
502
cpp
C++
src/PAT/P1041.cpp
TDYe123/Algorithm
9c7cc2b2b79db7245846affc5b263049fd866c87
[ "MIT" ]
1
2019-05-04T15:44:41.000Z
2019-05-04T15:44:41.000Z
src/PAT/P1041.cpp
TDYe123/Algorithm
9c7cc2b2b79db7245846affc5b263049fd866c87
[ "MIT" ]
null
null
null
src/PAT/P1041.cpp
TDYe123/Algorithm
9c7cc2b2b79db7245846affc5b263049fd866c87
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int maxn = 100010; int n; int arr[maxn]; int temp[maxn]; set<int> st; int main() { scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &arr[i]); temp[i] = arr[i]; } sort(temp, temp+n); for(int i=0; i<n-1; i++) { if(temp[i+1] == temp[i]) { st.insert(temp[i]); } } for(int i=0; i<n; i++) { if(st.find(arr[i]) == st.end()) { printf("%d\n", arr[i]); return 0; } } printf("None\n"); return 0; }
17.310345
36
0.486056
TDYe123
5b3737c5741abe62acbdf725a5a053811bae77b6
6,316
hpp
C++
src/include/AABB.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
1
2017-10-30T22:49:06.000Z
2017-10-30T22:49:06.000Z
src/include/AABB.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
src/include/AABB.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
// // AABB.hpp // PinkTopaz // // Created by Andrew Fox on 3/13/16. // // #ifndef AABB_hpp #define AABB_hpp #include <glm/glm.hpp> #include <glm/gtx/component_wise.hpp> #include <glm/gtx/string_cast.hpp> #include <vector> #include <sstream> #include <array> #include <boost/functional/hash.hpp> #include "CerealGLM.hpp" #include <spdlog/fmt/ostr.h> // An axis-aligned bounding box. template<typename TYPE> struct _AABB { // The point at the exact center of the bounding box. TYPE center; // The corners of the box are given given as the Cartesian Product of // {-a.x, -a.y, -a.z} and {+a.x, +a.y, +a.z} where a = center + extent. // This means that the length of the edge of the box along the X axis is // extent.x * 2, and ditto for the other two axii. TYPE extent; bool operator==(const _AABB<TYPE> &other) const { return (center == other.center) && (extent == other.extent); } bool operator!=(const _AABB<TYPE> &other) const { bool theSame = ((*this) == other); return !theSame; } bool operator<(const _AABB<TYPE> &right) const { return center.x < right.center.x; // This is arbitrary, but consistent. } inline TYPE mins() const { return center - extent; } inline TYPE maxs() const { return center + extent; } inline _AABB<TYPE> inset(TYPE inset) const { return _AABB<TYPE>{center, extent - inset}; } auto octants() const { const glm::vec3 subExtent = extent * 0.50f; const std::array<_AABB<TYPE>, 8> r = {{ { center + glm::vec3(-subExtent.x, -subExtent.y, -subExtent.z), subExtent}, { center + glm::vec3(-subExtent.x, -subExtent.y, +subExtent.z), subExtent}, { center + glm::vec3(-subExtent.x, +subExtent.y, -subExtent.z), subExtent}, { center + glm::vec3(-subExtent.x, +subExtent.y, +subExtent.z), subExtent}, { center + glm::vec3(+subExtent.x, -subExtent.y, -subExtent.z), subExtent}, { center + glm::vec3(+subExtent.x, -subExtent.y, +subExtent.z), subExtent}, { center + glm::vec3(+subExtent.x, +subExtent.y, -subExtent.z), subExtent}, { center + glm::vec3(+subExtent.x, +subExtent.y, +subExtent.z), subExtent} }}; return r; } inline _AABB<TYPE> intersect(const _AABB<TYPE> &thatBox) const { const TYPE thisMin = mins(); const TYPE thatMin = thatBox.mins(); const TYPE thisMax = maxs(); const TYPE thatMax = thatBox.maxs(); const TYPE min = TYPE(std::max(thisMin.x, thatMin.x), std::max(thisMin.y, thatMin.y), std::max(thisMin.z, thatMin.z)); const TYPE max = TYPE(std::min(thisMax.x, thatMax.x), std::min(thisMax.y, thatMax.y), std::min(thisMax.z, thatMax.z)); const TYPE center = (max + min) * 0.5f; const TYPE extent = (max - min) * 0.5f; return {center, extent}; } inline _AABB<TYPE> unionBox(const _AABB<TYPE> &thatBox) const { const TYPE thisMin = mins(); const TYPE thatMin = thatBox.mins(); const TYPE thisMax = maxs(); const TYPE thatMax = thatBox.maxs(); const TYPE min = TYPE(std::min(thisMin.x, thatMin.x), std::min(thisMin.y, thatMin.y), std::min(thisMin.z, thatMin.z)); const TYPE max = TYPE(std::max(thisMax.x, thatMax.x), std::max(thisMax.y, thatMax.y), std::max(thisMax.z, thatMax.z)); const TYPE center = (max + min) * 0.5f; const TYPE extent = (max - min) * 0.5f; return {center, extent}; } // Return the string representation of this bounding box. std::string to_string() const { std::ostringstream ss; ss << "{" << glm::to_string(mins()) << " x " << glm::to_string(maxs()) << "}"; return ss.str(); } // Permits logging with spdlog. template<typename OStream> friend OStream& operator<<(OStream &os, const _AABB<TYPE> &box) { os << "{" << glm::to_string(box.mins()) << " x " << glm::to_string(box.maxs()) << "}"; return os; } // Permits serialization with cereal. template<typename Archive> void serialize(Archive &archive) { archive(CEREAL_NVP(center), CEREAL_NVP(extent)); } }; using AABB = _AABB<glm::vec3>; namespace std { template <> struct hash<glm::vec3> { size_t operator()(const glm::vec3 &point) const { size_t seed = 0; boost::hash_combine(seed, point.x); boost::hash_combine(seed, point.y); boost::hash_combine(seed, point.z); return seed; } }; } namespace std { template <> struct hash<AABB> { size_t operator()(const AABB &box) const { size_t seed = 0; std::hash<glm::vec3> vecHasher; boost::hash_combine(seed, vecHasher(box.center)); boost::hash_combine(seed, vecHasher(box.extent)); return seed; } }; } template<typename PointType> inline bool isPointInsideBox(const PointType &point, const PointType &mins, const PointType &maxs) { return point.x >= mins.x && point.y >= mins.y && point.z >= mins.z && point.x < maxs.x && point.y < maxs.y && point.z < maxs.z; } inline bool isPointInsideBox(const glm::vec3 &point, const AABB &box) { return isPointInsideBox(point, box.mins(), box.maxs()); } inline bool doBoxesIntersect(const AABB &a, const AABB &b) { const glm::vec3 a_max = a.maxs(); const glm::vec3 b_max = b.maxs(); const glm::vec3 a_min = a.mins(); const glm::vec3 b_min = b.mins(); return (a_max.x >= b_min.x) && (a_min.x <= b_max.x) && (a_max.y >= b_min.y) && (a_min.y <= b_max.y) && (a_max.z >= b_min.z) && (a_min.z <= b_max.z); } #endif /* AABB_hpp */
29.933649
87
0.543382
foxostro
5b382f1b9ed26636288b24926df2b10b73304271
1,962
hpp
C++
include/gl/filtering/filter_blend.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/filtering/filter_blend.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/filtering/filter_blend.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_GL_FILTERING_FILTER_BLEND_HPP #define PIC_GL_FILTERING_FILTER_BLEND_HPP #include "../../gl/filtering/filter.hpp" namespace pic { /** * @brief The FilterGLBlend class */ class FilterGLBlend: public FilterGL { protected: /** * @brief initShaders */ void initShaders() { fragment_source = MAKE_STRING ( uniform sampler2D u_tex0; \n uniform sampler2D u_tex1; \n uniform sampler2D u_texMask; \n out vec4 f_color; \n void main(void) { \n ivec2 coords = ivec2(gl_FragCoord.xy);\n vec4 color0 = texelFetch(u_tex0, coords, 0);\n vec4 color1 = texelFetch(u_tex1, coords, 0);\n float weight = texelFetch(u_texMask, coords, 0).x;\n f_color = mix(color0, color1, weight); }\n ); technique.initStandard("330", vertex_source, fragment_source, "FilterGLBlend"); technique.bind(); technique.setUniform1i("u_tex0", 0); technique.setUniform1i("u_tex1", 1); technique.setUniform1i("u_texMask", 2); technique.unbind(); } public: /** * @brief FilterGLBlend */ FilterGLBlend() : FilterGL() { //protected values are assigned/computed initShaders(); } ~FilterGLBlend() { release(); } }; } // end namespace pic #endif /* PIC_GL_FILTERING_FILTER_BLEND_HPP */
23.357143
87
0.583588
ecarpita93
5b3b7d375504021fa1823ae4b0972f64e969d5cd
1,462
hpp
C++
include/mbgl/map/transform_state.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
2
2017-02-28T22:41:54.000Z
2020-02-13T20:54:55.000Z
include/mbgl/map/transform_state.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
include/mbgl/map/transform_state.hpp
free1978/mapbox-gl-native
2a50fccd24e762d0de5a53bac358e5ddfea8d213
[ "BSD-2-Clause" ]
null
null
null
#ifndef MBGL_MAP_TRANSFORM_STATE #define MBGL_MAP_TRANSFORM_STATE #include <mbgl/map/tile.hpp> #include <mbgl/util/mat4.hpp> #include <mbgl/util/vec.hpp> #include <cstdint> #include <array> #include <limits> namespace mbgl { class TransformState { friend class Transform; public: // Matrix void matrixFor(mat4& matrix, const Tile::ID& id) const; box cornersToBox(uint32_t z) const; // Dimensions bool hasSize() const; uint16_t getWidth() const; uint16_t getHeight() const; uint16_t getFramebufferWidth() const; uint16_t getFramebufferHeight() const; const std::array<uint16_t, 2> getFramebufferDimensions() const; float getPixelRatio() const; // Zoom float getNormalizedZoom() const; int32_t getIntegerZoom() const; double getZoom() const; double getScale() const; // Rotation float getAngle() const; // Changing bool isChanging() const; private: double pixel_x() const; double pixel_y() const; private: // logical dimensions uint16_t width = 0, height = 0; // physical (framebuffer) dimensions std::array<uint16_t, 2> framebuffer = {{ 0, 0 }}; // map scale factor float pixelRatio = 0; // animation state bool rotating = false; bool scaling = false; bool panning = false; // map position double x = 0, y = 0; double angle = 0; double scale = std::numeric_limits<double>::infinity(); }; } #endif
20.305556
67
0.664843
free1978
5b3e3e6c8d7fd573cd433450374f13e1c53089bc
19,088
cpp
C++
kotekan/kotekan.cpp
kotekan/kotekan
c88fe5c4c3ee275542b40ccf17debc2f84695925
[ "MIT" ]
19
2018-12-14T00:51:52.000Z
2022-02-20T02:43:50.000Z
kotekan/kotekan.cpp
kotekan/kotekan
c88fe5c4c3ee275542b40ccf17debc2f84695925
[ "MIT" ]
487
2018-12-13T00:59:53.000Z
2022-02-07T16:12:56.000Z
kotekan/kotekan.cpp
kotekan/kotekan
c88fe5c4c3ee275542b40ccf17debc2f84695925
[ "MIT" ]
5
2019-05-09T19:52:19.000Z
2021-03-27T20:13:21.000Z
#include "Config.hpp" // for Config #include "StageFactory.hpp" // for StageFactoryRegistry, StageMaker #include "basebandApiManager.hpp" // for basebandApiManager #include "errors.h" // for get_error_message, get_exit_code, __enable_syslog, exi... #include "kotekanLogging.hpp" // for INFO_NON_OO, logLevel, ERROR_NON_OO, FATAL_ERROR_NON_OO #include "kotekanMode.hpp" // for kotekanMode #include "kotekanTrackers.hpp" // for KotekanTrackers #include "prometheusMetrics.hpp" // for Metrics, Gauge #include "restServer.hpp" // for connectionInstance, HTTP_RESPONSE, restServer, HTTP_RE... #include "util.h" // for EVER #include "version.h" // for get_kotekan_version, get_cmake_build_options, get_git_... #include "visUtil.hpp" // for regex_split #include "fmt.hpp" // for format, fmt #include "json.hpp" // for basic_json<>::object_t, basic_json<>::value_type, json #include <algorithm> // for max #include <array> // for array #include <assert.h> // for assert #include <csignal> // for signal, SIGINT, sig_atomic_t #include <exception> // for exception #include <getopt.h> // for no_argument, getopt_long, required_argument, option #include <iostream> // for endl, basic_ostream, cout, ostream #include <iterator> // for reverse_iterator #include <map> // for map #include <memory> // for allocator, shared_ptr #include <mutex> // for mutex, lock_guard #include <stdexcept> // for runtime_error, out_of_range #include <stdio.h> // for printf, fprintf, feof, fgets, popen, stderr, pclose #include <stdlib.h> // for exit, free #include <string.h> // for strdup #include <string> // for string, basic_string, operator!=, operator<<, operator== #include <strings.h> // for strcasecmp #include <syslog.h> // for closelog, openlog, LOG_CONS, LOG_LOCAL1, LOG_NDELAY #include <type_traits> // for underlying_type, underlying_type<>::type #include <unistd.h> // for optarg, sleep #include <utility> // for pair #include <vector> // for vector #ifdef WITH_HSA #include "hsaBase.h" #endif using std::string; using json = nlohmann::json; using namespace kotekan; // Embedded script for converting the YAML config to json const std::string yaml_to_json = R"( import yaml, json, sys, os, subprocess, errno file_name = sys.argv[1] # Lint the YAML file, helpful for finding errors try: output = subprocess.Popen(["yamllint", "-d", "{extends: relaxed, \ rules: {line-length: {max: 100}, \ commas: disable, \ brackets: disable, \ trailing-spaces: {level: warning}}}" , file_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) response,stderr = output.communicate() if response != "": sys.stderr.write("yamllint warnings/errors for: ") sys.stderr.write(str(response)) # TODO: change to checking for OSError subtypes when Python 2 support is removed except OSError as e: if e.errno == errno.ENOENT: sys.stderr.write("yamllint not installed, skipping pre-validation\n") else: sys.stderr.write("error with yamllint, skipping pre-validation\n") with open(file_name, "r") as stream: try: config_json = yaml.load(stream) except yaml.YAMLError as exc: sys.stderr.write(exc) sys.stdout.write(json.dumps(config_json)) )"; kotekanMode* kotekan_mode = nullptr; bool running = false; std::mutex kotekan_state_lock; volatile std::sig_atomic_t sig_value = 0; void signal_handler(int signal) { sig_value = signal; } void print_help() { printf("usage: kotekan [opts]\n\n"); printf("Options:\n"); printf(" --config (-c) [file] The local JSON config file to use.\n"); printf(" --bind-address (-b) [ip:port] The IP address and port to bind" " (default 0.0.0.0:12048)\n"); printf(" --syslog (-s) Send a copy of the output to syslog.\n"); printf(" --no-stderr (-n) Disables output to std error if syslog (-s) is " "enabled.\n"); printf(" --version (-v) Prints the kotekan version and build details.\n"); printf(" --print-config (-p) Prints the config file being used.\n\n"); printf("If no options are given then kotekan runs in daemon mode and\n"); printf("expects to get it configuration via the REST endpoint '/start'.\n"); printf("In daemon mode output is only sent to syslog.\n\n"); } void print_version() { printf("Kotekan version %s\n", get_kotekan_version()); printf("Build branch: %s\n", get_git_branch()); printf("Git commit hash: %s\n\n", get_git_commit_hash()); printf("CMake build settings: \n%s\n", get_cmake_build_options()); printf("Available kotekan stages:\n"); std::map<std::string, StageMaker*> known_stages = StageFactoryRegistry::get_registered_stages(); for (auto& stage_maker : known_stages) { if (stage_maker.first != known_stages.rbegin()->first) { printf("%s, ", stage_maker.first.c_str()); } else { printf("%s\n\n", stage_maker.first.c_str()); } } } std::vector<std::string> split_string(const std::string& s, const std::string& delimiter) { std::vector<std::string> tokens; size_t start = 0; while (start <= s.size()) { size_t end = s.find(delimiter, start); // If no match was found, then we should select to the end of the string if (end == std::string::npos) end = s.size(); // If a match was found at the start then we shouldn't add anything if (end != start) tokens.push_back(s.substr(start, end - start)); start = end + delimiter.size(); } return tokens; } std::string trim(std::string& s) { s.erase(0, s.find_first_not_of(' ')); s.erase(s.find_last_not_of(' ') + 1); return s; } json parse_cmake_options() { auto options = split_string(get_cmake_build_options(), "\n"); json j; for (auto opt : options) { // Trim off the indent from any nested options if (opt[1] == '-') { opt = opt.substr(2, opt.size() - 2); } auto t = split_string(opt, ":"); auto key = trim(t[0]); auto val = trim(t[1]); j[key] = val; } return j; } json get_json_version_info() { // Create version information json version_json; version_json["kotekan_version"] = get_kotekan_version(); version_json["branch"] = get_git_branch(); version_json["git_commit_hash"] = get_git_commit_hash(); version_json["cmake_build_settings"] = parse_cmake_options(); std::vector<std::string> available_stages; std::map<std::string, StageMaker*> known_stages = StageFactoryRegistry::get_registered_stages(); for (auto& stage_maker : known_stages) available_stages.push_back(stage_maker.first); version_json["available_stages"] = available_stages; return version_json; } void print_json_version() { std::cout << get_json_version_info().dump(2) << std::endl; } std::string exec(const std::string& cmd) { std::array<char, 256> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose); if (!pipe) throw std::runtime_error(fmt::format(fmt("popen() for the command {:s} failed!"), cmd)); while (!feof(pipe.get())) { if (fgets(buffer.data(), 256, pipe.get()) != nullptr) result += buffer.data(); } return result; } void update_log_levels(Config& config) { // Adjust the log level string s_log_level = config.get<std::string>("/", "log_level"); logLevel log_level; if (strcasecmp(s_log_level.c_str(), "off") == 0) { log_level = logLevel::OFF; } else if (strcasecmp(s_log_level.c_str(), "error") == 0) { log_level = logLevel::ERROR; } else if (strcasecmp(s_log_level.c_str(), "warn") == 0) { log_level = logLevel::WARN; } else if (strcasecmp(s_log_level.c_str(), "info") == 0) { log_level = logLevel::INFO; } else if (strcasecmp(s_log_level.c_str(), "debug") == 0) { log_level = logLevel::DEBUG; } else if (strcasecmp(s_log_level.c_str(), "debug2") == 0) { log_level = logLevel::DEBUG2; } else { throw std::runtime_error( fmt::format(fmt("The value given for log_level: '{:s}' is not valid! (It should be one " "of 'off', 'error', 'warn', 'info', 'debug', 'debug2')"), s_log_level)); } _global_log_level = static_cast<std::underlying_type<logLevel>::type>(log_level); } /** * @brief Starts a new kotekan mode (config instance) * * @param config The config to generate the instance from * @param dump_config If set to true, then the config file is printed to stdout. */ void start_new_kotekan_mode(Config& config, bool dump_config) { if (dump_config) config.dump_config(); update_log_levels(config); kotekan_mode = new kotekanMode(config); kotekan_mode->initalize_stages(); kotekan_mode->start_stages(); running = true; } int main(int argc, char** argv) { std::signal(SIGINT, signal_handler); char* config_file_name = (char*)"none"; int log_options = LOG_CONS | LOG_PID | LOG_NDELAY; bool enable_stderr = true; bool dump_config = false; std::string bind_address = "0.0.0.0:12048"; // We disable syslog to start. // If only --config is provided, then we only send messages to stderr // If --syslog is added, then output is to both syslog and stderr // If no options are given then stderr is disabled, and syslog is enabled. // The no options mode is the default daemon mode where it expects a remote config __enable_syslog = 0; for (;;) { static struct option long_options[] = {{"config", required_argument, nullptr, 'c'}, {"bind-address", required_argument, nullptr, 'b'}, {"help", no_argument, nullptr, 'h'}, {"syslog", no_argument, nullptr, 's'}, {"no-stderr", no_argument, nullptr, 'n'}, {"version", no_argument, nullptr, 'v'}, {"version-json", no_argument, nullptr, 'j'}, {"print-config", no_argument, nullptr, 'p'}, {nullptr, 0, nullptr, 0}}; int option_index = 0; int opt_val = getopt_long(argc, argv, "hc:b:snvp", long_options, &option_index); // End of args if (opt_val == -1) { break; } switch (opt_val) { case 'h': print_help(); return 0; break; case 'c': config_file_name = strdup(optarg); break; case 'b': bind_address = string(optarg); break; case 's': __enable_syslog = 1; break; case 'n': enable_stderr = false; break; case 'v': print_version(); return 0; break; case 'j': print_json_version(); return 0; break; case 'p': dump_config = true; break; default: printf("Invalid option, run with -h to see options"); return -1; break; } } #ifdef WITH_HSA kotekan_hsa_start(); #endif if (string(config_file_name) == "none") { __enable_syslog = 1; fprintf(stderr, "Kotekan running in daemon mode, output is to syslog only.\n"); fprintf(stderr, "Configuration should be provided via the `/start` REST endpoint.\n"); } if (string(config_file_name) != "none" && enable_stderr) { log_options |= LOG_PERROR; } if (__enable_syslog == 1) { openlog("kotekan", log_options, LOG_LOCAL1); if (!enable_stderr) fprintf(stderr, "Kotekan logging to syslog only!"); } // Load configuration file. INFO_NON_OO("Kotekan version {:s} starting...", get_kotekan_version()); Config config; restServer& rest_server = restServer::instance(); std::vector<std::string> address_parts = regex_split(bind_address, ":"); // TODO validate IP and port rest_server.start(address_parts.at(0), std::stoi(address_parts.at(1))); if (string(config_file_name) != "none") { // TODO should be in a try catch block, to make failures cleaner. std::lock_guard<std::mutex> lock(kotekan_state_lock); INFO_NON_OO("Opening config file {:s}", config_file_name); std::string exec_command = fmt::format(fmt("python -c '{:s}' {:s}"), yaml_to_json, config_file_name); std::string json_string = exec(exec_command.c_str()); json config_json = json::parse(json_string); config.update_config(config_json); try { start_new_kotekan_mode(config, dump_config); } catch (const std::exception& ex) { ERROR_NON_OO("Failed to start kotekan with config file {:s}, error message: {:s}", config_file_name, ex.what()); ERROR_NON_OO("Exiting..."); exit(-1); } free(config_file_name); config_file_name = nullptr; } // Main REST callbacks. rest_server.register_post_callback("/start", [&](connectionInstance& conn, json& json_config) { std::lock_guard<std::mutex> lock(kotekan_state_lock); if (running) { WARN_NON_OO( "/start was called, but the system is already running, ignoring start request."); conn.send_error("Already running", HTTP_RESPONSE::REQUEST_FAILED); return; } config.update_config(json_config); try { INFO_NON_OO("Starting new kotekan mode using POSTed config."); start_new_kotekan_mode(config, dump_config); } catch (const std::out_of_range& ex) { delete kotekan_mode; kotekan_mode = nullptr; conn.send_error(ex.what(), HTTP_RESPONSE::BAD_REQUEST); // TODO This exit shouldn't be required, but some stages aren't able // to fully clean up on system failure. This results in the system // getting into a bad state if the posted config is invalid. // See ticket: #464 // The same applies to exit (raise) statements in other parts of // this try statement. FATAL_ERROR_NON_OO("Provided config had an out of range exception: {:s}", ex.what()); return; } catch (const std::runtime_error& ex) { delete kotekan_mode; kotekan_mode = nullptr; conn.send_error(ex.what(), HTTP_RESPONSE::BAD_REQUEST); FATAL_ERROR_NON_OO("Provided config failed to start with runtime error: {:s}", ex.what()); return; } catch (const std::exception& ex) { delete kotekan_mode; kotekan_mode = nullptr; conn.send_error(ex.what(), HTTP_RESPONSE::BAD_REQUEST); FATAL_ERROR_NON_OO("Provided config failed with exception: {:s}", ex.what()); return; } conn.send_empty_reply(HTTP_RESPONSE::OK); }); rest_server.register_get_callback("/stop", [&](connectionInstance& conn) { std::lock_guard<std::mutex> lock(kotekan_state_lock); if (!running) { WARN_NON_OO("/stop called, but the system is already stopped, ignoring stop request."); conn.send_error("kotekan is already stopped", HTTP_RESPONSE::REQUEST_FAILED); return; } INFO_NON_OO("/stop endpoint called, shutting down current config."); assert(kotekan_mode != nullptr); kotekan_mode->stop_stages(); // TODO should we have three states (running, shutting down, and stopped)? // This would prevent this function from blocking on join. kotekan_mode->join(); delete kotekan_mode; kotekan_mode = nullptr; running = false; conn.send_empty_reply(HTTP_RESPONSE::OK); }); rest_server.register_get_callback("/kill", [&](connectionInstance& conn) { ERROR_NON_OO( "/kill endpoint called, raising SIGINT to shutdown the kotekan system process."); kotekan::kotekanLogging::set_error_message("/kill endpoint called."); exit_kotekan(ReturnCode::CLEAN_EXIT); conn.send_empty_reply(HTTP_RESPONSE::OK); }); rest_server.register_get_callback("/status", [&](connectionInstance& conn) { std::lock_guard<std::mutex> lock(kotekan_state_lock); json reply; reply["running"] = running; conn.send_json_reply(reply); }); json version_json = get_json_version_info(); rest_server.register_get_callback( "/version", [&](connectionInstance& conn) { conn.send_json_reply(version_json); }); auto& metrics = prometheus::Metrics::instance(); metrics.register_with_server(&rest_server); auto& kotekan_running_metric = metrics.add_gauge("kotekan_running", "main"); kotekan_running_metric.set(running); basebandApiManager& baseband = basebandApiManager::instance(); baseband.register_with_server(&rest_server); for (EVER) { sleep(1); // Update running state { std::lock_guard<std::mutex> lock(kotekan_state_lock); kotekan_running_metric.set(running); } if (sig_value == SIGINT) { INFO_NON_OO("Got SIGINT, shutting down kotekan..."); std::lock_guard<std::mutex> lock(kotekan_state_lock); if (kotekan_mode != nullptr) { INFO_NON_OO("Attempting to stop and join kotekan_stages..."); kotekan_mode->stop_stages(); kotekan_mode->join(); if (string(get_error_message()) != "not set") { KotekanTrackers::instance().dump_trackers(); } delete kotekan_mode; } break; } } INFO_NON_OO("kotekan shutdown with status: {:s}", get_exit_code_string(get_exit_code())); // Print error message if there is one. if (string(get_error_message()) != "not set") { INFO_NON_OO("Fatal error message was: {:s}", get_error_message()); } closelog(); return get_exit_code(); }
37.648915
100
0.593305
kotekan
5b443db36310a5197c157d7f87b33a096003638c
22,026
cpp
C++
KinectV2/KinectV2InputService/m+mKinectV2BlobEventThread.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
KinectV2/KinectV2InputService/m+mKinectV2BlobEventThread.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
KinectV2/KinectV2InputService/m+mKinectV2BlobEventThread.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------------------------------- // // File: m+mKinectV2BlobEventThread.cpp // // Project: m+m // // Contains: The class definition for a thread that generates output from Kinect V2 data. // // Written by: Norman Jaffe // // Copyright: (c) 2015 by H Plus Technologies Ltd. and Simon Fraser University. // // All rights reserved. Redistribution and use in source and binary forms, with or // without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and / or // other materials provided with the distribution. // * Neither the name of the copyright holders nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // Created: 2015-07-26 // //-------------------------------------------------------------------------------------------------- #include "m+mKinectV2BlobEventThread.hpp" //#include <odlEnable.h> #include <odlInclude.h> #if defined(__APPLE__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunknown-pragmas" # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif // defined(__APPLE__) /*! @file @brief The class definition for a thread that generates output from Kinect V2 data. */ #if defined(__APPLE__) # pragma clang diagnostic pop #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Namespace references #endif // defined(__APPLE__) using namespace MplusM; using namespace MplusM::KinectV2Blob; using std::cerr; using std::endl; #if defined(__APPLE__) # pragma mark Private structures, constants and variables #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Global constants and variables #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Local functions #endif // defined(__APPLE__) #if (! defined(MpM_BuildDummyServices)) /*! @brief Add the description of a joint to the output. @param[in,out] outBuffer The output buffer to be updated with the body data. @param[in] scale The translation scale to be applied. @param[in] jointTag The name of the bone. @param[in] jointData The joint position. @param[in] orientationData The orientation of the joint. */ # if defined(MpM_UseCustomStringBuffer) static void addJointToBuffer(Common::StringBuffer & outBuffer, const double scale, const YarpString & jointTag, const Joint & jointData, const JointOrientation & orientationData) # else // ! defined(MpM_UseCustomStringBuffer) static void addJointToBuffer(std::stringstream & outBuffer, const double scale, const YarpString & jointTag, const Joint & jointData, const JointOrientation & orientationData) # endif // ! defined(MpM_UseCustomStringBuffer) { ODL_ENTER(); //#### ODL_P3("outBuffer = ", &outBuffer, "jointData = ", &jointData, "orientationData = ", //#### &orientationData); //#### ODL_D1("scale = ", scale); //#### // If we can't find either of these joints, exit if (TrackingState_NotTracked != jointData.TrackingState) { // Don't process if point is inferred if (TrackingState_Inferred != jointData.TrackingState) { # if defined(MpM_UseCustomStringBuffer) outBuffer.addString(jointTag).addTab(); outBuffer.addDouble(jointData.Position.X * scale).addTab(); outBuffer.addDouble(jointData.Position.Y * scale).addTab(); outBuffer.addDouble(jointData.Position.Z * scale).addTab(); outBuffer.addDouble(orientationData.Orientation.x).addTab(); outBuffer.addDouble(orientationData.Orientation.y).addTab(); outBuffer.addDouble(orientationData.Orientation.z).addTab(); outBuffer.addDouble(orientationData.Orientation.w).addString(LINE_END_); # else // ! defined(MpM_UseCustomStringBuffer) outBuffer << jointTag << "\t" << (jointData.Position.X * scale) << "\t" << (jointData.Position.Y * scale) << "\t" << (jointData.Position.Z * scale) << "\t" << orientationData.Orientation.x << "\t" << orientationData.Orientation.y << orientationData.Orientation.z << "\t" << orientationData.Orientation.w << LINE_END_; # endif // ! defined(MpM_UseCustomStringBuffer) } } ODL_EXIT(); //#### } // addJointToBuffer #endif // ! defined(MpM_BuildDummyServices) #if (! defined(MpM_BuildDummyServices)) /*! @brief Add a joint to the output that's being built. @param[in] str_ The name for the joint. @param[in] index_ The joint index. */ # if defined(MpM_UseCustomStringBuffer) # define ADD_JOINT_TO_BUFFER_(str_, index_) \ addJointToBuffer(outBuffer, scale, str_, jointData[index_], orientationData[index_]) # else // ! defined(MpM_UseCustomStringBuffer) # define ADD_JOINT_TO_BUFFER_(str_, index_) \ addJointToBuffer(outBuffer, scale, str_, jointData[index_], orientationData[index_]) # endif // ! defined(MpM_UseCustomStringBuffer) #endif // ! defined(MpM_BuildDummyServices) #if (! defined(MpM_BuildDummyServices)) /*! @brief Add the data for a body to a message. @param[in,out] outBuffer The output buffer to be updated with the body data. @param[in] scale The translation scale to be applied. @param[in] jointData The set of joints for the body. @param[in] orientationData The orientations of the joints. */ # if defined(MpM_UseCustomStringBuffer) static void addBodyToMessage(Common::StringBuffer & outBuffer, const double scale, const Joint * jointData, const JointOrientation * orientationData) # else // ! defined(MpM_UseCustomStringBuffer) static void addBodyToMessage(std::stringstream & outBuffer, const double scale, const Joint * jointData, const JointOrientation * orientationData) # endif // ! defined(MpM_UseCustomStringBuffer) { ODL_ENTER(); //#### ODL_P3("outBuffer = ", &outBuffer, "jointData = ", jointData, "orientationData = ", //#### orientationData); //#### ODL_D1("scale = ", scale); //#### // Torso ADD_JOINT_TO_BUFFER_("head", JointType_Head); ADD_JOINT_TO_BUFFER_("neck", JointType_Neck); ADD_JOINT_TO_BUFFER_("spineshoulder", JointType_SpineShoulder); ADD_JOINT_TO_BUFFER_("spinemid", JointType_SpineMid); ADD_JOINT_TO_BUFFER_("spinebase", JointType_SpineBase); ADD_JOINT_TO_BUFFER_("shoulderright", JointType_ShoulderRight); ADD_JOINT_TO_BUFFER_("shoulderleft", JointType_ShoulderLeft); ADD_JOINT_TO_BUFFER_("hipright", JointType_HipRight); ADD_JOINT_TO_BUFFER_("hipleft", JointType_HipLeft); // Right arm ADD_JOINT_TO_BUFFER_("elbowright", JointType_ElbowRight); ADD_JOINT_TO_BUFFER_("wristright", JointType_WristRight); ADD_JOINT_TO_BUFFER_("handright", JointType_HandRight); ADD_JOINT_TO_BUFFER_("handtipright", JointType_HandTipRight); ADD_JOINT_TO_BUFFER_("thumbright", JointType_ThumbRight); // Left arm ADD_JOINT_TO_BUFFER_("elbowleft", JointType_ElbowLeft); ADD_JOINT_TO_BUFFER_("wristleft", JointType_WristLeft); ADD_JOINT_TO_BUFFER_("handleft", JointType_HandLeft); ADD_JOINT_TO_BUFFER_("handtipleft", JointType_HandTipLeft); ADD_JOINT_TO_BUFFER_("thumbleft", JointType_ThumbLeft); // Right leg ADD_JOINT_TO_BUFFER_("kneeright", JointType_KneeRight); ADD_JOINT_TO_BUFFER_("ankleright", JointType_AnkleRight); ADD_JOINT_TO_BUFFER_("footright", JointType_FootRight); // Left leg ADD_JOINT_TO_BUFFER_("kneeleft", JointType_KneeLeft); ADD_JOINT_TO_BUFFER_("ankleleft", JointType_AnkleLeft); ADD_JOINT_TO_BUFFER_("footleft", JointType_FootLeft); ODL_EXIT(); //#### } // addBodyToMessage #endif // ! defined(MpM_BuildDummyServices) #if (! defined(MpM_BuildDummyServices)) /*! @brief Process the data returned by the Kinect V2 sensor. @param[in,out] outBuffer The output buffer to be updated with the body data. @param[in] scale The translation scale to be applied. @param[in] nBodyCount The number of 'bodies' in the sensor data. @param[in] ppBodies The sensor data. @return @c true if at least one body was added to the message successfully, and @c false otherwise. */ # if defined(MpM_UseCustomStringBuffer) static bool processBody(Common::StringBuffer & outBuffer, const double scale, const int nBodyCount, IBody * * ppBodies) # else // ! defined(MpM_UseCustomStringBuffer) static bool processBody(std::stringstream & outBuffer, const double scale, const int nBodyCount, IBody * * ppBodies) # endif // ! defined(MpM_UseCustomStringBuffer) { ODL_ENTER(); //#### ODL_P2("outBuffer = ", outBuffer, "ppBodies = ", ppBodies); //#### ODL_I1("nBodyCount = ", nBodyCount); //#### bool result = false; int actualBodyCount = 0; for (int ii = 0; nBodyCount > ii; ++ii) { IBody * pBody = ppBodies[ii]; if (pBody) { BOOLEAN bTracked = false; HRESULT hr = pBody->get_IsTracked(&bTracked); if (SUCCEEDED(hr) && bTracked) { Joint jointData[JointType_Count]; hr = pBody->GetJoints(_countof(jointData), jointData); if (SUCCEEDED(hr)) { JointOrientation orientationData[JointType_Count]; hr = pBody->GetJointOrientations(_countof(orientationData), orientationData); } if (SUCCEEDED(hr)) { ++actualBodyCount; } } } } # if defined(MpM_UseCustomStringBuffer) outBuffer.reset().addLong(actualBodyCount).addString(LINE_END_); # else // ! defined(MpM_UseCustomStringBuffer) outBuffer.seekp(0); outBuffer << actualBodyCount << LINE_END_; # endif // ! defined(MpM_UseCustomStringBuffer) for (int ii = 0; nBodyCount > ii; ++ii) { IBody * pBody = ppBodies[ii]; if (pBody) { BOOLEAN bTracked = false; HRESULT hr = pBody->get_IsTracked(&bTracked); if (SUCCEEDED(hr) && bTracked) { Joint jointData[JointType_Count]; JointOrientation orientationData[JointType_Count]; hr = pBody->GetJoints(_countof(jointData), jointData); if (SUCCEEDED(hr)) { hr = pBody->GetJointOrientations(_countof(orientationData), orientationData); } if (SUCCEEDED(hr)) { int actualJointCount = 0; for (int jj = 0; JointType_Count > jj; ++jj) { // If we can't find either of these joints, exit if (TrackingState_NotTracked != jointData[jj].TrackingState) { // Don't process if point is inferred if (TrackingState_Inferred != jointData[jj].TrackingState) { ++actualJointCount; } } } # if defined(MpM_UseCustomStringBuffer) outBuffer.addLong(static_cast<int>(ii)).addTab(). addLong(actualJointCount).addString(LINE_END_); # else // ! defined(MpM_UseCustomStringBuffer) outBuffer << ii << "\t" << actualJointCount << LINE_END_; # endif // ! defined(MpM_UseCustomStringBuffer) addBodyToMessage(outBuffer, scale, jointData, orientationData); result = true; } } } } # if defined(MpM_UseCustomStringBuffer) outBuffer.addString("END" LINE_END_); # else // ! defined(MpM_UseCustomStringBuffer) outBuffer << "END" LINE_END_; # endif // ! defined(MpM_UseCustomStringBuffer) ODL_EXIT_B(result); //#### return result; } // processBody #endif // ! defined(MpM_BuildDummyServices) #if defined(__APPLE__) # pragma mark Class methods #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Constructors and Destructors #endif // defined(__APPLE__) KinectV2BlobEventThread::KinectV2BlobEventThread(Common::GeneralChannel * outChannel) : inherited(), _translationScale(1), #if (! defined(MpM_BuildDummyServices)) _kinectSensor(NULL), _bodyFrameReader(NULL), _bodyFrameSource(NULL), #endif // ! defined(MpM_BuildDummyServices) _outChannel(outChannel) { ODL_ENTER(); //#### ODL_P1("outChannel = ", outChannel); //#### ODL_EXIT_P(this); //#### } // KinectV2BlobEventThread::KinectV2BlobEventThread KinectV2BlobEventThread::~KinectV2BlobEventThread(void) { ODL_OBJENTER(); //#### ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::~KinectV2BlobEventThread #if defined(__APPLE__) # pragma mark Actions and Accessors #endif // defined(__APPLE__) void KinectV2BlobEventThread::clearOutputChannel(void) { ODL_OBJENTER(); //#### _outChannel = NULL; ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::clearOutputChannel #if (! defined(MpM_BuildDummyServices)) HRESULT KinectV2BlobEventThread::initializeDefaultSensor(void) { ODL_OBJENTER(); //#### HRESULT hr = GetDefaultKinectSensor(&_kinectSensor); if (! FAILED(hr)) { if (_kinectSensor) { // Initialize the Kinect and get the body reader hr = _kinectSensor->Open(); if (SUCCEEDED(hr)) { hr = _kinectSensor->get_BodyFrameSource(&_bodyFrameSource); } if (SUCCEEDED(hr)) { hr = _bodyFrameSource->OpenReader(&_bodyFrameReader); } if (SUCCEEDED(hr)) { hr = _bodyFrameReader->SubscribeFrameArrived(&_frameEventHandle); } } if ((! _kinectSensor) || FAILED(hr)) { cerr << "problem?!?!" << endl; //SetStatusMessage(L"No ready Kinect found!", 10000, true); hr = E_FAIL; } } ODL_OBJEXIT_I(hr); //#### return hr; } // KinectV2BlobEventThread::initializeDefaultSensor #endif // ! defined(MpM_BuildDummyServices) void KinectV2BlobEventThread::processEventData(void) { ODL_OBJENTER(); //#### #if (! defined(MpM_BuildDummyServices)) if (_bodyFrameReader) { IBodyFrameArrivedEventArgs * eventData = NULL; HRESULT hr = _bodyFrameReader->GetFrameArrivedEventData(_frameEventHandle, &eventData); if (SUCCEEDED(hr)) { IBodyFrameReference * frameRef = NULL; hr = eventData->get_FrameReference(&frameRef); if (SUCCEEDED(hr)) { IBodyFrame * bodyFrame = NULL; hr = frameRef->AcquireFrame(&bodyFrame); if (SUCCEEDED(hr)) { IBody * ppBodies[BODY_COUNT] = { NULL }; hr = bodyFrame->GetAndRefreshBodyData(_countof(ppBodies), ppBodies); if (SUCCEEDED(hr)) { # if (! defined(MpM_UseCustomStringBuffer)) std::stringstream outBuffer; # endif // ! defined(MpM_UseCustomStringBuffer) _messageBottle.clear(); # if defined(MpM_UseCustomStringBuffer) if (processBody(_outBuffer, _translationScale, BODY_COUNT, ppBodies)) # else // ! defined(MpM_UseCustomStringBuffer) if (processBody(outBuffer, BODY_COUNT, ppBodies)) # endif // ! defined(MpM_UseCustomStringBuffer) { const char * outString; size_t outLength; # if (! defined(MpM_UseCustomStringBuffer)) std::string buffAsString(outBuffer.str()); # endif // ! defined(MpM_UseCustomStringBuffer) # if defined(MpM_UseCustomStringBuffer) outString = _outBuffer.getString(outLength); # else // ! defined(MpM_UseCustomStringBuffer) outString = bufAsString.c_str(); outLength = bufAsString.length(); # endif // ! defined(MpM_UseCustomStringBuffer) if (outString && outLength) { void * rawString = static_cast<void *>(const_cast<char *>(outString)); yarp::os::Value blobValue(rawString, static_cast<int>(outLength)); _messageBottle.add(blobValue); } } else { hr = S_FALSE; } } for (int ii = 0; _countof(ppBodies) > ii; ++ii) { SafeRelease(ppBodies[ii]); } SafeRelease(bodyFrame); if (SUCCEEDED(hr) && _outChannel) { if (0 < _messageBottle.size()) { if (! _outChannel->write(_messageBottle)) { ODL_LOG("(! _outChannel->write(_messageBottle))"); //#### # if defined(MpM_StallOnSendProblem) Stall(); # endif // defined(MpM_StallOnSendProblem) } } } } } } } #endif // ! defined(MpM_BuildDummyServices) ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::processEventData void KinectV2BlobEventThread::run(void) { ODL_OBJENTER(); //#### for ( ; ! isStopping(); ) { #if (! defined(MpM_BuildDummyServices)) MSG msg; #endif // ! defined(MpM_BuildDummyServices) #if (! defined(MpM_BuildDummyServices)) while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { DispatchMessage(&msg); } if (_frameEventHandle) { HANDLE handles[] = { reinterpret_cast<HANDLE>(_frameEventHandle) }; switch (MsgWaitForMultipleObjects(_countof(handles), handles, false, 1000, QS_ALLINPUT)) { case WAIT_OBJECT_0 : processEventData(); break; default : break; } } if (WM_QUIT == msg.message) { stop(); } #endif // ! defined(MpM_BuildDummyServices) ConsumeSomeTime(); } ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::run void KinectV2BlobEventThread::setScale(const double newScale) { ODL_OBJENTER(); //#### ODL_D1("newScale = ", newScale); //#### _translationScale = newScale; ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::setScale bool KinectV2BlobEventThread::threadInit(void) { ODL_OBJENTER(); //#### #if defined(MpM_BuildDummyServices) bool result = true; #else // ! defined(MpM_BuildDummyServices) bool result = SUCCEEDED(initializeDefaultSensor()); #endif // ! defined(MpM_BuildDummyServices) ODL_OBJEXIT_B(result); //#### return result; } // KinectV2BlobEventThread::threadInit void KinectV2BlobEventThread::threadRelease(void) { ODL_OBJENTER(); //#### #if (! defined(MpM_BuildDummyServices)) if (_bodyFrameReader && _frameEventHandle) { _bodyFrameReader->UnsubscribeFrameArrived(_frameEventHandle); } _frameEventHandle = NULL; // done with body frame reader SafeRelease(_bodyFrameReader); SafeRelease(_bodyFrameSource); // close the Kinect Sensor if (_kinectSensor) { _kinectSensor->Close(); } SafeRelease(_kinectSensor); #endif // ! defined(MpM_BuildDummyServices) ODL_OBJEXIT(); //#### } // KinectV2BlobEventThread::threadRelease #if defined(__APPLE__) # pragma mark Global functions #endif // defined(__APPLE__)
37.780446
100
0.596976
opendragon
5b448e15e50d931d5db42b5e4c1798ce6273fa06
457
cpp
C++
chap13/Page532_rvalue_reference.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap13/Page532_rvalue_reference.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap13/Page532_rvalue_reference.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
// Warning: this is for verification. It cannot compile. // The problem lies in line 7 and 8. int main() { int i = 42; int &r = i; // ok: r refers to i int &&rr = i;// error: cannot bind an rvalue reference to an lvalue int &r2 = i * 42; // error: i * 42 is an rvalue const int &r3 = i * 42; // ok: we can bind a reference to const to an rvalue int &&rr2 = i * 42; // ok: bind rr2 to the result of the multiplication return 0; }
35.153846
80
0.608315
sjbarigye
5b50bbceb41a7f60e4fed5b55b625caeb5501685
807
cpp
C++
llvm/lib/Transforms/Obfuscation/HelloWorld.cpp
bluesadi/Pluto-Obfuscator
b79a9d7d855dc771bcbd04602a31cf51e6518794
[ "MIT" ]
181
2022-01-24T17:39:42.000Z
2022-03-29T14:39:58.000Z
llvm/lib/Transforms/Obfuscation/HelloWorld.cpp
bluesadi/Pluto-Obfuscator
b79a9d7d855dc771bcbd04602a31cf51e6518794
[ "MIT" ]
9
2022-01-30T14:01:01.000Z
2022-03-30T04:33:20.000Z
llvm/lib/Transforms/Obfuscation/HelloWorld.cpp
bluesadi/Pluto-Obfuscator
b79a9d7d855dc771bcbd04602a31cf51e6518794
[ "MIT" ]
41
2022-01-25T07:12:50.000Z
2022-03-26T06:17:04.000Z
#include "llvm/Transforms/Obfuscation/HelloWorld.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "Eigen/Dense" #include <iostream> using namespace Eigen; using namespace llvm; bool HelloWorld::runOnFunction(Function &F){ if(enable){ MatrixXd A(4, 5); Vector4d b; A << 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1; b << 0, 0, 0, 0; VectorXd x = A.fullPivLu().kernel().col(0); std::cout << "DEBUG: " << x << "\n"; outs() << "Hello, " << F.getName() << "\n"; } return false; } FunctionPass* llvm::createHelloWorldPass(bool enable){ return new HelloWorld(enable); } char HelloWorld::ID = 0;
26.9
54
0.577447
bluesadi
5b51bce57c7c78fa5ef15f2f7efa4a73feaebdf6
726
hpp
C++
Engine/helpers/TaskManager.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
32
2015-07-04T02:47:22.000Z
2022-01-19T00:07:51.000Z
Engine/helpers/TaskManager.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
null
null
null
Engine/helpers/TaskManager.hpp
JuDelCo/SFML2-Game
b234eb59266c6969d3c57ee5d3833e4090205a90
[ "Zlib" ]
11
2016-11-14T15:53:15.000Z
2020-05-29T12:12:54.000Z
// Copyright (c) 2013 Juan Delgado (JuDelCo) // License: zlib/libpng License // zlib/libpng License web page: http://opensource.org/licenses/Zlib #pragma once #ifndef TASK_MANAGER_HPP #define TASK_MANAGER_HPP #include <memory> #include <list> #include "TaskInterface.hpp" class ITaskManager : public ITask { public: ITaskManager(unsigned int priority = 10000) : ITask(priority) {}; ~ITaskManager() {} bool addTask(ITask::Ptr& task); void updateTaskList(); void suspendTask(ITask::Ptr& task); void resumeTask(ITask::Ptr& task); void removeTask(ITask::Ptr& task); void killAllTasks(); protected: std::list<ITask::Ptr> m_taskList; std::list<ITask::Ptr> m_pausedTaskList; }; #endif // TASK_MANAGER_HPP
22.6875
68
0.725895
JuDelCo
5b557dca11be97d6064cc54b1db78aa1072e4959
2,553
hpp
C++
include/disposer/core/exec_input.hpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
null
null
null
include/disposer/core/exec_input.hpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
24
2017-03-10T10:45:36.000Z
2018-07-05T19:38:58.000Z
include/disposer/core/exec_input.hpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
2
2017-02-21T06:45:42.000Z
2020-04-18T11:22:33.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2015-2018 Benjamin Buch // // https://github.com/bebuch/disposer // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) //----------------------------------------------------------------------------- #ifndef _disposer__core__exec_input__hpp_INCLUDED_ #define _disposer__core__exec_input__hpp_INCLUDED_ #include "exec_input_base.hpp" #include "exec_output.hpp" #include "../tool/input_data.hpp" namespace disposer{ /// \brief The actual exec_input type template < typename Name, typename T, bool IsRequired > class exec_input: public exec_input_base{ public: /// \brief The actual type using type = T; /// \brief Whether the input must always be connected with an output static constexpr auto is_required = std::bool_constant< IsRequired >(); /// \brief Compile time name of the input using name_type = Name; /// \brief Name object static constexpr auto name = name_type{}; /// \brief Constructor exec_input(hana::tuple< input< Name, T, IsRequired > const&, output_map_type const& > const& data )noexcept : exec_input_base( data[hana::size_c< 0 >].output_ptr() != nullptr ? data[hana::size_c< 1 >] .at(data[hana::size_c< 0 >].output_ptr()) : nullptr) {} /// \brief Is the input connected to an output bool is_connected()noexcept{ static_assert(IsRequired, "Input is required and therefore always connected! " "Just don't ask ;-)"); return output_ptr() != nullptr; } /// \brief Get all data without transferring ownership input_data_r< T > references(){ verify_connection(); return output_ptr()->references(); } /// \brief Get all data with transferring ownership input_data_v< T > values(){ verify_connection(); return output_ptr()->values(); } /// \brief Tell the connected output that this input finished void cleanup()noexcept{ if(output_ptr()){ output_ptr()->cleanup(); } } private: /// \brief Get a pointer to the connected exec_output or a nullptr unnamed_exec_output< T >* output_ptr()const noexcept{ return static_cast< unnamed_exec_output< T >* >( exec_input_base::output_ptr()); } void verify_connection()noexcept(IsRequired){ if constexpr(!IsRequired) if(!output_ptr()){ throw std::logic_error("input(" + to_std_string(name) + ") is not linked to an output"); } } }; } #endif
25.787879
79
0.650215
bebuch
5b5b4794649f5f3e6c1c811ce35d0c74e2e7aeed
1,254
hpp
C++
include/list_sort.hpp
tjolsen/tmpl
e49e605fe622ed556dab94fb6560b5d3fa46e8e8
[ "BSD-3-Clause" ]
8
2018-02-10T17:44:45.000Z
2022-03-22T18:49:44.000Z
include/list_sort.hpp
tjolsen/tmpl
e49e605fe622ed556dab94fb6560b5d3fa46e8e8
[ "BSD-3-Clause" ]
null
null
null
include/list_sort.hpp
tjolsen/tmpl
e49e605fe622ed556dab94fb6560b5d3fa46e8e8
[ "BSD-3-Clause" ]
1
2019-02-19T14:54:11.000Z
2019-02-19T14:54:11.000Z
// // Created by tyler on 1/14/18. // #ifndef TMPL_LIST_SORT_HPP #define TMPL_LIST_SORT_HPP #include "detail/list_sort_detail.hpp" #include "tmpl_common.hpp" #include "type_list.hpp" #include "value_list.hpp" NAMESPACE_TMPL_OPEN /** * Implementation of constexpr mergesort on value_list using a user-supplied * comparison function */ template <auto... V, typename Compare> auto sort(value_list<V...> List, Compare &&compare) { if constexpr (List.size() == 0 || List.size() == 1) { return List; } else { constexpr auto Midpoint = List.size() / 2; return detail::merge(slice<0, Midpoint>(List), slice<Midpoint, List.size()>(List), compare); } } /** * Implementation of constexpr mergesort on type_list using a user-supplied * comparison function */ template <typename... T, typename Compare> auto sort(type_list<T...> List, Compare &&compare) { if constexpr (List.size() == 0 || List.size() == 1) { return List; } else { constexpr auto Midpoint = List.size() / 2; return detail::merge(slice<0, Midpoint>(List), slice<Midpoint, List.size()>(List), compare); } } NAMESPACE_TMPL_CLOSE #endif // TMPL_LIST_SORT_HPP
25.08
76
0.637161
tjolsen
5b6372708d883dc511fced211a6397c029a94a30
1,897
hpp
C++
Engine/Core/Headers/Molten/Utility/FpsTracker.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Headers/Molten/Utility/FpsTracker.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Headers/Molten/Utility/FpsTracker.hpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2021 Jimmie Bergmann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files(the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions : * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef MOLTEN_CORE_UTILITY_FPSTRACKER_HPP #define MOLTEN_CORE_UTILITY_FPSTRACKER_HPP #include "Molten/System/Time.hpp" #include <vector> namespace Molten { /** Utility class for tracking fps over time. */ class MOLTEN_API FpsTracker { public: explicit FpsTracker(const size_t averageSampleCount); void ResetFrameSamples(); void RegisterSampleFrame(const Time frameTime); [[nodiscard]] Time GetMinFrameTime() const; [[nodiscard]] Time GetMaxFrameTime() const; [[nodiscard]] Time GetAverageFrameTime() const; private: Time m_minFrameTime; Time m_maxFrameTime; size_t m_registeredFrames; size_t m_currentSample; std::vector<Time> m_frameSamples; }; } #endif
30.596774
80
0.735372
jimmiebergmann
5b64342accd946d8e399f38e53c67df946a40cd9
1,142
cpp
C++
2019/cpp/1915.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
1
2021-12-04T20:55:02.000Z
2021-12-04T20:55:02.000Z
2019/cpp/1915.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
2019/cpp/1915.cpp
Chrinkus/advent-of-code
b2ae137dc7a1d6fc9e20f29549e891404591c47f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <sstream> #include <unordered_map> #include "Intcode_vm.hpp" #include "Point.hpp" class Droid { enum class Dir { north=1, south, west, east }; enum class Status { wall, moved, goal }; public: Droid() = delete; Droid(const std::string& intcode) : brain{intcode} { } Point location() const { return loc; } private: Intcode_vm brain; Point loc; std::stringstream input; std::stringstream output; }; std::unordered_map<std::string,char> feel_around_in_the_dark(Droid& droid) { std::unordered_map<std::string,char> umap; return umap; } int shortest_path(const std::unordered_map<std::string,char>& um) { return um.size(); } int main() { std::cout << "Advent of Code 2019 - Day 15\n" << "Oxygen System\n"; std::string input; std::cin >> input; Droid droid {input}; std::unordered_map<std::string,char> umap = feel_around_in_the_dark(droid); auto part1 = shortest_path(umap); auto part2 = 0; std::cout << "Part 1: " << part1 << '\n'; std::cout << "Part 2: " << part2 << '\n'; }
20.392857
79
0.6331
Chrinkus
5b67eb4865fad099f78c58617bc5b6c66dc2a411
6,870
cpp
C++
src/HydroMonitorNetwork.cpp
wvmarle/HydroMonitor
c3f6701bd84d13d74bd5a5f7e6b4b83944f30003
[ "MIT" ]
1
2021-12-31T01:44:38.000Z
2021-12-31T01:44:38.000Z
src/HydroMonitorNetwork.cpp
wvmarle/HydroMonitor
c3f6701bd84d13d74bd5a5f7e6b4b83944f30003
[ "MIT" ]
null
null
null
src/HydroMonitorNetwork.cpp
wvmarle/HydroMonitor
c3f6701bd84d13d74bd5a5f7e6b4b83944f30003
[ "MIT" ]
2
2018-11-12T09:21:33.000Z
2020-07-09T02:35:30.000Z
#include <HydroMonitorNetwork.h> /* Take care of network connections and building up html pages. */ /* The constructor. */ HydroMonitorNetwork::HydroMonitorNetwork() { } /* Start the network services. */ void HydroMonitorNetwork::begin(HydroMonitorCore::SensorData *sd, HydroMonitorLogging *l, ESP8266WebServer *srv) { sensorData = sd; logging = l; logging->writeTrace(F("HydroMonitorNetwork: configured networking services.")); if (NETWORK_EEPROM > 0) { #ifdef USE_24LC256_EEPROM sensorData->EEPROM->get(NETWORK_EEPROM, settings); #else EEPROM.get(NETWORK_EEPROM, settings); #endif } server = srv; } /* Send html response. */ void HydroMonitorNetwork::htmlResponse() { server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); server->sendHeader(F("Pragma"), F("no-cache")); server->sendHeader(F("Expires"), F("-1")); server->setContentLength(CONTENT_LENGTH_UNKNOWN); // here begin chunked transfer server->send(200, F("text/html"), F("")); } /* send plain response. */ void HydroMonitorNetwork::plainResponse() { server->send_P(200, PSTR("text/plain"), ""); } /* Initiate NTP update if connection was established */ void HydroMonitorNetwork::ntpUpdateInit() { udp.begin(LOCAL_NTP_PORT); updateTime = millis(); startTime = millis(); if (WiFi.hostByName(NTP_SERVER_NAME, timeServerIP) ) { // Get a random server from the pool. sendNTPpacket(timeServerIP); // Send an NTP packet to a time server. } else { udp.stop(); } } /** This function should be called frequently until it returns false, meaning either time has been received, or an ntp timeout. Check if NTP packet was received Re-request every 5 seconds Stop trying after a timeout Returns true if not done updating; false if either timeout or a time has been received. */ bool HydroMonitorNetwork::ntpCheck() { // Timeout after 30 seconds. if (millis() - startTime > 30 * 1000ul) { logging->writeTrace(F("HydroMonitorNetwork: NTP timeout.")); return false; } // Re-request every 5 seconds. if (millis() - updateTime > 5 * 1000ul) { logging->writeTrace(F("HydroMonitorNetwork: Re-requesting the time from NTP server.")); udp.stop(); yield(); udp.begin(LOCAL_NTP_PORT); sendNTPpacket(timeServerIP); updateTime = millis(); return true; } // Check whether a response has been received. if (doNtpUpdateCheck()) { udp.stop(); setTime(epoch); // We use UTC internally, easier overall. logging->writeTrace(F("HydroMonitorNetwork: successfully received time over NTP.")); return false; } // No response; no timeout; we're still updating. return true; } /** Send NTP packet to NTP server */ uint32_t HydroMonitorNetwork::sendNTPpacket(IPAddress & address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: udp.beginPacket(address, 123); //NTP requests are to port 123 udp.write(packetBuffer, NTP_PACKET_SIZE); udp.endPacket(); yield(); logging->writeTrace(F("HydroMonitorNetwork: NTP packet sent.")); } /** Check if a packet was recieved. Process NTP information if yes */ bool HydroMonitorNetwork::doNtpUpdateCheck() { yield(); uint16_t cb = udp.parsePacket(); if (cb) { // We've received a packet, read the data from it udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: uint32_t highWord = word(packetBuffer[40], packetBuffer[41]); uint32_t lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): uint32_t secsSince1900 = highWord << 16 | lowWord; // now convert NTP time into everyday time: // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: const uint32_t seventyYears = 2208988800UL; // subtract seventy years: epoch = secsSince1900 - seventyYears; return (epoch != 0); } return false; } /* Create the header part of the main html page. */ void HydroMonitorNetwork::htmlPageHeader(bool refresh) { char buff[12]; server->sendContent_P(PSTR("\ <!DOCTYPE html>\n\ <html><head>\n")); if (refresh) { server->sendContent_P(PSTR("\ <meta http-equiv=\"refresh\" content=\"")); server->sendContent(itoa(REFRESH, buff, 10)); server->sendContent_P(PSTR("\">\n")); } server->sendContent_P(PSTR("\ <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n\ <title>City Hydroponics - grow your own, in the city! - HydroMonitor output</title>\n\ </head>\n\ <body>\n\ <a href=\"/\">\n\ <img src=\"https://www.cityhydroponics.hk/tmp/logo_banner.jpg\" alt=\"City Hydroponics\">\n\ </a>\n\ <h1>HydroMonitor - monitor your hydroponic system data</h1>\n\ <h2>")); if (strlen(sensorData->systemName) > 0) { server->sendContent(sensorData->systemName); } server->sendContent_P(PSTR("</h2>\n\ <p></p>\n")); } void HydroMonitorNetwork::htmlPageFooter() { server->sendContent_P(PSTR("\ </body></html>")); server->sendContent(F("")); // this tells web client that transfer is done server->client().stop(); } void HydroMonitorNetwork::redirectTo(char* target) { htmlResponse(); server->sendContent_P(PSTR("\ <!DOCTYPE html>\n\ <html>\n\ <head>\n\ <meta http-equiv = \"refresh\" content = \"0; url = ")); server->sendContent(target); server->sendContent_P(PSTR("\" />\n\ </head>\n\ <body>\n\ </body>\n\ </html>")); server->sendContent(F("")); // this tells web client that transfer is done server->client().stop(); } /* The settings as HTML. */ void HydroMonitorNetwork::settingsHtml(ESP8266WebServer *server) { } /* The settings as JSON. */ bool HydroMonitorNetwork::settingsJSON(ESP8266WebServer* server) { return false; // None. } /* Update the settings. */ void HydroMonitorNetwork::updateSettings(ESP8266WebServer* server) { }
28.271605
114
0.658661
wvmarle
5b6a7dfb5f80236de8b1327a9f49742dcb2e9809
69,831
cpp
C++
src/engine/rhi/rhi-vulkan.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
16
2015-12-15T17:17:37.000Z
2021-12-07T20:19:38.000Z
src/engine/rhi/rhi-vulkan.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
null
null
null
src/engine/rhi/rhi-vulkan.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
1
2016-03-25T08:04:58.000Z
2016-03-25T08:04:58.000Z
#include "rhi-internal.h" #include <sstream> #include <map> #define GLFW_INCLUDE_NONE #include <vulkan/vulkan.h> #include <GLFW/glfw3.h> #pragma comment(lib, "vulkan-1.lib") #include <queue> #include <set> #include <iostream> auto get_tuple(const VkAttachmentDescription & desc) { return std::tie(desc.flags, desc.format, desc.samples, desc.loadOp, desc.storeOp, desc.stencilLoadOp, desc.stencilStoreOp, desc.initialLayout, desc.finalLayout); } bool operator < (const VkAttachmentDescription & a, const VkAttachmentDescription & b) { return get_tuple(a) < get_tuple(b); } bool operator < (const VkAttachmentReference & a, const VkAttachmentReference & b) { return std::tie(a.attachment, a.layout) < std::tie(b.attachment, b.layout); } namespace rhi { // Initialize tables auto convert_vk(shader_stage stage) { switch(stage) { default: fail_fast(); #define RHI_SHADER_STAGE(CASE, VK, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(address_mode mode) { switch(mode) { default: fail_fast(); #define RHI_ADDRESS_MODE(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(primitive_topology topology) { switch(topology) { default: fail_fast(); #define RHI_PRIMITIVE_TOPOLOGY(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(cull_mode mode) { switch(mode) { default: fail_fast(); #define RHI_CULL_MODE(CASE, VK, DX, GL_ENABLED, GL_CULL_FACE) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(compare_op op) { switch(op) { default: fail_fast(); #define RHI_COMPARE_OP(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(stencil_op op) { switch(op) { default: fail_fast(); #define RHI_STENCIL_OP(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(blend_op op) { switch(op) { default: fail_fast(); #define RHI_BLEND_OP(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(blend_factor factor) { switch(factor) { default: fail_fast(); #define RHI_BLEND_FACTOR(CASE, VK, DX, GL) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(attribute_format format) { switch(format) { default: fail_fast(); #define RHI_ATTRIBUTE_FORMAT(CASE, VK, DX, GL_SIZE, GL_TYPE, GL_NORMALIZED) case CASE: return VK; #include "rhi-tables.inl" }} auto convert_vk(image_format format) { switch(format) { default: fail_fast(); #define RHI_IMAGE_FORMAT(CASE, SIZE, TYPE, VK, DX, GLI, GLF, GLT) case CASE: return VK; #include "rhi-tables.inl" }} struct vk_render_pass_desc { std::vector<VkAttachmentDescription> attachments; std::vector<VkAttachmentReference> color_refs; std::optional<VkAttachmentReference> depth_ref; }; bool operator < (const vk_render_pass_desc & a, const vk_render_pass_desc & b) { return std::tie(a.attachments, a.color_refs, a.depth_ref) < std::tie(b.attachments, b.color_refs, b.depth_ref); } struct physical_device_selection { VkPhysicalDevice physical_device; uint32_t queue_family; VkSurfaceFormatKHR surface_format; VkPresentModeKHR present_mode; uint32_t swap_image_count; VkSurfaceTransformFlagBitsKHR surface_transform; }; struct vk_device : device { // Core Vulkan objects std::function<void(const char *)> debug_callback; VkInstance instance {}; PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT {}; VkDebugReportCallbackEXT callback {}; physical_device_selection selection {}; VkDevice dev {}; VkQueue queue {}; VkPhysicalDeviceProperties device_props {}; VkPhysicalDeviceMemoryProperties mem_props {}; // Resources for staging memory size_t staging_buffer_size {32*1024*1024}; VkBuffer staging_buffer {}; VkDeviceMemory staging_memory {}; void * mapped_staging_memory {}; VkCommandPool staging_pool {}; // Scheduling constexpr static int fence_ring_size = 256, fence_ring_mask = 0xFF; VkFence ring_fences[fence_ring_size]; uint64_t submitted_index, completed_index; struct scheduled_action { uint64_t after_completion_index; std::function<void(vk_device &)> execute; }; std::queue<scheduled_action> scheduled_actions; // Deduplicated render passes std::map<vk_render_pass_desc, VkRenderPass> render_passes; vk_device(std::function<void(const char *)> debug_callback); ~vk_device(); // Core helper functions void destroy_immediate(VkRenderPass pass) { vkDestroyRenderPass(dev, pass, nullptr); } void destroy_immediate(VkDeviceMemory memory) { vkFreeMemory(dev, memory, nullptr); } void destroy_immediate(VkBuffer buffer) { vkDestroyBuffer(dev, buffer, nullptr); } void destroy_immediate(VkSampler sampler) { vkDestroySampler(dev, sampler, nullptr); } void destroy_immediate(VkImage image) { vkDestroyImage(dev, image, nullptr); } void destroy_immediate(VkImageView image_view) { vkDestroyImageView(dev, image_view, nullptr); } void destroy_immediate(VkFramebuffer framebuffer) { vkDestroyFramebuffer(dev, framebuffer, nullptr); } void destroy_immediate(VkDescriptorSetLayout layout) { vkDestroyDescriptorSetLayout(dev, layout, nullptr); } void destroy_immediate(VkPipelineLayout layout) { vkDestroyPipelineLayout(dev, layout, nullptr); } void destroy_immediate(VkShaderModule module) { vkDestroyShaderModule(dev, module, nullptr); } void destroy_immediate(VkPipeline pipeline) { vkDestroyPipeline(dev, pipeline, nullptr); } void destroy_immediate(VkDescriptorPool pool) { vkDestroyDescriptorPool(dev, pool, nullptr); } void destroy_immediate(VkSemaphore semaphore) { vkDestroySemaphore(dev, semaphore, nullptr); } void destroy_immediate(VkFence fence) { vkDestroyFence(dev, fence, nullptr); } void destroy_immediate(VkSurfaceKHR surface) { vkDestroySurfaceKHR(instance, surface, nullptr); } void destroy_immediate(VkSwapchainKHR swapchain) { vkDestroySwapchainKHR(dev, swapchain, nullptr); } void destroy_immediate(GLFWwindow * window) { glfwDestroyWindow(window); } template<class T> void destroy(T object) { scheduled_actions.push({submitted_index, [object](vk_device & dev) { dev.destroy_immediate(object); }}); } VkDeviceMemory allocate(const VkMemoryRequirements & reqs, VkMemoryPropertyFlags props); VkRenderPass get_render_pass(const vk_render_pass_desc & desc); uint64_t submit(const VkSubmitInfo & submit_info); // info device_info get_info() const final { return {linalg::zero_to_one, false}; } // resources ptr<buffer> create_buffer(const buffer_desc & desc, const void * initial_data) final; ptr<image> create_image(const image_desc & desc, std::vector<const void *> initial_data) final; ptr<sampler> create_sampler(const sampler_desc & desc) final; ptr<framebuffer> create_framebuffer(const framebuffer_desc & desc) final; ptr<window> create_window(const int2 & dimensions, std::string_view title) final; ptr<descriptor_set_layout> create_descriptor_set_layout(const std::vector<descriptor_binding> & bindings) final; ptr<pipeline_layout> create_pipeline_layout(const std::vector<const descriptor_set_layout *> & sets) final; ptr<shader> create_shader(const shader_desc & desc) final; ptr<pipeline> create_pipeline(const pipeline_desc & desc) final; ptr<descriptor_pool> create_descriptor_pool() final; ptr<command_buffer> create_command_buffer() final; uint64_t submit(command_buffer & cmd) final; uint64_t acquire_and_submit_and_present(command_buffer & cmd, window & window) final; uint64_t get_last_submission_id() final { return submitted_index; } void wait_until_complete(uint64_t submit_id) final; }; autoregister_backend<vk_device> autoregister_vk_backend {"Vulkan 1.0", client_api::vulkan}; struct vk_buffer : buffer { ptr<vk_device> device; VkDeviceMemory memory_object; VkBuffer buffer_object; char * mapped = 0; vk_buffer(vk_device * device, const buffer_desc & desc, const void * initial_data); ~vk_buffer(); size_t get_offset_alignment() final { return exactly(device->device_props.limits.minUniformBufferOffsetAlignment); } char * get_mapped_memory() final { return mapped; } }; struct vk_image : image { ptr<vk_device> device; image_desc desc; VkDeviceMemory device_memory; VkImage image_object; VkImageView image_view; VkImageCreateInfo image_info; VkImageViewCreateInfo view_info; vk_image(vk_device * device, const image_desc & desc, std::vector<const void *> initial_data); ~vk_image(); VkImageView create_view(int mip, int layer) const; }; struct vk_sampler : sampler { ptr<vk_device> device; VkSampler sampler; vk_sampler(vk_device * device, const sampler_desc & desc); ~vk_sampler(); }; struct vk_framebuffer : framebuffer { ptr<vk_device> device; std::vector<VkFormat> color_formats; std::optional<VkFormat> depth_format; int2 dims; GLFWwindow * glfw_window {}; VkSurfaceKHR surface {}; VkSwapchainKHR swapchain {}; std::vector<VkImageView> views; // Views belonging to this framebuffer std::vector<VkFramebuffer> framebuffers; // If this framebuffer targets a swapchain, the framebuffers for each swapchain image uint32_t current_index {0}; // If this framebuffer targets a swapchain, the index of the current backbuffer vk_framebuffer(vk_device * device, const framebuffer_desc & desc); vk_framebuffer(vk_device * device, vk_image & depth_image, const std::string & title); ~vk_framebuffer(); coord_system get_ndc_coords() const final { return {coord_axis::right, coord_axis::down, coord_axis::forward}; } vk_render_pass_desc get_render_pass_desc(const render_pass_desc & desc) const; }; struct vk_window : window { ptr<vk_device> device; ptr<image> depth_image; ptr<vk_framebuffer> swapchain_framebuffer; VkSemaphore image_available {}, render_finished {}; vk_window(vk_device * device, const int2 & dimensions, std::string title); ~vk_window(); GLFWwindow * get_glfw_window() { return swapchain_framebuffer->glfw_window; } framebuffer & get_swapchain_framebuffer() { return *swapchain_framebuffer; } }; struct vk_descriptor_set_layout : descriptor_set_layout { ptr<vk_device> device; VkDescriptorSetLayout layout; vk_descriptor_set_layout(vk_device * device, const std::vector<descriptor_binding> & bindings); ~vk_descriptor_set_layout(); }; struct vk_pipeline_layout : base_pipeline_layout { ptr<vk_device> device; VkPipelineLayout layout; vk_pipeline_layout(vk_device * device, const std::vector<const descriptor_set_layout *> & sets); ~vk_pipeline_layout(); }; struct vk_shader : shader { ptr<vk_device> device; VkShaderModule module; VkShaderStageFlagBits stage; vk_shader(vk_device * device, const shader_desc & desc); ~vk_shader(); }; struct vk_pipeline : base_pipeline { ptr<vk_device> device; pipeline_desc desc; mutable std::unordered_map<VkRenderPass, VkPipeline> pipeline_objects; vk_pipeline(vk_device * device, const pipeline_desc & desc); ~vk_pipeline(); VkPipeline get_pipeline(VkRenderPass render_pass) const; }; struct vk_descriptor_set : descriptor_set { VkDevice device; VkDescriptorSet set; void write(int binding, buffer_range range) final; void write(int binding, sampler & sampler, image & image) final; }; struct vk_descriptor_pool : descriptor_pool { ptr<vk_device> device; VkDescriptorPool pool; std::vector<counted<vk_descriptor_set>> sets; size_t used_sets; vk_descriptor_pool(vk_device * device); ~vk_descriptor_pool(); void reset() final; ptr<descriptor_set> alloc(const descriptor_set_layout & layout) final; }; struct vk_command_buffer : command_buffer { ptr<vk_device> device; std::set<ptr<const object>> referenced_objects; VkCommandBuffer cmd; VkRenderPass current_pass; vk_framebuffer * current_framebuffer; void record_reference(const object & object); void generate_mipmaps(image & image) final; void begin_render_pass(const render_pass_desc & desc, framebuffer & framebuffer) final; void clear_depth(float depth) final; void clear_stencil(uint8_t stencil) final; void set_viewport_rect(int x0, int y0, int x1, int y1) final; void set_scissor_rect(int x0, int y0, int x1, int y1) final; void set_stencil_ref(uint8_t stencil) final; void bind_pipeline(const pipeline & pipe) final; void bind_descriptor_set(const pipeline_layout & layout, int set_index, const descriptor_set & set) final; void bind_vertex_buffer(int index, buffer_range range) final; void bind_index_buffer(buffer_range range) final; void draw(int first_vertex, int vertex_count) final; void draw_indexed(int first_index, int index_count) final; void end_render_pass() final; }; ptr<buffer> vk_device::create_buffer(const buffer_desc & desc, const void * initial_data) { return new delete_when_unreferenced<vk_buffer>{this, desc, initial_data}; } ptr<image> vk_device::create_image(const image_desc & desc, std::vector<const void *> initial_data) { return new delete_when_unreferenced<vk_image>{this, desc, initial_data}; } ptr<sampler> vk_device::create_sampler(const sampler_desc & desc) { return new delete_when_unreferenced<vk_sampler>{this, desc}; } ptr<framebuffer> vk_device::create_framebuffer(const framebuffer_desc & desc) { return new delete_when_unreferenced<vk_framebuffer>{this, desc}; } ptr<window> vk_device::create_window(const int2 & dimensions, std::string_view title) { return new delete_when_unreferenced<vk_window>{this, dimensions, std::string{title}}; } ptr<descriptor_set_layout> vk_device::create_descriptor_set_layout(const std::vector<descriptor_binding> & bindings) { return new delete_when_unreferenced<vk_descriptor_set_layout>{this, bindings}; } ptr<pipeline_layout> vk_device::create_pipeline_layout(const std::vector<const descriptor_set_layout *> & sets) { return new delete_when_unreferenced<vk_pipeline_layout>{this, sets}; } ptr<shader> vk_device::create_shader(const shader_desc & desc) { return new delete_when_unreferenced<vk_shader>{this, desc}; } ptr<pipeline> vk_device::create_pipeline(const pipeline_desc & desc) { return new delete_when_unreferenced<vk_pipeline>{this, desc}; } ptr<descriptor_pool> vk_device::create_descriptor_pool() { return new delete_when_unreferenced<vk_descriptor_pool>{this}; } } namespace rhi { struct vulkan_error : public std::error_category { const char * name() const noexcept final { return "VkResult"; } std::string message(int value) const final { return std::to_string(value); } static const std::error_category & instance() { static vulkan_error inst; return inst; } }; void check(const char * func, VkResult result) { if(result != VK_SUCCESS) { throw std::system_error(std::error_code(exactly(static_cast<std::underlying_type_t<VkResult>>(result)), vulkan_error::instance()), to_string(func, "(...) failed")); } } static bool has_extension(const std::vector<VkExtensionProperties> & extensions, std::string_view name) { return std::find_if(begin(extensions), end(extensions), [name](const VkExtensionProperties & p) { return p.extensionName == name; }) != end(extensions); } static VkPresentModeKHR select_present_mode(const std::vector<VkPresentModeKHR> & supported_modes) { for(auto mode : supported_modes) if(mode == VK_PRESENT_MODE_MAILBOX_KHR) return mode; return VK_PRESENT_MODE_FIFO_KHR; } static std::optional<VkSurfaceFormatKHR> select_surface_format(const std::vector<VkSurfaceFormatKHR> & supported_formats) { if(supported_formats.size() == 1 && supported_formats[0].format == VK_FORMAT_UNDEFINED) return VkSurfaceFormatKHR{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; for(auto & f : supported_formats) if(f.format == VK_FORMAT_R8G8B8A8_SRGB || f.format == VK_FORMAT_B8G8R8A8_SRGB || f.format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) return f; return std::nullopt; } static physical_device_selection select_physical_device(VkInstance instance, const std::vector<const char *> & required_extensions) { glfwDefaultWindowHints(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_VISIBLE, 0); GLFWwindow * example_window = glfwCreateWindow(256, 256, "", nullptr, nullptr); VkSurfaceKHR example_surface = 0; check("glfwCreateWindowSurface", glfwCreateWindowSurface(instance, example_window, nullptr, &example_surface)); uint32_t device_count = 0; check("vkEnumeratePhysicalDevices", vkEnumeratePhysicalDevices(instance, &device_count, nullptr)); std::vector<VkPhysicalDevice> physical_devices(device_count); check("vkEnumeratePhysicalDevices", vkEnumeratePhysicalDevices(instance, &device_count, physical_devices.data())); for(auto & d : physical_devices) { // Skip physical devices which do not support our desired extensions uint32_t extension_count = 0; check("vkEnumerateDeviceExtensionProperties", vkEnumerateDeviceExtensionProperties(d, 0, &extension_count, nullptr)); std::vector<VkExtensionProperties> extensions(extension_count); check("vkEnumerateDeviceExtensionProperties", vkEnumerateDeviceExtensionProperties(d, 0, &extension_count, extensions.data())); for(auto req : required_extensions) if(!has_extension(extensions, req)) continue; // Skip physical devices who do not support at least one format and present mode for our example surface VkSurfaceCapabilitiesKHR surface_caps; check("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", vkGetPhysicalDeviceSurfaceCapabilitiesKHR(d, example_surface, &surface_caps)); uint32_t surface_format_count = 0, present_mode_count = 0; check("vkGetPhysicalDeviceSurfaceFormatsKHR", vkGetPhysicalDeviceSurfaceFormatsKHR(d, example_surface, &surface_format_count, nullptr)); std::vector<VkSurfaceFormatKHR> surface_formats(surface_format_count); check("vkGetPhysicalDeviceSurfaceFormatsKHR", vkGetPhysicalDeviceSurfaceFormatsKHR(d, example_surface, &surface_format_count, surface_formats.data())); auto surface_format = select_surface_format(surface_formats); if(!surface_format) continue; // Select a presentation mode check("vkGetPhysicalDeviceSurfacePresentModesKHR", vkGetPhysicalDeviceSurfacePresentModesKHR(d, example_surface, &present_mode_count, nullptr)); std::vector<VkPresentModeKHR> surface_present_modes(present_mode_count); check("vkGetPhysicalDeviceSurfacePresentModesKHR", vkGetPhysicalDeviceSurfacePresentModesKHR(d, example_surface, &present_mode_count, surface_present_modes.data())); const VkPresentModeKHR present_mode = select_present_mode(surface_present_modes); // Look for a queue family that supports both graphics and presentation to our example surface uint32_t queue_family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, nullptr); std::vector<VkQueueFamilyProperties> queue_family_props(queue_family_count); vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, queue_family_props.data()); for(uint32_t i=0; i<queue_family_props.size(); ++i) { VkBool32 present = VK_FALSE; check("vkGetPhysicalDeviceSurfaceSupportKHR", vkGetPhysicalDeviceSurfaceSupportKHR(d, i, example_surface, &present)); if((queue_family_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && present) { vkDestroySurfaceKHR(instance, example_surface, nullptr); glfwDestroyWindow(example_window); return {d, i, *surface_format, present_mode, std::min(surface_caps.minImageCount+1, surface_caps.maxImageCount), surface_caps.currentTransform}; } } } throw std::runtime_error("no suitable Vulkan device present"); } } //////////////// // vk_device // //////////////// using namespace rhi; vk_device::vk_device(std::function<void(const char *)> debug_callback) : debug_callback{debug_callback} { uint32_t extension_count = 0; auto ext = glfwGetRequiredInstanceExtensions(&extension_count); std::vector<const char *> extensions{ext, ext+extension_count}; const VkApplicationInfo app_info {VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "simple-scene", VK_MAKE_VERSION(1,0,0), "No Engine", VK_MAKE_VERSION(0,0,0), VK_API_VERSION_1_0}; const char * layers[] {"VK_LAYER_LUNARG_standard_validation"}; extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); const VkInstanceCreateInfo instance_info {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, nullptr, {}, &app_info, 1, layers, exactly(extensions.size()), extensions.data()}; check("vkCreateInstance", vkCreateInstance(&instance_info, nullptr, &instance)); auto vkCreateDebugReportCallbackEXT = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT")); vkDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT")); const VkDebugReportCallbackCreateInfoEXT callback_info {VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, nullptr, VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT, [](VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT object_type, uint64_t object, size_t location, int32_t message_code, const char * layer_prefix, const char * message, void * user_data) -> VkBool32 { auto & ctx = *reinterpret_cast<vk_device *>(user_data); if(ctx.debug_callback) ctx.debug_callback(message); return VK_FALSE; }, this}; check("vkCreateDebugReportCallbackEXT", vkCreateDebugReportCallbackEXT(instance, &callback_info, nullptr, &callback)); std::vector<const char *> device_extensions {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; selection = select_physical_device(instance, device_extensions); const float queue_priorities[] {1.0f}; const VkDeviceQueueCreateInfo queue_infos[] {{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, nullptr, {}, selection.queue_family, 1, queue_priorities}}; const VkDeviceCreateInfo device_info {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, nullptr, {}, 1, queue_infos, 1, layers, exactly(device_extensions.size()), device_extensions.data()}; check("vkCreateDevice", vkCreateDevice(selection.physical_device, &device_info, nullptr, &dev)); vkGetDeviceQueue(dev, selection.queue_family, 0, &queue); vkGetPhysicalDeviceProperties(selection.physical_device, &device_props); vkGetPhysicalDeviceMemoryProperties(selection.physical_device, &mem_props); // Set up staging buffer VkBufferCreateInfo buffer_info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; buffer_info.size = staging_buffer_size; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; check("vkCreateBuffer", vkCreateBuffer(dev, &buffer_info, nullptr, &staging_buffer)); VkMemoryRequirements mem_reqs; vkGetBufferMemoryRequirements(dev, staging_buffer, &mem_reqs); staging_memory = allocate(mem_reqs, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); check("vkBindBufferMemory", vkBindBufferMemory(dev, staging_buffer, staging_memory, 0)); check("vkMapMemory", vkMapMemory(dev, staging_memory, 0, buffer_info.size, 0, &mapped_staging_memory)); VkCommandPoolCreateInfo command_pool_info {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; command_pool_info.queueFamilyIndex = selection.queue_family; // TODO: Could use an explicit transfer queue command_pool_info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; check("vkCreateCommandPool", vkCreateCommandPool(dev, &command_pool_info, nullptr, &staging_pool)); // Initialize fence ring const VkFenceCreateInfo fence_info {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; for(auto & fence : ring_fences) check("vkCreateFence", vkCreateFence(dev, &fence_info, nullptr, &fence)); submitted_index = completed_index = 0; } vk_device::~vk_device() { // Flush our queue wait_until_complete(submitted_index); for(auto & fence : ring_fences) destroy_immediate(fence); for(auto & pair : render_passes) destroy_immediate(pair.second); // NOTE: We expect the higher level software layer to ensure that all API objects have been destroyed by this point vkDestroyCommandPool(dev, staging_pool, nullptr); vkDestroyBuffer(dev, staging_buffer, nullptr); vkUnmapMemory(dev, staging_memory); vkFreeMemory(dev, staging_memory, nullptr); vkDestroyDevice(dev, nullptr); vkDestroyDebugReportCallbackEXT(instance, callback, nullptr); vkDestroyInstance(instance, nullptr); } VkDeviceMemory vk_device::allocate(const VkMemoryRequirements & reqs, VkMemoryPropertyFlags props) { for(uint32_t i=0; i<mem_props.memoryTypeCount; ++i) { if(reqs.memoryTypeBits & (1 << i) && (mem_props.memoryTypes[i].propertyFlags & props) == props) { VkMemoryAllocateInfo alloc_info {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = reqs.size; alloc_info.memoryTypeIndex = i; VkDeviceMemory memory; check("vkAllocateMemory", vkAllocateMemory(dev, &alloc_info, nullptr, &memory)); return memory; } } throw std::runtime_error("no suitable memory type"); } VkRenderPass vk_device::get_render_pass(const vk_render_pass_desc & desc) { auto & pass = render_passes[desc]; if(!pass) { VkSubpassDescription subpass_desc {}; subpass_desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass_desc.colorAttachmentCount = exactly(countof(desc.color_refs)); subpass_desc.pColorAttachments = desc.color_refs.data(); subpass_desc.pDepthStencilAttachment = desc.depth_ref ? &*desc.depth_ref : nullptr; VkRenderPassCreateInfo render_pass_info {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; render_pass_info.attachmentCount = exactly(countof(desc.attachments)); render_pass_info.pAttachments = desc.attachments.data(); render_pass_info.subpassCount = 1; render_pass_info.pSubpasses = &subpass_desc; check("vkCreateRenderPass", vkCreateRenderPass(dev, &render_pass_info, nullptr, &pass)); } return pass; } ///////////////////////// // vk_device resources // ///////////////////////// vk_buffer::vk_buffer(vk_device * device, const buffer_desc & desc, const void * initial_data) : device{device} { // Create buffer with appropriate usage flags VkBufferCreateInfo buffer_info {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; buffer_info.size = desc.size; if(desc.flags & rhi::vertex_buffer_bit) buffer_info.usage |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; if(desc.flags & rhi::index_buffer_bit) buffer_info.usage |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT; if(desc.flags & rhi::uniform_buffer_bit) buffer_info.usage |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; if(desc.flags & rhi::storage_buffer_bit) buffer_info.usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; if(initial_data) buffer_info.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; check("vkCreateBuffer", vkCreateBuffer(device->dev, &buffer_info, nullptr, &buffer_object)); // Obtain and bind memory (TODO: Pool allocations) VkMemoryRequirements mem_reqs; vkGetBufferMemoryRequirements(device->dev, buffer_object, &mem_reqs); VkMemoryPropertyFlags memory_property_flags = 0; if(desc.flags & rhi::mapped_memory_bit) memory_property_flags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; else memory_property_flags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; memory_object = device->allocate(mem_reqs, memory_property_flags); check("vkBindBufferMemory", vkBindBufferMemory(device->dev, buffer_object, memory_object, 0)); // Initialize memory if requested to do so if(initial_data) { memcpy(device->mapped_staging_memory, initial_data, desc.size); auto cmd = device->create_command_buffer(); const VkBufferCopy copy {0, 0, desc.size}; vkCmdCopyBuffer(static_cast<vk_command_buffer &>(*cmd).cmd, device->staging_buffer, buffer_object, 1, &copy); device->submit(*cmd); } // Map memory if requested to do so if(desc.flags & rhi::mapped_memory_bit) { check("vkMapMemory", vkMapMemory(device->dev, memory_object, 0, desc.size, 0, reinterpret_cast<void**>(&mapped))); } } vk_buffer::~vk_buffer() { if(mapped) vkUnmapMemory(device->dev, memory_object); device->destroy(buffer_object); device->destroy(memory_object); } static void transition_image(VkCommandBuffer command_buffer, VkImage image, uint32_t mip_level, uint32_t array_layer, VkPipelineStageFlags src_stage_mask, VkAccessFlags src_access_mask, VkImageLayout old_layout, VkPipelineStageFlags dst_stage_mask, VkAccessFlags dst_access_mask, VkImageLayout new_layout) { const VkImageMemoryBarrier barriers[] {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, 0, src_access_mask, dst_access_mask, old_layout, new_layout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, {VK_IMAGE_ASPECT_COLOR_BIT, mip_level, 1, array_layer, 1}}; vkCmdPipelineBarrier(command_buffer, src_stage_mask, dst_stage_mask, 0, 0, nullptr, 0, nullptr, exactly(countof(barriers)), barriers); } vk_image::vk_image(vk_device * device, const image_desc & desc, std::vector<const void *> initial_data) : device{device}, desc{desc} { image_info = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; image_info.arrayLayers = 1; VkImageViewType view_type; switch(desc.shape) { case image_shape::_1d: image_info.imageType = VK_IMAGE_TYPE_1D; view_type = VK_IMAGE_VIEW_TYPE_1D; break; case image_shape::_2d: image_info.imageType = VK_IMAGE_TYPE_2D; view_type = VK_IMAGE_VIEW_TYPE_2D;break; case image_shape::_3d: image_info.imageType = VK_IMAGE_TYPE_3D; view_type = VK_IMAGE_VIEW_TYPE_3D;break; case image_shape::cube: image_info.imageType = VK_IMAGE_TYPE_2D; view_type = VK_IMAGE_VIEW_TYPE_CUBE; image_info.arrayLayers *= 6; image_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; break; default: fail_fast(); } image_info.format = convert_vk(desc.format); image_info.extent = {static_cast<uint32_t>(desc.dimensions.x), static_cast<uint32_t>(desc.dimensions.y), static_cast<uint32_t>(desc.dimensions.z)}; image_info.mipLevels = desc.mip_levels; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; if(image_info.mipLevels > 1) image_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if(desc.flags & image_flag::sampled_image_bit) image_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if(desc.flags & image_flag::color_attachment_bit) image_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if(desc.flags & image_flag::depth_attachment_bit) image_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; check("vkCreateImage", vkCreateImage(device->dev, &image_info, nullptr, &image_object)); VkMemoryRequirements mem_reqs; vkGetImageMemoryRequirements(device->dev, image_object, &mem_reqs); device_memory = device->allocate(mem_reqs, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); check("vkBindImageMemory", vkBindImageMemory(device->dev, image_object, device_memory, 0)); if(initial_data.size()) { if(initial_data.size() != image_info.arrayLayers) throw std::logic_error("not enough initial_data pointers"); for(size_t layer=0; layer<initial_data.size(); ++layer) { // Write initial data for this layer into the staging area const size_t image_size = get_pixel_size(desc.format) * product(desc.dimensions); if(image_size > device->staging_buffer_size) throw std::runtime_error("staging buffer exhausted"); memcpy(device->mapped_staging_memory, initial_data[layer], image_size); VkImageSubresourceLayers layers {}; layers.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; layers.baseArrayLayer = exactly(layer); layers.layerCount = 1; // Copy image contents from staging buffer into mip level zero auto cmd = device->create_command_buffer(); // Must transition to transfer_dst_optimal before any transfers occur transition_image(static_cast<vk_command_buffer &>(*cmd).cmd, image_object, 0, exactly(layer), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); // Copy to the image VkBufferImageCopy copy_region {}; copy_region.imageSubresource = layers; copy_region.imageExtent = image_info.extent; vkCmdCopyBufferToImage(static_cast<vk_command_buffer &>(*cmd).cmd, device->staging_buffer, image_object, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region); // After transfer finishes, transition to shader_read_only_optimal, and complete that before any shaders execute transition_image(static_cast<vk_command_buffer &>(*cmd).cmd, image_object, 0, exactly(layer), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); device->submit(*cmd); } } // Create a view of the overall object view_info = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; view_info.image = image_object; view_info.viewType = view_type; view_info.format = image_info.format; if(desc.flags & image_flag::depth_attachment_bit) view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; else view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.levelCount = image_info.mipLevels; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.layerCount = image_info.arrayLayers; check("vkCreateImageView", vkCreateImageView(device->dev, &view_info, nullptr, &image_view)); } vk_image::~vk_image() { device->destroy(image_view); device->destroy(image_object); device->destroy(device_memory); } VkImageView vk_image::create_view(int mip, int layer) const { auto info = view_info; switch(info.viewType) { case VK_IMAGE_VIEW_TYPE_CUBE: info.viewType = VK_IMAGE_VIEW_TYPE_2D; break; case VK_IMAGE_VIEW_TYPE_1D_ARRAY: info.viewType = VK_IMAGE_VIEW_TYPE_1D; break; case VK_IMAGE_VIEW_TYPE_2D_ARRAY: info.viewType = VK_IMAGE_VIEW_TYPE_2D; break; case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: info.viewType = VK_IMAGE_VIEW_TYPE_2D; break; } info.subresourceRange.baseMipLevel = exactly(mip); info.subresourceRange.levelCount = 1; info.subresourceRange.baseArrayLayer = exactly(layer); info.subresourceRange.layerCount = 1; VkImageView view; check("vkCreateImageView", vkCreateImageView(device->dev, &info, nullptr, &view)); return view; } vk_sampler::vk_sampler(vk_device * device, const sampler_desc & desc) : device{device} { auto convert_filter = [](rhi::filter filter) { switch(filter) { case rhi::filter::nearest: return VK_FILTER_NEAREST; case rhi::filter::linear: return VK_FILTER_LINEAR; default: fail_fast(); } }; auto convert_mipmap_mode = [](rhi::filter filter) { switch(filter) { case rhi::filter::nearest: return VK_SAMPLER_MIPMAP_MODE_NEAREST; case rhi::filter::linear: return VK_SAMPLER_MIPMAP_MODE_LINEAR; default: fail_fast(); } }; VkSamplerCreateInfo sampler_info = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; sampler_info.addressModeU = convert_vk(desc.wrap_s); sampler_info.addressModeV = convert_vk(desc.wrap_t); sampler_info.addressModeW = convert_vk(desc.wrap_r); sampler_info.magFilter = convert_filter(desc.mag_filter); sampler_info.minFilter = convert_filter(desc.min_filter); sampler_info.maxAnisotropy = 1.0; if(desc.mip_filter) { sampler_info.maxLod = 1000; sampler_info.mipmapMode = convert_mipmap_mode(*desc.mip_filter); } check("vkCreateSampler", vkCreateSampler(device->dev, &sampler_info, nullptr, &sampler)); } vk_sampler::~vk_sampler() { device->destroy(sampler); } vk_framebuffer::vk_framebuffer(vk_device * device, const framebuffer_desc & desc) : device{device} { dims = desc.dimensions; framebuffers.push_back(VK_NULL_HANDLE); rhi::render_pass_desc pass_desc; for(auto & color_attachment : desc.color_attachments) { color_formats.push_back(convert_vk(static_cast<vk_image &>(*color_attachment.image).desc.format)); views.push_back(static_cast<vk_image &>(*color_attachment.image).create_view(color_attachment.mip, color_attachment.layer)); pass_desc.color_attachments.push_back({dont_care{}, dont_care{}}); } if(desc.depth_attachment) { depth_format = convert_vk(static_cast<vk_image &>(*desc.depth_attachment->image).desc.format); views.push_back(static_cast<vk_image &>(*desc.depth_attachment->image).create_view(desc.depth_attachment->mip, desc.depth_attachment->layer)); pass_desc.depth_attachment = {dont_care{}, dont_care{}}; } VkFramebufferCreateInfo framebuffer_info {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; framebuffer_info.renderPass = device->get_render_pass(get_render_pass_desc(pass_desc)); framebuffer_info.attachmentCount = exactly(views.size()); framebuffer_info.pAttachments = views.data(); framebuffer_info.width = exactly(desc.dimensions.x); framebuffer_info.height = exactly(desc.dimensions.y); framebuffer_info.layers = 1; check("vkCreateFramebuffer", vkCreateFramebuffer(device->dev, &framebuffer_info, nullptr, &framebuffers[0])); } vk_framebuffer::vk_framebuffer(vk_device * device, vk_image & depth_image, const std::string & title) : device{device} { const int2 dimensions = depth_image.desc.dimensions.xy(); const std::string buffer {begin(title), end(title)}; glfwDefaultWindowHints(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfw_window = glfwCreateWindow(dimensions.x, dimensions.y, buffer.c_str(), nullptr, nullptr); check("glfwCreateWindowSurface", glfwCreateWindowSurface(device->instance, glfw_window, nullptr, &surface)); VkBool32 present = VK_FALSE; check("vkGetPhysicalDeviceSurfaceSupportKHR", vkGetPhysicalDeviceSurfaceSupportKHR(device->selection.physical_device, device->selection.queue_family, surface, &present)); if(!present) throw std::runtime_error("vkGetPhysicalDeviceSurfaceSupportKHR(...) inconsistent"); // Determine swap extent VkExtent2D swap_extent {static_cast<uint32_t>(dimensions.x), static_cast<uint32_t>(dimensions.y)}; VkSurfaceCapabilitiesKHR surface_caps; check("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device->selection.physical_device, surface, &surface_caps)); swap_extent.width = std::min(std::max(swap_extent.width, surface_caps.minImageExtent.width), surface_caps.maxImageExtent.width); swap_extent.height = std::min(std::max(swap_extent.height, surface_caps.minImageExtent.height), surface_caps.maxImageExtent.height); VkSwapchainCreateInfoKHR swapchain_info {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; swapchain_info.surface = surface; swapchain_info.minImageCount = device->selection.swap_image_count; swapchain_info.imageFormat = device->selection.surface_format.format; swapchain_info.imageColorSpace = device->selection.surface_format.colorSpace; swapchain_info.imageExtent = swap_extent; swapchain_info.imageArrayLayers = 1; swapchain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_info.preTransform = device->selection.surface_transform; swapchain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchain_info.presentMode = device->selection.present_mode; swapchain_info.clipped = VK_TRUE; check("vkCreateSwapchainKHR", vkCreateSwapchainKHR(device->dev, &swapchain_info, nullptr, &swapchain)); uint32_t swapchain_image_count; check("vkGetSwapchainImagesKHR", vkGetSwapchainImagesKHR(device->dev, swapchain, &swapchain_image_count, nullptr)); std::vector<VkImage> swapchain_images(swapchain_image_count); check("vkGetSwapchainImagesKHR", vkGetSwapchainImagesKHR(device->dev, swapchain, &swapchain_image_count, swapchain_images.data())); views.resize(swapchain_image_count); for(uint32_t i=0; i<swapchain_image_count; ++i) { VkImageViewCreateInfo view_info {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; view_info.image = swapchain_images[i]; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = device->selection.surface_format.format; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.levelCount = 1; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.layerCount = 1; check("vkCreateImageView", vkCreateImageView(device->dev, &view_info, nullptr, &views[i])); } // Create swapchain framebuffer dims = dimensions; framebuffers.resize(views.size()); color_formats = {device->selection.surface_format.format}; depth_format = convert_vk(rhi::image_format::depth_float32); auto render_pass = device->get_render_pass(get_render_pass_desc({{{dont_care{}, dont_care{}}}, depth_attachment_desc{dont_care{}, dont_care{}}})); for(size_t i=0; i<views.size(); ++i) { std::vector<VkImageView> attachments {views[i], depth_image.image_view}; VkFramebufferCreateInfo framebuffer_info {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; framebuffer_info.renderPass = render_pass; framebuffer_info.attachmentCount = exactly(attachments.size()); framebuffer_info.pAttachments = attachments.data(); framebuffer_info.width = dimensions.x; framebuffer_info.height = dimensions.y; framebuffer_info.layers = 1; check("vkCreateFramebuffer", vkCreateFramebuffer(device->dev, &framebuffer_info, nullptr, &framebuffers[i])); } } vk_framebuffer::~vk_framebuffer() { for(auto fb : framebuffers) device->destroy(fb); for(auto view : views) device->destroy(view); if(swapchain) device->destroy(swapchain); if(surface) device->destroy(surface); if(glfw_window) device->destroy(glfw_window); } template<class T> static VkAttachmentDescription make_attachment_description(VkFormat format, const T & desc, VkImageLayout attachment_optimal_layout) { VkAttachmentDescription attachment {0, format, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_UNDEFINED, attachment_optimal_layout}; auto convert_layout = [=](rhi::layout layout) { switch(layout) { case rhi::layout::attachment_optimal: return attachment_optimal_layout; case rhi::layout::shader_read_only_optimal: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; case rhi::layout::present_source: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; default: fail_fast(); } }; auto visitor = overload( [](dont_care) {}, [&](clear_color) { attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; }, [&](clear_depth) { attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; }, [&](load load) { attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; attachment.initialLayout = convert_layout(load.initial_layout); }, [&](store store) { attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attachment.finalLayout = convert_layout(store.final_layout); } ); std::visit(visitor, desc.load_op); std::visit(visitor, desc.store_op); return attachment; } vk_render_pass_desc vk_framebuffer::get_render_pass_desc(const render_pass_desc & desc) const { vk_render_pass_desc r; if(desc.color_attachments.size() != color_formats.size()) throw std::logic_error("render pass color attachments mismatch"); if(desc.depth_attachment.has_value() != depth_format.has_value()) throw std::logic_error("render pass color attachments mismatch"); for(size_t i=0; i<desc.color_attachments.size(); ++i) { r.color_refs.push_back({exactly(r.attachments.size()), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}); r.attachments.push_back(make_attachment_description(color_formats[i], desc.color_attachments[i], VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)); } if(desc.depth_attachment) { r.depth_ref = {exactly(r.attachments.size()), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; r.attachments.push_back(make_attachment_description(*depth_format, *desc.depth_attachment, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)); } return r; } vk_window::vk_window(vk_device * device, const int2 & dimensions, std::string title) : device{device} { depth_image = device->create_image({rhi::image_shape::_2d, {dimensions,1}, 1, rhi::image_format::depth_float32, rhi::depth_attachment_bit}, {}); swapchain_framebuffer = new delete_when_unreferenced<vk_framebuffer>{device, static_cast<vk_image &>(*depth_image), title}; VkSemaphoreCreateInfo semaphore_info {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; check("vkCreateSemaphore", vkCreateSemaphore(device->dev, &semaphore_info, nullptr, &image_available)); check("vkCreateSemaphore", vkCreateSemaphore(device->dev, &semaphore_info, nullptr, &render_finished)); // Acquire the first image check("vkAcquireNextImageKHR", vkAcquireNextImageKHR(device->dev, swapchain_framebuffer->swapchain, std::numeric_limits<uint64_t>::max(), image_available, VK_NULL_HANDLE, &swapchain_framebuffer->current_index)); } vk_window::~vk_window() { device->destroy(render_finished); device->destroy(image_available); } vk_descriptor_set_layout::vk_descriptor_set_layout(vk_device * device, const std::vector<descriptor_binding> & bindings) : device{device} { std::vector<VkDescriptorSetLayoutBinding> set_bindings(bindings.size()); for(size_t i=0; i<bindings.size(); ++i) { set_bindings[i].binding = bindings[i].index; switch(bindings[i].type) { case descriptor_type::combined_image_sampler: set_bindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; break; case descriptor_type::uniform_buffer: set_bindings[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; break; } set_bindings[i].descriptorCount = bindings[i].count; set_bindings[i].stageFlags = VK_SHADER_STAGE_ALL_GRAPHICS; } VkDescriptorSetLayoutCreateInfo create_info {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; create_info.bindingCount = exactly(set_bindings.size()); create_info.pBindings = set_bindings.data(); check("vkCreateDescriptorSetLayout", vkCreateDescriptorSetLayout(device->dev, &create_info, nullptr, &layout)); } vk_descriptor_set_layout::~vk_descriptor_set_layout() { device->destroy(layout); } vk_pipeline_layout::vk_pipeline_layout(vk_device * device, const std::vector<const descriptor_set_layout *> & sets) : base_pipeline_layout{sets}, device{device} { std::vector<VkDescriptorSetLayout> set_layouts; for(auto s : sets) set_layouts.push_back(static_cast<const vk_descriptor_set_layout *>(s)->layout); VkPipelineLayoutCreateInfo create_info {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; create_info.setLayoutCount = exactly(set_layouts.size()); create_info.pSetLayouts = set_layouts.data(); check("vkCreatePipelineLayout", vkCreatePipelineLayout(device->dev, &create_info, nullptr, &layout)); } vk_pipeline_layout::~vk_pipeline_layout() { device->destroy(layout); } vk_shader::vk_shader(vk_device * device, const shader_desc & desc) : device{device} { VkShaderModuleCreateInfo create_info {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; create_info.codeSize = desc.spirv.size() * sizeof(uint32_t); create_info.pCode = desc.spirv.data(); check("vkCreateShaderModule", vkCreateShaderModule(device->dev, &create_info, nullptr, &this->module)); stage = convert_vk(desc.stage); } vk_shader::~vk_shader() { device->destroy(module); } vk_pipeline::vk_pipeline(vk_device * device, const pipeline_desc & desc) : base_pipeline{*desc.layout}, device{device}, desc{desc} {} VkPipeline vk_pipeline::get_pipeline(VkRenderPass render_pass) const { auto & pipe = pipeline_objects[render_pass]; if(pipe) return pipe; std::vector<VkPipelineShaderStageCreateInfo> shader_stages; for(auto & s : desc.stages) { auto & shader = static_cast<const vk_shader &>(*s); shader_stages.push_back({VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, shader.stage, shader.module, "main"}); }; std::vector<VkVertexInputBindingDescription> bindings; std::vector<VkVertexInputAttributeDescription> attributes; for(auto & b : desc.input) { bindings.push_back({(uint32_t)b.index, (uint32_t)b.stride, VK_VERTEX_INPUT_RATE_VERTEX}); for(auto & a : b.attributes) attributes.push_back({(uint32_t)a.index, (uint32_t)b.index, convert_vk(a.type), (uint32_t)a.offset}); } const VkPipelineVertexInputStateCreateInfo vertex_input_state {VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, nullptr, 0, exactly(bindings.size()), bindings.data(), exactly(attributes.size()), attributes.data()}; const VkPipelineInputAssemblyStateCreateInfo input_assembly_state {VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, nullptr, 0, convert_vk(desc.topology)}; const VkPipelineViewportStateCreateInfo viewport_state {VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, nullptr, 0, 1, nullptr, 1, nullptr}; VkPipelineRasterizationStateCreateInfo rasterization_state {VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rasterization_state.polygonMode = VK_POLYGON_MODE_FILL; rasterization_state.cullMode = convert_vk(desc.cull_mode); rasterization_state.frontFace = (desc.front_face == rhi::front_face::clockwise ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE); rasterization_state.lineWidth = 1.0f; const VkPipelineMultisampleStateCreateInfo multisample_state {VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, nullptr, 0, VK_SAMPLE_COUNT_1_BIT}; VkPipelineDepthStencilStateCreateInfo depth_stencil_state {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; if(desc.depth) { depth_stencil_state.depthTestEnable = VK_TRUE; depth_stencil_state.depthCompareOp = convert_vk(desc.depth->test); depth_stencil_state.depthWriteEnable = desc.depth->write_mask ? VK_TRUE : VK_FALSE; } if(desc.stencil) { depth_stencil_state.stencilTestEnable = VK_TRUE; depth_stencil_state.front.compareOp = convert_vk(desc.stencil->front.test); depth_stencil_state.front.failOp = convert_vk(desc.stencil->front.stencil_fail_op); depth_stencil_state.front.depthFailOp = convert_vk(desc.stencil->front.stencil_pass_depth_fail_op); depth_stencil_state.front.passOp = convert_vk(desc.stencil->front.stencil_pass_depth_pass_op); depth_stencil_state.front.compareMask = desc.stencil->read_mask; depth_stencil_state.front.writeMask = desc.stencil->write_mask; depth_stencil_state.back.compareOp = convert_vk(desc.stencil->back.test); depth_stencil_state.back.failOp = convert_vk(desc.stencil->back.stencil_fail_op); depth_stencil_state.back.depthFailOp = convert_vk(desc.stencil->back.stencil_pass_depth_fail_op); depth_stencil_state.back.passOp = convert_vk(desc.stencil->back.stencil_pass_depth_pass_op); depth_stencil_state.back.compareMask = desc.stencil->read_mask; depth_stencil_state.back.writeMask = desc.stencil->write_mask; } std::vector<VkPipelineColorBlendAttachmentState> blend_attachments; for(auto & b : desc.blend) { blend_attachments.push_back({b.enable, convert_vk(b.color.source_factor), convert_vk(b.color.dest_factor), convert_vk(b.color.op), convert_vk(b.alpha.source_factor), convert_vk(b.alpha.dest_factor), convert_vk(b.alpha.op), exactly(b.write_mask ? 0xF : 0)}); } const VkPipelineColorBlendStateCreateInfo color_blend_state {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, nullptr, 0, VK_FALSE, VK_LOGIC_OP_COPY, exactly(countof(blend_attachments)), blend_attachments.data(), {0,0,0,0}}; const VkDynamicState dynamic_states[] {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_REFERENCE}; const VkPipelineDynamicStateCreateInfo dynamic_state {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, nullptr, 0, exactly(countof(dynamic_states)), dynamic_states}; const VkGraphicsPipelineCreateInfo pipelineInfo { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, nullptr, 0, exactly(countof(shader_stages)), shader_stages.data(), &vertex_input_state, &input_assembly_state, nullptr, &viewport_state, &rasterization_state, &multisample_state, &depth_stencil_state, &color_blend_state, &dynamic_state, static_cast<const vk_pipeline_layout &>(*desc.layout).layout, render_pass, 0, VK_NULL_HANDLE, -1 }; check("vkCreateGraphicsPipelines", vkCreateGraphicsPipelines(device->dev, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipe)); return pipe; } vk_pipeline::~vk_pipeline() { for(auto & pass_to_pipe : pipeline_objects) device->destroy(pass_to_pipe.second); } void vk_descriptor_set::write(int binding, buffer_range range) { VkDescriptorBufferInfo buffer_info { static_cast<vk_buffer &>(range.buffer).buffer_object, range.offset, range.size }; VkWriteDescriptorSet write { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, exactly(binding), 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, nullptr, &buffer_info, nullptr}; vkUpdateDescriptorSets(device, 1, &write, 0, nullptr); } void vk_descriptor_set::write(int binding, sampler & sampler, image & image) { VkDescriptorImageInfo image_info {static_cast<vk_sampler &>(sampler).sampler, static_cast<vk_image &>(image).image_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; VkWriteDescriptorSet write { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, exactly(binding), 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &image_info, nullptr, nullptr}; vkUpdateDescriptorSets(device, 1, &write, 0, nullptr); } vk_descriptor_pool::vk_descriptor_pool(vk_device * device) : device{device}, sets{1024}, used_sets{0} { const VkDescriptorPoolSize pool_sizes[] {{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,1024}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,1024}}; VkDescriptorPoolCreateInfo descriptor_pool_info {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; descriptor_pool_info.poolSizeCount = 2; descriptor_pool_info.pPoolSizes = pool_sizes; descriptor_pool_info.maxSets = 1024; descriptor_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; check("vkCreateDescriptorPool", vkCreateDescriptorPool(device->dev, &descriptor_pool_info, nullptr, &pool)); for(auto & set : sets) set.device = device->dev; } vk_descriptor_pool::~vk_descriptor_pool() { device->destroy(pool); } void vk_descriptor_pool::reset() { for(size_t i=0; i<used_sets; ++i) { if(sets[i].ref_count != 0) throw std::logic_error("rhi::descriptor_pool::reset called with descriptor sets outstanding"); vkFreeDescriptorSets(device->dev, pool, 1, &sets[i].set); } vkResetDescriptorPool(device->dev, pool, 0); used_sets = 0; } ptr<descriptor_set> vk_descriptor_pool::alloc(const descriptor_set_layout & layout) { if(used_sets == sets.size()) throw std::logic_error("out of descriptor sets"); VkDescriptorSetAllocateInfo alloc_info {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; alloc_info.descriptorPool = pool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &static_cast<const vk_descriptor_set_layout &>(layout).layout; check("vkAllocateDescriptorSets", vkAllocateDescriptorSets(device->dev, &alloc_info, &sets[used_sets].set)); return &sets[used_sets++]; } ////////////////////////// // vk_device rendering // ////////////////////////// ptr<command_buffer> vk_device::create_command_buffer() { ptr<vk_command_buffer> cmd {new delete_when_unreferenced<vk_command_buffer>{}}; cmd->device = this; VkCommandBufferAllocateInfo alloc_info {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; alloc_info.commandPool = staging_pool; alloc_info.commandBufferCount = 1; check("vkAllocateCommandBuffers", vkAllocateCommandBuffers(dev, &alloc_info, &cmd->cmd)); VkCommandBufferBeginInfo begin_info {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; check("vkBeginCommandBuffer", vkBeginCommandBuffer(cmd->cmd, &begin_info)); cmd->current_pass = nullptr; return cmd; } void vk_command_buffer::record_reference(const object & object) { auto it = referenced_objects.find(&object); if(it == referenced_objects.end()) referenced_objects.insert(&object); } void vk_command_buffer::generate_mipmaps(image & image) { record_reference(image); auto & im = static_cast<vk_image &>(image); for(uint32_t layer=0; layer<im.image_info.arrayLayers; ++layer) { VkImageSubresourceLayers layers {}; layers.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; layers.baseArrayLayer = exactly(layer); layers.layerCount = 1; VkOffset3D dims {exactly(im.image_info.extent.width), exactly(im.image_info.extent.height), exactly(im.image_info.extent.depth)}; transition_image(cmd, im.image_object, 0, exactly(layer), VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); for(uint32_t i=1; i<im.image_info.mipLevels; ++i) { VkImageBlit blit {}; blit.srcSubresource = layers; blit.srcSubresource.mipLevel = i-1; blit.srcOffsets[1] = dims; dims.x = std::max(dims.x/2,1); dims.y = std::max(dims.y/2,1); dims.z = std::max(dims.z/2,1); blit.dstSubresource = layers; blit.dstSubresource.mipLevel = i; blit.dstOffsets[1] = dims; transition_image(cmd, im.image_object, i, exactly(layer), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); vkCmdBlitImage(cmd, im.image_object, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, im.image_object, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); transition_image(cmd, im.image_object, i, exactly(layer), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); } for(uint32_t i=1; i<im.image_info.mipLevels; ++i) { transition_image(cmd, im.image_object, i, exactly(layer), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } } } void vk_command_buffer::begin_render_pass(const render_pass_desc & pass_desc, framebuffer & framebuffer) { record_reference(framebuffer); auto & fb = static_cast<vk_framebuffer &>(framebuffer); std::vector<VkClearValue> clear_values; for(size_t i=0; i<pass_desc.color_attachments.size(); ++i) { if(auto op = std::get_if<clear_color>(&pass_desc.color_attachments[i].load_op)) { clear_values.resize(i+1); clear_values[i].color = {op->r, op->g, op->b, op->a}; } } if(pass_desc.depth_attachment) { if(auto op = std::get_if<rhi::clear_depth>(&pass_desc.depth_attachment->load_op)) { clear_values.resize(pass_desc.color_attachments.size()+1); clear_values.back().depthStencil = {op->depth, op->stencil}; } } current_framebuffer = &fb; current_pass = device->get_render_pass(fb.get_render_pass_desc(pass_desc)); VkRenderPassBeginInfo pass_begin_info {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; pass_begin_info.renderPass = current_pass; pass_begin_info.framebuffer = fb.framebuffers[fb.current_index]; pass_begin_info.renderArea = {{0,0},{exactly(fb.dims.x),exactly(fb.dims.y)}}; pass_begin_info.clearValueCount = exactly(countof(clear_values)); pass_begin_info.pClearValues = clear_values.data(); vkCmdBeginRenderPass(cmd, &pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); set_viewport_rect(0, 0, fb.dims.x, fb.dims.y); set_scissor_rect(0, 0, fb.dims.x, fb.dims.y); set_stencil_ref(0); } void vk_command_buffer::clear_depth(float depth) { VkClearAttachment clear {VK_IMAGE_ASPECT_DEPTH_BIT}; clear.clearValue.depthStencil.depth = depth; const VkClearRect rect {{{0,0}, {exactly(current_framebuffer->dims.x),exactly(current_framebuffer->dims.y)}}, 0, 1}; vkCmdClearAttachments(cmd, 1, &clear, 1, &rect); } void vk_command_buffer::clear_stencil(uint8_t stencil) { VkClearAttachment clear {VK_IMAGE_ASPECT_STENCIL_BIT}; clear.clearValue.depthStencil.stencil = stencil; const VkClearRect rect {{{0,0}, {current_framebuffer->dims.x,current_framebuffer->dims.y}}, 0, 1}; vkCmdClearAttachments(cmd, 1, &clear, 1, &rect); } void vk_command_buffer::set_viewport_rect(int x0, int y0, int x1, int y1) { const VkViewport viewport {exactly(x0), exactly(y0), exactly(x1-x0), exactly(y1-y0), 0, 1}; vkCmdSetViewport(cmd, 0, 1, &viewport); } void vk_command_buffer::set_scissor_rect(int x0, int y0, int x1, int y1) { const VkRect2D scissor {{exactly(x0), exactly(y0)}, {exactly(x1-x0), exactly(y1-y0)}}; vkCmdSetScissor(cmd, 0, 1, &scissor); } void vk_command_buffer::set_stencil_ref(uint8_t stencil) { vkCmdSetStencilReference(cmd, VK_STENCIL_FRONT_AND_BACK, stencil); } void vk_command_buffer::bind_pipeline(const pipeline & pipe) { record_reference(pipe); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, static_cast<const vk_pipeline &>(pipe).get_pipeline(current_pass)); } void vk_command_buffer::bind_descriptor_set(const pipeline_layout & layout, int set_index, const descriptor_set & set) { record_reference(layout); record_reference(set); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, static_cast<const vk_pipeline_layout &>(layout).layout, set_index, 1, &static_cast<const vk_descriptor_set &>(set).set, 0, nullptr); } void vk_command_buffer::bind_vertex_buffer(int index, buffer_range range) { record_reference(range.buffer); VkDeviceSize offset = range.offset; vkCmdBindVertexBuffers(cmd, index, 1, &static_cast<vk_buffer &>(range.buffer).buffer_object, &offset); } void vk_command_buffer::bind_index_buffer(buffer_range range) { record_reference(range.buffer); vkCmdBindIndexBuffer(cmd, static_cast<vk_buffer &>(range.buffer).buffer_object, range.offset, VK_INDEX_TYPE_UINT32); } void vk_command_buffer::draw(int first_vertex, int vertex_count) { vkCmdDraw(cmd, vertex_count, 1, first_vertex, 0); } void vk_command_buffer::draw_indexed(int first_index, int index_count) { vkCmdDrawIndexed(cmd, index_count, 1, first_index, 0, 0); } void vk_command_buffer::end_render_pass() { vkCmdEndRenderPass(cmd); current_pass = 0; } uint64_t vk_device::submit(const VkSubmitInfo & submit_info) { if(completed_index + fence_ring_size == submitted_index) wait_until_complete(submitted_index - fence_ring_mask); check("vkQueueSubmit", vkQueueSubmit(queue, 1, &submit_info, ring_fences[submitted_index & fence_ring_mask])); ++submitted_index; for(uint32_t i=0; i<submit_info.commandBufferCount; ++i) scheduled_actions.push({submitted_index, [cmd=submit_info.pCommandBuffers[i]](vk_device & dev) { vkFreeCommandBuffers(dev.dev, dev.staging_pool, 1, &cmd); }}); return submitted_index; } void vk_device::wait_until_complete(uint64_t submission_index) { while(completed_index < submission_index) { check("vkWaitForFences", vkWaitForFences(dev, 1, &ring_fences[completed_index & fence_ring_mask], VK_TRUE, std::numeric_limits<uint64_t>::max())); check("vkResetFences", vkResetFences(dev, 1, &ring_fences[completed_index & fence_ring_mask])); ++completed_index; } while(!scheduled_actions.empty() && completed_index >= scheduled_actions.front().after_completion_index) { scheduled_actions.front().execute(*this); scheduled_actions.pop(); } } uint64_t vk_device::submit(command_buffer & cmd) { check("vkEndCommandBuffer", vkEndCommandBuffer(static_cast<vk_command_buffer &>(cmd).cmd)); VkSubmitInfo submit_info {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &static_cast<vk_command_buffer &>(cmd).cmd; submit(submit_info); return submitted_index; } uint64_t vk_device::acquire_and_submit_and_present(command_buffer & cmd, window & window) { check("vkEndCommandBuffer", vkEndCommandBuffer(static_cast<vk_command_buffer &>(cmd).cmd)); auto & win = static_cast<vk_window &>(window); VkPipelineStageFlags wait_stages[] {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; VkSubmitInfo submit_info {VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = &win.image_available; submit_info.pWaitDstStageMask = wait_stages; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &static_cast<vk_command_buffer &>(cmd).cmd; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = &win.render_finished; submit(submit_info); VkPresentInfoKHR present_info {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; present_info.waitSemaphoreCount = 1; present_info.pWaitSemaphores = &win.render_finished; present_info.swapchainCount = 1; present_info.pSwapchains = &win.swapchain_framebuffer->swapchain; present_info.pImageIndices = &win.swapchain_framebuffer->current_index; check("vkQueuePresentKHR", vkQueuePresentKHR(queue, &present_info)); check("vkAcquireNextImageKHR", vkAcquireNextImageKHR(dev, win.swapchain_framebuffer->swapchain, std::numeric_limits<uint64_t>::max(), win.image_available, VK_NULL_HANDLE, &win.swapchain_framebuffer->current_index)); return submitted_index; }
50.202013
271
0.736263
sgorsten
5b6b3d330fc7795c7376f20cd88d98e9c4c13851
337
hpp
C++
qltest/Trade.hpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
qltest/Trade.hpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
qltest/Trade.hpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
#ifndef QLTEST_TRADE_HPP_ #define QLTEST_TRADE_HPP_ #include <cstdint> #include <string> namespace QLTest { using std::int32_t; using std::int64_t; struct Trade { int64_t time; int32_t symbolId; int32_t quantity; int32_t price; void load(const char* const record); }; } // namespace QLTest #endif // QLTEST_TRADE_HPP_
14.041667
38
0.732938
longztian
5b6b4a4ff743a6c3140ce7cee6c0fdfd889b0092
12,062
cpp
C++
Samples/JTSP/TSP/Phone.cpp
markjulmar/tsplib3
f58a281ce43f4d57ef10e24d306fd46e6febcc41
[ "MIT" ]
1
2021-02-08T20:31:46.000Z
2021-02-08T20:31:46.000Z
Samples/JTSP/TSP/Phone.cpp
markjulmar/tsplib3
f58a281ce43f4d57ef10e24d306fd46e6febcc41
[ "MIT" ]
null
null
null
Samples/JTSP/TSP/Phone.cpp
markjulmar/tsplib3
f58a281ce43f4d57ef10e24d306fd46e6febcc41
[ "MIT" ]
4
2019-11-14T03:47:33.000Z
2021-03-08T01:18:05.000Z
/*************************************************************************** // // PHONE.CPP // // JulMar Sample TAPI Service provider for TSP++ version 3.00 // Phone management functions // // Copyright (C) 1998 JulMar Entertainment Technology, Inc. // All rights reserved // // This source code is intended only as a supplement to the // TSP++ Class Library product documentation. This source code cannot // be used in part or whole in any form outside the TSP++ library. // // Modification History // ------------------------------------------------------------------------ // 09/04/1998 MCS@Julmar Generated from TSPWizard.exe // /***************************************************************************/ /*-------------------------------------------------------------------------------*/ // INCLUDE FILES /*-------------------------------------------------------------------------------*/ #include "stdafx.h" #include "jtsp.h" /*-------------------------------------------------------------------------------*/ // DEBUG SUPPORT /*-------------------------------------------------------------------------------*/ #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /*-------------------------------------------------------------------------------*/ // TSPI Request map /*-------------------------------------------------------------------------------*/ BEGIN_TSPI_REQUEST(CJTPhone) ON_TSPI_REQUEST_SETHOOKSWITCHGAIN(OnSetGain) ON_TSPI_REQUEST_SETHOOKSWITCH(OnSetHookswitch) ON_TSPI_REQUEST_SETHOOKSWITCHVOL(OnSetVolume) END_TSPI_REQUEST() /***************************************************************************** ** Procedure: CJTPhone::read ** ** Arguments: 'istm' - Input stream ** ** Returns: pointer to istm ** ** Description: This function is called to serialize data in from the ** registry. The phone object has already been completely ** initialized by the TSP++ library ** *****************************************************************************/ TStream& CJTPhone::read(TStream& istm) { // Load our default display which is used while we have no agent // logged into this station. SetDisplay(_T(" NOT LOGGED ON")); // Return the base class loading. return CTSPIPhoneConnection::read(istm); }// CJTPhone::read /***************************************************************************** ** Procedure: CJTPhone::OpenDevice ** ** Arguments: void ** ** Returns: void ** ** Description: This method is called when the phone is opened by TAPI. ** We want to check and see if the associated line is currently CONNECTED ** to the TL server. ** *****************************************************************************/ bool CJTPhone::OpenDevice() { // If the associated line is not connected then fail the open request. // The connected flag on the line is used to determine whether we are connected // to the simulator. if ((GetAssociatedLine()->GetLineDevStatus()->dwDevStatusFlags & LINEDEVSTATUSFLAGS_CONNECTED) == 0) return false; return CTSPIPhoneConnection::OpenDevice(); }// CJTPhone::OpenDevice /***************************************************************************** ** Procedure: CJTPhone::OnTimer ** ** Arguments: void ** ** Returns: void ** ** Description: This method is called periodically by the interval timer ** *****************************************************************************/ void CJTPhone::OnTimer() { // Poll the active request for timeout ReceiveData(); }// CJTPhone::OnTimer /***************************************************************************** ** Procedure: CJTPhone::OnSetGain ** ** Arguments: 'pReq' - Request object representing this phone request ** 'lpBuff' - Our CEventBlock* pointer ** ** Returns: void ** ** Description: This function manages the TSPI_phoneSetGain processing ** for this service provider. ** *****************************************************************************/ bool CJTPhone::OnSetGain(RTSetGain* pRequest, LPCVOID lpBuff) { // Cast our pointer back to an event block const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff); // If we are in the initial state (i.e. this request has not been processed // before by any other thread). Then move the packet to the waiting state so // other threads will not interfere with other events or timers. This is // guarenteed to be thread-safe and atomic. if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING)) { // Send the command to the switch GetDeviceInfo()->DRV_SetGain(this, pRequest->GetGain()); } // If we are in the waiting stage (2) then see if we received an event from the // switch (vs. an interval timer) and if that event was an ACK/NAK in response // to the command we issued. else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL) { // If this is a command response for our SETGAIN, then manage it. const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command)); const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode)); if (pBlock->GetEventType() == CEventBlock::CommandResponse && peCommand->GetCommand() == CPECommand::SetGain && pidError != NULL) { // Complete the request with the appropriate error code. TranslateErrorCode(pRequest, pidError->GetError()); return true; } } // Check to see if our request has exceeded the limit for processing. If // so, tell TAPI that the request failed and delete the request. if (pRequest->GetState() == STATE_WAITING && (pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount()) CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED); // Let the request fall through to the unsolicited handler where we // set all the options concerning the newly found call. return false; }// CJTPhone::OnSetGain /***************************************************************************** ** Procedure: CJTPhone::OnSetHookswitch ** ** Arguments: 'pReq' - Request object representing this phone request ** 'lpBuff' - Our CEventBlock* pointer ** ** Returns: void ** ** Description: This function manages the TSPI_phoneSetHookSwitch processing ** for this service provider. ** *****************************************************************************/ bool CJTPhone::OnSetHookswitch(RTSetHookswitch* pRequest, LPCVOID lpBuff) { // Cast our pointer back to an event block const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff); // If we are in the initial state (i.e. this request has not been processed // before by any other thread). Then move the packet to the waiting state so // other threads will not interfere with other events or timers. This is // guarenteed to be thread-safe and atomic. if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING)) { // Validate the state passed if (pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_ONHOOK || pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_MIC) CompleteRequest(pRequest, PHONEERR_INVALHOOKSWITCHMODE); // Send the command to the switch else GetDeviceInfo()->DRV_SetHookswitch(this, (pRequest->GetHookswitchState() == PHONEHOOKSWITCHMODE_MICSPEAKER) ? 1 : 0); } // If we are in the waiting stage (2) then see if we received an event from the // switch (vs. an interval timer) and if that event was an ACK/NAK in response // to the command we issued. else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL) { // If this is a command response for our SETGAIN, then manage it. const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command)); const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode)); if (pBlock->GetEventType() == CEventBlock::CommandResponse && peCommand->GetCommand() == CPECommand::SetHookSwitch && pidError != NULL) { // Complete the request with the appropriate error code. TranslateErrorCode(pRequest, pidError->GetError()); return true; } } // Check to see if our request has exceeded the limit for processing. If // so, tell TAPI that the request failed and delete the request. if (pRequest->GetState() == STATE_WAITING && (pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount()) CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED); // Let the request fall through to the unsolicited handler where we // set all the options concerning the newly found call. return false; }// CJTPhone::OnSetHookswitch /***************************************************************************** ** Procedure: CJTPhone::OnSetVolume ** ** Arguments: 'pReq' - Request object representing this phone request ** 'lpBuff' - Our CEventBlock* pointer ** ** Returns: void ** ** Description: This function manages the TSPI_phoneSetVolume processing ** for this service provider. ** *****************************************************************************/ bool CJTPhone::OnSetVolume(RTSetVolume* pRequest, LPCVOID lpBuff) { // Cast our pointer back to an event block const CEventBlock* pBlock = static_cast<const CEventBlock*>(lpBuff); // If we are in the initial state (i.e. this request has not been processed // before by any other thread). Then move the packet to the waiting state so // other threads will not interfere with other events or timers. This is // guarenteed to be thread-safe and atomic. if (pRequest->EnterState(STATE_INITIAL, STATE_WAITING)) { // Send the command to the switch GetDeviceInfo()->DRV_SetVolume(this, pRequest->GetVolume()); } // If we are in the waiting stage (2) then see if we received an event from the // switch (vs. an interval timer) and if that event was an ACK/NAK in response // to the command we issued. else if (pRequest->GetState() == STATE_WAITING && pBlock != NULL) { // If this is a command response for our SETGAIN, then manage it. const CPECommand* peCommand = dynamic_cast<const CPECommand*>(pBlock->GetElement(CPBXElement::Command)); const CPEErrorCode* pidError = dynamic_cast<const CPEErrorCode*>(pBlock->GetElement(CPBXElement::ErrorCode)); if (pBlock->GetEventType() == CEventBlock::CommandResponse && peCommand->GetCommand() == CPECommand::SetVolume && pidError != NULL) { // Complete the request with the appropriate error code. TranslateErrorCode(pRequest, pidError->GetError()); return true; } } // Check to see if our request has exceeded the limit for processing. If // so, tell TAPI that the request failed and delete the request. if (pRequest->GetState() == STATE_WAITING && (pRequest->GetStateTime()+REQUEST_TIMEOUT) < GetTickCount()) CompleteRequest(pRequest, PHONEERR_OPERATIONFAILED); // Let the request fall through to the unsolicited handler where we // set all the options concerning the newly found call. return false; }// CJTPhone::OnSetVolume /***************************************************************************** ** Procedure: CJTPhone::TranslateErrorCode ** ** Arguments: 'pRequest' - Request object representing this phone request ** 'dwError' - Error code ** ** Returns: void ** ** Description: This function completes the request with an appropriate ** TAPI error code based on the PBX error received. ** *****************************************************************************/ void CJTPhone::TranslateErrorCode(CTSPIRequest* pRequest, DWORD dwError) { switch (dwError) { case CPEErrorCode::None: dwError = 0; break; case CPEErrorCode::InvalidDevice: dwError = PHONEERR_BADDEVICEID; break; case CPEErrorCode::BadCommand: dwError = PHONEERR_INVALPHONESTATE; break; case CPEErrorCode::InvalidParameter: dwError = PHONEERR_INVALPARAM; break; default: dwError = PHONEERR_OPERATIONFAILED; break; } CompleteRequest(pRequest, dwError); }// CJTPhone::TranslateErrorCode
39.418301
120
0.615155
markjulmar
5b6b777f04b388ae4557490a1582e747b8e86e94
8,266
hpp
C++
dist/include/ellipsefitter.hpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
dist/include/ellipsefitter.hpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
dist/include/ellipsefitter.hpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
/** * RUNETag fiducial markers library * * ----------------------------------------------------------------------------- * The MIT License (MIT) * * Copyright (c) 2015 Filippo Bergamasco * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ELLIPSE_FITTER_H #define ELLIPSE_FITTER_H //#include "precomp.h" #include "ellipsepoint.hpp" #include "auxmath.hpp" namespace cv { namespace runetag { class EllipseFitter { public: cv::Matx33d VR; private: const double coplanar_threshold; const double size_err_threshold; const EllipsePoint& e1; const EllipsePoint& e2; const cv::Mat& intrinsics; mutable cv::Matx33d Qfit1c; mutable cv::Matx33d Qfit2c; double rad_avg; double radius; /* Main operation provided by getFit1WithOffset and getFit2WithOffset */ cv::Matx33d getFitWithOffset( double rad_mul, cv::Matx33d& Qfit, double k ) const; bool chooseAvgVR( const EllipsePoint& ep1, const EllipsePoint& ep2, double& r, double& r_other, cv::Matx33d& Qc, cv::Matx33d& Qc_other ); // AUX OPERATION static cv::Matx33d& transformToCircle( const cv::Matx33d& Q, const cv::Matx33d& VR, cv::Matx33d& targetMatrix ); static void normalize( cv::Matx31d& vector ); static cv::Matx31d buildN( const cv::Matx33d& VR ); static double circleRonZ0( const cv::Matx33d& Qc ); static bool fitCircles( const cv::Point2d& center1, const cv::Point2d& center2, double radius2, cv::Matx33d& circle1, cv::Matx33d& circle2 ); static void buildCircle( cv::Matx33d& target, double a, double b, double radius ); // AUX STRUCTURE class CandidateVR { private: const cv::Matx33d* VR1; const cv::Matx33d* VR2; const cv::Matx31d* normal1; const cv::Matx31d* normal2; public: CandidateVR( const cv::Matx33d& _VR1, const cv::Matx31d& _normal1, const cv::Matx33d& _VR2, const cv::Matx31d& _normal2 ); inline const cv::Matx33d& getVR1() const { return *VR1; } inline const cv::Matx33d& getVR2() const { return *VR2; } inline const cv::Matx31d& getNormal1() const { return *normal1; } inline const cv::Matx31d& getNormal2() const { return *normal2; } double cosAngle() const; }; template <typename T> class Quaternion { private: T w, i, j, k; public: explicit Quaternion() : w(0), i(0), j(0), k(0) {} explicit Quaternion(const T* p) : w(p[0]), i(p[1]), j(p[2]), k(p[3]) {} explicit Quaternion( const cv::Matx33d& R ); Quaternion(T ww, T ii, T jj, T kk) : w(ww), i(ii), j(jj), k(kk) {} inline void normalize(); cv::Matx33f toRotationMatrix() const; Quaternion<T> operator+( const Quaternion<T>& q ) const; Quaternion<T> operator-( const Quaternion<T>& q ) const; Quaternion<T> operator*( const Quaternion<T>& q ) const; T dot( const Quaternion<T>& q ) const; }; public: EllipseFitter( const EllipsePoint& _e1, const EllipsePoint& _e2, const cv::Mat& _intrinsics, double _coplanar_threshold=0.97, double _size_err_threshold=0.5 ) : e1( _e1 ), e2( _e2 ), intrinsics(_intrinsics), coplanar_threshold(_coplanar_threshold), size_err_threshold(_size_err_threshold) {} inline const cv::Matx33d& getVR() const { return VR; } // MAIN OPERATIONS bool fitEllipseAvg( double _radius_ratio ); cv::Matx33d getFit1WithOffset( double rad_mul ) const; cv::Matx33d getFit2WithOffset( double rad_mul ) const; }; /* * BEGIN TEMPLATE CLASS IMPLEMENTATION */ template<typename T> EllipseFitter::Quaternion<T>::Quaternion( const cv::Matx33d& m ) { const T m00 = m(0,0); const T m11 = m(1,1); const T m22 = -m(2,2); const T m01 = m(0,1); const T m02 = -m(0,2); const T m10 = m(1,0); const T m12 = -m(1,2); const T m20 = m(2,0); const T m21 = m(2,1); const T tr = m00 + m11 + m22; if (tr > 0) { T s = std::sqrt(tr+T(1)) * 2; // S=4*qw w = 0.25 * s; i = (m21 - m12) / s; j = (m02 - m20) / s; k = (m10 - m01) / s; } else if ((m00 > m11)&&(m00 > m22)) { const T s = std::sqrt(T(1) + m00 - m11 - m22) * 2; // S=4*qx w = (m21 - m12) / s; i = 0.25 * s; j = (m01 + m10) / s; k = (m02 + m20) / s; } else if (m11 > m22) { const T s = std::sqrt(T(1) + m11 - m00 - m22) * 2; // S=4*qy w = (m02 - m20) / s; i = (m01 + m10) / s; j = 0.25 * s; k = (m12 + m21) / s; } else { const T s = std::sqrt(T(1) + m22 - m00 - m11) * 2; // S=4*qz w = (m10 - m01) / s; i = (m02 + m20) / s; j = (m12 + m21) / s; k = 0.25 * s; } } template<typename T> EllipseFitter::Quaternion<T> EllipseFitter::Quaternion<T>::operator -( const Quaternion<T>& q ) const { return Quaternion<T> (w - q.w, i - q.i, j - q.j, k - q.k); } template<typename T> EllipseFitter::Quaternion<T> EllipseFitter::Quaternion<T>::operator +( const Quaternion<T>& q ) const { return Quaternion<T> (w + q.w, i + q.i, j + q.j, k + q.k); } template<typename T> EllipseFitter::Quaternion<T> EllipseFitter::Quaternion<T>::operator *( const Quaternion<T>& q ) const { return Quaternion<T>(w*q.w - (i*q.i + j*q.j + k*q.k), w*q.i + q.w*i + j*q.k - k*q.j, w*q.j + q.w*j + k*q.i - i*q.k, w*q.k + q.w*k + i*q.j - j*q.i); } template<typename T> T EllipseFitter::Quaternion<T>::dot( const Quaternion<T>& q ) const { return w*q.w + i*q.i + j*q.j + k*q.k; } template<typename T> cv::Matx33f EllipseFitter::Quaternion<T>::toRotationMatrix() const { cv::Matx33f matrix; matrix(0,0) = static_cast<float>(1 - 2*j*j - 2*k*k); matrix(0,1) = static_cast<float>(2*i*j - 2*k*w); matrix(0,2) = static_cast<float>(-(2*i*k + 2*j*w)); matrix(1,0) = static_cast<float>(2*i*j + 2*k*w); matrix(1,1) = static_cast<float>(1 - 2*i*i - 2*k*k); matrix(1,2) = static_cast<float>(-(2*j*k - 2*i*w)); matrix(2,0) = static_cast<float>(2*i*k - 2*j*w); matrix(2,1) = static_cast<float>(2*j*k + 2*i*w); matrix(2,2) = static_cast<float>(-(1 - 2*i*i - 2*j*j)); return matrix; } template<typename T> inline void EllipseFitter::Quaternion<T>::normalize() { T magnitude = w * w + i * i + j * j + k * k; if (!almost_zero(magnitude - T(1), 1e-10)) { magnitude = std::sqrt(magnitude); w /= magnitude; i /= magnitude; j /= magnitude; k /= magnitude; } } /* * END TEMPLATE CLASS IMPLEMENTATION */ } // namespace runetag } // namespace cv #endif
30.167883
295
0.560731
vshesh
5b6e893cff06e65cd751e632fb385bf96966dfa3
253
hh
C++
include/MyPhysicsList.hh
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
null
null
null
include/MyPhysicsList.hh
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
null
null
null
include/MyPhysicsList.hh
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
1
2022-03-15T04:52:09.000Z
2022-03-15T04:52:09.000Z
#ifndef MYPHYSICSLIST_HH #define MYPHYSICSLIST_HH #include "G4VModularPhysicsList.hh" #include "G4EmStandardPhysics_option4.hh" class MyPhysicsList : public G4VModularPhysicsList { public: MyPhysicsList(); virtual ~MyPhysicsList(); }; #endif
16.866667
50
0.786561
wangshishe
5b6ffe51779edb3e815e976863fc26299cf3b2e6
29,795
cpp
C++
dbms/src/Storages/Page/V3/tests/gtest_page_storage.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
4
2022-03-25T21:34:15.000Z
2022-03-25T21:35:12.000Z
dbms/src/Storages/Page/V3/tests/gtest_page_storage.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
null
null
null
dbms/src/Storages/Page/V3/tests/gtest_page_storage.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
8
2022-03-25T10:20:08.000Z
2022-03-31T10:17:25.000Z
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Storages/Page/Page.h> #include <Storages/Page/PageDefines.h> #include <Storages/Page/PageStorage.h> #include <Storages/Page/V3/BlobStore.h> #include <Storages/Page/V3/PageDirectory.h> #include <Storages/Page/V3/PageEntriesEdit.h> #include <Storages/Page/V3/PageEntry.h> #include <Storages/Page/V3/PageStorageImpl.h> #include <Storages/Page/V3/tests/entries_helper.h> #include <Storages/PathPool.h> #include <Storages/tests/TiFlashStorageTestBasic.h> #include <TestUtils/MockDiskDelegator.h> #include <TestUtils/TiFlashTestBasic.h> #include <common/types.h> namespace DB { namespace FailPoints { extern const char exception_before_page_file_write_sync[]; extern const char force_set_page_file_write_errno[]; } // namespace FailPoints namespace PS::V3::tests { class PageStorageTest : public DB::base::TiFlashStorageTestBasic { public: void SetUp() override { TiFlashStorageTestBasic::SetUp(); auto path = getTemporaryPath(); createIfNotExist(path); file_provider = DB::tests::TiFlashTestEnv::getContext().getFileProvider(); auto delegator = std::make_shared<DB::tests::MockDiskDelegatorSingle>(path); page_storage = std::make_shared<PageStorageImpl>("test.t", delegator, config, file_provider); page_storage->restore(); } std::shared_ptr<PageStorageImpl> reopenWithConfig(const PageStorage::Config & config_) { auto path = getTemporaryPath(); auto delegator = std::make_shared<DB::tests::MockDiskDelegatorSingle>(path); auto storage = std::make_shared<PageStorageImpl>("test.t", delegator, config_, file_provider); storage->restore(); return storage; } protected: FileProviderPtr file_provider; std::unique_ptr<StoragePathPool> path_pool; PageStorage::Config config; std::shared_ptr<PageStorageImpl> page_storage; std::list<PageDirectorySnapshotPtr> snapshots_holder; size_t fixed_test_buff_size = 1024; size_t epoch_offset = 0; }; TEST_F(PageStorageTest, WriteRead) try { const UInt64 tag = 0; const size_t buf_sz = 1024; char c_buff[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff[i] = i % 0xff; } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(0, tag, buff, buf_sz); buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(1, tag, buff, buf_sz); page_storage->write(std::move(batch)); } DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), static_cast<char>(i % 0xff)); } DB::Page page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); ASSERT_EQ(page1.page_id, 1UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page1.data.begin() + i), static_cast<char>(i % 0xff)); } } CATCH TEST_F(PageStorageTest, WriteMultipleBatchRead1) try { const UInt64 tag = 0; const size_t buf_sz = 1024; char c_buff[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff[i] = i % 0xff; } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(0, tag, buff, buf_sz); page_storage->write(std::move(batch)); } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(1, tag, buff, buf_sz); page_storage->write(std::move(batch)); } DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), static_cast<char>(i % 0xff)); } DB::Page page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); ASSERT_EQ(page1.page_id, 1UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page1.data.begin() + i), static_cast<char>(i % 0xff)); } } CATCH TEST_F(PageStorageTest, WriteMultipleBatchRead2) try { const UInt64 tag = 0; const size_t buf_sz = 1024; char c_buff1[buf_sz], c_buff2[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff1[i] = i % 0xff; c_buff2[i] = i % 0xff + 1; } { WriteBatch batch; ReadBufferPtr buff1 = std::make_shared<ReadBufferFromMemory>(c_buff1, buf_sz); ReadBufferPtr buff2 = std::make_shared<ReadBufferFromMemory>(c_buff2, buf_sz); batch.putPage(0, tag, buff1, buf_sz); batch.putPage(1, tag, buff2, buf_sz); page_storage->write(std::move(batch)); } DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), static_cast<char>(i % 0xff)); } DB::Page page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); ASSERT_EQ(page1.page_id, 1UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page1.data.begin() + i), static_cast<char>(i % 0xff + 1)); } } CATCH TEST_F(PageStorageTest, MultipleWriteRead) { size_t page_id_max = 100; for (DB::PageId page_id = 0; page_id <= page_id_max; ++page_id) { std::mt19937 size_gen; size_gen.seed(time(nullptr)); std::uniform_int_distribution<> dist(0, 3000); const size_t buff_sz = 2 * DB::MB + dist(size_gen); char * buff = static_cast<char *>(malloc(buff_sz)); if (buff == nullptr) { throw DB::Exception("Alloc fix memory failed.", DB::ErrorCodes::LOGICAL_ERROR); } const char buff_ch = page_id % 0xFF; memset(buff, buff_ch, buff_sz); DB::MemHolder holder = DB::createMemHolder(buff, [&](char * p) { free(p); }); auto read_buff = std::make_shared<DB::ReadBufferFromMemory>(const_cast<char *>(buff), buff_sz); DB::WriteBatch wb; wb.putPage(page_id, 0, read_buff, read_buff->buffer().size()); page_storage->write(std::move(wb)); } for (DB::PageId page_id = 0; page_id <= page_id_max; ++page_id) { page_storage->read(page_id); } } TEST_F(PageStorageTest, WriteReadOnSamePageId) { const UInt64 tag = 0; const size_t buf_sz = 1024; char c_buff[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff[i] = i % 0xff; } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(0, tag, buff, buf_sz); page_storage->write(std::move(batch)); DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), static_cast<char>(i % 0xff)); } } for (char & i : c_buff) { i = 0x1; } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(0, tag, buff, buf_sz); page_storage->write(std::move(batch)); DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), static_cast<char>(0x01)); } } } TEST_F(PageStorageTest, WriteReadAfterGc) try { const size_t buf_sz = 256; char c_buff[buf_sz]; const size_t num_repeat = 10; PageId pid = 1; const char page0_byte = 0x3f; { // put page0 WriteBatch batch; memset(c_buff, page0_byte, buf_sz); ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(0, 0, buff, buf_sz); page_storage->write(std::move(batch)); } // repeated put page1 for (size_t n = 1; n <= num_repeat; ++n) { WriteBatch batch; memset(c_buff, n, buf_sz); ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(pid, 0, buff, buf_sz); page_storage->write(std::move(batch)); } { DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), page0_byte); } DB::Page page1 = page_storage->read(pid); ASSERT_EQ(page1.data.size(), buf_sz); ASSERT_EQ(page1.page_id, pid); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page1.data.begin() + i), static_cast<char>(num_repeat % 0xff)); } } page_storage->gc(); { DB::Page page0 = page_storage->read(0); ASSERT_EQ(page0.data.size(), buf_sz); ASSERT_EQ(page0.page_id, 0UL); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page0.data.begin() + i), page0_byte); } DB::Page page1 = page_storage->read(pid); ASSERT_EQ(page1.data.size(), buf_sz); ASSERT_EQ(page1.page_id, pid); for (size_t i = 0; i < buf_sz; ++i) { EXPECT_EQ(*(page1.data.begin() + i), static_cast<char>(num_repeat % 0xff)); } } } CATCH TEST_F(PageStorageTest, DeadLockInMVCC) try { WriteBatch batch; { batch.putExternal(0, 0); batch.putRefPage(1, 0); batch.putExternal(1024, 0); page_storage->write(std::move(batch)); } auto snapshot = page_storage->getSnapshot(); { WriteBatch batch; batch.putRefPage(2, 1); // ref 2 -> 1 -> 0 batch.delPage(1); // free ref 1 -> 0 batch.delPage(1024); // free normal page 1024 page_storage->write(std::move(batch)); } } CATCH TEST_F(PageStorageTest, IngestFile) { WriteBatch wb; { wb.putExternal(100, 0); wb.putRefPage(101, 100); wb.putRefPage(102, 100); wb.delPage(100); page_storage->write(std::move(wb)); } auto snapshot = page_storage->getSnapshot(); EXPECT_ANY_THROW(page_storage->getNormalPageId(TEST_NAMESPACE_ID, 100, snapshot)); EXPECT_EQ(100, page_storage->getNormalPageId(TEST_NAMESPACE_ID, 101, snapshot)); EXPECT_EQ(100, page_storage->getNormalPageId(TEST_NAMESPACE_ID, 102, snapshot)); size_t times_remover_called = 0; ExternalPageCallbacks callbacks; callbacks.scanner = []() -> ExternalPageCallbacks::PathAndIdsVec { return {}; }; callbacks.remover = [&times_remover_called](const ExternalPageCallbacks::PathAndIdsVec &, const std::set<PageId> & living_page_ids) -> void { times_remover_called += 1; EXPECT_EQ(living_page_ids.size(), 1); EXPECT_GT(living_page_ids.count(100), 0); }; callbacks.ns_id = TEST_NAMESPACE_ID; page_storage->registerExternalPagesCallbacks(callbacks); page_storage->gc(); ASSERT_EQ(times_remover_called, 1); page_storage->gc(); ASSERT_EQ(times_remover_called, 2); page_storage->unregisterExternalPagesCallbacks(callbacks.ns_id); page_storage->gc(); ASSERT_EQ(times_remover_called, 2); } // TBD : enable after wal apply and restore TEST_F(PageStorageTest, DISABLED_IgnoreIncompleteWriteBatch1) try { // If there is any incomplete write batch, we should able to ignore those // broken write batches and continue to write more data. const size_t buf_sz = 1024; char buf[buf_sz]; { WriteBatch batch; memset(buf, 0x01, buf_sz); batch.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, PageFieldSizes{{32, 64, 79, 128, 196, 256, 269}}); batch.putPage(2, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, PageFieldSizes{{64, 79, 128, 196, 256, 301}}); batch.putRefPage(3, 2); batch.putRefPage(4, 2); try { FailPointHelper::enableFailPoint(FailPoints::exception_before_page_file_write_sync); page_storage->write(std::move(batch)); } catch (DB::Exception & e) { if (e.code() != ErrorCodes::FAIL_POINT_ERROR) throw; } } // Restore, the broken meta should be ignored page_storage = reopenWithConfig(PageStorage::Config{}); { size_t num_pages = 0; page_storage->traverse([&num_pages](const DB::Page &) { num_pages += 1; }); ASSERT_EQ(num_pages, 0); } // Continue to write some pages { WriteBatch batch; memset(buf, 0x02, buf_sz); batch.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, // PageFieldSizes{{32, 128, 196, 256, 12, 99, 1, 300}}); page_storage->write(std::move(batch)); auto page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); for (size_t i = 0; i < page1.data.size(); ++i) { auto * p = page1.data.begin(); EXPECT_EQ(*p, 0x02); } } // Restore again, we should be able to read page 1 page_storage = reopenWithConfig(PageStorage::Config{}); { size_t num_pages = 0; page_storage->traverse([&num_pages](const Page &) { num_pages += 1; }); ASSERT_EQ(num_pages, 1); auto page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); for (size_t i = 0; i < page1.data.size(); ++i) { auto * p = page1.data.begin(); EXPECT_EQ(*p, 0x02); } } } CATCH // TBD : enable after wal apply and restore TEST_F(PageStorageTest, DISABLED_IgnoreIncompleteWriteBatch2) try { // If there is any incomplete write batch, we should able to ignore those // broken write batches and continue to write more data. const size_t buf_sz = 1024; char buf[buf_sz]; { WriteBatch batch; memset(buf, 0x01, buf_sz); batch.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, PageFieldSizes{{32, 64, 79, 128, 196, 256, 269}}); batch.putPage(2, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, PageFieldSizes{{64, 79, 128, 196, 256, 301}}); batch.putRefPage(3, 2); batch.putRefPage(4, 2); try { FailPointHelper::enableFailPoint(FailPoints::force_set_page_file_write_errno); page_storage->write(std::move(batch)); } catch (DB::Exception & e) { // Mock to catch and ignore the exception in background thread if (e.code() != ErrorCodes::CANNOT_WRITE_TO_FILE_DESCRIPTOR) throw; } } FailPointHelper::disableFailPoint(FailPoints::force_set_page_file_write_errno); { size_t num_pages = 0; page_storage->traverse([&num_pages](const Page &) { num_pages += 1; }); ASSERT_EQ(num_pages, 0); } // Continue to write some pages { WriteBatch batch; memset(buf, 0x02, buf_sz); batch.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(buf, buf_sz), buf_sz, // PageFieldSizes{{32, 128, 196, 256, 12, 99, 1, 300}}); page_storage->write(std::move(batch)); auto page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); for (size_t i = 0; i < page1.data.size(); ++i) { auto * p = page1.data.begin(); EXPECT_EQ(*p, 0x02); } } // Restore again, we should be able to read page 1 page_storage = reopenWithConfig(PageStorage::Config{}); { size_t num_pages = 0; page_storage->traverse([&num_pages](const Page &) { num_pages += 1; }); ASSERT_EQ(num_pages, 1); auto page1 = page_storage->read(1); ASSERT_EQ(page1.data.size(), buf_sz); for (size_t i = 0; i < page1.data.size(); ++i) { auto * p = page1.data.begin(); EXPECT_EQ(*p, 0x02); } } } CATCH /** * PageStorage tests with predefine Page1 && Page2 */ class PageStorageWith2PagesTest : public PageStorageTest { public: PageStorageWith2PagesTest() = default; protected: void SetUp() override { PageStorageTest::SetUp(); // put predefine Page1, Page2 const size_t buf_sz = 1024; char buf1[buf_sz], buf2[buf_sz]; { WriteBatch wb; memset(buf1, 0x01, buf_sz); memset(buf2, 0x02, buf_sz); wb.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(buf1, buf_sz), buf_sz); wb.putPage(2, 0, std::make_shared<ReadBufferFromMemory>(buf2, buf_sz), buf_sz); page_storage->write(std::move(wb)); } } }; TEST_F(PageStorageWith2PagesTest, DeleteRefPages) { // put ref page: RefPage3 -> Page2, RefPage4 -> Page2 { WriteBatch batch; batch.putRefPage(3, 2); batch.putRefPage(4, 2); page_storage->write(std::move(batch)); } { // tests for delete Page // delete RefPage3, RefPage4 don't get deleted { WriteBatch batch; batch.delPage(3); page_storage->write(std::move(batch)); EXPECT_FALSE(page_storage->getEntry(3).isValid()); EXPECT_TRUE(page_storage->getEntry(4).isValid()); } // delete RefPage4 { WriteBatch batch; batch.delPage(4); page_storage->write(std::move(batch)); EXPECT_FALSE(page_storage->getEntry(4).isValid()); } } } TEST_F(PageStorageWith2PagesTest, PutRefPagesOverRefPages) { /// put ref page to ref page, ref path collapse to normal page { WriteBatch batch; // RefPage3 -> Page1 batch.putRefPage(3, 1); // RefPage4 -> RefPage3 -> Page1 batch.putRefPage(4, 2); page_storage->write(std::move(batch)); } const auto p0entry = page_storage->getEntry(1); const auto p2entry = page_storage->getEntry(2); { // check that RefPage3 -> Page1 auto entry = page_storage->getEntry(3); ASSERT_EQ(entry.fileIdLevel(), p0entry.fileIdLevel()); ASSERT_EQ(entry.offset, p0entry.offset); ASSERT_EQ(entry.size, p0entry.size); const Page page3 = page_storage->read(3); for (size_t i = 0; i < page3.data.size(); ++i) { EXPECT_EQ(*(page3.data.begin() + i), 0x01); } } { // check that RefPage4 -> Page1 auto entry = page_storage->getEntry(4); ASSERT_EQ(entry.fileIdLevel(), p2entry.fileIdLevel()); ASSERT_EQ(entry.offset, p2entry.offset); ASSERT_EQ(entry.size, p2entry.size); const Page page4 = page_storage->read(4); for (size_t i = 0; i < page4.data.size(); ++i) { EXPECT_EQ(*(page4.data.begin() + i), 0x02); } } } TEST_F(PageStorageWith2PagesTest, PutDuplicateRefPages) { /// put duplicated RefPages in different WriteBatch { WriteBatch batch; batch.putRefPage(3, 1); page_storage->write(std::move(batch)); WriteBatch batch2; batch2.putRefPage(3, 1); page_storage->write(std::move(batch)); // now Page1's entry has ref count == 2 but not 3 } PageEntry entry1 = page_storage->getEntry(1); ASSERT_TRUE(entry1.isValid()); PageEntry entry3 = page_storage->getEntry(3); ASSERT_TRUE(entry3.isValid()); EXPECT_EQ(entry1.fileIdLevel(), entry3.fileIdLevel()); EXPECT_EQ(entry1.offset, entry3.offset); EXPECT_EQ(entry1.size, entry3.size); EXPECT_EQ(entry1.checksum, entry3.checksum); // check Page1's entry has ref count == 2 but not 1 { WriteBatch batch; batch.delPage(1); page_storage->write(std::move(batch)); PageEntry entry_after_del1 = page_storage->getEntry(3); ASSERT_TRUE(entry_after_del1.isValid()); EXPECT_EQ(entry1.fileIdLevel(), entry_after_del1.fileIdLevel()); EXPECT_EQ(entry1.offset, entry_after_del1.offset); EXPECT_EQ(entry1.size, entry_after_del1.size); EXPECT_EQ(entry1.checksum, entry_after_del1.checksum); WriteBatch batch2; batch2.delPage(3); page_storage->write(std::move(batch2)); PageEntry entry_after_del2 = page_storage->getEntry(3); ASSERT_FALSE(entry_after_del2.isValid()); } } TEST_F(PageStorageWith2PagesTest, PutCollapseDuplicatedRefPages) { /// put duplicated RefPages due to ref-path-collapse { WriteBatch batch; // RefPage3 -> Page1 batch.putRefPage(3, 1); // RefPage4 -> RefPage3, collapse to RefPage4 -> Page1 batch.putRefPage(4, 3); page_storage->write(std::move(batch)); WriteBatch batch2; // RefPage4 -> Page1, duplicated due to ref-path-collapse batch2.putRefPage(4, 1); page_storage->write(std::move(batch)); // now Page1's entry has ref count == 3 but not 2 } PageEntry entry1 = page_storage->getEntry(1); ASSERT_TRUE(entry1.isValid()); PageEntry entry3 = page_storage->getEntry(3); ASSERT_TRUE(entry3.isValid()); PageEntry entry4 = page_storage->getEntry(4); ASSERT_TRUE(entry4.isValid()); EXPECT_EQ(entry1.fileIdLevel(), entry4.fileIdLevel()); EXPECT_EQ(entry1.offset, entry4.offset); EXPECT_EQ(entry1.size, entry4.size); EXPECT_EQ(entry1.checksum, entry4.checksum); // check Page1's entry has ref count == 3 but not 2 { WriteBatch batch; batch.delPage(1); batch.delPage(4); page_storage->write(std::move(batch)); PageEntry entry_after_del2 = page_storage->getEntry(3); ASSERT_TRUE(entry_after_del2.isValid()); EXPECT_EQ(entry1.fileIdLevel(), entry_after_del2.fileIdLevel()); EXPECT_EQ(entry1.offset, entry_after_del2.offset); EXPECT_EQ(entry1.size, entry_after_del2.size); EXPECT_EQ(entry1.checksum, entry_after_del2.checksum); WriteBatch batch2; batch2.delPage(3); page_storage->write(std::move(batch2)); PageEntry entry_after_del3 = page_storage->getEntry(3); ASSERT_FALSE(entry_after_del3.isValid()); } } TEST_F(PageStorageWith2PagesTest, DISABLED_AddRefPageToNonExistPage) try { { WriteBatch batch; // RefPage3 -> non-exist Page999 batch.putRefPage(3, 999); ASSERT_NO_THROW(page_storage->write(std::move(batch))); } ASSERT_FALSE(page_storage->getEntry(3).isValid()); ASSERT_THROW(page_storage->read(3), DB::Exception); // page_storage->read(3); // Invalid Pages is filtered after reopen PageStorage ASSERT_NO_THROW(reopenWithConfig(config)); ASSERT_FALSE(page_storage->getEntry(3).isValid()); ASSERT_THROW(page_storage->read(3), DB::Exception); // page_storage->read(3); // Test Add RefPage to non exists page with snapshot acuqired. { auto snap = page_storage->getSnapshot(); { WriteBatch batch; // RefPage3 -> non-exist Page999 batch.putRefPage(8, 999); ASSERT_NO_THROW(page_storage->write(std::move(batch))); } ASSERT_FALSE(page_storage->getEntry(8).isValid()); ASSERT_THROW(page_storage->read(8), DB::Exception); // page_storage->read(8); } // Invalid Pages is filtered after reopen PageStorage ASSERT_NO_THROW(reopenWithConfig(config)); ASSERT_FALSE(page_storage->getEntry(8).isValid()); ASSERT_THROW(page_storage->read(8), DB::Exception); // page_storage->read(8); } CATCH TEST_F(PageStorageTest, WriteReadGcExternalPage) try { WriteBatch batch; { // External 0, 1024 // Ref 1->0 batch.putExternal(0, 0); batch.putRefPage(1, 0); batch.putExternal(1024, 0); page_storage->write(std::move(batch)); } size_t times_remover_called = 0; ExternalPageCallbacks callbacks; callbacks.scanner = []() -> ExternalPageCallbacks::PathAndIdsVec { return {}; }; callbacks.remover = [&times_remover_called](const ExternalPageCallbacks::PathAndIdsVec &, const std::set<PageId> & living_page_ids) -> void { times_remover_called += 1; // 0, 1024 are still alive EXPECT_EQ(living_page_ids.size(), 2); EXPECT_GT(living_page_ids.count(0), 0); EXPECT_GT(living_page_ids.count(1024), 0); }; callbacks.ns_id = TEST_NAMESPACE_ID; page_storage->registerExternalPagesCallbacks(callbacks); { SCOPED_TRACE("fist gc"); page_storage->gc(); EXPECT_EQ(times_remover_called, 1); } auto snapshot = page_storage->getSnapshot(); { WriteBatch batch; batch.putRefPage(2, 1); // ref 2 -> 1 ==> 2 -> 0 batch.delPage(1); // free ref 1 -> 0 batch.delPage(1024); // free ext page 1024 // External: 0, 1024(deleted) // Ref: 2->0, 1->0(deleted) page_storage->write(std::move(batch)); } { // With `snapshot` is being held, nothing is need to be deleted SCOPED_TRACE("gc with snapshot"); page_storage->gc(); EXPECT_EQ(times_remover_called, 2); } { auto ori_id_0 = page_storage->getNormalPageId(TEST_NAMESPACE_ID, 0, nullptr); ASSERT_EQ(ori_id_0, 0); auto ori_id_2 = page_storage->getNormalPageId(TEST_NAMESPACE_ID, 2, nullptr); ASSERT_EQ(ori_id_2, 0); ASSERT_EQ(1024, page_storage->getNormalPageId(TEST_NAMESPACE_ID, 1024, snapshot)); ASSERT_EQ(0, page_storage->getNormalPageId(TEST_NAMESPACE_ID, 1, snapshot)); ASSERT_ANY_THROW(page_storage->getNormalPageId(TEST_NAMESPACE_ID, 1024, nullptr)); ASSERT_ANY_THROW(page_storage->getNormalPageId(TEST_NAMESPACE_ID, 1, nullptr)); } /// After `snapshot` released, 1024 should be removed from `living` snapshot.reset(); callbacks.remover = [&times_remover_called](const ExternalPageCallbacks::PathAndIdsVec &, const std::set<PageId> & living_page_ids) -> void { times_remover_called += 1; EXPECT_EQ(living_page_ids.size(), 1); EXPECT_GT(living_page_ids.count(0), 0); }; page_storage->unregisterExternalPagesCallbacks(callbacks.ns_id); page_storage->registerExternalPagesCallbacks(callbacks); { SCOPED_TRACE("gc with snapshot released"); page_storage->gc(); EXPECT_EQ(times_remover_called, 3); } } CATCH TEST_F(PageStorageTest, GcReuseSpaceThenRestore) try { DB::UInt64 tag = 0; const size_t buf_sz = 1024; char c_buff[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff[i] = i % 0xff; } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(1, tag, buff, buf_sz); page_storage->write(std::move(batch)); } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(1, tag, buff, buf_sz); page_storage->write(std::move(batch)); } { SCOPED_TRACE("fist gc"); page_storage->gc(); } { WriteBatch batch; ReadBufferPtr buff = std::make_shared<ReadBufferFromMemory>(c_buff, sizeof(c_buff)); batch.putPage(1, tag, buff, buf_sz); page_storage->write(std::move(batch)); } page_storage.reset(); page_storage = reopenWithConfig(config); } CATCH TEST_F(PageStorageTest, readRefAfterRestore) try { const size_t buf_sz = 1024; char c_buff[buf_sz]; for (size_t i = 0; i < buf_sz; ++i) { c_buff[i] = i % 0xff; } { WriteBatch batch; batch.putPage(1, 0, std::make_shared<ReadBufferFromMemory>(c_buff, buf_sz), buf_sz, PageFieldSizes{{32, 64, 79, 128, 196, 256, 269}}); batch.putRefPage(3, 1); batch.delPage(1); batch.putPage(4, 0, std::make_shared<ReadBufferFromMemory>(c_buff, buf_sz), buf_sz, {}); page_storage->write(std::move(batch)); } page_storage = reopenWithConfig(config); { WriteBatch batch; memset(c_buff, 0, buf_sz); batch.putPage(5, 0, std::make_shared<ReadBufferFromMemory>(c_buff, buf_sz), buf_sz, {}); page_storage->write(std::move(batch)); } std::vector<PageStorage::PageReadFields> fields; PageStorage::PageReadFields field; field.first = 3; field.second = {0, 1, 2, 3, 4, 5, 6}; fields.emplace_back(field); ASSERT_NO_THROW(page_storage->read(fields)); } CATCH } // namespace PS::V3::tests } // namespace DB
31.363158
145
0.618426
solotzg
5b7293b4ca39d3f3817e492ea25bb5dfbb3501e4
15,783
cpp
C++
transport_utils/rpc_delay_measurer.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
1
2020-05-22T08:47:00.000Z
2020-05-22T08:47:00.000Z
transport_utils/rpc_delay_measurer.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
transport_utils/rpc_delay_measurer.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
#include <tm_kit/infra/Environments.hpp> #include <tm_kit/infra/TerminationController.hpp> #include <tm_kit/infra/RealTimeApp.hpp> #include <tm_kit/infra/DeclarativeGraph.hpp> #include <tm_kit/infra/SynchronousRunner.hpp> #include <tm_kit/basic/SpdLoggingComponent.hpp> #include <tm_kit/basic/real_time_clock/ClockComponent.hpp> #include <tm_kit/basic/SerializationHelperMacros.hpp> #include <tm_kit/transport/CrossGuidComponent.hpp> #include <tm_kit/transport/MultiTransportRemoteFacilityManagingUtils.hpp> #include <tm_kit/transport/MultiTransportRemoteFacilityManagingUtils_SynchronousRunner.hpp> #include <tm_kit/transport/MultiTransportFacilityWrapper.hpp> #include <tm_kit/transport/HeartbeatAndAlertComponent.hpp> #include <tclap/CmdLine.h> using namespace dev::cd606::tm; using Environment = infra::Environment< infra::CheckTimeComponent<true>, infra::TrivialExitControlComponent, basic::SpdLoggingComponent, basic::real_time_clock::ClockComponent, transport::CrossGuidComponent, transport::AllNetworkTransportComponents, transport::HeartbeatAndAlertComponent >; using M = infra::RealTimeApp<Environment>; using R = infra::AppRunner<M>; using SR = infra::SynchronousRunner<M>; #define FACILITY_INPUT_FIELDS \ ((int64_t, timestamp)) \ ((int, data)) #define FACILITY_OUTPUT_FIELDS \ ((int, data)) TM_BASIC_CBOR_CAPABLE_STRUCT(FacilityInput, FACILITY_INPUT_FIELDS); TM_BASIC_CBOR_CAPABLE_STRUCT(FacilityOutput, FACILITY_OUTPUT_FIELDS); TM_BASIC_CBOR_CAPABLE_STRUCT_SERIALIZE_NO_FIELD_NAMES(FacilityInput, FACILITY_INPUT_FIELDS); TM_BASIC_CBOR_CAPABLE_STRUCT_SERIALIZE_NO_FIELD_NAMES(FacilityOutput, FACILITY_OUTPUT_FIELDS); void runServer(std::string const &serviceDescriptor, transport::HeartbeatAndAlertComponentTouchupParameters const &heartbeatParam) { Environment env; R r(&env); transport::HeartbeatAndAlertComponentTouchup<R> { r , heartbeatParam }; infra::GenericComponentLiftAndRegistration<R> _(r); auto facility = _("facility", infra::LiftAsFacility{}, [](FacilityInput &&x) -> FacilityOutput { return {x.data*2}; }); transport::MultiTransportFacilityWrapper<R>::wrap<FacilityInput,FacilityOutput>( r , facility , serviceDescriptor , "wrapper" ); r.finalize(); infra::terminationController(infra::RunForever {}); } void runClient(transport::SimpleRemoteFacilitySpec const &spec, int repeatTimes) { Environment env; R r(&env); int64_t firstTimeStamp = 0; int64_t count = 0; int64_t recvCount = 0; auto facilitioidAndTrigger = transport::MultiTransportRemoteFacilityManagingUtils<R> ::setupSimpleRemoteFacilitioid<FacilityInput, FacilityOutput> ( r , spec , "remoteConnection" ); infra::DeclarativeGraph<R>("", { {"data", infra::DelayImporter<basic::VoidStruct>{}, [repeatTimes](Environment *e) -> std::tuple<bool, M::Data<int>> { static int count = 0; ++count; return std::tuple<bool, M::Data<int>> { (count<repeatTimes) , M::InnerData<int> { e , { e->resolveTime() , count , (count >= repeatTimes) } } }; }} , {"keyify", [](M::InnerData<int> &&x) -> M::Data<M::Key<FacilityInput>> { return M::InnerData<M::Key<FacilityInput>> { x.environment , { x.timedData.timePoint , M::keyify(FacilityInput { infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(x.timedData.timePoint) , x.timedData.value }) , x.timedData.finalFlag } }; }} , {"exporter", [&firstTimeStamp,&count,&recvCount,repeatTimes](M::InnerData<M::KeyedData<FacilityInput,FacilityOutput>> &&data) { auto now = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(data.timedData.timePoint); count += (now-data.timedData.value.key.key().timestamp); if (data.timedData.value.key.key().data == 1) { firstTimeStamp = data.timedData.value.key.key().timestamp; } ++recvCount; //if (data.timedData.value.key.key().data >= repeatTimes) { if (recvCount >= repeatTimes) { data.environment->log(infra::LogLevel::Info, std::string("average delay of ")+std::to_string(recvCount)+" calls is "+std::to_string(count*1.0/repeatTimes)+" microseconds"); data.environment->log(infra::LogLevel::Info, std::string("total time for ")+std::to_string(recvCount)+" calls is "+std::to_string(now-firstTimeStamp)+" microseconds"); data.environment->exit(); } }} , {"data", "keyify"} , {"keyify", facilitioidAndTrigger.facility, "exporter"} , {facilitioidAndTrigger.facilityFirstReady.clone(), "data"} })(r); r.finalize(); infra::terminationController(infra::RunForever {}); } void runClientSynchronousMode(transport::SimpleRemoteFacilitySpec const &spec, int repeatTimes) { Environment env; SR r(&env); int64_t firstTimeStamp = 0; int64_t count = 0; int64_t recvCount = 0; auto facility = transport::MultiTransportRemoteFacilityManagingUtils<SR> ::setupSimpleRemoteFacility<FacilityInput, FacilityOutput> ( r , spec ); for (int ii=0; ii<repeatTimes; ++ii) { auto data = r.placeOrderWithFacility( FacilityInput {infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(env.now()), ii+1} , facility )->front_with_time_out(std::chrono::milliseconds(500)); if (data) { auto now = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(data->timedData.timePoint); count += (now-data->timedData.value.key.key().timestamp); if (data->timedData.value.key.key().data == 1) { firstTimeStamp = data->timedData.value.key.key().timestamp; } ++recvCount; if (data->timedData.value.key.key().data >= repeatTimes) { env.log(infra::LogLevel::Info, std::string("average delay of ")+std::to_string(recvCount)+" calls is "+std::to_string(count*1.0/repeatTimes)+" microseconds"); env.log(infra::LogLevel::Info, std::string("total time for ")+std::to_string(recvCount)+" calls is "+std::to_string(now-firstTimeStamp)+" microseconds"); } } } env.log(infra::LogLevel::Info, "done"); } void runClientOneShotMode(transport::SimpleRemoteFacilitySpec const &spec, int repeatTimes, bool autoDisconnect) { Environment env; int64_t firstTimeStamp = 0; int64_t count = 0; int64_t now = 0; if (spec.index() == 0) { for (int ii=0; ii<repeatTimes; ++ii) { auto sentTime = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(env.now()); auto data = transport::OneShotMultiTransportRemoteFacilityCall<Environment> ::call<FacilityInput, FacilityOutput>( &env , std::get<0>(spec) , FacilityInput {sentTime, ii+1} , std::nullopt , autoDisconnect ).get(); //env.log(infra::LogLevel::Info, std::to_string(data.data)); now = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(env.now()); count += (now-sentTime); if (ii == 0) { firstTimeStamp = sentTime; } } } else { env.log(infra::LogLevel::Warning, "client-oneshot don't use heartbeat mode beause the repeated heartbeat wait-time will distort the delay measurement"); } env.log(infra::LogLevel::Info, std::string("average delay of ")+std::to_string(repeatTimes)+" calls is "+std::to_string(count*1.0/repeatTimes)+" microseconds"); env.log(infra::LogLevel::Info, std::string("total time for ")+std::to_string(repeatTimes)+" calls is "+std::to_string(now-firstTimeStamp)+" microseconds"); env.log(infra::LogLevel::Info, "done"); } void runClientSimOneShotMode(transport::SimpleRemoteFacilitySpec const &spec, int repeatTimes) { Environment env; R r(&env); int64_t firstTimeStamp = 0; int64_t count = 0; int64_t now = 0; auto facilitioidAndTrigger = transport::MultiTransportRemoteFacilityManagingUtils<R> ::setupSimpleRemoteFacilitioid<FacilityInput, FacilityOutput> ( r , spec , "remoteConnection" ); auto promiseMap = std::make_shared<std::unordered_map<Environment::IDType, std::shared_ptr<std::promise<FacilityOutput>>, Environment::IDHash>>(); r.preservePointer(promiseMap); auto importerPair = M::triggerImporter<M::Key<FacilityInput>>(); auto startPromise = std::make_shared<std::promise<void>>(); r.preservePointer(startPromise); infra::DeclarativeGraph<R>("", { {"importer", std::get<0>(importerPair)} , {"exporter", [promiseMap](M::KeyedData<FacilityInput,FacilityOutput> &&data) { auto iter = promiseMap->find(data.key.id()); if (iter != promiseMap->end()) { iter->second->set_value(data.data); promiseMap->erase(iter); } }} , {"importer", facilitioidAndTrigger.facility, "exporter"} , {"waitForStart", [startPromise](basic::VoidStruct &&) { startPromise->set_value(); }} , {facilitioidAndTrigger.facilityFirstReady.clone(), "waitForStart"} })(r); r.finalize(); startPromise->get_future().wait(); for (int ii=0; ii<repeatTimes; ++ii) { auto sentTime = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(env.now()); M::Key<FacilityInput> req( FacilityInput {sentTime, ii+1} ); auto fut = promiseMap->emplace(req.id(), std::make_shared<std::promise<FacilityOutput>>()).first->second->get_future(); std::get<1>(importerPair)(std::move(req)); auto res = fut.get(); now = infra::withtime_utils::sinceEpoch<std::chrono::microseconds>(env.now()); count += (now-sentTime); if (ii == 0) { firstTimeStamp = sentTime; } } env.log(infra::LogLevel::Info, std::string("average delay of ")+std::to_string(repeatTimes)+" calls is "+std::to_string(count*1.0/repeatTimes)+" microseconds"); env.log(infra::LogLevel::Info, std::string("total time for ")+std::to_string(repeatTimes)+" calls is "+std::to_string(now-firstTimeStamp)+" microseconds"); env.log(infra::LogLevel::Info, "done"); env.exit(0); } int main(int argc, char **argv) { TCLAP::CmdLine cmd("RPC Delay Measurer", ' ', "0.0.1"); TCLAP::ValueArg<std::string> modeArg("m", "mode", "server, client, client-sync, client-oneshot, client-oneshot-disconnect or client-sim-oneshot", true, "", "string"); TCLAP::ValueArg<std::string> serviceDescriptorArg("d", "serviceDescriptor", "service descriptor", false, "", "string"); TCLAP::ValueArg<std::string> heartbeatDescriptorArg("H", "heartbeatDescriptor", "heartbeat descriptor", false, "", "string"); TCLAP::ValueArg<std::string> heartbeatTopicArg("T", "heartbeatTopic", "heartbeat topic", false, "tm.examples.heartbeats", "string"); TCLAP::ValueArg<std::string> heartbeatIdentityArg("I", "heartbeatIdentity", "heartbeat identity", false, "rpc_delay_measurer", "string"); TCLAP::ValueArg<int> repeatTimesArg("r", "repeatTimes", "repeat times", false, 1000, "int"); cmd.add(modeArg); cmd.add(serviceDescriptorArg); cmd.add(heartbeatDescriptorArg); cmd.add(heartbeatTopicArg); cmd.add(heartbeatIdentityArg); cmd.add(repeatTimesArg); cmd.parse(argc, argv); if (modeArg.getValue() == "server") { if (!serviceDescriptorArg.isSet()) { std::cerr << "Server mode requires descriptor\n"; return 1; } transport::HeartbeatAndAlertComponentTouchupParameters heartbeatParam { heartbeatDescriptorArg.getValue() , heartbeatTopicArg.getValue() , heartbeatIdentityArg.getValue() , std::chrono::seconds(2) }; runServer(serviceDescriptorArg.getValue(), heartbeatParam); return 0; } else if (modeArg.getValue() == "client") { if (serviceDescriptorArg.isSet()) { runClient(serviceDescriptorArg.getValue(), repeatTimesArg.getValue()); return 0; } else if (heartbeatDescriptorArg.isSet()) { runClient(transport::SimpleRemoteFacilitySpecByHeartbeat { heartbeatDescriptorArg.getValue() , heartbeatTopicArg.getValue() , std::regex {heartbeatIdentityArg.getValue()} , "facility" }, repeatTimesArg.getValue()); return 0; } else { std::cerr << "Client mode requires either service descriptor or heartbeat descriptor\n"; return 1; } } else if (modeArg.getValue() == "client-sync") { if (serviceDescriptorArg.isSet()) { runClientSynchronousMode(serviceDescriptorArg.getValue(), repeatTimesArg.getValue()); return 0; } else if (heartbeatDescriptorArg.isSet()) { runClientSynchronousMode(transport::SimpleRemoteFacilitySpecByHeartbeat { heartbeatDescriptorArg.getValue() , heartbeatTopicArg.getValue() , std::regex {heartbeatIdentityArg.getValue()} , "facility" }, repeatTimesArg.getValue()); return 0; } else { std::cerr << "Client-sync mode requires either service descriptor or heartbeat descriptor\n"; return 1; } } else if (modeArg.getValue() == "client-oneshot" || modeArg.getValue() == "client-oneshot-disconnect") { if (serviceDescriptorArg.isSet()) { runClientOneShotMode(serviceDescriptorArg.getValue(), repeatTimesArg.getValue(), (modeArg.getValue() == "client-oneshot-disconnect")); return 0; } else if (heartbeatDescriptorArg.isSet()) { std::cerr << modeArg.getValue() << " doesn't use heartbeat mode beause the repeated heartbeat wait-time will distort the delay measurement\n"; return 1; } else { std::cerr << "Client-oneshot mode requires either service descriptor or heartbeat descriptor\n"; return 1; } } else if (modeArg.getValue() == "client-sim-oneshot") { if (serviceDescriptorArg.isSet()) { runClientSimOneShotMode(serviceDescriptorArg.getValue(), repeatTimesArg.getValue()); return 0; } else if (heartbeatDescriptorArg.isSet()) { runClientSimOneShotMode(transport::SimpleRemoteFacilitySpecByHeartbeat { heartbeatDescriptorArg.getValue() , heartbeatTopicArg.getValue() , std::regex {heartbeatIdentityArg.getValue()} , "facility" }, repeatTimesArg.getValue()); } else { std::cerr << "Client-sim-oneshot mode requires either service descriptor or heartbeat descriptor\n"; return 1; } } else { std::cerr << "Mode must be server, client, client-sync, client-oneshot, client-oneshot-disconnect or client-sim-oneshot\n"; return 1; } }
44.33427
188
0.625356
cd606
ac8bb4964d1ca7a3f3e61140fcc388e923c439ec
36,409
cpp
C++
project/test/algorithm/arithmetic/in_arithmetic_range.cpp
daishe/commander
0a23abcbe406e234a4242e0d508bb89d72b28e25
[ "BSL-1.0" ]
null
null
null
project/test/algorithm/arithmetic/in_arithmetic_range.cpp
daishe/commander
0a23abcbe406e234a4242e0d508bb89d72b28e25
[ "BSL-1.0" ]
null
null
null
project/test/algorithm/arithmetic/in_arithmetic_range.cpp
daishe/commander
0a23abcbe406e234a4242e0d508bb89d72b28e25
[ "BSL-1.0" ]
null
null
null
// Copyright Marek Dalewski 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <commander/algorithm.hpp> #include <boost/test/unit_test.hpp> #include "arithmetic_helpers.hpp" #include <type_traits> BOOST_AUTO_TEST_CASE( in_arithmetic_range ) { namespace comd = commander::detail; { BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int64_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<int64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint64_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<bool>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(true) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(false) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(false) == true); } { { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint8_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint8_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint8_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint8_t>(nl<int8_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int16_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int16_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int16_t>(nl<int8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint16_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint16_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint16_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint16_t>(nl<int8_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int32_t>(nl<int8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint32_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint32_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint32_t>(nl<int8_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<int64_t>(nl<int8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint64_t>(nl<int8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint64_t>(nl<int8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int8_t>(sc<uint64_t>(nl<int8_t>::max(), +1)) == false); } } { { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int8_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int8_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int8_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int8_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int16_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int16_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int16_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint16_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint16_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int32_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint32_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<int64_t>(nl<uint8_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint8_t>(sc<uint64_t>(nl<uint8_t>::lowest(), +1)) == true); } } { { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint16_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint16_t>(nl<int16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint16_t>(nl<int16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint16_t>(nl<int16_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int32_t>(nl<int16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint32_t>(nl<int16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint32_t>(nl<int16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint32_t>(nl<int16_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<int64_t>(nl<int16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint64_t>(nl<int16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint64_t>(nl<int16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int16_t>(sc<uint64_t>(nl<int16_t>::max(), +1)) == false); } } { { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int8_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int8_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int8_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int8_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint8_t>(nl<uint16_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint8_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint8_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int16_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int16_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int16_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int16_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int32_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint32_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<int64_t>(nl<uint16_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint16_t>(sc<uint64_t>(nl<uint16_t>::lowest(), +1)) == true); } } { { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int32_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint32_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint32_t>(nl<int32_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint32_t>(nl<int32_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint32_t>(nl<int32_t>::max(), +1)) == false); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<int64_t>(nl<int32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint64_t>(nl<int32_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint64_t>(nl<int32_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int32_t>(sc<uint64_t>(nl<int32_t>::max(), +1)) == false); } } { { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int8_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int8_t>(nl<uint32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int8_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int8_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint8_t>(nl<uint32_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint8_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint8_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int16_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int16_t>(nl<uint32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int16_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int16_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint16_t>(nl<uint32_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint16_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint16_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int32_t>(nl<uint32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int32_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int32_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint32_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<int64_t>(nl<uint32_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::max(), +1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint32_t>(sc<uint64_t>(nl<uint32_t>::lowest(), +1)) == true); } } { { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint8_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint16_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int32_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint32_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int64_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<int64_t>::lowest()) == true); } { BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint64_t>::max()) == false); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(nl<uint64_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(sc<uint64_t>(nl<int64_t>::max(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(sc<uint64_t>(nl<int64_t>::max())) == true); BOOST_CHECK(comd::in_arithmetic_range<int64_t>(sc<uint64_t>(nl<int64_t>::max(), +1)) == false); } } { { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int8_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int8_t>(nl<uint64_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int8_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int8_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint8_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint8_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint8_t>(nl<uint64_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint8_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint8_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int16_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int16_t>(nl<uint64_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int16_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int16_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint16_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint16_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint16_t>(nl<uint64_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint16_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint16_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int32_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int32_t>(nl<uint64_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int32_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int32_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint32_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint32_t>::lowest()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint32_t>(nl<uint64_t>::lowest(), -1)) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint32_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<uint32_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int64_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<int64_t>::lowest()) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int64_t>(nl<uint64_t>::lowest(), -1)) == false); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int64_t>(nl<uint64_t>::lowest())) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(sc<int64_t>(nl<uint64_t>::lowest(), +1)) == true); } { BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint64_t>::max()) == true); BOOST_CHECK(comd::in_arithmetic_range<uint64_t>(nl<uint64_t>::lowest()) == true); } } }
58.62963
112
0.618583
daishe
ac8d04e5823b681f82991d54c539e8a5049e258d
852
cpp
C++
AquaEngine/Core/Allocators/EndAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
55
2015-05-29T20:19:28.000Z
2022-01-18T21:23:15.000Z
AquaEngine/Core/Allocators/EndAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
null
null
null
AquaEngine/Core/Allocators/EndAllocator.cpp
tiagovcosta/aquaengine
aea6de9f47ba0243b90c144dee4422efb2389cc7
[ "MIT" ]
6
2015-09-02T09:51:38.000Z
2020-08-16T07:54:34.000Z
#include "EndAllocator.h" #include "..\..\Utilities\Debug.h" using namespace aqua; EndAllocator::EndAllocator(size_t size, void* start) : FixedLinearAllocator(size, start) { } EndAllocator::~EndAllocator() {} void* EndAllocator::allocate(size_t size, u8 alignment) { ASSERT(size != 0 && alignment != 0); void* address = pointer_math::subtract(_current_pos, size); u8 adjustment = pointer_math::alignBackwardAdjustment(address, alignment); if(_used_memory + adjustment + size > _size) return nullptr; void* aligned_address = pointer_math::subtract(address, adjustment); _current_pos = aligned_address; _used_memory = (uptr)_start - (uptr)_current_pos; return aligned_address; } void EndAllocator::rewind(void* p) { ASSERT(_current_pos <= p && _start >= p); _current_pos = p; _used_memory = (uptr)_start - (uptr)_current_pos; }
21.3
75
0.732394
tiagovcosta
ac9576c96415e5cf87ba8000379cbe2342a343f6
4,732
cpp
C++
Week14/src/main.cpp
deciduously/SDEV345
1ebe552878fe692126ca1f56046b43d34ae7d3d3
[ "BSD-3-Clause" ]
2
2020-01-14T20:00:37.000Z
2020-04-08T17:59:04.000Z
Week14/src/main.cpp
deciduously/SDEV345
1ebe552878fe692126ca1f56046b43d34ae7d3d3
[ "BSD-3-Clause" ]
null
null
null
Week14/src/main.cpp
deciduously/SDEV345
1ebe552878fe692126ca1f56046b43d34ae7d3d3
[ "BSD-3-Clause" ]
null
null
null
/** * SDEV 345 Week 13 * Hash table * A hash table with a menu-driven CLI using quadratic probing on collisions * Ben Lovy * April 19, 2020 */ #include <algorithm> #include <iostream> #include <string> #include <vector> struct DataMember { std::string data; DataMember() : data("") {} DataMember(const std::string& d) : data(d) {} }; class HashTable { std::vector<DataMember*> data; size_t length; DataMember* nullMember; // Hash a key int get_hash(const std::string& key) { int some_prime = 37, prime_two = 54059, prime_three = 76963; int ret = some_prime; for (size_t i = 0; i < key.size(); ++i) { ret = (ret * prime_two) ^ (key[0] * prime_three); } return ret % length; } // Check if the table is full bool isFull() { return std::all_of(data.begin(), data.end(), [](auto member) { return member != nullptr; }); } public: HashTable(int size) : length(size) { data.resize(length); // Init all members to null std::fill(data.begin(), data.end(), nullptr); nullMember = new DataMember(); } // Show off full table void display() { using std::cout; cout << "[ "; for (auto member : data) { if (member) cout << member->data << " "; else cout << "__ "; } cout << "]\n"; } // Insert a key void insert(DataMember* item_ptr) { if (isFull()) { std::cerr << "Cannot insert - table full!\n"; return; } // Hash the data std::string s = item_ptr->data; int hash = get_hash(s); // Tell user if there was a collision if (data[hash]) std::cout << "Note: hash collision!\n"; // Adjust hash via quadratic probing until free int currentCollision = 0; // this will increase each iteration while (data[hash] && data[hash]->data != "") { //++hash; // This was the linear probe version - simply increment // Instead, we probe qaudratically each iteration, incrementing the base step hash += 2 * ++currentCollision -1; hash %= length; // And adjust back to the size of the set } // Insert data[hash] = item_ptr; } // Locate a key DataMember* locate(const std::string& key) { // Get the hash int hash = get_hash(key); // Look for it while (data[hash]) { if (data[hash]->data == key) { return data[hash]; } ++hash; hash %= length; } // Not found return nullptr; } DataMember* remove(const std::string& key) { // Get the hash int hash = get_hash(key); // Look for it while (data[hash]) { if (data[hash]->data == key) { // Delete and return it DataMember* del = data[hash]; data[hash] = nullMember; return del; } ++hash; hash %= length; } // Not found return nullptr; } }; int main() { using std::cin; using std::cout; using std::string; DataMember* item_ptr; int selection; string key; // Init table to prime number of buckets HashTable table(19); // Menu for (;;) { cout << "1) Insert Key\n2) Delete Key\n3) Display hash table\n4) Find key\nSelection> "; cin >> selection; switch (selection) { case 1: cout << "Enter string to insert> "; cin >> key; // Init member item_ptr = new DataMember(key); // Add to table table.insert(item_ptr); break; case 2: cout << "Enter string to delete> "; cin >> key; table.remove(key); break; case 3: table.display(); break; case 4: cout << "Enter string to locate> "; cin >> key; item_ptr = table.locate(key); if (item_ptr) cout << "Successfully located "; else cout << "Unable to locate "; cout << key << "\n"; break; default: std::cerr << "Unknown option! Try again\n"; } } return 0; }
23.66
96
0.464708
deciduously
aca15fe07310e6416c525c4d76269e7059e87e32
1,204
cpp
C++
Retro3D/src/Component/audio_component.cpp
mlavik1/Retro3D
bb9808444d20ae0fa38cfc9d48c029d70d11c537
[ "MIT" ]
10
2017-06-28T12:43:02.000Z
2022-02-14T12:43:57.000Z
Retro3D/src/Component/audio_component.cpp
mlavik1/Retro3D
bb9808444d20ae0fa38cfc9d48c029d70d11c537
[ "MIT" ]
8
2019-04-07T23:25:28.000Z
2019-04-17T22:19:44.000Z
Retro3D/src/Component/audio_component.cpp
mlavik1/Retro3D
bb9808444d20ae0fa38cfc9d48c029d70d11c537
[ "MIT" ]
4
2019-04-08T15:21:09.000Z
2021-04-06T18:49:20.000Z
#include "audio_component.h" #include "Resource/resource_manager.h" #include "Engine/game_engine.h" #include "Audio/audio_manager.h" namespace Retro3D { AudioTrack* AudioComponent::LoadAudio(std::string arg_file, std::string arg_name) { // TODO: can we do this async? - block until loaded if we try to use the audio before it's done loading. ResPtr<AudioRes> audioRes = GGameEngine->GetResourceManager()->LoadResource<AudioRes>(arg_file); if (audioRes.IsValid()) { auto existingTrack = mAudioTracks.find(arg_name); if (existingTrack != mAudioTracks.end()) { delete existingTrack->second; } AudioTrack* audioTrack = new AudioTrack(audioRes.Get()); mAudioTracks[arg_name] = audioTrack; return audioTrack; } return nullptr; } void AudioComponent::PlayAudioTrack(std::string arg_name) { auto trackIter = mAudioTracks.find(arg_name); if (trackIter != mAudioTracks.end()) { AudioTrack* track = trackIter->second; GGameEngine->GetAudioManager()->PlayAudioTrack(track); } } void AudioComponent::PlayAllAudioTracks() { for (auto audioTrackIter : mAudioTracks) { GGameEngine->GetAudioManager()->PlayAudioTrack(audioTrackIter.second); } } }
26.755556
107
0.727575
mlavik1
aca1a1012246e30327bb55a911f71d6659a7ed35
483
cpp
C++
01. Mathematics/05 HCF/05c hcf.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
190
2021-02-10T17:01:01.000Z
2022-03-20T00:21:43.000Z
01. Mathematics/05 HCF/05c hcf.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
null
null
null
01. Mathematics/05 HCF/05c hcf.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
27
2021-03-26T11:35:15.000Z
2022-03-06T07:34:54.000Z
#include<bits/stdc++.h> using namespace std; //Euclid's Theorem Optimised int hcf(int a, int b)//time comp. O(log(min(a,b)) { if (b == 0) { return a; } return hcf(b, a % b); } int hcf_one_liner(int a, int b) { return b == 0 ? a : hcf_one_liner(b, a % b); } int main() { int a1 = 13, b1 = 17; int a2 = 100, b2 = 200; cout << hcf(a1, b1) << endl; cout << hcf(a2, b2) << endl; cout << hcf_one_liner(a1, b1) << endl; cout << hcf_one_liner(a2, b2) << endl; return 0; }
15.580645
49
0.573499
VivekYadav105
aca32ea587e7dddea49d8e01dd454a7baad55a98
2,953
cpp
C++
Codes/1340.cpp
whitesimian/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
1
2019-10-13T03:43:59.000Z
2019-10-13T03:43:59.000Z
Codes/1340.cpp
rafflezs/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
null
null
null
Codes/1340.cpp
rafflezs/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
2
2021-02-16T05:47:06.000Z
2021-02-24T14:11:54.000Z
#include <iostream> #include <vector> using namespace std; void inserir(int ordenado[], int tamanho, int elemento){ int i = tamanho - 1; while(elemento<ordenado[i] && i>=0) { ordenado[i+1] = ordenado[i]; i--; } ordenado[i+1] = elemento; } int main() { int n; while(cin>>n) { bool prioridade = true, fila = true, pilha = true; bool impossivel = false; vector<int> vetor; vetor.clear(); int ordenado[1001], tam = 0; for(int i=0;i<n;i++) { int op,elem; cin>>op>>elem; if(!impossivel) { if(op==1) { vetor.push_back(elem); if(prioridade) { inserir(ordenado,tam,elem); tam++; } } else //RETIRAR { if(vetor.size()==0) { impossivel = true; continue; } if(prioridade) { if(elem == ordenado[tam-1]) tam--; else prioridade = false; } if(vetor.size()==1) { if(elem == vetor[0]) vetor.erase(vetor.begin()); else { impossivel = true; continue; } } else { if(elem == vetor[0]) { pilha = false; vetor.erase(vetor.begin()); } else if(elem == vetor[vetor.size()-1]) { fila = false; vetor.erase(vetor.begin()+vetor.size()-1); } else if(prioridade) { pilha = false; fila = false; } else if(!prioridade) impossivel = true; } } } } if(impossivel) cout << "impossible\n"; else { if(fila && !pilha && !prioridade) cout<<"queue\n"; else if(pilha && !fila && !prioridade) cout<<"stack\n"; else if(prioridade && !fila && !pilha) cout<<"priority queue\n"; else cout<<"not sure\n"; } } return 0; }
26.366071
70
0.299695
whitesimian
aca80575d2ab1004076210ff18e94c6451bcd56d
16,644
hpp
C++
include/recompression/util.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
5
2019-07-18T12:48:14.000Z
2022-01-04T13:54:13.000Z
include/recompression/util.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/recompression/util.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <unordered_map> #include <vector> #include "defs.hpp" namespace recomp { namespace util { size_t file_size_in_bytes(std::string& file_name, const size_t prefix_size = 0) { std::ifstream in(file_name, std::ios::binary | std::ios::ate); size_t size = in.tellg(); if (prefix_size > 0) { size = std::min(size, prefix_size); } in.close(); return size; } /** * @brief Generates (pseudo) random number from 0 (inclusive) to max (exclusive). * * @param max_val The maximum value (exclusive) * @return A random number */ inline size_t random_number(size_t max_val) { return ((((size_t)std::rand()) << 32) + std::rand()) % max_val; } /** * @brief Faster loading of a file but with more memory consumption. * * @tparam text_t The type of text * @param[in] file_name The file name * @param[out] text The read text */ template<typename text_t> void read_file_fast(const std::string& file_name, ui_vector<text_t>& text, const size_t prefix_size = 0) { std::cout << "Reading file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::end); uint64_t file_size = ifs.tellg(); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } ifs.seekg(0, std::ios::beg); text.resize(file_size); // ifs.read(reinterpret_cast<char*>(text.data()), file_size); std::vector<char> in(file_size); ifs.read(reinterpret_cast<char*>(in.data()), file_size); for (size_t i = 0; i < in.size(); ++i) { text[i] = static_cast<text_t>(in[i]); } ifs.close(); std::cout << "Read " << file_size << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads in a file to the specified data. * * @tparam text_t The type of text * @param file_name The file name * @param text[out] The read text */ template<typename text_t> void read_file_fill(const std::string& file_name, ui_vector<text_t>& text, const size_t prefix_size) { std::cout << "Reading file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); text.resize(prefix_size); char c; size_t index = 0; while (ifs.get(c) && index < prefix_size) { text[index++] = static_cast<text_t>((unsigned char)c); } ifs.close(); size_t idx = 0; while (index < prefix_size) { text[index++] = text[idx++]; } std::cout << "Read " << prefix_size << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads in a file to the specified data. * * @tparam text_t The type of text * @param file_name The file name * @param text[out] The read text */ template<typename text_t> void read_file(const std::string& file_name, ui_vector<text_t>& text, const size_t prefix_size = 0) { std::cout << "Reading file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); uint64_t file_size = ifs.tellg(); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } text.resize(file_size); char c; size_t index = 0; while (ifs.get(c) && index < file_size) { text[index++] = static_cast<text_t>((unsigned char)c); } ifs.close(); std::cout << "Read " << file_size << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads in a file to the specified data. * * @tparam text_t The type of text * @param file_name The file name * @param text[out] The read text */ template<typename text_t> void read_file_without_zeroes(const std::string& file_name, ui_vector<text_t>& text, const size_t prefix_size = 0) { std::cout << "Reading file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); uint64_t file_size = ifs.tellg(); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } text.resize(file_size); char c; size_t index = 0; size_t idx = 0; while (ifs.get(c) && index < file_size) { if (static_cast<text_t>((unsigned char)c) != 0) { text[idx++] = static_cast<text_t>((unsigned char)c); } index++; } ifs.close(); text.resize(idx); std::cout << "Read " << text.size() << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads a file to a string. * * @param file_name The file name * @param text[out] The read text */ void read_text_file(const std::string& file_name, std::string& text, const size_t prefix_size = 0) { std::cout << "Reading text file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); uint64_t file_size = ifs.tellg(); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } text.resize(file_size, '\0'); ifs.read((char*)text.data(), file_size); ifs.close(); std::cout << "Read " << file_size << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads a file to a string. * * @param file_name The file name * @param text[out] The read text */ void read_text_file_fill(const std::string& file_name, std::string& text, size_t prefix_size = 0) { std::cout << "Reading text file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); uint64_t file_size = ifs.tellg(); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } text.resize(prefix_size, '\0'); ifs.read((char*)text.data(), file_size); ifs.close(); size_t index = file_size; size_t idx = 0; while (index < prefix_size) { text[index++] = text[idx++]; } std::cout << "Read " << prefix_size << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Reads a file to a string. * * @param file_name The file name * @param text[out] The read text */ void read_text_file_without_zeroes(const std::string& file_name, std::string& text, const size_t prefix_size = 0) { std::cout << "Reading text file: " << file_name << std::endl; std::ifstream ifs(file_name.c_str(), std::ios::in | std::ios::binary | std::ios::ate); uint64_t file_size = ifs.tellg(); if (!ifs) { std::cerr << "Failed to read file " << file_name << std::endl; exit(1); } ifs.seekg(0, std::ios::beg); if (prefix_size > 0) { file_size = std::min(file_size, prefix_size); } text.resize(file_size, '\0'); ifs.read((char*)text.data(), file_size); ifs.close(); size_t j = 0; for (size_t i = 0; i < text.size(); ++i) { if (text[i] != 0) { text[j++] = text[i]; } } text.resize(j); text.shrink_to_fit(); std::cout << "Read " << text.size() << " bytes" << std::endl; std::cout << "Finished reading file" << std::endl; } /** * @brief Returns a string representation of the text. * * @tparam text_t The type of text * @param text The text * @return The string representation of the text */ template<typename text_t> std::string text_vector_to_string(const std::vector<text_t>& text) { std::stringstream text_stream; for (const auto& c : text) { text_stream << c << " "; } return text_stream.str(); } /** * @brief Returns a string representation an unordered map of blocks. * * @tparam block_t The type of blocks * @tparam variable_t The type of non-terminals * @param blocks The blocks * @return The string representation */ template<typename block_t, typename variable_t> std::string blocks_to_string(const std::unordered_map<block_t, variable_t, pair_hash>& blocks) { std::stringstream block_stream; for (const auto& block : blocks) { block_stream << "(" << block.first.first << ", " << block.first.second << ") "; } return block_stream.str(); } /** * @brief Returns a string representation a vector of blocks. * * @tparam block_t The type of blocks * @param blocks The blocks * @return The string representation */ template<typename block_t> std::string vector_blocks_to_string(const std::vector<block_t>& blocks) { std::stringstream stream; for (const auto& block : blocks) { stream << "(" << block.first << ", " << block.second << ") "; } return stream.str(); } /** * @brief Returns a string representation of the positions vector of blocks. * * @tparam position_t The type of block positions * @param positions A vector of block positions * @return The string representation */ template<typename position_t> std::string block_positions_to_string(const std::vector<position_t>& positions) { std::stringstream pos_stream; for (const auto& pos : positions) { pos_stream << pos.second << " "; } return pos_stream.str(); } /** * @brief Returns a string representation of the positions vector of pairs. * * @tparam pair_position_t The type of pair positions * @param positions A vector of pair positions * @return The string representation */ template<typename pair_position_t> std::string pair_positions_to_string(const std::vector<pair_position_t>& positions) { std::stringstream pos_stream; for (const auto& pos : positions) { pos_stream << pos << " "; } return pos_stream.str(); } /** * @brief Returns a string representation of a partition. * * @tparam partition_t The type of partition * @param partition The partition * @return The string representation */ template<typename partition_t> std::string partition_to_string(const partition_t& partition) { std::stringstream sstream; std::map<var_t, bool> part; for (const auto& par : partition) { part[par.first] = par.second; } for (const auto& par : part) { sstream << "(" << par.first << ": " << par.second << ") " << std::endl; } return sstream.str(); } /** * @brief Returns a string representation of a multiset. * * @tparam multiset_t The type of multiset * @param multiset The multiset * @return The string representation */ template<typename multiset_t> std::string multiset_to_string(const multiset_t& multiset) { std::stringstream sstream; for (const auto& tup : multiset) { sstream << "(" << std::get<0>(tup) << "," << std::get<1>(tup) << "," << std::get<2>(tup) << ") "; } return sstream.str(); } template<size_t n> std::string array_to_string(const std::array<size_t, n>& positions) { std::stringstream sstream; for (const auto& pos : positions) { sstream << pos << " "; } return sstream.str(); } /** * @brief Checks whether the elements in the given vector are sorted increasingly. * * @tparam vector_t The type of vector * @param vector The vector * @return @code{True} if the vector is sorted, otherwise @code{false} */ template<typename vector_t> bool is_sorted(std::vector<vector_t> vector) { for (size_t i = 1; i < vector.size(); ++i) { if (vector[i-1] > vector[i]) { return false; } } return true; } void replace_all(std::string& s, std::string replace, std::string replace_with) { size_t pos = s.find(replace); while(pos != std::string::npos) { s.replace(pos, replace.size(), replace_with); pos = s.find(replace, pos + replace_with.size()); } } void split(std::string s, std::string delimiter, std::vector<std::string>& split) { size_t pos = 0, end; size_t delim_len = delimiter.size(); while ((end = s.find(delimiter, pos)) != std::string::npos) { split.push_back(s.substr(pos, end - pos)); pos = end + delim_len; } split.push_back(s.substr(pos)); } void file_name_without_path(std::string& file_name) { size_t pos = file_name.find_last_of('/'); if (pos != std::string::npos) { file_name = file_name.substr(pos + 1); } } void file_name_without_extension(std::string& file_name) { size_t pos = file_name.find_last_of('.'); if (pos != std::string::npos) { file_name = file_name.substr(0, pos); } } int str_to_int(std::string s) { std::istringstream ss(s); int n; if (!(ss >> n)) { std::cerr << "Invalid number: " << s; return -1; } else if (!ss.eof()) { std::cerr << "Trailing characters after number: " << s; return -1; } return n; } void check_graph(std::string file_name) { std::ifstream in_file(file_name, std::ifstream::in | std::ios::binary | std::ifstream::ate); std::string part_str; in_file.seekg(0, std::ios::beg); std::unordered_map<int, std::unordered_map<int, int>> adj; std::getline(in_file, part_str); std::vector<std::string> split; util::split(part_str, " ", split); int nodes = str_to_int(split[0]); int edges = str_to_int(split[1]); int m = 0; int v = 0; bool weights; if (split.size() == 2) { weights = false; } else { if (!split[2].empty()) { weights = (util::str_to_int(split[2]) == 1); } else { weights = false; } } std::cout << "weights: " << weights << std::endl; while (std::getline(in_file, part_str)) { split.clear(); util::split(part_str, " ", split); // if (split.size() % 2 == 1) { // std::cout << split[split.size() - 2] << ", " << split[split.size() - 1] << std::endl; // } if (weights) { for (size_t i = 0; i < split.size() - 1; i += 2) { auto u = str_to_int(split[i]); auto wgt = str_to_int(split[i + 1]); adj[v][u - 1] = wgt; m++; } } else { for (size_t i = 0; i < split.size() - 1; ++i) { auto u = str_to_int(split[i]); adj[v][u - 1] = 1; m++; } } v++; } std::cout << "edges: " << m << " " << edges << std::endl; std::cout << "nodes: " << adj.size() << " " << nodes << std::endl; bool correct = true; for (const auto& ad : adj) { for (const auto& a : ad.second) { if (adj[a.first][ad.first] != a.second) { std::cout << ad.first << " " << a.first << " " << a.second << std::endl; std::cout << a.first << " " << ad.first << " " << adj[a.first][ad.first] << std::endl; std::cout << "Graph not correct" << std::endl; correct = false; } } } if (correct) { std::cout << "Graph is correct" << std::endl; } else { std::cout << "Graph is NOT correct" << std::endl; } in_file.close(); } template<typename T> inline ui_vector<T> create_ui_vector(std::vector<T> vec) { ui_vector<T> ui_vec(vec.size()); for (size_t i = 0; i < vec.size(); ++i) { ui_vec[i] = vec[i]; } return ui_vec; } inline std::string variants_options(std::vector<std::string>& variants) { std::stringstream stringstream; for (size_t i = 0; i < variants.size(); ++i) { stringstream << variants[i]; if (i < variants.size() - 1) { stringstream << " | "; } } return stringstream.str(); } inline constexpr uint8_t bits_for(size_t value) { return value == 0 ? (uint8_t)1 : 64 - __builtin_clzll(value); } } // namespace util } // namespace recomp
29.251318
116
0.590904
christopherosthues
acafd269bbe698f492c1a0b970cc266ef4d205d2
940
hpp
C++
terminalpp/include/terminalpp/detail/export.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
terminalpp/include/terminalpp/detail/export.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
terminalpp/include/terminalpp/detail/export.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
#ifndef TERMINALPP_EXPORT_H #define TERMINALPP_EXPORT_H #ifdef TERMINALPP_STATIC_DEFINE # define TERMINALPP_EXPORT # define TERMINALPP_NO_EXPORT #else # ifndef TERMINALPP_EXPORT # ifdef terminalpp_EXPORTS /* We are building this library */ # define TERMINALPP_EXPORT # else /* We are using this library */ # define TERMINALPP_EXPORT # endif # endif # ifndef TERMINALPP_NO_EXPORT # define TERMINALPP_NO_EXPORT # endif #endif #ifndef TERMINALPP_DEPRECATED # define TERMINALPP_DEPRECATED __attribute__ ((__deprecated__)) #endif #ifndef TERMINALPP_DEPRECATED_EXPORT # define TERMINALPP_DEPRECATED_EXPORT TERMINALPP_EXPORT TERMINALPP_DEPRECATED #endif #ifndef TERMINALPP_DEPRECATED_NO_EXPORT # define TERMINALPP_DEPRECATED_NO_EXPORT TERMINALPP_NO_EXPORT TERMINALPP_DEPRECATED #endif #define DEFINE_NO_DEPRECATED 0 #if DEFINE_NO_DEPRECATED # define TERMINALPP_NO_DEPRECATED #endif #endif
22.380952
84
0.798936
CalielOfSeptem
acc24b0e7060f555fae6265b12064bb4294690b3
246
cpp
C++
Divisibility_problem.cpp
shalini264/Coding-problem-solutions
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
4
2021-07-11T20:13:56.000Z
2022-02-19T17:22:42.000Z
Divisibility_problem.cpp
shalini264/long-challenge-solutions-in-my-way
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
null
null
null
Divisibility_problem.cpp
shalini264/long-challenge-solutions-in-my-way
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() {long long int T; cin>>T; while(T) {long long int a,b,x; cin>>a>>b; if(a>=b) {if(a%b==0) x=0; else {x=a%b; x=b-x;}} else x=b-a; cout<<x<<"\n"; T--;} return 0;}
12.3
23
0.5
shalini264
acc371d7edf19a498ee9d1a4ed4d79820e6a22e9
143
cpp
C++
yellow_belt/week_3/3_source_class_declaration/Solution/main.cpp
VladimirYugay/cpp_coursera
d4fc1322757f2ae84991266c408bca02266f1f2a
[ "Unlicense" ]
null
null
null
yellow_belt/week_3/3_source_class_declaration/Solution/main.cpp
VladimirYugay/cpp_coursera
d4fc1322757f2ae84991266c408bca02266f1f2a
[ "Unlicense" ]
null
null
null
yellow_belt/week_3/3_source_class_declaration/Solution/main.cpp
VladimirYugay/cpp_coursera
d4fc1322757f2ae84991266c408bca02266f1f2a
[ "Unlicense" ]
null
null
null
#include <iostream> #include "rectangle.h" using namespace std; int main(){ Rectangle r(0, 0); cout << r.GetArea(); return 0; }
11.916667
24
0.608392
VladimirYugay