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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e6b4de51daf9e7e954e640ecb6fc2b84cfb19e6f
| 1,317
|
cpp
|
C++
|
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
src/memory.cpp
|
habs1337/hack-lib
|
4bd4c7182eba5e738d6d1a87daa1d4b37dfae798
|
[
"MIT"
] | null | null | null |
#include "../includes/includes.h"
namespace g_mini_crt::memory {
wchar_t get_bits(char x) {
return g_mini_crt::string::is_digit(x) ? (x - '0') : ((x - 'A') + 0xA);
}
BYTE get_byts(const char* x) {
return ((BYTE)(get_bits(x[0]) << 4 | get_bits(x[1])));
}
int mem_cmp(const void* str1, const void* str2, size_t count) {
const unsigned char* s1 = reinterpret_cast<const unsigned char*> (str1);
const unsigned char* s2 = reinterpret_cast<const unsigned char*> (str2);
while (count-- > 0) {
if (*s1++ != *s2++)
return s1[-1] < s2[-1] ? -1 : 1;
}
return 0;
}
void* mem_cpy(void* dest, const void* src, size_t len) {
char* d = reinterpret_cast<char*>(dest);
const char* s = reinterpret_cast<const char*>(src);;
while (len--)
*d++ = *s++;
return dest;
}
void* mem_move(void* dest, const void* src, size_t len) {
char* d = reinterpret_cast<char*>(dest);
const char* s = reinterpret_cast<const char*>(src);
if (d < s)
while (len--)
*d++ = *s++;
else {
const char* lasts = s + (len - 1);
char* lastd = d + (len - 1);
while (len--)
*lastd-- = *lasts--;
}
return dest;
}
void* mem_set(void* dest, int val, size_t len) {
unsigned char* ptr = reinterpret_cast<unsigned char*>(dest);
while (len-- > 0)
*ptr++ = val;
return dest;
}
}
| 21.95
| 74
| 0.589977
|
habs1337
|
e6b96c963aaa6ff7916ac2f32554582f6b03240e
| 1,062
|
cpp
|
C++
|
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
cpp/tut/main.cpp
|
VeerabadraLokesh/miniature-guide
|
057e524ed8ffdac15cfaa9585800235234306225
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
// typedef int age;
int main() {
cout << "Hello world\n";
/* in comment */
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of long int : " << sizeof(long long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
typedef int age;
age my_age = 100;
cout << "my age: " << my_age << endl;
{
// enums
enum color { red, green, black=9, blue, gray } a, b; a = red; b = green;
color c = blue, d = black, e = gray;
cout << "color a: " << a << endl << "color b: " << b << endl << "color c: " << c << endl << "color d: " << d << endl << "color e: " << e << endl;
}
int a, b, c, d, e;
// return
return 0;
}
| 27.947368
| 153
| 0.496234
|
VeerabadraLokesh
|
e6b9929694ad270fa8eb8773d4405e37393a483b
| 307
|
cpp
|
C++
|
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP3/CPP3.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
#include "VTable.h"
// VTables
void test1::Simple::run() {}
void test2::Simple::run() {}
void test4::Sub::run() {}
void test5::Sub::run() {}
void test6::Sub::run() {}
void test11::Sub::run3() {}
template class test12::Simple<int>;
// Weak-Defined RTTI
__attribute__((visibility("hidden"))) test7::Sub a;
| 20.466667
| 51
| 0.651466
|
JunyiXie
|
e6c3773935366bf41cb30bfd9608e9495c028d0c
| 99
|
cc
|
C++
|
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
cpp/accelerated_c++/chapter08/my_max.cc
|
zhouzhiqi/book_and_code
|
3ffadd6cb721af280a00c1e1f97d509ab4b210ab
|
[
"Apache-2.0"
] | null | null | null |
template <class T>
T max(const T& left, const T& right)
{
return left > right ? left : right;
}
| 14.142857
| 36
| 0.636364
|
zhouzhiqi
|
e6c70fea1a7bfd84c3ff6fd041fb3ef65e4992a2
| 28,735
|
cpp
|
C++
|
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
csl/cslbase/arith12.cpp
|
arthurcnorman/general
|
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
|
[
"BSD-2-Clause"
] | null | null | null |
// arith12.cpp Copyright (C) 1990-2020 Codemist
//
// Arithmetic functions... specials for Reduce (esp. factoriser)
//
//
/**************************************************************************
* Copyright (C) 2020, Codemist. A C Norman *
* *
* 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 relevant *
* 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 OWNERS 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. *
*************************************************************************/
// $Id: arith12.cpp 5390 2020-09-03 20:57:57Z arthurcnorman $
#include "headers.h"
#define FP_EVALUATE 1
LispObject Lfrexp(LispObject env, LispObject a)
{
#ifdef HAVE_SOFTFLOAT
if (is_long_float(a))
{ float128_t d;
int x;
f128M_frexp(reinterpret_cast<float128_t *>(long_float_addr(a)), &d,
&x);
return cons(fixnum_of_int(x), make_boxfloat128(d));
}
else
#endif // HAVE_SOFTFLOAT
if (is_single_float(a))
{ int x;
float d = std::frexp(single_float_val(a), &x);
return cons(fixnum_of_int(x), pack_single_float(d));
}
else if (is_short_float(a))
{ int x;
// I can afford to do the frexp on a double here.
double d = std::frexp(value_of_immediate_float(a), &x);
return cons(fixnum_of_int(x), pack_short_float(d));
}
else
{ int x;
double d = std::frexp(float_of_number(a), &x);
// I clearly once encountered a C library that failed on this edge case!
if (d == 1.0) d = 0.5, x++;
return cons(fixnum_of_int(x),make_boxfloat(d));
}
}
// N.B. that the modular arithmetic functions must cope with any small
// modulus that could fit in a fixnum.
LispObject Lmodular_difference(LispObject env, LispObject a,
LispObject b)
{ intptr_t r;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-difference", a);
if (!is_fixnum(b)) return aerror1("modular-difference", b);
r = int_of_fixnum(a) - int_of_fixnum(b);
if (r < 0) r += current_modulus;
return onevalue(fixnum_of_int(r));
}
a = difference2(a, b);
return modulus(a, large_modulus);
}
LispObject Lmodular_minus(LispObject env, LispObject a)
{ if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-minus", a);
if (a != fixnum_of_int(0))
{ intptr_t r = current_modulus - int_of_fixnum(a);
a = fixnum_of_int(r);
}
return onevalue(a);
}
a = negate(a);
return modulus(a, large_modulus);
}
LispObject Lmodular_number(LispObject env, LispObject a)
{ intptr_t r;
if (!modulus_is_large)
{ a = Cremainder(a, fixnum_of_int(current_modulus));
r = int_of_fixnum(a);
if (r < 0) r += current_modulus;
return onevalue(fixnum_of_int(r));
}
return modulus(a, large_modulus);
}
LispObject Lmodular_plus(LispObject env, LispObject a, LispObject b)
{ intptr_t r;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-plus", a);
if (!is_fixnum(b)) return aerror1("modular-plus", b);
r = int_of_fixnum(a) + int_of_fixnum(b);
if (r >= current_modulus) r -= current_modulus;
return onevalue(fixnum_of_int(r));
}
a = plus2(a, b);
return modulus(a, large_modulus);
}
LispObject large_modular_reciprocal(LispObject n, bool safe)
{ LispObject a, b, x, y;
b = n;
x = fixnum_of_int(0);
y = fixnum_of_int(1);
if (b == fixnum_of_int(0))
{ if (safe) return onevalue(nil);
else return aerror1("modular-reciprocal", n);
}
b = modulus(b, large_modulus);
a = large_modulus;
while (b != fixnum_of_int(1))
{ LispObject w, t;
if (b == fixnum_of_int(0))
{ if (safe) return onevalue(nil);
else return aerror2("non-prime modulus in modular-reciprocal",
large_modulus, n);
}
push(x, y);
w = quot2(a, b);
pop(y, x);
t = b;
push(a, x, y, w, t);
b = times2(b, w);
pop(t, w, y, x, a);
push(x, y, w, t);
b = difference2(a, b);
pop(t, w, y, x);
a = t;
t = y;
push(a, b, x, t);
y = times2(y, w);
pop(t, x, b, a);
push(a, b, t);
y = difference2(x, y);
pop(t, b, a);
x = t;
}
y = modulus(y, large_modulus);
return onevalue(y);
}
LispObject Lmodular_reciprocal(LispObject, LispObject n)
{ intptr_t a, b, x, y;
if (modulus_is_large) return large_modular_reciprocal(n, false);
// If the modulus is "small" I can do all this using native integer
// arithmetic.
if (!is_fixnum(n)) return aerror1("modular-reciprocal", n);
a = current_modulus;
b = int_of_fixnum(n);
x = 0;
y = 1;
if (b == 0) return aerror1("modular-reciprocal", n);
if (b < 0) b = current_modulus - ((-b)%current_modulus);
while (b != 1)
{ intptr_t w, t;
if (b == 0)
return aerror2("non-prime modulus in modular-reciprocal",
fixnum_of_int(current_modulus), n);
w = a / b;
t = b;
b = a - b*w;
a = t;
t = y;
y = x - y*w;
x = t;
}
if (y < 0) y += current_modulus;
return onevalue(fixnum_of_int(y));
}
LispObject Lsafe_modular_reciprocal(LispObject env, LispObject n)
{ intptr_t a, b, x, y;
if (modulus_is_large) return large_modular_reciprocal(n, true);
if (!is_fixnum(n)) return aerror1("modular-reciprocal", n);
a = current_modulus;
b = int_of_fixnum(n);
x = 0;
y = 1;
if (b == 0) return onevalue(nil);
if (b < 0) b = current_modulus - ((-b)%current_modulus);
while (b != 1)
{ intptr_t w, t;
if (b == 0) return onevalue(nil);
w = a / b;
t = b;
b = a - b*w;
a = t;
t = y;
y = x - y*w;
x = t;
}
if (y < 0) y += current_modulus;
return onevalue(fixnum_of_int(y));
}
LispObject Lmodular_times(LispObject env, LispObject a, LispObject b)
{ uintptr_t cm;
intptr_t aa, bb;
if (!modulus_is_large)
{ if (!is_fixnum(a)) return aerror1("modular-times", a);
if (!is_fixnum(b)) return aerror1("modular-times", b);
cm = (uintptr_t)current_modulus;
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
// If I am on a 32-bit machine and the modulus is at worst 16 bits I can use
// 32-bit arithmetic to complete the job.
if (!SIXTY_FOUR_BIT && cm <= 0xffffU)
{ uint32_t r = ((uint32_t)aa * (uint32_t)bb) % (uint32_t)cm;
return onevalue(fixnum_of_int((intptr_t)r));
}
// On a 32 or 64-bit machine if the modulus is at worst 32 bits I can do
// a 64-bit (unsigned) multiplication and remainder step.
else if (cm <= 0xffffffffU)
{ uint64_t r = ((uint64_t)aa*(uint64_t)bb) % (uint64_t)cm;
// Because I am in a state where modulus_is_large is not set I know that the
// modulus fits in a fixnum, hence the result will. So even though all value
// that are of type uint64_t might not be valid as fixnums the one I have
// here will be.
return onevalue(fixnum_of_int((intptr_t)r));
}
// Now my modulus is over 32-bits...
// Using an int128_t bit type I can use it and the code is really neat!
// On some platforms this goes via C++ templates and operator overloading
// into a software implementation of 128-bit integer arithmetic!
else
{ int64_t r = static_cast<int64_t>(
(static_cast<int128_t>(aa) * static_cast<int128_t>(bb)) %
static_cast<int128_t>(cm));
return onevalue(fixnum_of_int((intptr_t)r));
}
}
a = times2(a, b);
return modulus(a, large_modulus);
}
LispObject Lmodular_quotient(LispObject env, LispObject a,
LispObject b)
{ push(a);
b = Lmodular_reciprocal(nil, b);
pop(a);
return Lmodular_times(nil, a, b);
}
LispObject large_modular_expt(LispObject a, int x)
{ LispObject r, p, w;
p = modulus(a, large_modulus);
while ((x & 1) == 0)
{ p = times2(p, p);
p = modulus(p, large_modulus);
x = x/2;
}
r = p;
while (x != 1)
{ push(r);
w = times2(p, p);
pop(r);
push(r);
p = modulus(w, large_modulus);
pop(r);
x = x/2;
if ((x & 1) != 0)
{ push(p);
w = times2(r, p);
pop(p);
push(p);
r = modulus(w, large_modulus);
pop(p);
}
}
return onevalue(r);
}
inline intptr_t muldivptr(uintptr_t a, uintptr_t b, uintptr_t c)
{ if (!SIXTY_FOUR_BIT || c <= 0xffffffffU)
return ((uint64_t)a*(uint64_t)b)%(uintptr_t)c;
else return (intptr_t)static_cast<int64_t>(
(uint128((uint64_t)a) * uint128((uint64_t)a)) % (uintptr_t)c);
}
LispObject Lmodular_expt(LispObject env, LispObject a, LispObject b)
{ intptr_t x, r, p;
x = int_of_fixnum(b);
if (x == 0) return onevalue(fixnum_of_int(1));
if (modulus_is_large) return large_modular_expt(a, x);
p = int_of_fixnum(a);
p = p % current_modulus; // In case somebody is being silly!
// I now want this to work for any modulus up to the size of the largest
// fixnum. That could be 60-bits in the newer world. The function
// muldivptr takes unsigned arguments but that should be OK because any
// valid modulus and any valid modular number will be positive.
while ((x & 1) == 0)
{ p = muldivptr((uintptr_t)p, (uintptr_t)p,
(uintptr_t)current_modulus);
x = x/2;
}
r = p;
while (x != 1)
{ p = muldivptr((uintptr_t)p, (uintptr_t)p,
(uintptr_t)current_modulus);
x = x/2;
if ((x & 1) != 0)
{ r = muldivptr((uintptr_t)r, (uintptr_t)p,
(uintptr_t)current_modulus);
}
}
return onevalue(fixnum_of_int(r));
}
// I can set any (positive) integer as a modulus here. I will treat it
// internally as "small" if it fits in a fixnum.
LispObject Lset_small_modulus(LispObject env, LispObject a)
{ LispObject old = modulus_is_large ? large_modulus :
fixnum_of_int(current_modulus);
if (a==nil) return onevalue(old);
else if (!is_fixnum(a))
{ if (!is_numbers(a) ||
!is_bignum(a) ||
minusp(a))
return aerror1("set-small-modulus", a);
modulus_is_large = 1;
current_modulus = 0; // should not be referenced.
large_modulus = a;
return old;
}
if ((intptr_t)a < 0 || a == fixnum_of_int(0))
return aerror1("set!-small!-modulus", a);
modulus_is_large = 0;
large_modulus = nil; // Should not be referenced.
current_modulus = int_of_fixnum(a);;
return onevalue(old);
}
LispObject Liadd1(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("iadd1", a);
return onevalue(static_cast<LispObject>((intptr_t)a + 0x10));
}
LispObject Lidifference_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("idifference", a, b);
return onevalue(static_cast<LispObject>((intptr_t)a -
(intptr_t)b + TAG_FIXNUM));
}
//
// xdifference is provided just for the support of the CASE operator. It
// subtracts its arguments but returns NIL if either argument is not
// an small integer or if the result overflows. Small is 28-bits in this
// context at present, which is maybe strange!
//
LispObject Lxdifference(LispObject env, LispObject a, LispObject b)
{ int32_t r;
if (!is_fixnum(a) || !is_fixnum(b)) return onevalue(nil);
r = int_of_fixnum(a) - int_of_fixnum(b);
if (r < -0x08000000 || r > 0x07ffffff) return onevalue(nil);
return onevalue(fixnum_of_int(r));
}
LispObject Ligreaterp_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("igreaterp", a, b);
return onevalue(Lispify_predicate(a > b));
}
LispObject Lilessp_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("ilessp", a, b);
return onevalue(Lispify_predicate(a < b));
}
LispObject Ligeq_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("igeq", a, b);
return onevalue(Lispify_predicate(a >= b));
}
LispObject Lileq_2(LispObject env, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("ileq", a, b);
return onevalue(Lispify_predicate(a <= b));
}
static LispObject Lilogand_0(LispObject)
{ return onevalue(fixnum_of_int(-1));
}
static LispObject Lilogor_0(LispObject)
{ return onevalue(fixnum_of_int(0));
}
static LispObject Lilogxor_0(LispObject)
{ return onevalue(fixnum_of_int(0));
}
static LispObject Lilogand_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogor_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogxor_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
static LispObject Lilogand_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogand", a1, a2);
return onevalue(a1 & a2);
}
static LispObject Lilogor_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogor", a1, a2);
return onevalue(a1 | a2);
}
static LispObject Lilogxor_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("ilogxor", a1, a2);
return onevalue((a1 ^ a2) + TAG_FIXNUM);
}
static LispObject Lilogand_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogand", a2, a2, a3);
return onevalue(a1 & a2 & a3);
}
static LispObject Lilogor_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogor", a2, a2, a3);
return onevalue(a1 | a2 | a3);
}
static LispObject Lilogxor_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogxor", a2, a2, a3);
return onevalue(a1 ^ a2 ^ a3);
}
static LispObject Lilogand_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogand", a2, a2, a3);
a1 = a1 & a2 & a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogand", a2);
a1 = a1 & a2;
}
return onevalue(a1);
}
static LispObject Lilogor_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogor", a2, a2, a3);
a1 = a1 | a2 | a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogor", a2);
a1 = a1 | a2;
}
return onevalue(a1);
}
static LispObject Lilogxor_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("ilogxor", a2, a2, a3);
a1 = a1 ^ a2 ^ a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("ilogxor", a2);
a1 = a1 ^ a2;
}
a1 = (a1 & ~static_cast<LispObject>(TAG_BITS)) | TAG_FIXNUM;
return onevalue(a1);
}
LispObject Limin_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("imin", a, b);
return onevalue(a < b ? a : b);
}
LispObject Limax_2(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("imax", a, b);
return onevalue(a > b ? a : b);
}
LispObject Liminus(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("iminus", a);
return onevalue(static_cast<LispObject>(2*TAG_FIXNUM - (intptr_t)a));
}
LispObject Liminusp(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a <
(intptr_t)fixnum_of_int(0)));
}
LispObject Liplus_0(LispObject)
{ return onevalue(fixnum_of_int(1));
}
LispObject Liplus_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
LispObject Liplus_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("iplus2", a1, a2);
return onevalue(static_cast<LispObject>((intptr_t)a1 +
(intptr_t)a2 - TAG_FIXNUM));
}
LispObject Liplus_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
return onevalue(static_cast<LispObject>((intptr_t)a1 +
(intptr_t)a2 - 2*TAG_FIXNUM +
(intptr_t)a3));
}
static LispObject Liplus_4up(LispObject, LispObject a1, LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
a1 = (intptr_t)a1 + (intptr_t)a2 - 2*TAG_FIXNUM + (intptr_t)a3;
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("iplus", a2);
a1 = a1 + (intptr_t)a2 - TAG_FIXNUM;
}
return onevalue(a1);
}
LispObject Liquotient_2(LispObject, LispObject a, LispObject b)
{ intptr_t aa, bb, c;
if (!is_fixnum(a) || !is_fixnum(b) ||
b == fixnum_of_int(0)) return aerror2("iquotient", a, b);
// C does not define the exact behaviour of /, % on -ve args
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
c = aa % bb;
if (aa < 0)
{ if (c > 0) c -= bb;
}
else if (c < 0) c += bb;
return onevalue(fixnum_of_int((aa-c)/bb));
}
LispObject Liremainder_2(LispObject, LispObject a, LispObject b)
{ intptr_t aa, bb, c;
if (!is_fixnum(a) || !is_fixnum(b) ||
b == fixnum_of_int(0)) return aerror2("iremainder", a, b);
// C does not define the exact behaviour of /, % on -ve args
aa = int_of_fixnum(a);
bb = int_of_fixnum(b);
c = aa % bb;
if (aa < 0)
{ if (c > 0) c -= bb;
}
else if (c < 0) c += bb;
return onevalue(fixnum_of_int(c));
}
LispObject Lirightshift(LispObject, LispObject a, LispObject b)
{ if (!is_fixnum(a) || !is_fixnum(b)) return aerror2("irightshift", a, b);
return onevalue(fixnum_of_int(int_of_fixnum(a) >> int_of_fixnum(b)));
}
LispObject Lisub1(LispObject, LispObject a)
{ if (!is_fixnum(a)) return aerror1("isub1", a);
return onevalue(static_cast<LispObject>((intptr_t)a - 0x10));
}
LispObject Litimes_0(LispObject)
{ return onevalue(fixnum_of_int(1));
}
LispObject Litimes_1(LispObject, LispObject a1)
{ return onevalue(a1);
}
LispObject Litimes_2(LispObject, LispObject a1, LispObject a2)
{ if (!is_fixnum(a1) || !is_fixnum(a2)) return aerror2("itimes2", a1, a2);
return onevalue(fixnum_of_int(int_of_fixnum(a1) * int_of_fixnum(a2)));
}
LispObject Litimes_3(LispObject, LispObject a1, LispObject a2,
LispObject a3)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("itimes", a1, a2, a3);
return onevalue(fixnum_of_int(int_of_fixnum(a1) *
int_of_fixnum(a2) *
int_of_fixnum(a3)));
}
static LispObject Litimes_4up(LispObject env, LispObject a1,
LispObject a2,
LispObject a3, LispObject a4up)
{ if (!is_fixnum(a1) || !is_fixnum(a2) || !is_fixnum(a3))
return aerror3("iplus", a1, a2, a3);
intptr_t r = int_of_fixnum(a1) * int_of_fixnum(a2) * int_of_fixnum(
a3);
while (a4up != nil)
{ a2 = car(a4up);
a4up = cdr(a4up);
if (!is_fixnum(a2)) return aerror1("itimes", a2);
r = r * int_of_fixnum(a2);
}
return onevalue(fixnum_of_int(r));
}
LispObject Lionep(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a ==
(intptr_t)fixnum_of_int(1)));
}
LispObject Lizerop(LispObject env, LispObject a)
{ return onevalue(Lispify_predicate((intptr_t)a ==
(intptr_t)fixnum_of_int(0)));
}
#ifdef FP_EVALUATE
static double fp_args[32];
static double fp_stack[16];
// codes 0 to 31 just load up arguments
#define FP_RETURN 32
#define FP_PLUS 33
#define FP_DIFFERENCE 34
#define FP_TIMES 35
#define FP_QUOTIENT 36
#define FP_MINUS 37
#define FP_SQUARE 38
#define FP_CUBE 39
#define FP_SIN 40
#define FP_COS 41
#define FP_TAN 42
#define FP_EXP 43
#define FP_LOG 44
#define FP_SQRT 45
static LispObject Lfp_eval(LispObject env, LispObject code,
LispObject args)
//
// The object of this code is to support fast evaluation of numeric
// expressions. The first argument is a vector of byte opcodes, while
// the second arg is a list of floating point values whose value will (or
// at least may) be used. There are at most 32 values in this list.
//
{ int n = 0;
double w;
unsigned char *p;
if (!is_vector(code)) return aerror("fp-evaluate");
while (consp(args))
{ fp_args[n++] = float_of_number(car(args));
args = cdr(args);
}
n = 0;
p = reinterpret_cast<unsigned char *>(&ucelt(code, 0));
for (;;)
{ int op = *p++;
//
// Opcodes 0 to 31 just load up the corresponding input value.
//
if (op < 32)
{ fp_stack[n++] = fp_args[op];
continue;
}
switch (op)
{ default:
return aerror("Bad op in fp-evaluate");
case FP_RETURN:
args = make_boxfloat(fp_stack[0], TYPE_DOUBLE_FLOAT);
return onevalue(args);
case FP_PLUS:
n--;
fp_stack[n] += fp_stack[n-1];
continue;
case FP_DIFFERENCE:
n--;
fp_stack[n] -= fp_stack[n-1];
continue;
case FP_TIMES:
n--;
fp_stack[n] *= fp_stack[n-1];
continue;
case FP_QUOTIENT:
n--;
fp_stack[n] /= fp_stack[n-1];
continue;
case FP_MINUS:
fp_stack[n] = -fp_stack[n];
continue;
case FP_SQUARE:
fp_stack[n] *= fp_stack[n];
continue;
case FP_CUBE:
w = fp_stack[n];
w *= w;
fp_stack[n] *= w;
continue;
case FP_SIN:
fp_stack[n] = std::sin(fp_stack[n]);
continue;
case FP_COS:
fp_stack[n] = std::cos(fp_stack[n]);
continue;
case FP_TAN:
fp_stack[n] = std::tan(fp_stack[n]);
continue;
case FP_EXP:
fp_stack[n] = std::exp(fp_stack[n]);
continue;
case FP_LOG:
fp_stack[n] = std::log(fp_stack[n]);
continue;
case FP_SQRT:
fp_stack[n] = std::sqrt(fp_stack[n]);
continue;
}
}
}
#endif
setup_type const arith12_setup[] =
{ {"frexp", G0W1, Lfrexp, G2W1, G3W1, G4W1},
{"modular-difference", G0W2, G1W2, Lmodular_difference, G3W2, G4W2},
{"modular-minus", G0W1, Lmodular_minus, G2W1, G3W1, G4W1},
{"modular-number", G0W1, Lmodular_number, G2W1, G3W1, G4W1},
{"modular-plus", G0W2, G1W2, Lmodular_plus, G3W2, G4W2},
{"modular-quotient", G0W2, G1W2, Lmodular_quotient, G3W2, G4W2},
{"modular-reciprocal", G0W1, Lmodular_reciprocal, G2W1, G3W1, G4W1},
{"safe-modular-reciprocal", G0W1, Lsafe_modular_reciprocal, G2W1, G3W1, G4W1},
{"modular-times", G0W2, G1W2, Lmodular_times, G3W2, G4W2},
{"modular-expt", G0W2, G1W2, Lmodular_expt, G3W2, G4W2},
{"set-small-modulus", G0W1, Lset_small_modulus, G2W1, G3W1, G4W1},
{"iadd1", G0W1, Liadd1, G2W1, G3W1, G4W1},
{"idifference", G0W2, G1W2, Lidifference_2, G3W2, G4W2},
{"xdifference", G0W2, G1W2, Lxdifference, G3W2, G4W2},
{"igeq", G0W2, G1W2, Ligeq_2, G3W2, G4W2},
{"igreaterp", G0W2, G1W2, Ligreaterp_2, G3W2, G4W2},
{"ileq", G0W2, G1W2, Lileq_2, G3W2, G4W2},
{"ilessp", G0W2, G1W2, Lilessp_2, G3W2, G4W2},
{"ilogand", Lilogand_0, Lilogand_1, Lilogand_2, Lilogand_3, Lilogand_4up},
{"ilogor", Lilogor_0, Lilogor_1, Lilogor_2, Lilogor_3, Lilogor_4up},
{"ilogxor", Lilogxor_0, Lilogxor_1, Lilogxor_2, Lilogxor_3, Lilogxor_4up},
{"imax", G0W2, G1W2, Limax_2, G3W2, G4W2},
{"imin", G0W2, G1W2, Limin_2, G3W2, G4W2},
{"iminus", G0W1, Liminus, G2W1, G3W1, G4W1},
{"iminusp", G0W1, Liminusp, G2W1, G3W1, G4W1},
{"iplus", Liplus_0, Liplus_1, Liplus_2, Liplus_3, Liplus_4up},
{"iplus2", G0W2, G1W2, Liplus_2, G3W2, G4W2},
{"iquotient", G0W2, G1W2, Liquotient_2, G3W2, G4W2},
{"iremainder", G0W2, G1W2, Liremainder_2, G3W2, G4W2},
{"irightshift", G0W2, G1W2, Lirightshift, G3W2, G4W2},
{"isub1", G0W1, Lisub1, G2W1, G3W1, G4W1},
{"itimes", Litimes_0, Litimes_1, Litimes_2, Litimes_3, Litimes_4up},
{"itimes2", G0W2, G1W2, Litimes_2, G3W2, G4W2},
{"ionep", G0W1, Lionep, G2W1, G3W1, G4W1},
{"izerop", G0W1, Lizerop, G2W1, G3W1, G4W1},
#ifdef FP_EVALUATE
{"fp-evaluate", G0W2, G1W2, Lfp_eval, G3W2, G4W2},
#endif
{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}
};
// end of arith12.cpp
| 35.344403
| 94
| 0.569549
|
arthurcnorman
|
e6ce22d78d8edf8283a150c8442b93af4b801a54
| 28,405
|
cpp
|
C++
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 20
|
2016-08-11T19:51:13.000Z
|
2021-09-02T13:10:58.000Z
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 9
|
2016-08-11T11:59:24.000Z
|
2021-07-16T09:44:28.000Z
|
reve/reve/lib/Assignment.cpp
|
mattulbrich/llreve
|
68cb958c1c02177fa0db1965a8afd879a97c2fc4
|
[
"BSD-3-Clause"
] | 7
|
2017-08-19T14:42:27.000Z
|
2020-05-20T16:14:13.000Z
|
/*
* This file is part of
* llreve - Automatic regression verification for LLVM programs
*
* Copyright (C) 2016 Karlsruhe Institute of Technology
*
* The system is published under a BSD license.
* See LICENSE (distributed with this file) for details.
*/
#include "Assignment.h"
#include "Helper.h"
#include "Opts.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
using llvm::CmpInst;
using llvm::Instruction;
using std::make_unique;
using std::string;
using std::unique_ptr;
using std::vector;
using namespace smt;
using namespace llreve::opts;
/// Convert a basic block to a list of assignments
vector<DefOrCallInfo> blockAssignments(const llvm::BasicBlock &BB,
const llvm::BasicBlock *prevBb,
bool onlyPhis, Program prog) {
const int progIndex = programIndex(prog);
vector<DefOrCallInfo> definitions;
definitions.reserve(BB.size());
assert(BB.size() >= 1); // There should be at least a terminator instruction
bool ignorePhis = prevBb == nullptr;
AssignmentVec phiAssgns;
for (auto instr = BB.begin(), e = std::prev(BB.end(), 1); instr != e;
++instr) {
// Ignore phi nodes if we are in a loop as they're bound in a
// forall quantifier
if (!ignorePhis && llvm::isa<llvm::PHINode>(instr)) {
auto assignments = instrAssignment(*instr, prevBb, prog);
for (auto &assignment : assignments) {
phiAssgns.insert(phiAssgns.end(), assignment->assgns.begin(),
assignment->assgns.end());
}
}
if (!llvm::isa<llvm::PHINode>(instr)) {
definitions.emplace_back(
std::make_unique<AssignmentGroup>(std::move(phiAssgns)));
phiAssgns.clear();
}
if (!onlyPhis && !llvm::isa<llvm::PHINode>(instr)) {
if (const auto CallInst = llvm::dyn_cast<llvm::CallInst>(instr)) {
const auto fun = CallInst->getCalledFunction();
if (!fun) {
logErrorData("Call to undeclared function\n", *CallInst);
exit(1);
}
if (fun->getIntrinsicID() == llvm::Intrinsic::memcpy) {
vector<DefOrCallInfo> defs =
memcpyIntrinsic(CallInst, prog);
for (auto &def : defs) {
definitions.emplace_back(std::move(def));
}
} else {
if (SMTGenerationOpts::getInstance().Heap ==
HeapOpt::Enabled) {
definitions.emplace_back(makeAssignment(
heapName(progIndex),
memoryVariable(heapName(progIndex))));
}
definitions.emplace_back(
toCallInfo(CallInst->getName(), prog, *CallInst));
if (SMTGenerationOpts::getInstance().Heap ==
HeapOpt::Enabled) {
definitions.emplace_back(makeAssignment(
heapName(progIndex),
memoryVariable(heapResultName(prog))));
}
if (SMTGenerationOpts::getInstance().Stack ==
StackOpt::Enabled) {
definitions.emplace_back(makeAssignment(
stackName(progIndex),
memoryVariable(stackResultName(prog))));
}
}
} else {
auto assignments = instrAssignment(*instr, prevBb, prog);
for (auto &assignment : assignments) {
definitions.push_back(std::move(assignment));
}
}
}
}
if (!phiAssgns.empty()) {
definitions.emplace_back(
std::make_unique<AssignmentGroup>(std::move(phiAssgns)));
}
if (const auto retInst =
llvm::dyn_cast<llvm::ReturnInst>(BB.getTerminator())) {
// TODO (moritz): use a more clever approach for void functions
unique_ptr<SMTExpr> retName =
std::make_unique<ConstantInt>(llvm::APInt(64, 0));
if (retInst->getReturnValue() != nullptr) {
retName =
instrNameOrVal(retInst->getReturnValue(), retInst->getType());
}
definitions.push_back(DefOrCallInfo(
makeAssignment(resultName(prog), std::move(retName))));
if (SMTGenerationOpts::getInstance().Heap == HeapOpt::Enabled) {
definitions.push_back(DefOrCallInfo(makeAssignment(
heapResultName(prog), memoryVariable(heapName(progIndex)))));
}
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
definitions.push_back(DefOrCallInfo(makeAssignment(
stackResultName(prog), memoryVariable(stackName(progIndex)))));
}
}
return definitions;
}
/// Convert a single instruction to an assignment
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1>
instrAssignment(const llvm::Instruction &Instr, const llvm::BasicBlock *prevBb,
Program prog) {
const int progIndex = programIndex(prog);
if (const auto BinOp = llvm::dyn_cast<llvm::BinaryOperator>(&Instr)) {
if (BinOp->getType()->isFloatingPointTy()) {
auto op = std::make_unique<BinaryFPOperator>(
binaryFPOpcode(BinOp->getOpcode()), llvmType(BinOp->getType()),
instrNameOrVal(BinOp->getOperand(0)),
instrNameOrVal(BinOp->getOperand(1)));
return vecSingleton(
makeAssignment(BinOp->getName(), std::move(op)));
}
if (SMTGenerationOpts::getInstance().ByteHeap ==
ByteHeapOpt::Disabled &&
BinOp->getOpcode() == Instruction::SDiv) {
// This is a heuristic to remove divisions by 4 of pointer
// subtractions
// Since we treat every int as a single value, we expect the
// division to return the number of elements and not the number
// of
// bytes
if (const auto instr =
llvm::dyn_cast<llvm::Instruction>(BinOp->getOperand(0))) {
if (const auto ConstInt = llvm::dyn_cast<llvm::ConstantInt>(
BinOp->getOperand(1))) {
if (ConstInt->getSExtValue() == 4 && isPtrDiff(*instr)) {
return vecSingleton(makeAssignment(
BinOp->getName(),
instrNameOrVal(BinOp->getOperand(0))));
} else {
logWarning("Division of pointer difference by " +
std::to_string(ConstInt->getSExtValue()) +
"\n");
}
}
}
}
if (!SMTGenerationOpts::getInstance().BitVect &&
(BinOp->getOpcode() == Instruction::Or ||
BinOp->getOpcode() == Instruction::And ||
BinOp->getOpcode() == Instruction::Xor)) {
if (!(BinOp->getOperand(0)->getType()->isIntegerTy(1) &&
BinOp->getOperand(1)->getType()->isIntegerTy(1))) {
logWarningData(
"Bitwise operators of bitwidth > 1 is not supported\n",
*BinOp);
}
}
return vecSingleton(makeAssignment(
BinOp->getName(), combineOp(*BinOp, opName(*BinOp),
instrNameOrVal(BinOp->getOperand(0)),
instrNameOrVal(BinOp->getOperand(1)))));
}
if (const auto cmpInst = llvm::dyn_cast<llvm::CmpInst>(&Instr)) {
SMTRef cmp = makeOp(
predicateName(cmpInst->getPredicate()),
predicateFun(*cmpInst, instrNameOrVal(cmpInst->getOperand(0))),
predicateFun(*cmpInst, instrNameOrVal(cmpInst->getOperand(1))));
return vecSingleton(makeAssignment(cmpInst->getName(), std::move(cmp)));
}
if (const auto phiInst = llvm::dyn_cast<llvm::PHINode>(&Instr)) {
const auto val = phiInst->getIncomingValueForBlock(prevBb);
assert(val);
auto assgn = makeAssignment(phiInst->getName(), instrNameOrVal(val));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
phiInst->getType()->isPointerTy()) {
auto locAssgn = makeAssignment(
string(phiInst->getName()) + "_OnStack", instrLocation(val));
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(std::move(locAssgn));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto selectInst = llvm::dyn_cast<llvm::SelectInst>(&Instr)) {
const auto cond = selectInst->getCondition();
const auto trueVal = selectInst->getTrueValue();
const auto falseVal = selectInst->getFalseValue();
const vector<SharedSMTRef> args = {instrNameOrVal(cond),
instrNameOrVal(trueVal),
instrNameOrVal(falseVal)};
auto assgn = makeAssignment(selectInst->getName(),
std::make_unique<Op>("ite", args));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
trueVal->getType()->isPointerTy()) {
assert(falseVal->getType()->isPointerTy());
auto location =
makeOp("ite", instrNameOrVal(cond), instrLocation(trueVal),
instrLocation(falseVal));
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(
makeAssignment(string(selectInst->getName()) + "_OnStack",
std::move(location)));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto ptrToIntInst = llvm::dyn_cast<llvm::PtrToIntInst>(&Instr)) {
return vecSingleton(
makeAssignment(ptrToIntInst->getName(),
instrNameOrVal(ptrToIntInst->getPointerOperand(),
ptrToIntInst->getType())));
}
if (const auto getElementPtrInst =
llvm::dyn_cast<llvm::GetElementPtrInst>(&Instr)) {
auto assgn = makeAssignment(getElementPtrInst->getName(),
resolveGEP(*getElementPtrInst));
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(std::move(assgn));
result.push_back(makeAssignment(
string(getElementPtrInst->getName()) + "_OnStack",
instrLocation(getElementPtrInst->getPointerOperand())));
return result;
} else {
return vecSingleton(std::move(assgn));
}
}
if (const auto loadInst = llvm::dyn_cast<llvm::LoadInst>(&Instr)) {
SharedSMTRef pointer = instrNameOrVal(loadInst->getOperand(0));
if (SMTGenerationOpts::getInstance().BitVect) {
// We load single bytes
unsigned bytes = loadInst->getType()->getIntegerBitWidth() / 8;
auto load =
makeOp("select", memoryVariable(heapName(progIndex)), pointer);
for (unsigned i = 1; i < bytes; ++i) {
load =
makeOp("concat", std::move(load),
makeOp("select", memoryVariable(heapName(progIndex)),
makeOp("bvadd", pointer,
std::make_unique<ConstantInt>(
llvm::APInt(64, i)))));
}
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
} else {
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
SMTRef load =
makeOp("select_", memoryVariable(heapName(progIndex)),
memoryVariable(stackName(progIndex)), pointer,
instrLocation(loadInst->getPointerOperand()));
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
} else {
SMTRef load = makeOp(
"select", memoryVariable(heapName(progIndex)), pointer);
return vecSingleton(
makeAssignment(loadInst->getName(), std::move(load)));
}
}
}
if (const auto storeInst = llvm::dyn_cast<llvm::StoreInst>(&Instr)) {
string heap = heapName(progIndex);
SharedSMTRef pointer = instrNameOrVal(storeInst->getPointerOperand());
SharedSMTRef val = instrNameOrVal(storeInst->getValueOperand());
if (SMTGenerationOpts::getInstance().BitVect) {
int bytes =
storeInst->getValueOperand()->getType()->getIntegerBitWidth() /
8;
auto newHeap = memoryVariable(heap);
for (int i = 0; i < bytes; ++i) {
SharedSMTRef offset =
makeOp("bvadd", pointer,
std::make_unique<ConstantInt>(llvm::APInt(64, i)));
SharedSMTRef elem = makeOp(
"(_ extract " + std::to_string(8 * (bytes - i - 1) + 7) +
" " + std::to_string(8 * (bytes - i - 1)) + ")",
val);
std::vector<SharedSMTRef> args = {std::move(newHeap), offset,
elem};
newHeap = make_unique<Op>("store", std::move(args));
}
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(newHeap)));
} else {
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled) {
const std::vector<SharedSMTRef> args = {
memoryVariable(heap), memoryVariable(stackName(progIndex)),
pointer, instrLocation(storeInst->getPointerOperand()),
val};
auto store = make_unique<Op>("store_", args);
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(store)));
} else {
const std::vector<SharedSMTRef> args = {memoryVariable(heap),
pointer, val};
auto store = make_unique<Op>("store", args);
return vecSingleton(
makeAssignment(heapName(progIndex), std::move(store)));
}
}
}
if (const auto bitCast = llvm::dyn_cast<llvm::CastInst>(&Instr)) {
auto cast = std::make_unique<TypeCast>(
bitCast->getOpcode(), llvmType(bitCast->getSrcTy()),
llvmType(bitCast->getDestTy()),
instrNameOrVal(bitCast->getOperand(0)));
return vecSingleton(
makeAssignment(bitCast->getName(), std::move(cast)));
}
if (const auto allocaInst = llvm::dyn_cast<llvm::AllocaInst>(&Instr)) {
unsigned allocatedSize =
typeSize(allocaInst->getAllocatedType(),
allocaInst->getModule()->getDataLayout());
std::string sp = stackPointerName(progIndex);
llvm::SmallVector<unique_ptr<AssignmentGroup>, 1> result;
result.push_back(
makeAssignment(sp, makeOp("-", sp,
std::make_unique<ConstantInt>(
llvm::APInt(64, allocatedSize)))));
result.push_back(
makeAssignment(allocaInst->getName(),
make_unique<TypedVariable>(sp, pointerType())));
result.push_back(
makeAssignment(string(allocaInst->getName()) + "_OnStack",
make_unique<ConstantBool>(true)));
return result;
}
if (const auto fcmpInst = llvm::dyn_cast<llvm::FCmpInst>(&Instr)) {
auto cmp = std::make_unique<FPCmp>(
fpPredicate(fcmpInst->getPredicate()),
llvmType(fcmpInst->getOperand(0)->getType()),
instrNameOrVal(fcmpInst->getOperand(0)),
instrNameOrVal(fcmpInst->getOperand(1)));
return vecSingleton(
makeAssignment(fcmpInst->getName(), std::move(cmp)));
}
logErrorData("Couldn’t convert instruction to def\n", Instr);
return vecSingleton(
makeAssignment("UNKNOWN INSTRUCTION", stringExpr("UNKNOWN ARGS")));
}
/// Convert an LLVM predicate to an SMT predicate
string predicateName(llvm::CmpInst::Predicate pred) {
if (SMTGenerationOpts::getInstance().BitVect) {
switch (pred) {
case CmpInst::ICMP_SLT:
return "bvslt";
case CmpInst::ICMP_ULT:
return "bvult";
case CmpInst::ICMP_SLE:
return "bvsle";
case CmpInst::ICMP_ULE:
return "bvule";
case CmpInst::ICMP_EQ:
return "=";
case CmpInst::ICMP_SGE:
return "bvsge";
case CmpInst::ICMP_UGE:
return "bvuge";
case CmpInst::ICMP_SGT:
return "bvsgt";
case CmpInst::ICMP_UGT:
return "bvugt";
case CmpInst::ICMP_NE:
return "distinct";
default:
return "unsupported predicate";
}
} else {
switch (pred) {
case CmpInst::ICMP_SLT:
case CmpInst::ICMP_ULT:
return "<";
case CmpInst::ICMP_SLE:
case CmpInst::ICMP_ULE:
return "<=";
case CmpInst::ICMP_EQ:
return "=";
case CmpInst::ICMP_SGE:
case CmpInst::ICMP_UGE:
return ">=";
case CmpInst::ICMP_SGT:
case CmpInst::ICMP_UGT:
return ">";
case CmpInst::ICMP_NE:
return "distinct";
default:
return "unsupported predicate";
}
}
}
FPCmp::Predicate fpPredicate(llvm::CmpInst::Predicate pred) {
switch (pred) {
case CmpInst::FCMP_FALSE:
return FPCmp::Predicate::False;
case CmpInst::FCMP_OEQ:
return FPCmp::Predicate::OEQ;
case CmpInst::FCMP_OGT:
return FPCmp::Predicate::OGT;
case CmpInst::FCMP_OGE:
return FPCmp::Predicate::OGE;
case CmpInst::FCMP_OLT:
return FPCmp::Predicate::OLT;
case CmpInst::FCMP_OLE:
return FPCmp::Predicate::OLE;
case CmpInst::FCMP_ONE:
return FPCmp::Predicate::ONE;
case CmpInst::FCMP_ORD:
return FPCmp::Predicate::ORD;
case CmpInst::FCMP_UNO:
return FPCmp::Predicate::UNO;
case CmpInst::FCMP_UEQ:
return FPCmp::Predicate::UEQ;
case CmpInst::FCMP_UGT:
return FPCmp::Predicate::UGT;
case CmpInst::FCMP_UGE:
return FPCmp::Predicate::UGE;
case CmpInst::FCMP_ULT:
return FPCmp::Predicate::ULT;
case CmpInst::FCMP_ULE:
return FPCmp::Predicate::ULE;
case CmpInst::FCMP_UNE:
return FPCmp::Predicate::UNE;
case CmpInst::FCMP_TRUE:
return FPCmp::Predicate::True;
default:
logError("No floating point predicate\n");
exit(1);
}
}
BinaryFPOperator::Opcode binaryFPOpcode(llvm::Instruction::BinaryOps op) {
switch (op) {
case Instruction::FAdd:
return BinaryFPOperator::Opcode::FAdd;
case Instruction::FSub:
return BinaryFPOperator::Opcode::FSub;
case Instruction::FMul:
return BinaryFPOperator::Opcode::FMul;
case Instruction::FDiv:
return BinaryFPOperator::Opcode::FDiv;
case Instruction::FRem:
return BinaryFPOperator::Opcode::FRem;
default:
logError("Not a floating point binary operator\n");
exit(1);
}
}
/// A function that is abblied to the arguments of a predicate
SMTRef predicateFun(const llvm::CmpInst &cmp, SMTRef expr) {
if (!SMTGenerationOpts::getInstance().BitVect && cmp.isUnsigned() &&
!SMTGenerationOpts::getInstance().EverythingSigned) {
return makeOp("abs", std::move(expr));
}
return expr;
}
/// Convert an LLVM op to an SMT op
string opName(const llvm::BinaryOperator &Op) {
if (SMTGenerationOpts::getInstance().BitVect) {
switch (Op.getOpcode()) {
case Instruction::Add:
return "bvadd";
case Instruction::Sub:
return "bvsub";
case Instruction::Mul:
return "bvmul";
case Instruction::SDiv:
return "bvsdiv";
case Instruction::UDiv:
return "bvudiv";
case Instruction::SRem:
return "bvsrem";
case Instruction::URem:
return "bvurem";
case Instruction::Or:
return "bvor";
case Instruction::And:
return "bvand";
case Instruction::Xor:
return "bvxor";
case Instruction::AShr:
return "bvashr";
case Instruction::LShr:
return "bvlshr";
case Instruction::Shl:
return "bvshl";
default:
logError("Unknown opcode: " + std::string(Op.getOpcodeName()) +
"\n");
return Op.getOpcodeName();
}
} else {
switch (Op.getOpcode()) {
case Instruction::Add:
return "+";
case Instruction::Sub:
return "-";
case Instruction::Mul:
return "*";
case Instruction::SDiv:
return "div";
case Instruction::UDiv:
return "div";
case Instruction::SRem:
return "mod";
case Instruction::URem:
return "mod";
case Instruction::Or:
return "or";
case Instruction::And:
return "and";
case Instruction::Xor:
return "xor";
case Instruction::AShr:
case Instruction::LShr:
return "div";
case Instruction::Shl:
return "*";
default:
logError("Unknown opcode: " + std::string(Op.getOpcodeName()) +
"\n");
return Op.getOpcodeName();
}
}
}
SMTRef combineOp(const llvm::BinaryOperator &Op, std::string opName,
SMTRef firstArg, SMTRef secondArg) {
if (!SMTGenerationOpts::getInstance().BitVect &&
(Op.getOpcode() == Instruction::AShr ||
Op.getOpcode() == Instruction::LShr ||
Op.getOpcode() == Instruction::Shl)) {
// We can only do that if there is a constant on the right side
if (const auto constInt =
llvm::dyn_cast<llvm::ConstantInt>(Op.getOperand(1))) {
// rounding conversion to guard for floating point errors
uint64_t divisor =
static_cast<uint64_t>(pow(2, constInt->getZExtValue()) + 0.5);
return makeOp(
std::move(opName), std::move(firstArg),
std::make_unique<ConstantInt>(llvm::APInt(64, divisor)));
} else {
logErrorData("Only shifts by a constant are supported\n", Op);
}
}
return makeOp(std::move(opName), std::move(firstArg), std::move(secondArg));
}
vector<DefOrCallInfo> memcpyIntrinsic(const llvm::CallInst *callInst,
Program prog) {
vector<DefOrCallInfo> definitions;
const auto castInst0 =
llvm::dyn_cast<llvm::CastInst>(callInst->getArgOperand(0));
const auto castInst1 =
llvm::dyn_cast<llvm::CastInst>(callInst->getArgOperand(1));
if (castInst0 && castInst1) {
const auto ty0 =
llvm::dyn_cast<llvm::PointerType>(castInst0->getSrcTy());
const auto ty1 =
llvm::dyn_cast<llvm::PointerType>(castInst1->getSrcTy());
const auto StructTy0 =
llvm::dyn_cast<llvm::StructType>(ty0->getElementType());
const auto StructTy1 =
llvm::dyn_cast<llvm::StructType>(ty1->getElementType());
if (StructTy0 && StructTy1) {
assert(StructTy0->isLayoutIdentical(StructTy1));
SharedSMTRef basePointerDest =
instrNameOrVal(callInst->getArgOperand(0));
SharedSMTRef basePointerSrc =
instrNameOrVal(callInst->getArgOperand(1));
string heapNameSelect = heapName(prog);
string heapNameStore = heapName(prog);
int i = 0;
for (const auto elTy : StructTy0->elements()) {
SharedSMTRef heapSelect = memoryVariable(heapNameSelect);
SharedSMTRef heapStore = memoryVariable(heapNameStore);
for (int j = 0;
j < typeSize(elTy, callInst->getModule()->getDataLayout());
++j) {
SMTRef select = makeOp("select", heapSelect,
makeOp("+", basePointerSrc,
std::make_unique<ConstantInt>(
llvm::APInt(64, i))));
const vector<SharedSMTRef> args = {
heapStore,
makeOp(
"+", basePointerDest,
std::make_unique<ConstantInt>(llvm::APInt(64, i))),
std::move(select)};
definitions.push_back(makeAssignment(
heapNameStore, make_unique<Op>("store", args)));
++i;
}
}
} else {
logError("currently only memcpy of structs is "
"supported\n");
exit(1);
}
} else {
logError("currently only memcpy of "
"bitcasted pointers is supported\n");
exit(1);
}
return definitions;
}
unique_ptr<CallInfo> toCallInfo(string assignedTo, Program prog,
const llvm::CallInst &callInst) {
vector<SharedSMTRef> args;
if (assignedTo.empty()) {
assignedTo = "res" + std::to_string(programIndex(prog));
}
uint32_t i = 0;
unsigned suppliedArgs = 0;
const auto &funTy = *callInst.getFunctionType();
const llvm::Function &fun = *callInst.getCalledFunction();
for (auto &arg : callInst.arg_operands()) {
args.push_back(instrNameOrVal(arg, funTy.getParamType(i)));
++suppliedArgs;
if (SMTGenerationOpts::getInstance().Stack == StackOpt::Enabled &&
arg->getType()->isPointerTy()) {
args.push_back(instrLocation(arg));
}
++i;
}
unsigned varargs = suppliedArgs - funTy.getNumParams();
return std::make_unique<CallInfo>(assignedTo, fun.getName(), args, varargs,
fun);
}
bool isPtrDiff(const llvm::Instruction &instr) {
if (const auto binOp = llvm::dyn_cast<llvm::BinaryOperator>(&instr)) {
return binOp->getOpcode() == Instruction::Sub &&
llvm::isa<llvm::PtrToIntInst>(binOp->getOperand(0)) &&
llvm::isa<llvm::PtrToIntInst>(binOp->getOperand(1));
}
return false;
}
auto coupledCalls(const CallInfo &call1, const CallInfo &call2) -> bool {
const auto &coupledFunctions =
SMTGenerationOpts::getInstance().CoupledFunctions;
bool coupledNames = false;
// The const cast here is safe because we are only comparing pointers
coupledNames =
coupledFunctions.find({const_cast<llvm::Function *>(&call1.fun),
const_cast<llvm::Function *>(&call2.fun)}) !=
coupledFunctions.end();
if (!hasFixedAbstraction(call1.fun) || !hasFixedAbstraction(call2.fun)) {
return coupledNames;
}
return coupledNames && call1.fun.getFunctionType()->getNumParams() ==
call2.fun.getFunctionType()->getNumParams();
}
| 41.58858
| 80
| 0.545256
|
mattulbrich
|
e6d12ea3f53d333c65b074f699c0a1393446eabd
| 1,121
|
hpp
|
C++
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 44
|
2016-09-19T15:28:25.000Z
|
2018-08-09T13:17:40.000Z
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 44
|
2016-11-03T17:27:30.000Z
|
2017-12-10T16:17:31.000Z
|
include/disccord/models/invite_metadata.hpp
|
FiniteReality/disccord
|
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
|
[
"MIT"
] | 13
|
2016-11-01T00:17:20.000Z
|
2018-08-03T19:51:16.000Z
|
#ifndef _invite_metadata_hpp_
#define _invite_metadata_hpp_
#include <disccord/models/entity.hpp>
#include <disccord/models/user.hpp>
namespace disccord
{
namespace models
{
class invite_metadata : public model
{
public:
invite_metadata();
virtual ~invite_metadata();
virtual void decode(web::json::value json) override;
util::optional<user> get_inviter();
std::string get_created_at();
uint32_t get_uses();
uint32_t get_max_uses();
uint32_t get_max_age();
bool get_temporary();
bool get_revoked();
protected:
virtual void encode_to(
std::unordered_map<std::string, web::json::value> &info
) override;
private:
util::optional<user> inviter;
std::string created_at;
uint32_t uses, max_uses, max_age;
bool temporary, revoked;
};
}
}
#endif /* _invite_metadata_hpp_ */
| 26.690476
| 75
| 0.531668
|
FiniteReality
|
e6d47cd0d1594ea1ed44564eb7577a032c12856e
| 2,069
|
cc
|
C++
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868
|
2021-05-28T04:00:22.000Z
|
2022-03-31T08:57:14.000Z
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33
|
2021-05-28T08:44:47.000Z
|
2021-09-26T13:09:21.000Z
|
flare/base/buffer/zero_copy_stream_test.cc
|
AriCheng/flare
|
b2c84588fe4ac52f0875791d22284d7e063fd057
|
[
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122
|
2021-05-28T08:22:23.000Z
|
2022-03-29T09:52:09.000Z
|
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "flare/base/buffer/zero_copy_stream.h"
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "google/protobuf/util/message_differencer.h"
#include "flare/testing/message.pb.h"
namespace flare {
TEST(ZeroCopyStream, SerializeAndDeserialize) {
testing::ComplexMessage src;
src.set_integer(556);
src.set_enumeration(testing::ENUM_0);
src.set_str("short str");
src.mutable_one()->set_str("a missing string" + std::string(16777216, 'a'));
NoncontiguousBufferBuilder nbb;
NoncontiguousBufferOutputStream zbos(&nbb);
CHECK(src.SerializeToZeroCopyStream(&zbos));
zbos.Flush();
auto serialized = nbb.DestructiveGet();
NoncontiguousBuffer cp1 = CreateBufferSlow(FlattenSlow(serialized));
NoncontiguousBuffer cp2 = serialized;
// Same size as serialized to string.
ASSERT_EQ(src.SerializeAsString().size(), serialized.ByteSize());
NoncontiguousBuffer splited;
splited.Append(serialized.Cut(1));
splited.Append(serialized.Cut(2));
splited.Append(serialized.Cut(3));
splited.Append(serialized.Cut(4));
splited.Append(std::move(serialized));
for (auto&& e : {&cp1, &cp2, &splited}) {
// Parseable.
NoncontiguousBufferInputStream nbis(e);
testing::ComplexMessage dest;
ASSERT_TRUE(dest.ParseFromZeroCopyStream(&nbis));
// Same as the original one.
ASSERT_TRUE(google::protobuf::util::MessageDifferencer::Equals(src, dest));
}
}
} // namespace flare
| 32.328125
| 80
| 0.740938
|
AriCheng
|
e6d4a327d3d13fc6a4257f7e90bb4aa25e33cd21
| 1,707
|
cpp
|
C++
|
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
scss/class/class3.cpp
|
chth2116/Faux-Compania
|
c8bc0e06ee5c67c59334195817b831481b9125ee
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
void passByValue(int a){
a++;
}
void passByPointer(int *ptr){
//this will give same address as that stored in b (ptr and b are pointing to the same location)
cout << "address stored in ptr " << ptr << endl;
*ptr = *ptr + 1; // this is the same as: (*ptr)++
}
int main(){
int a = 5;
//pointer and address it points to have to be the same type
int *b = &a;
//b gives address, *b gets the value stored at b which is the address of a
//* has two meanings
//use it to declare pointers
//use it to dereference the pointers
//dereference - go to address stored in pointer and get the value at that address
//cout << &b<< ", " << b<< ", " << *b << endl;
//*b gets updated as a gets updated because the address of a has not changed
a = 10;
int c = 20;
b = &c; //change the address stored in b to address of c
//cout << *b << endl;
int arrayA[5];
cout << arrayA << endl; //name of array gives us address of first element in arrayA
//Functions
passByValue(a);//the changes made to a in the function are local to that Functions
// pass by value basically made a copy of a and stored it at a new address unique to the function
//cout << a << endl;
//address' are unlike variables in that they are universal. If we change something at in address in one Functions
//that variable at that address changes for all other Functions
//in this case, we send the address of b to the function and the function changes the value at that address by adding one
//we then check b and get 21 which is the value of *b+1;
cout << "address stored in b " << b << endl;
passByPointer(b);
cout << *b << endl;
}
| 32.826923
| 123
| 0.66198
|
chth2116
|
5c798c111fb83e1cefd54d1eff981c94f1ffdad7
| 4,499
|
cc
|
C++
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 59
|
2015-01-23T01:02:50.000Z
|
2021-11-26T00:01:45.000Z
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 2
|
2017-05-26T15:26:24.000Z
|
2020-09-25T03:54:01.000Z
|
moui/core/android/device_android.cc
|
ollix/moui
|
4a931aa15fac42b308baae170a855c2d78f9ee9f
|
[
"Apache-2.0"
] | 7
|
2015-09-25T08:09:20.000Z
|
2019-11-24T15:24:28.000Z
|
// Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/core/device.h"
#include <map>
#include "jni.h" // NOLINT
#include "moui/core/application.h"
namespace {
// The screen scale factor of the current device.
float screen_scale_factor = 0;
// The smallest screen dp that should consider as a tablet. This value can
// be changed through the SetSmallestScreenWidthDpForTablet() method.
float tablet_smallest_screen_width_dp = 600;
std::map<JNIEnv*, jobject> global_devices;
// Returns the instance of the com.ollix.moui.Device class on the Java side.
jobject GetJavaDevice(JNIEnv* env) {
auto match = global_devices.find(env);
if (match != global_devices.end()) {
return match->second;
}
jclass device_class = env->FindClass("com/ollix/moui/Device");
jmethodID constructor = env->GetMethodID(device_class, "<init>",
"(Landroid/content/Context;)V");
jobject device_obj = env->NewObject(device_class, constructor,
moui::Application::GetMainActivity());
jobject global_device = env->NewGlobalRef(device_obj);
env->DeleteLocalRef(device_class);
env->DeleteLocalRef(device_obj);
global_devices[env] = global_device;
return global_device;
}
} // namespace
namespace moui {
void Device::Init() {
GetScreenScaleFactor();
}
Device::BatteryState Device::GetBatteryState() {
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getBatteryState", "()I");
env->DeleteLocalRef(device_class);
const int kResult = env->CallIntMethod(device, java_method);
// BatteryManager.BATTERY_STATUS_CHARGING
if (kResult == 2)
return BatteryState::kCharging;
// BatteryManager.BATTERY_STATUS_DISCHARGING
if (kResult == 3)
return BatteryState::kUnplugged;
// BatteryManager.BATTERY_STATUS_NOT_CHARGING
if (kResult == 4)
return BatteryState::kNotCharging;
// BatteryManager.BATTERY_STATUS_FULL
if (kResult == 5)
return BatteryState::kFull;
return BatteryState::kUnknown;
}
// Calls com.ollix.moui.Device.getSmallestScreenWidthDp() on the Java side.
Device::Category Device::GetCategory() {
static float smallest_screen_width_dp = 0;
if (smallest_screen_width_dp >= tablet_smallest_screen_width_dp) {
return Category::kTablet;
} else if (smallest_screen_width_dp > 0) {
return Category::kPhone;
}
// Determines the smallest_screen_width_dp for the first time calling this
// method.
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getSmallestScreenWidthDp", "()F");
env->DeleteLocalRef(device_class);
smallest_screen_width_dp = env->CallFloatMethod(device, java_method);
return GetCategory();
}
// Calls com.ollix.moui.Device.getScreenScaleFactor() on the Java side.
float Device::GetScreenScaleFactor() {
if (screen_scale_factor > 0)
return screen_scale_factor;
JNIEnv* env = moui::Application::GetJNIEnv();
jobject device = GetJavaDevice(env);
jclass device_class = env->GetObjectClass(device);
jmethodID java_method = env->GetMethodID(
device_class, "getScreenScaleFactor", "()F");
env->DeleteLocalRef(device_class);
screen_scale_factor = env->CallFloatMethod(device, java_method);
return screen_scale_factor;
}
void Device::Reset() {
for (auto& pair : global_devices) {
JNIEnv* env = Application::GetJNIEnv();
jobject global_device = pair.second;
env->DeleteGlobalRef(global_device);
}
global_devices.clear();
}
void Device::SetSmallestScreenWidthDpForTablet(float screen_width_dp) {
tablet_smallest_screen_width_dp = screen_width_dp;
}
} // namespace moui
| 33.325926
| 76
| 0.728829
|
ollix
|
5c7d39a14fee99e4e5118aa6274302513e7e3236
| 29,733
|
hh
|
C++
|
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
dune/ax1/acme2/common/acme2_setup.hh
|
pederpansen/dune-ax1
|
152153824d95755a55bdd4fba80686863e928196
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef DUNE_AX1_ACME2_SETUP_HH
#define DUNE_AX1_ACME2_SETUP_HH
#include <dune/common/array.hh>
#include <dune/pdelab/backend/istlvectorbackend.hh>
//#include<dune/pdelab/finiteelementmap/q12dfem.hh>
//#include<dune/pdelab/finiteelementmap/q22dfem.hh>
#include <dune/pdelab/common/clock.hh>
#include <dune/pdelab/finiteelementmap/q1fem.hh>
#include <dune/pdelab/finiteelementmap/conformingconstraints.hh>
#include <dune/pdelab/function/selectcomponent.hh>
#include <dune/pdelab/gridoperator/gridoperator.hh>
#include <dune/pdelab/gridoperator/onestep.hh>
#include <dune/pdelab/backend/seqistlsolverbackend.hh>
#include <dune/pdelab/stationary/linearproblem.hh>
#include <dune/ax1/common/ax1_newton.hh>
#include <dune/ax1/common/ax1_linearproblem.hh>
#include <dune/ax1/common/ax1_discretegridfunction.hh>
#include <dune/ax1/common/ax1_simulationdata.hh>
#include <dune/ax1/common/ax1_simulationstate.hh>
#include <dune/ax1/common/chargedensitygridfunction.hh>
#include <dune/ax1/common/ionicstrengthgridfunction.hh>
#include <dune/ax1/common/membranefluxgridfunction.hh>
#include <dune/ax1/common/poisson_boltzmann_concentrationgridfunction.hh>
#include <dune/ax1/common/poisson_boltzmann_rhs_gridfunction.hh>
#include <dune/ax1/common/output.hh>
#include <dune/ax1/common/vectordiscretegridfunctiongradient.hh>
#include <dune/ax1/acme2/common/acme2_boundary.hh>
#include <dune/ax1/acme2/common/acme2_initial.hh>
#include <dune/ax1/acme2/common/acme2_output.hh>
#include <dune/ax1/acme2/common/acme2_solutionvectors.hh>
#include <dune/ax1/acme2/common/nernst_planck_parameters.hh>
#include <dune/ax1/acme2/common/poisson_parameters.hh>
#include <dune/ax1/acme2/common/poisson_boltzmann_parameters.hh>
#include <dune/ax1/acme2/common/acme2_simulation.hh>
#include <dune/ax1/acme2/operator/convectiondiffusionfem.hh>
#include <dune/ax1/acme2/operator/poisson_boltzmann_operator.hh>
#include <dune/ax1/acme2/operator/acme2_operator_fully_coupled.hh>
#include <dune/ax1/acme2/operator/acme2_toperator.hh>
template<class Grid, class GV, class PHYSICS, class SubGV>
class Acme2Setup
{
public:
//! Traits class providing function spaces and related data types for the acme2 use case
template<int NUMBER_OF_SPECIES>
struct Acme2Traits
{
typedef Acme2Setup<Grid,GV,PHYSICS,SubGV> SETUP;
typedef PHYSICS Physics;
typedef GV GridView;
typedef Grid GridType;
typedef typename GV::Grid::ctype Coord;
typedef double Real;
typedef SubGV SubGridView;
typedef typename SubGV::Grid SubGridType;
#if USE_PARALLEL==1
typedef Dune::PDELab::NonoverlappingConformingDirichletConstraints CONSTRAINTS;
#else
typedef Dune::PDELab::ConformingDirichletConstraints CONSTRAINTS;
#endif
typedef Dune::PDELab::ISTLVectorBackend<AX1_BLOCKSIZE> VBE;
typedef Dune::PDELab::Q1LocalFiniteElementMap<Coord,Real,GV::dimension> FEM_CON;
typedef Dune::PDELab::Q1LocalFiniteElementMap<Coord,Real,GV::dimension> FEM_POT;
//typedef Dune::PDELab::Pk1dLocalFiniteElementMap<Coord,Real> FEM_CON;
//typedef Dune::PDELab::Pk1dLocalFiniteElementMap<Coord,Real> FEM_POT;
// Nernst-Planck GFS (on electrolyte subdomain)
typedef Dune::PDELab::GridFunctionSpaceLexicographicMapper LexicographicOrdering;
typedef Dune::PDELab::GridFunctionSpaceComponentBlockwiseMapper<1,1,1> PowerGFSOrdering;
typedef Dune::PDELab::GridFunctionSpace<SubGV,FEM_CON,CONSTRAINTS,VBE> GFS_SINGLE_CON;
typedef Dune::PDELab::PowerGridFunctionSpace<
GFS_SINGLE_CON, NUMBER_OF_SPECIES, PowerGFSOrdering> GFS_CON;
// Poisson GFS (on electrolyte or membrane subdomain)
typedef Dune::PDELab::GridFunctionSpace<GV,FEM_POT,CONSTRAINTS,VBE> GFS_POT;
// Composite GFS for electrolyte
//typedef Dune::PDELab::GridFunctionSpaceLexicographicMapper CompositeGFSOrdering;
// This has no effect when using dune-multidomain => ordering always lexicographic!
typedef Dune::PDELab::GridFunctionSpaceComponentBlockwiseMapper<3,1> CompositeBlockedOrdering;
// Multidomain GFS
typedef Dune::PDELab::MultiDomain::MultiDomainGridFunctionSpace<GridType,VBE,GFS_CON,GFS_POT> MultiGFS;
// Extract SubGFS for use in gridfunctions; use these after creating MultiGFS!
typedef typename Dune::PDELab::GridFunctionSubSpace<MultiGFS,0> GFS_CON_SUB;
typedef typename Dune::PDELab::GridFunctionSubSpace<MultiGFS,1> GFS_POT_SUB;
// Extract solution vector type
//typedef typename Dune::PDELab::BackendVectorSelector<GFS_CON,Real>::Type U_CON;
//typedef typename Dune::PDELab::BackendVectorSelector<GFS_POT,Real>::Type U_POT;
typedef typename Dune::PDELab::BackendVectorSelector<MultiGFS,Real>::Type U;
// Various gridfunctions
typedef Dune::PDELab::VectorDiscreteGridFunction <GFS_CON_SUB,U> DGF_CON_SUB;
typedef Dune::PDELab::VectorDiscreteGridFunctionGradient <GFS_CON_SUB,U> DGF_CON_GRAD_SUB;
typedef Ax1MultiDomainGridFunctionExtension<GV, DGF_CON_SUB, PHYSICS> DGF_CON;
typedef Ax1MultiDomainGridFunctionExtension<GV, DGF_CON_GRAD_SUB, PHYSICS> DGF_CON_GRAD;
typedef Dune::PDELab::DiscreteGridFunction<GFS_POT_SUB,U> DGF_POT;
typedef Dune::PDELab::DiscreteGridFunctionGradient<GFS_POT_SUB,U> DGF_POT_GRAD;
typedef ChargeDensityGridFunction<DGF_CON, PHYSICS> GF_CD;
typedef IonicStrengthGridFunction<DGF_CON, PHYSICS> GF_IS;
typedef MembraneFluxGridFunction<DGF_CON,DGF_POT,PHYSICS> GF_MEMB_FLUX;
// Grid functions for initial values (subdomains)
typedef typename PHYSICS::Traits::INITIAL_CON INITIAL_GF_CON;
typedef InitialCon<GV,Real,NUMBER_OF_SPECIES,PHYSICS,INITIAL_GF_CON> INITIAL_CON;
typedef typename PHYSICS::Traits::INITIAL_POT INITIAL_GF_POT;
typedef InitialPot<GV,Real,PHYSICS,GF_CD,INITIAL_GF_POT> INITIAL_POT;
typedef Dune::PDELab::CompositeGridFunction<INITIAL_CON,INITIAL_POT> INITIAL_ELEC;
// Helper grid function to calculate equilibirum concentrations from stationary Poisson-Boltzmann potential
//typedef PoissonBoltzmannRHSGridFunction<DGF_POT, INITIAL_CON, PHYSICS> GF_PB_RHS;
//typedef PoissonBoltzmannConcentrationGridFunction<INITIAL_CON, DGF_POT, SubGV, PHYSICS> GF_PB_CON;
// Boundary values
typedef typename PHYSICS::Traits::NERNST_PLANCK_BOUNDARY BOUNDARY_CON;
typedef typename PHYSICS::Traits::POISSON_BOUNDARY BOUNDARY_POT;
// Parameter classes
typedef NernstPlanckParameters<GV,Real,PHYSICS,BOUNDARY_CON,GF_MEMB_FLUX> PARAMETERS_CON;
typedef PoissonParameters<GV,Real,PHYSICS,BOUNDARY_POT> PARAMETERS_POT;
};
// Choose domain and range field type
typedef GV GridView;
typedef typename GV::Grid GridType;
typedef typename GV::Grid::ctype Coord;
typedef double Real;
typedef typename GV::template Codim<0>::Iterator ElementIterator;
typedef Dune::SingleCodimSingleGeomTypeMapper<GV, 0> ElementMapper;
// SubGrid stuff
typedef typename SubGV::Grid SubGrid;
typedef Acme2Traits<NUMBER_OF_SPECIES> Traits;
static const bool writeIfNotConverged = true;
Acme2Setup(Grid& grid_, GV& gv_, PHYSICS& physics_,
SubGV& elecGV_, SubGV& membGV_)
: grid(grid_),
gv(gv_),
physics(physics_),
elecGV(elecGV_),
membGV(membGV_)
{}
void setup (double dtstart, double tend)
{
Real time = 0.0;
Real dt = dtstart;
const Acme2Parameters& params = physics.getParams();
Real tEquilibrium = physics.getParams().tEquilibrium();
if(tEquilibrium > time)
{
dt = physics.getParams().dtEquilibrium();
debug_info << "== Starting with initial dt = " << dt << " until tEquilibirum " << tEquilibrium
<< " ==" << std::endl;
}
const int dim = GV::dimension;
const int degreePot = 1, degreeCon = 1;
// Finite element map for CG
typename Traits::FEM_CON femCon;
typename Traits::FEM_POT femPot;
// =================== GFS SETUP ================================================================
// Single-component GFS for one ion species
typename Traits::GFS_SINGLE_CON gfsSingleCon(elecGV,femCon);
// Power grid function space for all ion species
typename Traits::GFS_CON gfsCon(gfsSingleCon);
// Full GFS for potential on electrolyte and membrane subdomain
typename Traits::GFS_POT gfsPot(gv,femPot);
// Multidomain GFS
//typename Traits::MultiGFS multigfs(grid,gfsCon,gfsPot);
typename Traits::MultiGFS multigfs(grid,gfsCon,gfsPot);
// SubGridFunctionSpaces for use in gridfunctions
typename Traits::GFS_CON_SUB gfsConSub(multigfs);
typename Traits::GFS_POT_SUB gfsPotSub(multigfs);
// ==============================================================================================
// =========== Define solution vectors ==========================================================
// Coefficient vectors on subdomains
//typename Traits::U_CON uoldCon(gfsCon,0.0);
//typename Traits::U_CON unewCon(gfsCon,0.0);
//debug_jochen << "U_CON.N(): " << unewCon.N() << std::endl;
//debug_jochen << "U_CON.flatsize(): " << unewCon.flatsize() << std::endl;
//typename Traits::U_POT uoldPot(gfsPot,0.0);
//typename Traits::U_POT unewPot(gfsPot,0.0);
//debug_jochen << "U_POT.N(): " << unewPot.N() << std::endl;
//debug_jochen << "U_POT.flatsize(): " << unewPot.flatsize() << std::endl;
typename Traits::U uold(multigfs,0.0);
typename Traits::U unew = uold;
debug_jochen << "U.N(): " << unew.N() << std::endl;
debug_jochen << "U.flatsize(): " << unew.flatsize() << std::endl;
debug_jochen << "con/pot GFS size: " << gfsConSub.size() << " / " << gfsPotSub.size() << std::endl;
// Now let's put 'em all into one structure!
//Acme2SolutionVectors<Traits> solutionVectors(uold, unew, uoldCon, unewCon, uoldPot, unewPot);
Acme2SolutionVectors<Traits> solutionVectors(uold, unew);
// ==============================================================================================
// ====== Create grid functions and interpolate initial values onto coefficient vectors =========
// Initial concentrations
typename Traits::INITIAL_GF_CON initialGFCon(gv,physics.getParams());
// Generic wrapper class for initial grid function
typename Traits::INITIAL_CON initialCon(gv,physics,initialGFCon);
initialCon.setTime(time);
typename Traits::DGF_CON_SUB dgfConElec(gfsConSub,unew);
typename Traits::DGF_CON_SUB dgfOldConElec(gfsConSub,uold);
typename Traits::DGF_CON_GRAD_SUB dgfGradConElec(gfsConSub, unew);
typename Traits::DGF_CON dgfCon(gv, dgfConElec, physics);
typename Traits::DGF_CON dgfOldCon(gv, dgfOldConElec, physics);
typename Traits::DGF_CON_GRAD dgfGradCon(gv, dgfGradConElec, physics);
typename Traits::GF_CD gfChargeDensity(dgfCon, dgfOldCon, physics);
typename Traits::GF_IS gfIonicStrength(dgfCon, physics);
// Initial potential
typename Traits::INITIAL_GF_POT initialGFPot(gv,physics.getParams());
typename Traits::INITIAL_POT initialPot(gv,physics,gfChargeDensity,initialGFPot,2*degreePot);
initialPot.setTime(time);
typename Traits::DGF_POT dgfPot(gfsPotSub, unew);
typename Traits::DGF_POT dgfOldPot(gfsPotSub, uold);
typename Traits::DGF_POT_GRAD dgfGradPot(gfsPotSub, unew);
// Flag 'true' for updating channel states in each time step
typename Traits::GF_MEMB_FLUX gfMembFlux(dgfOldCon, dgfOldPot, physics, true, tEquilibrium);
// Composite initial grid function for the electrolyte subdomain
typename Traits::INITIAL_ELEC initialElec(initialCon,initialPot);
// Define and instantiate output class
//typedef Acme2Output<Traits,GV,SubGV,typename Traits::GFS_CON,
// typename Traits::GFS_POT,typename Traits::U_CON,typename Traits::U_POT,PHYSICS> ACME2_OUTPUT;
typedef Acme2Output<Traits> ACME2_OUTPUT;
ACME2_OUTPUT acme2Output(gv,elecGV,membGV,multigfs,gfsConSub,gfsPotSub,solutionVectors,
gfMembFlux,physics,2*degreePot,2*degreeCon);
// ==============================================================================================
// ========== Define Parameter classes containing the model problem =============================
typename Traits::BOUNDARY_CON boundaryCon(physics.getParams(), initialGFCon);
typename Traits::PARAMETERS_CON parametersCon(gv,physics,boundaryCon,gfMembFlux,tEquilibrium);
typename Traits::BOUNDARY_POT boundaryPot(physics.getParams(), initialGFPot);
typename Traits::PARAMETERS_POT parametersPot(physics,boundaryPot);
// ==============================================================================================
// ============== BOUNDARY CONDITION TYPES ======================================================
typedef BCTypeSingleCon<typename Traits::PARAMETERS_CON,PHYSICS> BCType_SINGLE_CON;
typedef Dune::PDELab::PowerConstraintsParameters<BCType_SINGLE_CON,NUMBER_OF_SPECIES> BCType_CON;
typedef BCTypePot<typename Traits::PARAMETERS_POT,PHYSICS> BCType_POT;
typedef Dune::PDELab::CompositeConstraintsParameters<BCType_CON, BCType_POT> BCType_ELEC;
// Create NUMBER_OF_SPECIES boundary condition type classes
BCType_CON bctypeCon;
for(int i=0; i<NUMBER_OF_SPECIES; ++i)
{
BCType_SINGLE_CON* bctypeSingleCon = new BCType_SINGLE_CON(gv,parametersCon,physics,i);
bctypeCon.setChild(i,*bctypeSingleCon);
}
BCType_POT bctypePot(gv,parametersPot,physics);
BCType_ELEC bctypeElec(bctypeCon, bctypePot);
// ==============================================================================================
// ============== Define local operators ========================================================
// ##### Spatial part #####
// ### Standard FEM (CG) fully-coupled Poisson-Nernst-Planck local operator on electrolyte subdomain
typedef Acme2OperatorFullyCoupled<typename Traits::PARAMETERS_CON, typename Traits::PARAMETERS_POT,
typename Traits::FEM_CON, typename Traits::FEM_POT> LOP_ELEC;
LOP_ELEC lopElec(parametersCon, parametersPot);
// ### Standard FEM (CG) Poisson local operator on membrane subdomain
typedef Dune::PDELab::ConvectionDiffusionFEM<typename Traits::PARAMETERS_POT,typename Traits::FEM_POT> LOP_MEMB;
LOP_MEMB lopMemb(parametersPot);
// ##### Temporal part #####
typedef NernstPlanckTimeLocalOperator<PHYSICS> TLOP_ELEC;
TLOP_ELEC tlop(physics);
// ==============================================================================================
// =========== dune-multidomain setup stuff =====================================================
typedef Dune::PDELab::MultiDomain::SubDomainEqualityCondition<Grid> EC;
typedef Dune::PDELab::MultiDomain::SubDomainSupersetCondition<Grid> SC;
EC conditionElec(0); //only on subdomain 0
EC conditionMemb(1); //only on subdomain 1
SC conditionAll; //on all subdomains
// Empty constraints for subproblems
typename Traits::CONSTRAINTS constraints;
typedef Dune::PDELab::MultiDomain::TypeBasedSubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
LOP_ELEC,EC,typename Traits::GFS_CON,typename Traits::GFS_POT> ElecSubProblem;
ElecSubProblem elecSubProblem(lopElec,conditionElec);
typedef Dune::PDELab::MultiDomain::TypeBasedSubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
LOP_MEMB,EC,typename Traits::GFS_POT> MembSubProblem;
MembSubProblem membSubProblem(lopMemb,conditionMemb);
typedef Dune::PDELab::MultiDomain::SubProblem<typename Traits::MultiGFS,typename Traits::MultiGFS,
TLOP_ELEC,EC,0> TimeSubProblem;
TimeSubProblem timeSubProblem(tlop,conditionElec);
// ==============================================================================================
// =================== BOUNDARY CONDITIONS ======================================================
//typedef Traits::MultiGFS::ConstraintsContainer<Real>::Type CC;
typedef typename Traits::MultiGFS::template ConstraintsContainer<Real>::Type CC;
CC cc;
auto md_constraints = Dune::PDELab::MultiDomain::template constraints<Real>(multigfs,
Dune::PDELab::MultiDomain::constrainSubProblem(elecSubProblem, bctypeElec),
Dune::PDELab::MultiDomain::constrainSubProblem(membSubProblem, bctypePot));
md_constraints.assemble(cc);
std::cout << multigfs.size() << " DOF, " << cc.size() << " restricted" << std::endl;
// The following boundary value classes are not used, as they are assumed to be fulfilled by the
// initial conditions are not allowed to change over time!
// ###### Dirichlet values ########
typedef DirichletValuesSingleCon<typename Traits::PARAMETERS_CON> DirichletValuesSingleCon;
// Create NUMBER_OF_SPECIES Dirichlet value classes
typedef Dune::PDELab::PowerGridFunction<DirichletValuesSingleCon,NUMBER_OF_SPECIES> DirichletValuesCon;
DirichletValuesCon dirichletValuesCon;
for(int i=0; i<NUMBER_OF_SPECIES; ++i)
{
DirichletValuesSingleCon* dirichletValuesSingleCon
= new DirichletValuesSingleCon(gv,parametersCon,i);
dirichletValuesCon.setChild(i,*dirichletValuesSingleCon);
}
typedef Dune::PDELab::ConvectionDiffusionDirichletExtensionAdapter
<typename Traits::PARAMETERS_POT> DirichletValuesPot;
DirichletValuesPot dirichletValuesPot(gv,parametersPot);
// Is this necessary? Initial conditions should fulfill the boundary conditions anyways,
// otherwise we have an ill-posed problem!
//Dune::PDELab::interpolate(dirichletValuesCon_Inside,subGfsCon_Inside,unewCon_Inside);
//Dune::PDELab::copy_nonconstrained_dofs(ccCon_Inside,uoldCon_Inside,unewCon_Inside);
//Dune::PDELab::interpolate(dirichletValuesPot,gfsPot,uPot);
//Output::printSingleCoefficientVector(uPot, "uPot t=0");
// ==============================================================================================
// ============== Make grid operator ============================================================
typedef typename Traits::VBE::MatrixBackend MBE;
//typedef Dune::PDELab::GridOperator<GFS_POT,GFS_POT,STATIONARY_LOP_POT,MBE,Real,Real,Real,CC_POT,CC_POT>
// STATIONARY_GO_POT;
//STATIONARY_GO_POT stationaryGoPot(gfsPot,ccPot,gfsPot,ccPot,stationaryLopPot);
typedef Dune::PDELab::MultiDomain::GridOperator<typename Traits::MultiGFS,typename Traits::MultiGFS,
MBE,Real,Real,Real,CC,CC,ElecSubProblem,MembSubProblem> GO0;
typedef Dune::PDELab::MultiDomain::GridOperator<typename Traits::MultiGFS,typename Traits::MultiGFS,
MBE,Real,Real,Real,CC,CC,TimeSubProblem> GO1;
typedef Dune::PDELab::OneStepGridOperator<GO0,GO1> IGO;
GO0 go0(multigfs,multigfs,cc,cc,elecSubProblem,membSubProblem);
GO1 go1(multigfs,multigfs,cc,cc,timeSubProblem);
IGO igo(go0,go1);
// Here, initial values coming from the both subdomain initial GFs are written to uold
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialPot,membSubProblem);
unew = uold;
// ==============================================================================================
// ========== Select a linear solver backend ====================================================
#if USE_PARALLEL==1
//typedef Dune::PDELab::ISTLBackend_NOVLP_CG_NOPREC<typename Traits::MultiGFS> LS;
typedef Dune::PDELab::ISTLBackend_NOVLP_BCGS_SSORk<IGO> LS;
LS ls(multigfs);
#else
// funktionieren bei: PowerGFS lexicographic / PowerGFS blockwise<1,1,1> ?
//typedef Dune::PDELab::ISTLBackend_SEQ_LOOP_Jac LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_ILU0 LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_ILUn LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_SSOR LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_Jac LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_CG_AMG_SSOR<IGO> LS; // nö / ?
//typedef Dune::PDELab::ISTLBackend_SEQ_MINRES_SSOR LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_Jac LS; // nö / nö
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_SSOR LS; // nö / nö
// !!! Watch them constructor parameters !!!
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_ILU0 LS; //nö / ja
//LS ls(5000,5);
typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_ILUn LS; // hardly / ja
LS ls(1,1.0,5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_AMG_SSOR<IGO,true> LS; // nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_AMG_SOR<IGO,true> LS; // ? / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_LS_AMG_SSOR<IGO> LS; // nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_LS_AMG_SOR<IGO> LS; //nö / ja
//LS ls(5000,5);
//typedef Dune::PDELab::ISTLBackend_SEQ_SuperLU LS;
//LS ls(5); // verbose = 1
debug_info << "Using linear solver " << Tools::getTypeName(ls) << std::endl;
//typedef typename FAKE_IGO::Traits::Jacobian M;
//typename M::BaseT MatrixType ;
//typedef typename FAKE_IGO::Traits::Domain FAKE_V;
//typedef typename IGO::Traits::Domain REAL_V;
//REAL_V v1(unew);
//FAKE_V v2(unew);
//debug_jochen << "M: " << Tools::getTypeName(bla) << std::endl;
//debug_jochen << "V: " << Tools::getTypeName(v1) << std::endl;
//debug_jochen << "V: " << Tools::getTypeName(v2) << std::endl;
//debug_jochen << "VectorType: " << Tools::getTypeName(v2) << std::endl;
#endif
#if 1
// ==============================================================================================
// ========= Solver for nonlinear problem per stage ==========================================
typedef Ax1Newton<ACME2_OUTPUT,IGO,LS,typename Traits::U> PDESOLVER;
PDESOLVER pdesolver(acme2Output,igo,ls,"octave/acme2");
pdesolver.setReassembleThreshold(0.0);
pdesolver.setVerbosityLevel(5); // 2
pdesolver.setReduction(params.getReduction()); // 1e-10
pdesolver.setAbsoluteLimit(params.getAbsLimit()); // 1e-10
pdesolver.setMinLinearReduction(1e-5); // has no effect when using direct solver like SuperLU
pdesolver.setMaxIterations(50);
pdesolver.setLineSearchStrategy(PDESOLVER::hackbuschReuskenAcceptBest);
pdesolver.setLineSearchMaxIterations(50); // 10
pdesolver.setPrintMatrix(params.doPrintMatrix());
pdesolver.setPrintRhs(params.doPrintRhs());
pdesolver.setRowPreconditioner(params.useRowNormPreconditioner());
pdesolver.setReorderMatrix(params.doReorderMatrix());
// ==============================================================================================
// ========== time-stepper ======================================================================
//Dune::PDELab::Alexander3Parameter<Real> timeStepper;
//Dune::PDELab::Alexander3Parameter<Real> timeStepper;
Dune::PDELab::ImplicitEulerParameter<Real> timeStepper;
//Dune::PDELab::ExplicitEulerParameter<Real> timeStepper;
//Dune::PDELab::RK4Parameter<Real> timeStepper;
//Dune::PDELab::HeunParameter<Real> timeStepper;
typedef Dune::PDELab::OneStepMethod<Real,IGO,PDESOLVER,typename Traits::U,typename Traits::U> SOLVER;
SOLVER solver(timeStepper,igo,pdesolver);
solver.setVerbosityLevel(0); // 2
// In case we need access to the pdesolver later on
const PDESOLVER& pdesolverRef = solver.getPDESolver();
// ==============================================================================================
// ========== Load saved state ======================================================================
if(physics.getParams().doLoadState())
{
//solutionVectors.printHostGridVectors();
std::string loadFilename = physics.getParams().getLoadFilename();
acme2Output.loadState(time,dt,loadFilename);
debug_info << "======================================================================================"
<< std::endl;
debug_info << "Loaded simulation state from file " << loadFilename << std::endl;
debug_info << "======================================================================================"
<< std::endl;
// Enforcing boundary conditions is removed; use the loaded values and leave them untouched!
/*
// Set Dirichlet boundary values from the saved data just loaded
Real xReference = params.xMin() + 0.5 * (params.xMax() - params.xMin());
Real yReference = params.yMin() + 0.5 * (params.yMax() - params.yMin());
std::vector<Real> boundaryValues = physics.getBoundaryValues(dgfPot, xReference, yReference);
initialGFPot.setPotValues(boundaryValues);
debug_jochen << "Boundary values: ";
Output::printVector(boundaryValues);
// Enforce boundary conditions
typename Traits::U uold_save = uold;
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,uold,initialPot,membSubProblem);
Dune::PDELab::copy_nonconstrained_dofs(cc,uold_save,uold);
typename Traits::U unew_save = unew;
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,unew,initialElec,elecSubProblem);
Dune::PDELab::MultiDomain::interpolateOnTrialSpace(multigfs,unew,initialPot,membSubProblem);
Dune::PDELab::copy_nonconstrained_dofs(cc,unew_save,unew);
*/
if(not params.doContinueSimulation())
{
time = 0.0;
} else {
if(tend < time)
DUNE_THROW(Dune::Exception, "Start time (" << time << ") > end time (" << tend << ")!");
}
dt = dtstart;
if(tEquilibrium > time)
{
dt = physics.getParams().dtEquilibrium();
debug_info << "== Starting with initial dt = " << dt << " until tEquilibirum " << tEquilibrium
<< " ==" << std::endl;
}
//solutionVectors.printHostGridVectors();
}
// ==============================================================================================
// ========== Initial output ====================================================================
//Tools::compositeToChildCoefficientVector(multigfs, unew, unewCon, 0);
//uoldCon = unewCon;
//Tools::compositeToChildCoefficientVector(multigfs, unew, unewPot, 1);
//uoldPot = unewPot;
//Output::printSingleCoefficientVector(unewCon, "uCon");
//Output::printSingleCoefficientVector(unewPot, "uPot");
//Output::printSingleCoefficientVector(unew, "u");
double debyeLength, h_x, h_y;
physics.getDebyeLength(gfIonicStrength, debyeLength, h_x, h_y);
debug_info << std::endl;
debug_info << "@@@@@@@ minimum Debye length / length scale " << debyeLength / physics.getLengthScale()
<< std::endl;
debug_info << "@@@@@@@ h_x = " << h_x << ", h_y = " << h_y << std::endl;
if(h_x >= (debyeLength/physics.getLengthScale()) || h_y >= (debyeLength/physics.getLengthScale()))
{
debug_warn << "WARNING: Grid does not resolve Debye length [h_x = "
<< h_x << ", h_y = " << h_y << "]!" << std::endl;
}
debug_verb << "" << std::endl;
debug_jochen << "Diffusion length for this initial dt: "
<< 2*std::sqrt(physics.getDiffCoeff(Na, 0) * dt)
<< std::endl;
// ==============================================================================================
// ========== Run simulation ====================================================================
Acme2Simulation<Traits,ACME2_OUTPUT>::run(time, dt, dtstart, tend, tEquilibrium,
physics, gv, membGV,
solver,
parametersCon,
multigfs,
uold, unew,
//uoldCon, unewCon, uoldPot, unewPot,
gfMembFlux, dgfCon, dgfPot, dgfGradPot,
acme2Output, solutionVectors);
// ==============================================================================================
// ======= Save simulation state ================================================================
if(physics.getParams().doSaveState())
{
std::string saveFilename = physics.getParams().getSaveFilename();
acme2Output.saveState(time,dt,saveFilename);
debug_info << "=============================================================" << std::endl;
debug_info << "Saved simulation state to file " << saveFilename << std::endl;
debug_info << "=============================================================" << std::endl;
}
// ==============================================================================================
debug_info << "Total Acme2Output time: " << acme2Output.getTotalOutputTime() << "s" << std::endl;
#endif
}
private:
Grid& grid;
GV& gv;
PHYSICS& physics;
SubGV& elecGV;
SubGV& membGV;
};
#endif /* DUNE_AX1_ACME2_SETUP_HH */
| 48.82266
| 118
| 0.633908
|
pederpansen
|
5c82413d5761ffbcb270d723db59c0aae19fb02d
| 1,573
|
cpp
|
C++
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 1,566
|
2016-12-20T15:31:04.000Z
|
2022-03-31T18:17:34.000Z
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 620
|
2017-01-06T13:53:35.000Z
|
2022-03-31T12:05:50.000Z
|
tests/statement_serializator_tests/arithmetic_operators.cpp
|
tstrutz/sqlite_orm
|
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
|
[
"BSD-3-Clause"
] | 274
|
2017-01-07T05:34:24.000Z
|
2022-03-27T18:22:47.000Z
|
#include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
using namespace sqlite_orm;
TEST_CASE("statement_serializator arithmetic operators") {
internal::serializator_context_base context;
SECTION("add") {
std::string value;
SECTION("func") {
value = serialize(add(3, 5), context);
}
SECTION("operator") {
value = serialize(c(3) + 5, context);
}
REQUIRE(value == "(3 + 5)");
}
SECTION("sub") {
std::string value;
SECTION("func") {
value = serialize(sub(5, -9), context);
}
SECTION("operator") {
value = serialize(c(5) - -9, context);
}
REQUIRE(value == "(5 - -9)");
}
SECTION("mul") {
std::string value;
SECTION("func") {
value = serialize(mul(10, 0.5), context);
}
SECTION("operator") {
value = serialize(c(10) * 0.5, context);
}
REQUIRE(value == "(10 * 0.5)");
}
SECTION("div") {
std::string value;
SECTION("func") {
value = serialize(sqlite_orm::div(10, 2), context);
}
SECTION("operator") {
value = serialize(c(10) / 2, context);
}
REQUIRE(value == "(10 / 2)");
}
SECTION("mod") {
std::string value;
SECTION("func") {
value = serialize(mod(20, 3), context);
}
SECTION("operator") {
value = serialize(c(20) % 3, context);
}
REQUIRE(value == "(20 % 3)");
}
}
| 26.661017
| 63
| 0.479975
|
tstrutz
|
5c84be2240a447f3a324bf46e131da0f9d3bbce4
| 263
|
cpp
|
C++
|
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
Code full house/buoi19 nguyen dinh trung duc/bai1146A.cpp
|
ducyb2001/CbyTrungDuc
|
0e93394dce600876a098b90ae969575bac3788e1
|
[
"Apache-2.0"
] | null | null | null |
/*bai 1146A*/
#include<stdio.h>
#include<string.h>
int main(){
char c[100];
scanf("%s",c);
int i,cnt=0;
int len=strlen(c);
for(i=0; i<len;i++){
if((c[i]-'a')==0) cnt++;
}
if(cnt>(len/2)){
printf("%d",len);
return 0;
}
else printf("%d",2*cnt-1);
}
| 13.842105
| 27
| 0.528517
|
ducyb2001
|
5c867d124d49f0d0a622157b48250bf937968b74
| 5,186
|
cc
|
C++
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-02-18T06:12:13.000Z
|
2021-02-18T06:12:13.000Z
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-08-28T14:08:30.000Z
|
2021-08-28T14:09:32.000Z
|
tools/graft/graft.cc
|
fcharlie/git-analyze-sync
|
1c974ac4b6f695c01ee666aff60d7817f6c0acaf
|
[
"MIT"
] | 1
|
2021-08-28T14:00:29.000Z
|
2021-08-28T14:00:29.000Z
|
/// THIS IS GRAFT COMMAND
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>
#include <argv.hpp>
#include <git.hpp>
#include <optional>
#include <console.hpp>
#include <os.hpp>
struct graft_info_t {
std::string gitdir{"."};
std::string branch;
std::string commitid;
std::string message;
};
void PrintUsage() {
const char *ua = R"(OVERVIEW: git-graft
Usage: git-graft [options] <input>
OPTIONS:
-h [--help] print git-graft usage information and exit
-b [--branch] new branch name.
-d [--git-dir] repository path.
-m [--message] commit message
Example:
git-graft commit-id -m "message"
)";
printf("%s", ua);
}
bool parse_argv(int argc, char **argv, graft_info_t &gf) {
av::ParseArgv pv(argc, argv);
pv.Add("help", av::no_argument, 'h')
.Add("git-dir", av::required_argument, 'd')
.Add("message", av::required_argument, 'm')
.Add("branch", av::required_argument, 'b');
av::error_code ec;
auto result = pv.Execute(
[&](int ch, const char *optarg, const char *raw) {
switch (ch) {
case 'h':
PrintUsage();
exit(0);
break;
case 'b':
gf.branch = optarg;
break;
case 'm':
gf.message = optarg;
break;
case 'd':
gf.gitdir = optarg;
break;
default:
printf("Error Argument: %s\n", raw != nullptr ? raw : "unknown");
return false;
}
return true;
},
ec);
if (!result && ec.ec != av::SkipParse) {
aze::FPrintF(stderr, "ParseArgv: %s\n", ec.message);
return false;
}
if (pv.UnresolvedArgs().size() < 1) {
PrintUsage();
return false;
}
gf.commitid = pv.UnresolvedArgs()[0];
return true;
}
class SignatureSaver {
public:
SignatureSaver() = default;
SignatureSaver(const SignatureSaver &) = delete;
SignatureSaver &operator=(const SignatureSaver &) = delete;
void InitializeEnv() {
name = os::GetEnv("GIT_COMMITTER_NAME");
email = os::GetEnv("GIT_COMMITTER_EMAIL");
aname = os::GetEnv("GIT_AUTHOR_NAME");
aemail = os::GetEnv("GIT_AUTHOR_NAME");
}
void UpdateCommiter(git_signature *sig, const git_signature *old) {
sig->email = email.empty() ? old->email : email.data();
sig->name = name.empty() ? old->name : name.data();
sig->when = old->when;
}
void UpdateAuthor(git_signature *sig, const git_signature *old) {
sig->email = aemail.empty() ? old->email : aemail.data();
sig->name = aname.empty() ? old->name : aname.data();
sig->when = old->when;
}
private:
std::string name;
std::string email;
std::string aname;
std::string aemail;
};
void dump_error() {
auto ec = giterr_last();
if (ec != nullptr) {
aze::FPrintF(stderr, "%s\n", ec->message);
}
}
std::optional<std::string> make_refname(git::repository &r,
std::string_view sv) {
if (!sv.empty()) {
return std::make_optional(absl::StrCat("refs/heads/", sv));
}
auto ref = r.get_reference("HEAD");
if (!ref) {
return std::nullopt;
}
auto dr = ref->symbolic_target();
if (!dr) {
return std::nullopt;
}
auto p = git_reference_name(dr->p());
if (p != nullptr) {
return std::make_optional(p);
}
return std::nullopt;
}
bool graft_commit(const graft_info_t &gf) {
git::error_code ec;
auto repo = git::repository::make_repository_ex(gf.gitdir, ec);
if (!repo) {
aze::FPrintF(stderr, "Error: %s\n", ec.message);
return false;
}
auto commit = repo->get_commit(gf.commitid);
if (!commit) {
aze::FPrintF(stderr, "open commit: %s ", gf.commitid);
dump_error();
return false;
}
auto refname = make_refname(*repo, gf.branch);
if (!refname) {
aze::FPrintF(stderr, "unable lookup branch name\n");
return false;
}
auto parent = repo->get_reference_commit(*refname);
if (!parent) {
aze::FPrintF(stderr, "open par commit: %s ", gf.branch);
dump_error();
return false;
}
///
git_tree *tree = nullptr;
if (git_commit_tree(&tree, commit->p()) != 0) {
dump_error();
return false;
}
git_signature author, committer;
SignatureSaver saver;
saver.InitializeEnv();
saver.UpdateAuthor(&author, git_commit_author(commit->p()));
saver.UpdateCommiter(&committer, git_commit_committer(commit->p()));
std::string msg =
gf.message.empty() ? git_commit_message(commit->p()) : gf.message;
const git_commit *parents[] = {parent->p(), commit->p()};
aze::FPrintF(stderr, "New commit, message: '%s'\n", msg);
git_oid oid;
if (git_commit_create(&oid, repo->p(), refname->c_str(), &author, &committer,
nullptr, msg.c_str(), tree, 2, parents) != 0) {
dump_error();
git_tree_free(tree);
return false;
}
fprintf(stderr, "New commit id: %s\n", git_oid_tostr_s(&oid));
git_tree_free(tree);
return true;
}
int cmd_main(int argc, char **argv) {
git::global_initializer_t gi;
graft_info_t gf;
if (!parse_argv(argc, argv, gf)) {
return 1;
}
if (!graft_commit(gf)) {
return 1;
}
return 0;
}
| 26.324873
| 79
| 0.599306
|
fcharlie
|
5c882414a57083cd60b3f99239924d5285baf426
| 1,315
|
cpp
|
C++
|
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
monitor.cpp
|
n7jti/Freezer-Monitor-AWS-SNS
|
3eeb19135582839ae84943cfd0310a6b22a11853
|
[
"MIT"
] | null | null | null |
// monitor.cpp
#include <arduino.h>
#include "monitor.h"
Monitor::Monitor(Trigger *trigger, unsigned int timeout)
: _trigger(trigger)
, _timeout(timeout)
, _state(MONITOR_GREEN)
, _stateStartMs(millis())
{
}
bool Monitor::begin()
{
return _trigger->begin();
}
MONITOR_STATE Monitor::getState()
{
return _state;
}
unsigned int Monitor::getStateElapsedMs()
{
return millis() - _stateStartMs;
}
MONITOR_STATE Monitor::run()
{
unsigned int now = millis();
unsigned int elapsed = now - _stateStartMs;
bool triggered = _trigger->isTriggered();
switch(_state)
{
case MONITOR_RED:
if (triggered == false)
{
_stateStartMs = now;
_state = MONITOR_GREEN;
}
break;
case MONITOR_YELLOW:
if (triggered == false)
{
_stateStartMs = now;
_state = MONITOR_GREEN;
}
else if (elapsed > _timeout)
{
_state = MONITOR_RED;
}
break;
case MONITOR_GREEN:
if (triggered == true)
{
_stateStartMs = now;
_state = MONITOR_YELLOW;
}
break;
}
return _state;
}
int Monitor::getStatus(char* buffer, int length)
{
return _trigger->getStatus(buffer, length);
}
| 18.785714
| 57
| 0.571103
|
n7jti
|
5c8f9c5ab8dcad47af31d168f5086a6febef5480
| 633
|
cpp
|
C++
|
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | 1
|
2021-02-09T11:38:51.000Z
|
2021-02-09T11:38:51.000Z
|
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | null | null | null |
leetcode/844. Backspace String Compare/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | null | null | null |
// OJ: https://leetcode.com/problems/backspace-string-compare/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
private:
int normalize(string &S) {
int length = 0;
for (char c : S) {
if (c == '#') {
if (length) --length;
} else S[length++] = c;
}
return length;
}
public:
bool backspaceCompare(string S, string T) {
int s = normalize(S), t = normalize(T);
if (s != t) return false;
for (int i = 0; i < s; ++i) {
if (S[i] != T[i]) return false;
}
return true;
}
};
| 25.32
| 62
| 0.478673
|
contacttoakhil
|
5c97bbc3bf52ba514bb696920cb6b0b0f6d832af
| 4,904
|
hpp
|
C++
|
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 49
|
2018-05-09T23:17:45.000Z
|
2021-07-21T10:05:19.000Z
|
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | null | null | null |
include/argot/case/detail/as_constant.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 2
|
2019-08-04T03:51:36.000Z
|
2020-12-28T06:53:29.000Z
|
/*==============================================================================
Copyright (c) 2017, 2018 Matt Calabrese
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)
==============================================================================*/
#ifndef ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
#define ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
#include <argot/case/detail/cast_value_list_elements.hpp>
#include <argot/concepts/argument_receiver.hpp> // of
#include <argot/concepts/case_labels.hpp>
#include <argot/concepts/persistent_switch_body_case.hpp>
#include <argot/concepts/switch_body.hpp>
#include <argot/concepts/switch_body_case.hpp>
#include <argot/concepts/true.hpp>
#include <argot/detail/constant.hpp>
#include <argot/detail/unreachable.hpp>
#include <argot/detail/forward.hpp>
#include <argot/gen/access_raw_concept_map.hpp>
#include <argot/gen/concept_assert.hpp>
#include <argot/gen/requires.hpp>
#include <argot/receiver_traits/argument_list_kinds.hpp>
#include <argot/receiver_traits/argument_types.hpp>
#include <argot/receiver_traits/receive.hpp>
#include <argot/value_list.hpp>
#include <argot/value_zipper.hpp>
namespace argot {
namespace case_detail {
template< class Cases >
struct as_constant_t {};
template< class Values >
struct values_to_integral_constant_argument_list_kinds;
template< auto... Values >
struct values_to_integral_constant_argument_list_kinds
< value_list_t< Values... > >
{
using type
= receiver_traits::argument_list_kinds_t
< receiver_traits::argument_types_t
< call_detail::constant< Values >&& >...
>;
};
template< class Values >
using values_to_integral_constant_argument_list_kinds_t
= typename values_to_integral_constant_argument_list_kinds< Values >::type;
} // namespace argot(::case_detail)
template< class Cases >
struct make_concept_map< SwitchBody< case_detail::as_constant_t< Cases > > >
{
// TODO(mattcalabrese) Don't access raw
using case_values_t
= typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t;
template< template< auto... > class Template >
using expand_case_values_t
= typename access_raw_concept_map< CaseLabels< Cases > >
::template expand_case_values_t< Template >;
};
// TODO(mattcalabrese) Constrain
template< class Cases, auto Value >
struct make_concept_map
< SwitchBodyCase< case_detail::as_constant_t< Cases >, Value >
, ARGOT_REQUIRES
( True
< value_zipper_contains_v
< case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>
, Value
>
>
)
<>
>
{
private:
using typed_value_list
= case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>;
using partition = value_zipper_find_t< typed_value_list, Value >;
public:
using leading_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::leading_t >;
using trailing_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::trailing_t >;
// TODO(mattcalabrese) Constrain
template< class Receiver >
static constexpr decltype( auto ) provide_isolated_case
( case_detail::as_constant_t< Cases > self, Receiver&& rec )
{
return receiver_traits::receive
( ARGOT_FORWARD( Receiver )( rec )
, std::integral_constant< detail_argot::remove_cvref_t< decltype( Value ) >, Value >()
);
}
};
// TODO(mattcalabrese) Constrain
template< class Cases, auto Value >
struct make_concept_map
< PersistentSwitchBodyCase< case_detail::as_constant_t< Cases >, Value > >
{
private:
using typed_value_list
= case_detail::cast_value_list_elements_t
< decltype( Value )
, typename access_raw_concept_map< CaseLabels< Cases > >::case_values_t
>;
using partition = value_zipper_find_t< typed_value_list, Value >;
public:
using leading_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::leading_t >;
using trailing_argument_list_kinds_t
= case_detail::values_to_integral_constant_argument_list_kinds_t
< typename partition::trailing_t >;
// TODO(mattcalabrese) Constrain
template< class Receiver >
static constexpr decltype( auto ) provide_isolated_case
( case_detail::as_constant_t< Cases > self, Receiver&& rec )
{
// TODO(mattcalabrese) Use constant
return receiver_traits::receive
( ARGOT_FORWARD( Receiver )( rec )
, std::integral_constant< detail_argot::remove_cvref_t< decltype( Value ) >, Value >()
);
}
};
} // namespace argot
#endif // ARGOT_CASE_DETAIL_AS_CONSTANT_HPP_
| 31.844156
| 90
| 0.727977
|
mattcalabrese
|
5c9a2e881e4074428205f84ee26402159f5a20a7
| 5,794
|
hpp
|
C++
|
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | 1
|
2022-01-13T01:03:55.000Z
|
2022-01-13T01:03:55.000Z
|
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
INCLUDE/Vcl/dblocal.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
// Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'DBLocal.pas' rev: 6.00
#ifndef DBLocalHPP
#define DBLocalHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <Provider.hpp> // Pascal unit
#include <DBClient.hpp> // Pascal unit
#include <SqlTimSt.hpp> // Pascal unit
#include <Midas.hpp> // Pascal unit
#include <DBCommon.hpp> // Pascal unit
#include <DB.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Variants.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Dblocal
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TSqlDBType { typeDBX, typeBDE, typeADO, typeIBX };
#pragma option pop
class DELPHICLASS TCustomCachedDataSet;
class PASCALIMPLEMENTATION TCustomCachedDataSet : public Dbclient::TCustomClientDataSet
{
typedef Dbclient::TCustomClientDataSet inherited;
private:
Provider::TDataSetProvider* FProvider;
TSqlDBType FSqlDBType;
Provider::TBeforeUpdateRecordEvent __fastcall GetBeforeUpdateRecord();
void __fastcall SetBeforeUpdateRecord(Provider::TBeforeUpdateRecordEvent Value);
Provider::TAfterUpdateRecordEvent __fastcall GetAfterUpdateRecord();
void __fastcall SetAfterUpdateRecord(Provider::TAfterUpdateRecordEvent Value);
Provider::TGetTableNameEvent __fastcall GetOnGetTableName();
void __fastcall SetOnGetTableName(Provider::TGetTableNameEvent Value);
Provider::TProviderDataEvent __fastcall GetOnUpdateData();
void __fastcall SetOnUpdateData(Provider::TProviderDataEvent Value);
Provider::TResolverErrorEvent __fastcall GetOnUpdateError();
void __fastcall SetOnUpdateError(Provider::TResolverErrorEvent Value);
protected:
virtual void __fastcall CloseCursor(void);
virtual AnsiString __fastcall GetCommandText();
Provider::TProviderOptions __fastcall GetOptions(void);
Db::TUpdateMode __fastcall GetUpdateMode(void);
virtual void __fastcall SetActive(bool Value);
virtual void __fastcall SetAggregates(Dbclient::TAggregates* Value);
virtual void __fastcall SetCommandText(AnsiString Value);
void __fastcall SetOptions(Provider::TProviderOptions Value);
void __fastcall SetUpdateMode(Db::TUpdateMode Value);
__property Provider::TDataSetProvider* Provider = {read=FProvider, write=FProvider};
__property TSqlDBType SqlDBType = {read=FSqlDBType, write=FSqlDBType, nodefault};
public:
__fastcall virtual TCustomCachedDataSet(Classes::TComponent* AOwner);
__fastcall virtual ~TCustomCachedDataSet(void);
HIDESBASE void __fastcall LoadFromFile(const AnsiString AFileName = "");
__published:
__property Active = {default=0};
__property CommandText ;
__property Aggregates ;
__property AggregatesActive = {default=0};
__property AutoCalcFields = {default=1};
__property Constraints = {stored=ConstraintsStored};
__property DisableStringTrim = {default=0};
__property FetchOnDemand = {default=1};
__property FieldDefs ;
__property FileName ;
__property Filter ;
__property Filtered = {default=0};
__property FilterOptions = {default=0};
__property IndexDefs ;
__property IndexFieldNames ;
__property IndexName ;
__property MasterFields ;
__property MasterSource ;
__property Provider::TProviderOptions Options = {read=GetOptions, write=SetOptions, default=0};
__property ObjectView = {default=1};
__property PacketRecords = {default=-1};
__property Params ;
__property ReadOnly = {default=0};
__property Db::TUpdateMode UpdateMode = {read=GetUpdateMode, write=SetUpdateMode, default=0};
__property BeforeOpen ;
__property AfterOpen ;
__property BeforeClose ;
__property AfterClose ;
__property BeforeInsert ;
__property AfterInsert ;
__property BeforeEdit ;
__property AfterEdit ;
__property BeforePost ;
__property AfterPost ;
__property BeforeCancel ;
__property AfterCancel ;
__property BeforeDelete ;
__property AfterDelete ;
__property BeforeScroll ;
__property AfterScroll ;
__property BeforeRefresh ;
__property AfterRefresh ;
__property OnCalcFields ;
__property OnDeleteError ;
__property OnEditError ;
__property OnFilterRecord ;
__property OnNewRecord ;
__property OnPostError ;
__property OnReconcileError ;
__property BeforeApplyUpdates ;
__property AfterApplyUpdates ;
__property BeforeGetRecords ;
__property AfterGetRecords ;
__property BeforeRowRequest ;
__property AfterRowRequest ;
__property BeforeExecute ;
__property AfterExecute ;
__property BeforeGetParams ;
__property AfterGetParams ;
__property Provider::TBeforeUpdateRecordEvent BeforeUpdateRecord = {read=GetBeforeUpdateRecord, write=SetBeforeUpdateRecord};
__property Provider::TAfterUpdateRecordEvent AfterUpdateRecord = {read=GetAfterUpdateRecord, write=SetAfterUpdateRecord};
__property Provider::TGetTableNameEvent OnGetTableName = {read=GetOnGetTableName, write=SetOnGetTableName};
__property Provider::TProviderDataEvent OnUpdateData = {read=GetOnUpdateData, write=SetOnUpdateData};
__property Provider::TResolverErrorEvent OnUpdateError = {read=GetOnUpdateError, write=SetOnUpdateError};
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Dblocal */
using namespace Dblocal;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // DBLocal
| 38.626667
| 127
| 0.746634
|
earthsiege2
|
5ca36a3257ea70050ddcc68b9a46f3ad7cd8660b
| 479
|
cpp
|
C++
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 7
|
2015-03-10T03:36:16.000Z
|
2021-11-05T01:16:58.000Z
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 1
|
2020-06-23T10:02:33.000Z
|
2020-06-24T02:05:47.000Z
|
MonoNative.Tests/mscorlib/System/mscorlib_System_IDisposable_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | null | null | null |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System
// Name: IDisposable
// C++ Typed Name: mscorlib::System::IDisposable
#include <gtest/gtest.h>
#include <mscorlib/System/mscorlib_System_IDisposable.h>
namespace mscorlib
{
namespace System
{
//Public Methods Tests
// Method Dispose
// Signature:
TEST(mscorlib_System_IDisposable_Fixture,Dispose_Test)
{
}
}
}
| 15.451613
| 88
| 0.716075
|
brunolauze
|
5ca6e5bcac7c9d5625a7186af86632f2520fbd60
| 498
|
hpp
|
C++
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 6,792
|
2017-03-27T19:05:19.000Z
|
2022-03-31T20:21:26.000Z
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 764
|
2017-05-22T18:48:53.000Z
|
2022-03-31T22:04:27.000Z
|
src/entt/container/fwd.hpp
|
pgruenbacher/entt
|
2f06d1ce3c99c49ef61d7bc2080a16cdaa08e3ef
|
[
"MIT"
] | 811
|
2017-03-27T19:52:48.000Z
|
2022-03-30T11:32:57.000Z
|
#ifndef ENTT_CONTAINER_FWD_HPP
#define ENTT_CONTAINER_FWD_HPP
#include <functional>
#include <memory>
namespace entt {
template<
typename Key, typename Type,
typename = std::hash<Key>,
typename = std::equal_to<Key>,
typename = std::allocator<std::pair<const Key, Type>>>
class dense_hash_map;
template<
typename Type,
typename = std::hash<Type>,
typename = std::equal_to<Type>,
typename = std::allocator<Type>>
class dense_hash_set;
} // namespace entt
#endif
| 19.153846
| 58
| 0.704819
|
pgruenbacher
|
5cb857f907b589bbfea31f9fc79c3dbc46b0dcfd
| 1,006
|
hpp
|
C++
|
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
src/XmlNya.hpp
|
Akela1101/nya_qt
|
a305158af3a764b6856d977f4d95fa2c5649793c
|
[
"MIT"
] | null | null | null |
#ifndef XMLNYA_H
#define XMLNYA_H
/*
Usage:
while( ss.ReadNextChild() )
{
QStringRef s = ss.name();
if( s == "a1" ) a1 = ss.ReadElement().toLatin1();
else if( s == "a2" ) a2 = ss.ReadElement().toDouble();
// ...
else ss.SkipElement();
}
*/
#include <QXmlStreamReader>
#include <QHash>
typedef QXmlStreamReader::TokenType XmlType;
typedef QHash<QString, QString> AttrsType;
namespace nya
{
class XmlReader : public QXmlStreamReader
{
public:
static QString ToFormatted(char* data);
static QString ToHumanReadable(char* data);
using QXmlStreamReader::QXmlStreamReader;
bool ReadNextChild()
{
auto tt = readNext();
if (tt == TokenType::Characters) tt = readNext(); // skip '\n' and other trash
return tt == TokenType::StartElement;
}
inline QString ReadElement() { return readElementText(QXmlStreamReader::IncludeChildElements); }
inline void SkipElement() { readElementText(QXmlStreamReader::IncludeChildElements); }
AttrsType GetAttributes();
};
}
#endif // XMLNYA_H
| 21.404255
| 97
| 0.709742
|
Akela1101
|
5cba5821036a75b51b930ef28ed3d58167ff16a5
| 3,802
|
cpp
|
C++
|
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
volume_II/acm_1103.cpp
|
raidenluikang/acm.timus.ru
|
9b7c99eb03959acff9dd96326eec642a2c31ed04
|
[
"MIT"
] | null | null | null |
/* acm.timus.ru 1103. Pencils and Circles
*
* Strategy:
* Pick two points on the convex hull of the point set. If we form a circle with some other point,
* the largest such circle will encompass all points, the second largest will encompass all points
* except for one, etc. The angle formed by the two static points and the third that we pick will
* be inversely proportional to the radius of the circle that they form (the specific location of
* the third point on the circle does not affect the angle), so we find the median biggest angle
* out of all angles that we can form accordingly, and use the points constituting that circle as
* the answer.
*
* Performance:
* O(n), runs the test suite in 0.001s using 448KB memory.
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
struct point
{
int x;
int y;
};
typedef point vector;
vector operator - (point a, point b)
{
vector result = {a.x - b.x, a.y - b.y };
return result;
}
point operator + (point a, vector v)
{
point result = {a.x + v.x, a.y + v.y };
return result;
}
point operator * (point a, int k)
{
point result = {a.x * k, a.y * k };
return result;
}
long long operator * (vector a, vector b)
{
return a.x * 1ll * b.x + a.y * 1ll * b.y;
}
long long operator ^ (vector a, vector b)
{
return a.x * 1ll * b.y - a.y * 1ll * b.x;
}
struct cmp_point
{
bool operator()(point a, point b)const
{
return ( a.x < b.x ) || ( a.x == b.x && a.y < b.y ) ;
}
};
double dist(vector v)
{
return sqrt( v * v + 0.0);
}
struct scanner
{
char const* o;
char in[131072];
void init()
{
o = in;
in[fread(in,1,sizeof(in),stdin)] = 0;
}
int readInt()
{
unsigned u = 0, s = 0;
while(*o && *o <= 32)++o;
if (*o == '-') s= ~0u, ++o; else if (*o == '+')++o;
while(*o>='0') u = (u << 3) + (u << 1) + (*o++ - '0');
return (u ^ s) + !!s;
}
} sc ;
int n;
point p[ 5000 + 8 ];
struct angle
{
double cos_;
int i;
}angles[5000 + 8];
struct cmp_angle
{
// angle > 0 angle < 180
// cos(angle) = -1 .. +1
//
bool operator ()(angle a, angle b)const{ return a.cos_ > b.cos_ ; }
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
//I. readData.
// ---------------------------------------------------------------
sc.init();
n = sc.readInt();
for(int i= 0; i != n; ++i)
{
p[i].x = sc.readInt();
p[i].y = sc.readInt();
}
// -----------------------------------------------------------------
// II. find first point: minimum element.
// swap minimum with first point
{
point * pm = std::min_element(p, p + n, cmp_point());
std::swap( *pm, p[ 0 ] ) ;
}
point pa = p[ 0 ];
for(int i = 0; i < n ;++i)
p[ i ] = p[ i ] - pa;
// III. find second point: most right point than pa.
for(int i = 2; i < n; ++i)
{
if ( ( p[ i ] ^ p[ 1 ] ) >= 0 )
std::swap( p[ i ], p[ 1 ] );
}
point pb = p[ 1 ] ;
for(int i = 0; i < n - 2; ++i)
{
angles[i].i = 2 + i;
vector v = p[ i + 2 ];
vector u = p[ i + 2 ] - pb;
angles[i].cos_ = ( v * u ) / dist( u ) / dist( v );
}
std::nth_element(angles, angles + ( n - 2 ) / 2, angles + (n-2), cmp_angle() );
point pc = p[ angles[( n - 2 ) / 2 ].i ] ;
{
point ra = pa;
point rb = pb + pa;
point rc = pc + pa;
printf("%d %d\n", ra.x, ra.y ) ;
printf("%d %d\n", rb.x, rb.y ) ;
printf("%d %d\n", rc.x, rc.y ) ;
}
}
| 21.480226
| 98
| 0.477117
|
raidenluikang
|
5cc12a461f6665742765d93cfcce70a8df291a5f
| 17,569
|
hpp
|
C++
|
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | null | null | null |
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | 1
|
2021-01-31T11:20:44.000Z
|
2021-02-01T00:16:53.000Z
|
delaunay.hpp
|
GoldFeniks/delaunay
|
a96621d28a57bd6c73fbecf0ae5347714a3ed07e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <list>
#include <tuple>
#include <cmath>
#include <limits>
#include <vector>
#include <cstddef>
#include <utility>
#include <algorithm>
template<typename T>
class delaunay_triangulation {
private:
class edge;
class point;
class triangle;
template<typename V>
class data_value_wrapper;
public:
delaunay_triangulation() : _first_triangle(&_triangles, 0) {}
template<typename VX, typename VY>
delaunay_triangulation(const VX& x, const VY& y) : _first_triangle(&_triangles, 0) {
if (x.size() < 3)
throw std::runtime_error("At least 3 points are required for triangulation");
if (x.size() != y.size())
throw std::runtime_error("The number of x and y coordinates must match");
_points.reserve(x.size());
for (size_t i = 0; i < x.size(); ++i)
_points.emplace_back(x[i], y[i]);
triangulate();
}
delaunay_triangulation(const delaunay_triangulation& other) : _first_triangle(&_triangles, 0) {
*this = other;
}
delaunay_triangulation(delaunay_triangulation&& other) : _first_triangle(&_triangles, 0) {
*this = std::move(other);
}
auto& operator=(const delaunay_triangulation& other) {
_edges = other._edges;
_points = other._points;
_triangles = other._triangles;
_reassign_data();
return *this;
}
auto& operator=(delaunay_triangulation&& other) noexcept {
_edges = std::move(other._edges);
_points = std::move(other._points);
_triangles = std::move(other._triangles);
_reassign_data();
return *this;
}
const auto& edges() const {
return _edges;
}
const auto& points() const {
return _points;
}
const auto& triangles() const {
return _triangles;
}
const auto find_triangle(const T& x, const T& y) const {
return find_triangle({x, y});
}
const auto find_triangle(const point& p) const {
return find_triangle(_first_triangle, p);
}
const auto find_triangle(const data_value_wrapper<triangle>& t, const T& x, const T& y) const {
return find_triangle(t, {x, y});
}
const auto find_triangle(const data_value_wrapper<triangle>& t, const point& p) const {
return _find_triangle(t, p);
}
private:
const data_value_wrapper<triangle> _first_triangle;
std::vector<edge> _edges;
std::vector<point> _points;
std::vector<triangle> _triangles;
void _reassign_data() {
for (auto& it : _edges) {
it.a._data = &_points;
it.b._data = &_points;
it.t1._data = &_triangles;
if (it.t2.is_valid())
it.t2._data = &_triangles;
}
for (auto& it : _triangles) {
it.a._data = &_edges;
it.b._data = &_edges;
it.c._data = &_edges;
}
}
static constexpr auto eps = T(1e-8);
template<typename V>
class data_value_wrapper {
public:
data_value_wrapper() = default;
data_value_wrapper(std::vector<V>* data, const int64_t index) : _data(data), _index(index) {}
bool operator==(const data_value_wrapper<V>& other) const {
return _index == other._index;
}
bool operator!=(const data_value_wrapper<V>& other) const {
return !(*this == other);
}
bool is_valid() const {
return _data != nullptr;
}
const auto& get() const {
return (*_data)[_index];
}
auto& get() {
return (*_data)[_index];
}
const auto& index() const {
return _index;
}
private:
int64_t _index = -1;
std::vector<V>* _data = nullptr;
friend class delaunay_triangulation;
};
struct point {
T x, y;
point() = default;
point(T x, T y) : x(std::move(x)), y(std::move(y)) {}
};
struct edge {
data_value_wrapper<point> a, b;
data_value_wrapper<triangle> t1, t2;
edge(data_value_wrapper<point> a, data_value_wrapper<point> b) : a(std::move(a)), b(std::move(b)) {}
void flip() {
std::swap(a, b);
}
};
class triangle {
public:
data_value_wrapper<edge> a, b, c;
triangle(data_value_wrapper<edge> a, data_value_wrapper<edge> b, data_value_wrapper<edge> c) :
a(std::move(a)), b(std::move(b)), c(std::move(c)) {}
void rearrange(const data_value_wrapper<edge>& e) {
if (e == b)
std::swap(a, b);
else if (e == c)
std::swap(a, c);
_flip_edges(e.get().b, b, c);
}
auto barycentric_coordinates(const point& p) const {
const auto& [a, b, c] = get_points();
const auto v0x = a.x - c.x;
const auto v0y = a.y - c.y;
const auto v1x = b.x - c.x;
const auto v1y = b.y - c.y;
const auto v2x = p.x - c.x;
const auto v2y = p.y - c.y;
const auto den = T(1) / (v1y * v0x - v1x * v0y);
const auto v = (v1y * v2x - v1x * v2y) * den;
const auto w = (v0x * v2y - v0y * v2x) * den;
return std::make_tuple(v, w, T(1) - v - w);
}
auto points() const {
const auto& p0 = a.get().a;
const auto& p1 = a.get().b;
const auto& p2 = b.get().a;
if (p0 != p2 && p1 != p2)
return std::tie(p0, p1, p2);
return std::tie(p0, p1, b.get().b);
}
auto get_points() const {
const auto& [a, b, c] = points();
return std::tie(a.get(), b.get(), c.get());
}
bool contains_point(const point& p) const {
const auto& [a, b, c] = get_points();
const auto d1 = _sign(p, a, b);
const auto d2 = _sign(p, b, c);
const auto d3 = _sign(p, c, a);
const auto neg = (d1 < -eps) || (d2 < -eps) || (d3 < -eps);
const auto pos = (d1 > eps) || (d2 > eps) || (d3 > eps);
return !(neg && pos);
}
private:
static void _flip_edges(const data_value_wrapper<point>& p, data_value_wrapper<edge>& a, data_value_wrapper<edge>& b) {
auto& ag = a.get();
auto& bg = b.get();
if (p == ag.b)
ag.flip();
else if (p == bg.a)
std::swap(a, b);
else if (p == bg.b) {
bg.flip();
std::swap(a, b);
}
if (a.get().b != b.get().a)
b.get().flip();
}
static auto _sign(const point& a, const point& b, const point& c) {
return (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y);
}
};
void triangulate() {
const auto p0 = data_value_wrapper(&_points, 0);
const auto& p0g = p0.get();
std::vector<std::pair<T, data_value_wrapper<point>>> points;
points.reserve(_points.size() - 1);
for (size_t i = 0; i < _points.size() - 1; ++i)
points.emplace_back(_norm(p0g, _points[i + 1]), data_value_wrapper(&_points, i + 1));
std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
auto p1 = points[0].second;
const auto& p1g = p1.get();
auto p2 = points[1].second;
size_t di = 1;
auto [r, c] = _circle_center(p0g, p1g, p2.get());
for (size_t i = 2; i < points.size(); ++i) {
const auto [cr, cc] = _circle_center(p0g, p1g, points[i].second.get());
if (cr < r) {
r = cr;
c = cc;
p2 = points[i].second;
di = i;
}
}
points.erase(points.begin() + di);
if (_is_clockwise(p0g, p1g, p2.get()))
std::swap(p1, p2);
for (size_t i = 1; i < points.size(); ++i)
points[i].first = _norm(c, points[i].second.get());
std::sort(points.begin() + 1, points.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
auto e0 = _add_edge(p0, p1);
auto e1 = _add_edge(p1, p2);
auto e2 = _add_edge(p2, p0);
_add_triangle(e0, e1, e2);
std::list<data_value_wrapper<edge>> hull;
hull.push_back(e0);
hull.push_back(e1);
hull.push_back(e2);
for (size_t i = 1; i < points.size(); ++i) {
const auto& p = points[i].second;
auto& e = hull.front();
const auto buff = !_is_clockwise(e.get().a.get(), e.get().b.get(), p.get());
auto a = _find_first(++hull.begin(), p.get(), buff);
auto b = _find_first(hull.rbegin(), p.get(), buff).base();
if (!buff) {
if (b == hull.end()) {
auto t = _add_triangle(hull.front(), p);
e0 = t.get().a;
e1 = t.get().b;
_add_triangles(e1, ++hull.begin(), a);
} else {
auto t = _add_triangle(*b, p);
e0 = t.get().a;
e1 = t.get().b;
auto d = b;
_add_triangles(e1, ++d, hull.end());
_add_triangles(e1, hull.begin(), a);
hull.erase(b, hull.end());
}
a = hull.erase(hull.begin(), a);
} else {
auto t = _add_triangle(*a, p);
e0 = t.get().a;
e1 = t.get().b;
auto d = a;
_add_triangles(e1, ++d, b);
a = hull.erase(a, b);
}
hull.insert(a, {e0, e1});
}
_flip_triangles();
}
static auto _norm(const point& a, const point& b) {
return std::pow(a.x - b.x, 2) + std::pow(a.y - b.y, 2);
}
static auto _circle_center(const point& a, const point& b, const point& c) {
const auto& [x0, y0] = a;
const auto& [x1, y1] = b;
const auto& [x2, y2] = c;
if (std::abs((y0 - y1) * (x0 - x2) - (y0 - y2) * (x0 - x1)) < eps)
return std::make_tuple(std::numeric_limits<T>::infinity(), point(0, 0));
const auto y01 = y0 - y1;
const auto y02 = y0 - y2;
const auto y12 = y1 - y2;
const auto sx0 = std::pow(x0, 2);
const auto sx1 = std::pow(x1, 2);
const auto sx2 = std::pow(x2, 2);
const auto sy0 = std::pow(y0, 2);
const auto sy1 = std::pow(y1, 2);
const auto sy2 = std::pow(y2, 2);
const auto x = (sx2 * -y01 + sx1 * y02 - (sx0 + y01 * y02) * y12) / (T(2) * (x2 * -y01 + x1 * y02 + x0 * -y12));
const auto y = (-sx1 * x2 + sx0 * (x2 - x1) + x2 * y01 * (y0 + y1) + x0 * (sx1 - sx2 + sy1 - sy2) + x1 * (sx2 - sy0 + sy2)) /
(T(2) * (x2 * y01 + x0 * y12 + x1 * -y02));
const auto p = point(x, y);
return std::make_tuple(_norm(a, p), p);
}
static auto _is_clockwise(const point& a, const point& b, const point& c) {
const auto& [x0, y0] = a;
const auto& [x1, y1] = b;
const auto& [x2, y2] = c;
return x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1) < -eps;
}
auto _add_edge(const data_value_wrapper<point>& a, const data_value_wrapper<point>& b) {
_edges.emplace_back(a, b);
return data_value_wrapper(&_edges, _edges.size() - 1);
}
auto _add_triangle(data_value_wrapper<edge>& a, data_value_wrapper<edge>& b, data_value_wrapper<edge>& c) {
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t1 = res;
b.get().t1 = res;
c.get().t1 = res;
return res;
}
auto _add_triangle(data_value_wrapper<edge>& c, const data_value_wrapper<point>& p) {
auto a = _add_edge(c.get().a, p);
auto b = _add_edge(p, c.get().b);
c.get().flip();
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t1 = res;
b.get().t1 = res;
c.get().t2 = res;
return res;
}
auto _add_triangle(data_value_wrapper<edge>& a, data_value_wrapper<edge>& c) {
auto b = _add_edge(a.get().a, c.get().b);
c.get().flip();
_triangles.emplace_back(a, b, c);
auto res = data_value_wrapper(&_triangles, _triangles.size() - 1);
a.get().t2 = res;
b.get().t1 = res;
c.get().t2 = res;
return res;
}
template<typename It>
static auto _find_first(It it, const point& p, const bool val) {
while (true) {
const auto& e = it->get();
if (_is_clockwise(e.a.get(), e.b.get(), p) == val)
break;
++it;
}
return it;
}
template<typename It>
void _add_triangles(data_value_wrapper<edge>& e, It it, const It end) {
while (it != end) {
auto t = _add_triangle(e, *it);
e = t.get().b;
++it;
}
}
auto _flip_triangles() {
std::vector<data_value_wrapper<edge>> edges;
edges.reserve(_edges.size());
for (size_t i = 0; i < _edges.size(); ++i)
if (_edges[i].t2.is_valid())
edges.emplace_back(data_value_wrapper(&_edges, i));
bool do_flip = true;
while (do_flip) {
do_flip = false;
for (auto& it : edges)
do_flip |= _flip_triangles_over_edge(it);
}
}
static bool _flip_triangles_over_edge(data_value_wrapper<edge>& e) {
auto& eg = e.get();
auto& t1 = eg.t1.get();
auto& t2 = eg.t2.get();
t1.rearrange(e);
t2.rearrange(e);
if (_should_flip(t1.b.get().b, eg.b, eg.a, t2.b.get().b)) {
e.get().a = t2.b.get().b;
e.get().b = t1.b.get().b;
std::swap(t1.b, t2.c);
_reassign_triangle(t1.b, eg.t2, eg.t1);
_reassign_triangle(t2.c, eg.t1, eg.t2);
return true;
}
return false;
}
static void _reassign_triangle(data_value_wrapper<edge>& e, data_value_wrapper<triangle>& t1, data_value_wrapper<triangle>& t2) {
if (e.get().t1 == t1)
e.get().t1 = t2;
else
e.get().t2 = t2;
}
static bool _should_flip(const data_value_wrapper<point>& a, const data_value_wrapper<point>& b,
const data_value_wrapper<point>& c, const data_value_wrapper<point>& d) {
const auto& [xa, ya] = a.get();
const auto& [xb, yb] = b.get();
const auto& [xc, yc] = c.get();
const auto& [xd, yd] = d.get();
const auto xba = xb - xa;
const auto yba = yb - ya;
const auto xca = xc - xa;
const auto yca = yc - ya;
const auto xbd = xb - xd;
const auto ybd = yb - yd;
const auto xcd = xc - xd;
const auto ycd = yc - yd;
const auto cosa = xba * xca + yba * yca;
const auto cosb = xbd * xcd + ybd * ycd;
if (cosa < -eps && cosb < -eps)
return true;
if (cosa > eps && cosb > eps)
return false;
const auto sina = std::abs(xba * yca - yba * xca);
const auto sinb = std::abs(xbd * ycd - ybd * xcd);
if (cosa * sinb + sina * cosb < -eps)
return true;
return false;
}
static auto _find_triangle(const data_value_wrapper<triangle>& wt, const point& p) {
const auto& t = wt.get();
if (t.contains_point(p))
return wt;
const auto& rp = t.a.get().a;
point cp;
if (rp == t.b.get().a || rp == t.b.get().b)
cp = _half_way_point(rp.get(), t.c.get());
else
cp = _half_way_point(rp.get(), t.b.get());
if (_does_intersect(cp, p, t.a.get()))
return _find_triangle(t.a.get(), wt, p);
if (_does_intersect(cp, p, t.b.get()))
return _find_triangle(t.b.get(), wt, p);
return _find_triangle(t.c.get(), wt, p);
}
static auto _find_triangle(const edge& e, const data_value_wrapper<triangle>& wt, const point& p) {
if (e.t2.is_valid()) {
if (wt == e.t1)
return _find_triangle(e.t2, p);
return _find_triangle(e.t1, p);
}
return wt;
}
static auto _half_way_point(const point& p, const edge& e) {
const auto& a = e.a.get();
const auto& b = e.b.get();
const auto x = (b.x + a.x) / T(2);
const auto y = (b.y + a.y) / T(2);
return point((x + p.x) / T(2), (y + p.y) / T(2));
}
static bool _does_intersect(const point& a, const point& b, const edge& ed) {
const auto& [ax, ay] = a;
const auto& [bx, by] = b;
const auto& [cx, cy] = ed.a.get();
const auto& [dx, dy] = ed.b.get();
const auto e = _det(bx - ax, by - ay, dx - cx, dy - cy);
if (std::abs(e) < eps)
return false;
const auto f = _det(dy - cy, dx - cx, cy - ay, cx - ax) / e;
const auto g = _det(by - ay, bx - ax, cy - ay, cx - ax) / e;
return f > -eps && f < T(1) + eps && g > -eps && g < T(1) + eps;
}
static auto _det(const T& a, const T& b, const T& c, const T& d) {
return a * d - b * c;
}
};
| 31.655856
| 133
| 0.499516
|
GoldFeniks
|
5cc1cf304df5d0e0ab2a5b795ba88053dd55eb2e
| 881
|
cpp
|
C++
|
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
src/Renderer/FE_GPU_Info.cpp
|
antsouchlos/OxygenEngine
|
11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48
|
[
"MIT"
] | null | null | null |
#include "FE_GPU_Info.h"
FE_GPU_Info::FE_GPU_Info()
{
//ctor
}
FE_GPU_Info::~FE_GPU_Info()
{
//dtor
}
// find GPU objects by name easily
size_t FE_GPU_Info::findVBO(string a_name){
//cout << vbos.size() << endl;
for(size_t x =0; x < vbos.size(); x++)
if(vbos[x].name == a_name){
return x;
}
return vbos.size();
}
size_t FE_GPU_Info::findVAO(string a_name){
for(size_t x =0; x < vaos.size(); x++)
if(vaos[x].name == a_name){
return x;
}
return vaos.size();
}
size_t FE_GPU_Info::findProgram(string a_name){
for(size_t x =0; x < programs.size(); x++)
if(programs[x].name == a_name){
return x;
}
return programs.size();
}
size_t FE_GPU_Info::findUniform(string a_name){
for(size_t x =0; x < ubos.size(); x++)
if(ubos[x].name == a_name){
return x;
}
return ubos.size();
}
| 19.577778
| 47
| 0.582293
|
antsouchlos
|
5ccc2ae6acfeabfdc89ea685ee02dff9a26be907
| 2,459
|
cpp
|
C++
|
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
taco-oopsla2017/src/io/tns_file_format.cpp
|
peterahrens/FillEstimationIPDPS2017
|
857b6ee8866a2950aa5721d575d2d7d0797c4302
|
[
"BSD-3-Clause"
] | null | null | null |
#include "taco/io/tns_file_format.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cmath>
#include <limits.h>
#include "taco/tensor.h"
#include "taco/format.h"
#include "taco/error.h"
#include "taco/util/strings.h"
using namespace std;
namespace taco {
namespace io {
namespace tns {
TensorBase read(std::string filename, const Format& format, bool pack) {
std::ifstream file;
file.open(filename);
taco_uassert(file.is_open()) << "Error opening file: " << filename;
TensorBase tensor = read(file, format, pack);
file.close();
return tensor;
}
TensorBase read(std::istream& stream, const Format& format, bool pack) {
std::vector<int> coordinates;
std::vector<double> values;
std::string line;
if (!std::getline(stream, line)) {
return TensorBase();
}
// Infer tensor order from the first coordinate
vector<string> toks = util::split(line, " ");
size_t order = toks.size()-1;
std::vector<int> dimensions(order);
std::vector<int> coordinate(order);
// Load data
do {
char* linePtr = (char*)line.data();
for (size_t i = 0; i < order; i++) {
long idx = strtol(linePtr, &linePtr, 10);
taco_uassert(idx <= INT_MAX)<<"Coordinate in file is larger than INT_MAX";
coordinate[i] = (int)idx - 1;
dimensions[i] = std::max(dimensions[i], (int)idx);
}
coordinates.insert(coordinates.end(), coordinate.begin(), coordinate.end());
double val = strtod(linePtr, &linePtr);
values.push_back(val);
} while (std::getline(stream, line));
// Create tensor
const size_t nnz = values.size();
TensorBase tensor(type<double>(), dimensions, format);
tensor.reserve(nnz);
// Insert coordinates (TODO add and use bulk insertion)
for (size_t i = 0; i < nnz; i++) {
for (size_t j = 0; j < order; j++) {
coordinate[j] = coordinates[i*order + j];
}
tensor.insert(coordinate, values[i]);
}
if (pack) {
tensor.pack();
}
return tensor;
}
void write(std::string filename, const TensorBase& tensor) {
std::ofstream file;
file.open(filename);
taco_uassert(file.is_open()) << "Error opening file: " << filename;
write(file, tensor);
file.close();
}
void write(std::ostream& stream, const TensorBase& tensor) {
for (auto& value : iterate<double>(tensor)) {
for (int coord : value.first) {
stream << coord+1 << " ";
}
stream << value.second << endl;
}
}
}}}
| 24.838384
| 80
| 0.647824
|
peterahrens
|
5ccee7478fd0e8a053cba7962f9c04078dc9395c
| 760
|
cpp
|
C++
|
TypesetWidget/commanddeletetext.cpp
|
Math-Collection/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
c4e177bff5edff8122ec73a7ed8f325b42fc74b4
|
[
"MIT"
] | 2
|
2020-03-28T15:35:08.000Z
|
2021-01-10T06:50:05.000Z
|
TypesetWidget/commanddeletetext.cpp
|
Qt-Widgets/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
040383a8db795bb863c451caf4022018181afaf1
|
[
"MIT"
] | null | null | null |
TypesetWidget/commanddeletetext.cpp
|
Qt-Widgets/YAWYSIWYGEE-Qt-Equation-Editor-Widget
|
040383a8db795bb863c451caf4022018181afaf1
|
[
"MIT"
] | null | null | null |
#include "commanddeletetext.h"
#include "cursor.h"
namespace Typeset{
CommandDeleteText::CommandDeleteText(Cursor& cursor, Text* t, QTextCursor cL, QTextCursor cR)
: cursor(cursor),
t(t) {
pL = cL.position();
pR = cR.position();
c = cL;
c.setPosition(cR.position(), QTextCursor::KeepAnchor);
str = c.selectedText();
c = cL;
}
void CommandDeleteText::redo(){
c.setPosition(pL);
c.setPosition(c.position() + str.length(), QTextCursor::KeepAnchor);
c.removeSelectedText();
t->updateToTop();
cursor.setPosition(*t, c);
}
void CommandDeleteText::undo(){
c.setPosition(pL);
c.insertText(str);
t->updateToTop();
cursor.setPosition(*t, c);
c.setPosition(c.position() - str.length());
}
}
| 21.714286
| 93
| 0.643421
|
Math-Collection
|
5cd323e2d31d861165bfadfdce0e6c41f0e91ca8
| 4,970
|
tcc
|
C++
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 98
|
2015-01-26T20:31:37.000Z
|
2021-09-09T15:51:37.000Z
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 16
|
2015-01-21T07:43:45.000Z
|
2021-12-06T12:08:36.000Z
|
flens/blas/level1/raxpy.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 31
|
2015-01-05T08:06:45.000Z
|
2022-01-26T20:12:00.000Z
|
/*
* Copyright (c) 2012, Michael Lehn
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3) Neither the name of the FLENS development group 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.
*/
#ifndef FLENS_BLAS_LEVEL1_RAXPY_TCC
#define FLENS_BLAS_LEVEL1_RAXPY_TCC 1
#include <cxxblas/cxxblas.h>
#include <flens/auxiliary/auxiliary.h>
#include <flens/blas/closures/closures.h>
#include <flens/blas/level1/level1.h>
#include <flens/typedefs.h>
#ifdef FLENS_DEBUG_CLOSURES
# include <flens/blas/blaslogon.h>
#else
# include <flens/blas/blaslogoff.h>
#endif
namespace flens { namespace blas {
//-- raxpy
template <typename ALPHA, typename VX, typename VY>
typename RestrictTo<IsDenseVector<VX>::value
&& IsDenseVector<VY>::value,
void>::Type
raxpy(const ALPHA &alpha, const VX &x, VY &&y)
{
FLENS_BLASLOG_SETTAG("--> ");
FLENS_BLASLOG_BEGIN_RAXPY(alpha, x, y);
if (y.length()==0) {
//
// So we allow y += 1/alpha*x for an empty vector y
//
typedef typename RemoveRef<VY>::Type VectorY;
typedef typename VectorY::ElementType T;
const T Zero(0);
y.resize(x, Zero);
}
ASSERT(y.length()==x.length());
# ifdef HAVE_CXXBLAS_RAXPY
cxxblas::raxpy(x.length(), alpha,
x.data(), x.stride(),
y.data(), y.stride());
# else
ASSERT(0);
# endif
FLENS_BLASLOG_END;
FLENS_BLASLOG_UNSETTAG;
}
//-- geraxpy
//
// B += A/alpha
//
template <typename ALPHA, typename MA, typename MB>
typename RestrictTo<IsGeMatrix<MA>::value
&& IsGeMatrix<MB>::value,
void>::Type
raxpy(Transpose trans, const ALPHA &alpha, const MA &A, MB &&B)
{
typedef typename RemoveRef<MB>::Type MatrixB;
if (B.numRows()==0 || B.numCols()==0) {
//
// So we allow B += 1/alpha*A for an empty matrix B
//
typedef typename MatrixB::ElementType T;
const T Zero(0);
if ((trans==NoTrans) || (trans==Conj)) {
B.resize(A.numRows(), A.numCols(), Zero);
} else {
B.resize(A.numCols(), A.numRows(), Zero);
}
}
# ifndef NDEBUG
if ((trans==NoTrans) || (trans==Conj)) {
ASSERT((A.numRows()==B.numRows()) && (A.numCols()==B.numCols()));
} else {
ASSERT((A.numRows()==B.numCols()) && (A.numCols()==B.numRows()));
}
# endif
trans = (A.order()==B.order())
? Transpose(trans ^ NoTrans)
: Transpose(trans ^ Trans);
# ifndef FLENS_DEBUG_CLOSURES
# ifndef NDEBUG
if (trans==Trans || trans==ConjTrans) {
ASSERT(!DEBUGCLOSURE::identical(A, B));
}
# endif
# else
typedef typename RemoveRef<MA>::Type MatrixA;
//
// If A and B are identical a temporary is needed if we want to use axpy
// for B += A^T/alpha or B+= A^H/alpha
//
if ((trans==Trans || trans==ConjTrans) && DEBUGCLOSURE::identical(A, B)) {
typename Result<MatrixA>::Type A_ = A;
FLENS_BLASLOG_TMP_ADD(A_);
axpy(trans, alpha, A_, B);
FLENS_BLASLOG_TMP_REMOVE(A_, A);
return;
}
# endif
FLENS_BLASLOG_SETTAG("--> ");
FLENS_BLASLOG_BEGIN_MRAXPY(trans, alpha, A, B);
# ifdef HAVE_CXXBLAS_GERAXPY
geraxpy(B.order(), trans, B.numRows(), B.numCols(), alpha,
A.data(), A.leadingDimension(),
B.data(), B.leadingDimension());
# else
ASSERT(0);
# endif
FLENS_BLASLOG_END;
FLENS_BLASLOG_UNSETTAG;
}
} } // namespace blas, flens
#endif // FLENS_BLAS_LEVEL1_RAXPY_TCC
| 30.121212
| 78
| 0.645272
|
stip
|
5cd3570a357b9a4becdc314a42657c5218f9cf78
| 309
|
cpp
|
C++
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 59
|
2019-08-22T18:40:38.000Z
|
2022-03-09T04:12:42.000Z
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 137
|
2019-09-13T15:50:18.000Z
|
2021-12-06T14:19:46.000Z
|
examples/qcor_demos/pnnl_tutorials/1_kernels/ccnot_qfast.cpp
|
vetter/qcor
|
6f86835737277a26071593bb10dd8627c29d74a3
|
[
"BSD-3-Clause"
] | 26
|
2019-07-08T17:30:35.000Z
|
2021-12-03T16:24:12.000Z
|
__qpu__ void ccnot(qreg q) {
decompose {
UnitaryMatrix ccnot_mat = UnitaryMatrix::Identity(8, 8);
ccnot_mat(6, 6) = 0.0;
ccnot_mat(7, 7) = 0.0;
ccnot_mat(6, 7) = 1.0;
ccnot_mat(7, 6) = 1.0;
}
(q, QFAST);
}
int main() {
auto q = qalloc(3);
ccnot::print_kernel(q);
return 0;
}
| 17.166667
| 60
| 0.572816
|
vetter
|
5cd7b02652bcf3eb19abc275c3682832010e23a3
| 398
|
cpp
|
C++
|
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | 5
|
2016-03-17T07:02:11.000Z
|
2021-12-12T14:43:58.000Z
|
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | null | null | null |
src/algos/connection.cpp
|
mhough/braingl
|
53e2078adc10731ee62feec11dcb767c4c6c0d35
|
[
"MIT"
] | 3
|
2015-10-29T15:21:01.000Z
|
2020-11-25T09:41:21.000Z
|
/*
* connection.cpp
*
* Created on: Apr 30, 2013
* Author: boettgerj
*/
#include "connection.h"
#include "qmath.h"
Connection::Connection( QVector3D fn, QVector3D diff, float v ) :
fn( fn ),
diff( diff ),
v( v )
{
QVector3D diffn = diff.normalized();
r=qAbs(diffn.x());
g=qAbs(diffn.y());
b=qAbs(diffn.z());
}
Connection::~Connection()
{
}
| 13.724138
| 65
| 0.557789
|
mhough
|
5ce80c86538d991c55a3fe4c1c3693a440ac9c49
| 405
|
hpp
|
C++
|
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | 2
|
2022-03-29T08:39:24.000Z
|
2022-03-30T09:22:18.000Z
|
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | null | null | null |
src/games/chess.hpp
|
RememberOfLife/mirabel
|
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
|
[
"MIT"
] | null | null | null |
#pragma once
#include "surena/game.h"
#include "games/game_catalogue.hpp"
namespace Games {
class Chess : public BaseGameVariant {
public:
Chess();
~Chess();
game* new_game() override;
void draw_options() override;
void draw_state_editor(game* abstract_game) override;
const char* description() override;
};
}
| 18.409091
| 65
| 0.582716
|
RememberOfLife
|
5cee282eefe7faf54143a5c8da6d24341b0e2de5
| 4,436
|
cpp
|
C++
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_smartcontract/lang/sc_expression/ConstructorArray.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* ConstructorArray.cpp
*
* Created on: 2020/02/12
* Author: iizuka
*/
#include "lang/sc_expression/ConstructorArray.h"
#include "engine/sc_analyze/AnalyzeContext.h"
#include "engine/sc_analyze/AnalyzedType.h"
#include "engine/sc_analyze/AnalyzedThisClassStackPopper.h"
#include "engine/sc_analyze/ValidationError.h"
#include "instance/AbstractVmInstance.h"
#include "vm/VirtualMachine.h"
#include "base_io/ByteBuffer.h"
#include "lang/sc_expression/VariableIdentifier.h"
#include "lang/sc_expression_literal/NumberLiteral.h"
#include "instance/instance_array/VmArrayInstanceUtils.h"
#include "instance/instance_ref/PrimitiveReference.h"
#include "base/StackRelease.h"
namespace alinous {
ConstructorArray::ConstructorArray() : AbstractExpression(CodeElement::EXP_CONSTRUCTORARRAY) {
this->valId = nullptr;
this->atype = nullptr;
}
ConstructorArray::~ConstructorArray() {
delete this->valId;
this->dims.deleteElements();
delete this->atype;
}
int ConstructorArray::binarySize() const {
checkNotNull(this->valId);
int total = sizeof(uint16_t);
total += this->valId->binarySize();
int maxLoop = this->dims.size();
total += sizeof(int32_t);
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
total += exp->binarySize();
}
return total;
}
void ConstructorArray::toBinary(ByteBuffer* out) {
checkNotNull(this->valId);
out->putShort(CodeElement::EXP_CONSTRUCTORARRAY);
this->valId->toBinary(out);
int maxLoop = this->dims.size();
out->putInt(maxLoop);
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->toBinary(out);
}
}
void ConstructorArray::fromBinary(ByteBuffer* in) {
CodeElement* element = createFromBinary(in);
checkKind(element, CodeElement::EXP_VARIABLE_ID);
this->valId = dynamic_cast<VariableIdentifier*>(element);
int maxLoop = in->getInt();
for(int i = 0; i != maxLoop; ++i){
element = createFromBinary(in);
checkIsExp(element);
AbstractExpression* exp = dynamic_cast<AbstractExpression*>(element);
this->dims.addElement(exp);
}
}
void ConstructorArray::preAnalyze(AnalyzeContext* actx) {
this->valId->setParent(this);
this->valId->preAnalyze(actx);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->setParent(this);
exp->preAnalyze(actx);
}
}
void ConstructorArray::analyzeTypeRef(AnalyzeContext* actx) {
this->valId->analyzeTypeRef(actx);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->analyzeTypeRef(actx);
}
}
void ConstructorArray::analyze(AnalyzeContext* actx) {
{
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->analyze(actx);
// check array index type
AnalyzedType type = exp->getType(actx);
bool res = VmArrayInstanceUtils::isArrayIndex(type);
if(!res){
actx->addValidationError(ValidationError::CODE_ARRAY_INDEX_MUST_BE_NUMERIC, this, L"Array index must be numeric value.", {});
}
}
}
this->atype = new AnalyzedType(*actx->getTmpArrayType());
int dim = this->dims.size();
this->atype->setDim(dim);
}
AnalyzedType ConstructorArray::getType(AnalyzeContext* actx) {
return *this->atype;
}
void ConstructorArray::init(VirtualMachine* vm) {
this->valId->init(vm);
int maxLoop = this->dims.size();
for(int i = 0; i != maxLoop; ++i){
AbstractExpression* exp = this->dims.get(i);
exp->init(vm);
}
}
AbstractVmInstance* ConstructorArray::interpret(VirtualMachine* vm) {
int dim = this->atype->getDim();
int* arrayDim = new int[dim];
StackArrayRelease<int> __releaseArrayDim(arrayDim);
for(int i = 0; i != dim; ++i){
AbstractExpression* idxExp = this->dims.get(i);
AbstractVmInstance* idxInst = idxExp->interpret(vm);
PrimitiveReference* primitive = dynamic_cast<PrimitiveReference*>(idxInst);
int d = primitive->getIntValue();
arrayDim[i] = d;
}
vm->setLastElement(this);
return VmArrayInstanceUtils::buildArrayInstance(vm, arrayDim, dim, this->atype);
}
void ConstructorArray::setValId(VariableIdentifier* valId) noexcept {
this->valId = valId;
}
void ConstructorArray::addDim(AbstractExpression* dim) noexcept {
this->dims.addElement(dim);
}
const UnicodeString* ConstructorArray::getName() const noexcept {
return this->valId->getName();
}
} /* namespace alinous */
| 24.240437
| 129
| 0.714833
|
alinous-core
|
5cf4de84e9ae80dd20b510e889854a9125e9131b
| 17,124
|
cpp
|
C++
|
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
codec/encoder/core/src/svc_mode_decision.cpp
|
zhuling13/openh264
|
47a2e65327e0081bac87529ed26cfbc377ed4ddc
|
[
"BSD-2-Clause"
] | null | null | null |
/*!
* \copy
* Copyright (c) 2009-2013, Cisco Systems
* 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.
*
* 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.
*
*
* \file svc_mode_decision.c
*
* \brief Algorithmetic MD for:
* - multi-spatial Enhancement Layer MD;
* - Scrolling PSkip Decision for screen content
*
* \date 2009.7.29
*
**************************************************************************************
*/
#include "mv_pred.h"
#include "ls_defines.h"
#include "svc_base_layer_md.h"
#include "svc_mode_decision.h"
namespace WelsSVCEnc {
//
// md in enhancement layer
///
inline bool IsMbStatic (int32_t* pBlockType, EStaticBlockIdc eType) {
return (pBlockType != NULL &&
eType == pBlockType[0] &&
eType == pBlockType[1] &&
eType == pBlockType[2] &&
eType == pBlockType[3]);
}
inline bool IsMbCollocatedStatic (int32_t* pBlockType) {
return IsMbStatic (pBlockType, COLLOCATED_STATIC);
}
inline bool IsMbScrolledStatic (int32_t* pBlockType) {
return IsMbStatic (pBlockType, SCROLLED_STATIC);
}
inline int32_t CalUVSadCost (SWelsFuncPtrList* pFunc, uint8_t* pEncOri, int32_t iStrideUV, uint8_t* pRefOri,
int32_t iRefLineSize) {
return pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_8x8] (pEncOri, iStrideUV, pRefOri, iRefLineSize);
}
inline bool CheckBorder (int32_t iMbX, int32_t iMbY, int32_t iScrollMvX, int32_t iScrollMvY, int32_t iMbWidth,
int32_t iMbHeight) {
return ((iMbX << 4) + iScrollMvX < 0 ||
(iMbX << 4) + iScrollMvX > (iMbWidth - 1) << 4 ||
(iMbY << 4) + iScrollMvY < 0 ||
(iMbY << 4) + iScrollMvY > (iMbHeight - 1) << 4
); //border check for safety
}
void WelsMdSpatialelInterMbIlfmdNoilp (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SSlice* pSlice,
SMB* pCurMb, const Mb_Type kuiRefMbType) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SMbCache* pMbCache = &pSlice->sMbCacheInfo;
const uint32_t kuiNeighborAvail = pCurMb->uiNeighborAvail;
const int32_t kiMbWidth = pCurDqLayer->iMbWidth;
const SMB* kpTopMb = pCurMb - kiMbWidth;
const bool kbMbLeftAvailPskip = ((kuiNeighborAvail & LEFT_MB_POS) ? IS_SKIP ((pCurMb - 1)->uiMbType) : false);
const bool kbMbTopAvailPskip = ((kuiNeighborAvail & TOP_MB_POS) ? IS_SKIP (kpTopMb->uiMbType) : false);
const bool kbMbTopLeftAvailPskip = ((kuiNeighborAvail & TOPLEFT_MB_POS) ? IS_SKIP ((kpTopMb - 1)->uiMbType) : false);
const bool kbMbTopRightAvailPskip = ((kuiNeighborAvail & TOPRIGHT_MB_POS) ? IS_SKIP ((
kpTopMb + 1)->uiMbType) : false);
bool bTrySkip = kbMbLeftAvailPskip | kbMbTopAvailPskip | kbMbTopLeftAvailPskip | kbMbTopRightAvailPskip;
bool bKeepSkip = kbMbLeftAvailPskip & kbMbTopAvailPskip & kbMbTopRightAvailPskip;
bool bSkip = false;
if (pEncCtx->pFuncList->pfInterMdBackgroundDecision (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, &bKeepSkip)) {
return;
}
//step 1: try SKIP
bSkip = WelsMdInterJudgePskip (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, bTrySkip);
if (bSkip && bKeepSkip) {
WelsMdInterDecidedPskip (pEncCtx, pSlice, pCurMb, pMbCache);
return;
}
if (! IS_SVC_INTRA (kuiRefMbType)) {
if (!bSkip) {
PredictSad (pMbCache->sMvComponents.iRefIndexCache, pMbCache->iSadCost, 0, &pWelsMd->iSadPredMb);
//step 2: P_16x16
pWelsMd->iCostLuma = WelsMdP16x16 (pEncCtx->pFuncList, pCurDqLayer, pWelsMd, pSlice, pCurMb);
pCurMb->uiMbType = MB_TYPE_16x16;
}
WelsMdInterSecondaryModesEnc (pEncCtx, pWelsMd, pSlice, pCurMb, pMbCache, bSkip);
} else { //BLMODE == SVC_INTRA
//initial prediction memory for I_16x16
const int32_t kiCostI16x16 = WelsMdI16x16 (pEncCtx->pFuncList, pEncCtx->pCurDqLayer, pMbCache, pWelsMd->iLambda);
if (bSkip && (pWelsMd->iCostLuma <= kiCostI16x16)) {
WelsMdInterDecidedPskip (pEncCtx, pSlice, pCurMb, pMbCache);
} else {
pWelsMd->iCostLuma = kiCostI16x16;
pCurMb->uiMbType = MB_TYPE_INTRA16x16;
WelsMdIntraSecondaryModesEnc (pEncCtx, pWelsMd, pCurMb, pMbCache);
}
}
}
void WelsMdInterMbEnhancelayer (void* pEnc, void* pMd, SSlice* pSlice, SMB* pCurMb, SMbCache* pMbCache) {
sWelsEncCtx* pEncCtx = (sWelsEncCtx*)pEnc;
SDqLayer* pCurLayer = pEncCtx->pCurDqLayer;
SWelsMD* pWelsMd = (SWelsMD*)pMd;
const SMB* kpInterLayerRefMb = GetRefMb (pCurLayer, pCurMb);
const Mb_Type kuiInterLayerRefMbType = kpInterLayerRefMb->uiMbType;
SetMvBaseEnhancelayer (pWelsMd, pCurMb,
kpInterLayerRefMb); // initial sMvBase here only when pRef mb type is inter, if not sMvBase will be not used!
//step (3): do the MD process
WelsMdSpatialelInterMbIlfmdNoilp (pEncCtx, pWelsMd, pSlice, pCurMb, kuiInterLayerRefMbType); //MD process
}
///////////////////////
// do initiation for noILP (needed by ILFMD)
////////////////////////
SMB* GetRefMb (SDqLayer* pCurLayer, SMB* pCurMb) {
const SDqLayer* kpRefLayer = pCurLayer->pRefLayer;
const int32_t kiRefMbIdx = (pCurMb->iMbY >> 1) * kpRefLayer->iMbWidth + (pCurMb->iMbX >>
1); //because current lower layer is half size on both vertical and horizontal
return (&kpRefLayer->sMbDataP[kiRefMbIdx]);
}
void SetMvBaseEnhancelayer (SWelsMD* pMd, SMB* pCurMb, const SMB* kpRefMb) {
const Mb_Type kuiRefMbType = kpRefMb->uiMbType;
if (! IS_SVC_INTRA (kuiRefMbType)) {
SMVUnitXY sMv;
int32_t iRefMbPartIdx = ((pCurMb->iMbY & 0x01) << 1) + (pCurMb->iMbX & 0x01); //may be need modified
int32_t iScan4RefPartIdx = g_kuiMbCountScan4Idx[ (iRefMbPartIdx << 2)];
sMv.iMvX = kpRefMb->sMv[iScan4RefPartIdx].iMvX << 1;
sMv.iMvY = kpRefMb->sMv[iScan4RefPartIdx].iMvY << 1;
pMd->sMe.sMe16x16.sMvBase = sMv;
pMd->sMe.sMe8x8[0].sMvBase =
pMd->sMe.sMe8x8[1].sMvBase =
pMd->sMe.sMe8x8[2].sMvBase =
pMd->sMe.sMe8x8[3].sMvBase = sMv;
pMd->sMe.sMe16x8[0].sMvBase =
pMd->sMe.sMe16x8[1].sMvBase =
pMd->sMe.sMe8x16[0].sMvBase =
pMd->sMe.sMe8x16[1].sMvBase = sMv;
}
}
bool JudgeStaticSkip (sWelsEncCtx* pEncCtx, SMB* pCurMb, SMbCache* pMbCache, SWelsMD* pWelsMd) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
bool bTryStaticSkip = IsMbCollocatedStatic (pWelsMd->iBlock8x8StaticIdc);
if (bTryStaticSkip) {
int32_t iStrideUV, iOffsetUV;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SPicture* pRefOri = pCurDqLayer->pRefOri;
if (pRefOri != NULL) {
iStrideUV = pCurDqLayer->iEncStride[1];
iOffsetUV = (kiMbX + kiMbY * iStrideUV) << 3;
int32_t iSadCostCb = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[1], iStrideUV, pRefOri->pData[1] + iOffsetUV,
pRefOri->iLineSize[1]);
if (iSadCostCb == 0) {
int32_t iSadCostCr = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[2], iStrideUV, pRefOri->pData[2] + iOffsetUV,
pRefOri->iLineSize[1]);
bTryStaticSkip = (0 == iSadCostCr);
} else bTryStaticSkip = false;
}
}
return bTryStaticSkip;
}
bool JudgeScrollSkip (sWelsEncCtx* pEncCtx, SMB* pCurMb, SMbCache* pMbCache, SWelsMD* pWelsMd) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
const int32_t kiMbWidth = pCurDqLayer->iMbWidth;
const int32_t kiMbHeight = pCurDqLayer->iMbHeight;
// const int32_t block_width = mb_width << 1;
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pEncCtx->pVaa);
bool bTryScrollSkip = false;
if (pVaaExt->sScrollDetectInfo.bScrollDetectFlag)
bTryScrollSkip = IsMbCollocatedStatic (pWelsMd->iBlock8x8StaticIdc);
else return 0;
if (bTryScrollSkip) {
int32_t iStrideUV, iOffsetUV;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SPicture* pRefOri = pCurDqLayer->pRefOri;
if (pRefOri != NULL) {
int32_t iScrollMvX = pVaaExt->sScrollDetectInfo.iScrollMvX;
int32_t iScrollMvY = pVaaExt->sScrollDetectInfo.iScrollMvY;
if (CheckBorder (kiMbX, kiMbY, iScrollMvX, iScrollMvY, kiMbWidth, kiMbHeight)) {
bTryScrollSkip = false;
} else {
iStrideUV = pCurDqLayer->iEncStride[1];
iOffsetUV = (kiMbX << 3) + (iScrollMvX >> 1) + ((kiMbX << 3) + (iScrollMvY >> 1)) * iStrideUV;
int32_t iSadCostCb = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[1], iStrideUV, pRefOri->pData[1] + iOffsetUV,
pRefOri->iLineSize[1]);
if (iSadCostCb == 0) {
int32_t iSadCostCr = CalUVSadCost (pFunc, pMbCache->SPicData.pEncMb[2], iStrideUV, pRefOri->pData[2] + iOffsetUV,
pRefOri->iLineSize[1]);
bTryScrollSkip = (0 == iSadCostCr);
} else bTryScrollSkip = false;
}
}
}
return bTryScrollSkip;
}
void SvcMdSCDMbEnc (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SMB* pCurMb, SMbCache* pMbCache, SSlice* pSlice,
bool bQpSimilarFlag,
bool bMbSkipFlag, SMVUnitXY sCurMbMv[], ESkipModes eSkipMode) {
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SWelsFuncPtrList* pFunc = pEncCtx->pFuncList;
SMVUnitXY sMvp = { 0};
ST16 (&sMvp.iMvX, sCurMbMv[eSkipMode].iMvX);
ST16 (&sMvp.iMvY, sCurMbMv[eSkipMode].iMvY);
uint8_t* pRefLuma = pMbCache->SPicData.pRefMb[0];
uint8_t* pRefCb = pMbCache->SPicData.pRefMb[1];
uint8_t* pRefCr = pMbCache->SPicData.pRefMb[2];
int32_t iLineSizeY = pCurDqLayer->pRefPic->iLineSize[0];
int32_t iLineSizeUV = pCurDqLayer->pRefPic->iLineSize[1];
uint8_t* pDstLuma = pMbCache->pSkipMb;
uint8_t* pDstCb = pMbCache->pSkipMb + 256;
uint8_t* pDstCr = pMbCache->pSkipMb + 256 + 64;
const int32_t iOffsetY = (sCurMbMv[eSkipMode].iMvX >> 2) + (sCurMbMv[eSkipMode].iMvY >> 2) * iLineSizeY;
const int32_t iOffsetUV = (sCurMbMv[eSkipMode].iMvX >> 3) + (sCurMbMv[eSkipMode].iMvY >> 3) * iLineSizeUV;
if (!bQpSimilarFlag || !bMbSkipFlag) {
pDstLuma = pMbCache->pMemPredLuma;
pDstCb = pMbCache->pMemPredChroma;
pDstCr = pMbCache->pMemPredChroma + 64;
}
//MC
pFunc->sMcFuncs.pfLumaQuarpelMc[0] (pRefLuma + iOffsetY, iLineSizeY, pDstLuma, 16, 16);
pFunc->sMcFuncs.pfChromaMc (pRefCb + iOffsetUV, iLineSizeUV, pDstCb, 8, sMvp, 8, 8);
pFunc->sMcFuncs.pfChromaMc (pRefCr + iOffsetUV, iLineSizeUV, pDstCr, 8, sMvp, 8, 8);
pCurMb->uiCbp = 0;
pWelsMd->iCostLuma = 0;
pCurMb->pSadCost[0] = pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_16x16] (pMbCache->SPicData.pEncMb[0],
pCurDqLayer->iEncStride[0], pRefLuma + iOffsetY, iLineSizeY);
pWelsMd->iCostSkipMb = pCurMb->pSadCost[0];
ST16 (& (pCurMb->sP16x16Mv.iMvX), sCurMbMv[eSkipMode].iMvX);
ST16 (& (pCurMb->sP16x16Mv.iMvY), sCurMbMv[eSkipMode].iMvY);
ST16 (& (pCurDqLayer->pDecPic->sMvList[pCurMb->iMbXY].iMvX), sCurMbMv[eSkipMode].iMvX);
ST16 (& (pCurDqLayer->pDecPic->sMvList[pCurMb->iMbXY].iMvY), sCurMbMv[eSkipMode].iMvY);
if (bQpSimilarFlag && bMbSkipFlag) {
//update motion info to current MB
ST32 (pCurMb->pRefIndex, 0);
pFunc->pfUpdateMbMv (pCurMb->sMv, sMvp);
pCurMb->uiMbType = MB_TYPE_SKIP;
WelsRecPskip (pCurDqLayer, pEncCtx->pFuncList, pCurMb, pMbCache);
WelsMdInterUpdatePskip (pCurDqLayer, pSlice, pCurMb, pMbCache);
return;
}
pCurMb->uiMbType = MB_TYPE_16x16;
pWelsMd->sMe.sMe16x16.sMv.iMvX = sCurMbMv[eSkipMode].iMvX;
pWelsMd->sMe.sMe16x16.sMv.iMvY = sCurMbMv[eSkipMode].iMvY;
PredMv (&pMbCache->sMvComponents, 0, 4, 0, &pWelsMd->sMe.sMe16x16.sMvp);
pMbCache->sMbMvp[0] = pWelsMd->sMe.sMe16x16.sMvp;
UpdateP16x16MotionInfo (pMbCache, pCurMb, 0, &pWelsMd->sMe.sMe16x16.sMv);
if (pWelsMd->bMdUsingSad)
pWelsMd->iCostLuma = pCurMb->pSadCost[0];
else
pWelsMd->iCostLuma = pFunc->sSampleDealingFuncs.pfSampleSad[BLOCK_16x16] (pMbCache->SPicData.pEncMb[0],
pCurDqLayer->iEncStride[0], pRefLuma, iLineSizeY);
WelsInterMbEncode (pEncCtx, pSlice, pCurMb);
WelsPMbChromaEncode (pEncCtx, pSlice, pCurMb);
pFunc->pfCopy16x16Aligned (pMbCache->SPicData.pCsMb[0], pCurDqLayer->iCsStride[0], pMbCache->pMemPredLuma, 16);
pFunc->pfCopy8x8Aligned (pMbCache->SPicData.pCsMb[1], pCurDqLayer->iCsStride[1], pMbCache->pMemPredChroma, 8);
pFunc->pfCopy8x8Aligned (pMbCache->SPicData.pCsMb[2], pCurDqLayer->iCsStride[1], pMbCache->pMemPredChroma + 64, 8);
}
bool MdInterSCDPskipProcess (sWelsEncCtx* pEncCtx, SWelsMD* pWelsMd, SSlice* pSlice, SMB* pCurMb, SMbCache* pMbCache,
ESkipModes eSkipMode) {
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pEncCtx->pVaa);
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
const int32_t kiRefMbQp = pCurDqLayer->pRefPic->pRefMbQp[pCurMb->iMbXY];
const int32_t kiCurMbQp = pCurMb->uiLumaQp;// unsigned -> signed
pJudgeSkipFun pJudeSkip[2] = {JudgeStaticSkip, JudgeScrollSkip};
bool bSkipFlag = pJudeSkip[eSkipMode] (pEncCtx, pCurMb, pMbCache, pWelsMd);
if (bSkipFlag) {
bool bQpSimilarFlag = (kiRefMbQp - kiCurMbQp <= DELTA_QP_SCD_THD || kiRefMbQp <= 26);
SMVUnitXY sVaaPredSkipMv = { 0 }, sCurMbMv[2] = {0, 0, 0, 0};
PredSkipMv (pMbCache, &sVaaPredSkipMv);
if (eSkipMode == SCROLLED) {
sCurMbMv[1].iMvX = static_cast<int16_t> (pVaaExt->sScrollDetectInfo.iScrollMvX << 2);
sCurMbMv[1].iMvY = static_cast<int16_t> (pVaaExt->sScrollDetectInfo.iScrollMvY << 2);
}
bool bMbSkipFlag = (LD32 (&sVaaPredSkipMv) == LD32 (&sCurMbMv[eSkipMode])) ;
SvcMdSCDMbEnc (pEncCtx, pWelsMd, pCurMb, pMbCache, pSlice, bQpSimilarFlag, bMbSkipFlag, sCurMbMv, eSkipMode);
return true;
}
return false;
}
void SetBlockStaticIdcToMd (void* pVaa, void* pMd, SMB* pCurMb, void* pDqLay) {
SVAAFrameInfoExt_t* pVaaExt = static_cast<SVAAFrameInfoExt_t*> (pVaa);
SWelsMD* pWelsMd = static_cast<SWelsMD*> (pMd);
SDqLayer* pDqLayer = static_cast<SDqLayer*> (pDqLay);
const int32_t kiMbX = pCurMb->iMbX;
const int32_t kiMbY = pCurMb->iMbY;
const int32_t kiMbWidth = pDqLayer->iMbWidth;
const int32_t kiWidth = kiMbWidth << 1;
const int32_t kiBlockIndexUp = (kiMbY << 1) * kiWidth + (kiMbX << 1);
const int32_t kiBlockIndexLow = ((kiMbY << 1) + 1) * kiWidth + (kiMbX << 1);
//fill_blockstaticidc with pVaaExt->pVaaBestBlockStaticIdc
pWelsMd->iBlock8x8StaticIdc[0] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexUp];
pWelsMd->iBlock8x8StaticIdc[1] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexUp + 1];
pWelsMd->iBlock8x8StaticIdc[2] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexLow];
pWelsMd->iBlock8x8StaticIdc[3] = pVaaExt->pVaaBestBlockStaticIdc[kiBlockIndexLow + 1];
}
///////////////////////
// Scene Change Detection (SCD) PSkip Decision for screen content
////////////////////////
bool WelsMdInterJudgeSCDPskip (void* pCtx, void* pMd, SSlice* slice, SMB* pCurMb, SMbCache* pMbCache) {
sWelsEncCtx* pEncCtx = (sWelsEncCtx*)pCtx;
SWelsMD* pWelsMd = (SWelsMD*)pMd;
SDqLayer* pCurDqLayer = pEncCtx->pCurDqLayer;
SetBlockStaticIdcToMd (pEncCtx->pVaa, pWelsMd, pCurMb, pCurDqLayer);
//try static Pskip;
//try scrolled Pskip
//TBD
return false;
}
bool WelsMdInterJudgeSCDPskipFalse (void* pEncCtx, void* pWelsMd, SSlice* slice, SMB* pCurMb, SMbCache* pMbCache) {
return false;
}
void WelsInitSCDPskipFunc (SWelsFuncPtrList* pFuncList, const bool bScrollingDetection) {
if (bScrollingDetection) {
pFuncList->pfSCDPSkipDecision = WelsMdInterJudgeSCDPskip;
} else {
pFuncList->pfSCDPSkipDecision = WelsMdInterJudgeSCDPskipFalse;
}
}
} // namespace WelsSVCEnc
| 41.362319
| 134
| 0.683076
|
zhuling13
|
9dc660aa4e41a0a15474be534d00deb672134692
| 5,962
|
cpp
|
C++
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 34
|
2020-08-10T16:06:50.000Z
|
2022-03-02T18:58:03.000Z
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 18
|
2020-08-02T23:31:28.000Z
|
2022-03-29T11:55:06.000Z
|
xlw/InterfaceGenerator/ParserData.cpp
|
jbriand/xlw
|
82b98a12f3c99876e54baa33ff2cb6786df141f7
|
[
"BSD-3-Clause"
] | 11
|
2020-07-27T20:44:10.000Z
|
2022-02-02T20:58:59.000Z
|
/*
Copyright (C) 2006 Mark Joshi
Copyright (C) 2007, 2008 Eric Ehlers
Copyright (C) 2011 Narinder Claire
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - https://xlw.github.io/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
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 license for more details.
*/
#ifdef _MSC_VER
#if _MSC_VER < 1250
#pragma warning(disable:4786)
#endif
#endif
#include "ParserData.h"
#include <vector>
FunctionArgumentType::FunctionArgumentType(std::string NameIdentifier_,
const std::vector<std::string>& ConversionChain_,
const std::string& EXCELKey_)
:
NameIdentifier(NameIdentifier_),
ConversionChain(ConversionChain_),
EXCELKey(EXCELKey_)
{}
const std::string& FunctionArgumentType::GetNameIdentifier() const
{
return NameIdentifier;
}
const std::vector<std::string>& FunctionArgumentType::GetConversionChain() const
{
return ConversionChain;
}
FunctionArgumentType FunctionArgument::GetTheType() const
{
return TheType;
}
const std::string& FunctionArgumentType::GetEXCELKey() const
{
return EXCELKey;
}
std::string FunctionArgument::GetArgumentName() const
{
return ArgumentName;
}
std::string FunctionArgument::GetArgumentDescription() const
{
return ArgumentDescription;
}
FunctionArgument::FunctionArgument(const FunctionArgumentType& TheType_,
std::string ArgumentName_,
std::string ArgumentDescription_)
:
TheType(TheType_),
ArgumentName(ArgumentName_),
ArgumentDescription(ArgumentDescription_)
{
}
std::string FunctionDescription::GetFunctionName() const
{
return FunctionName;
}
std::string FunctionDescription::GetDisplayName() const
{
return DisplayName;
}
void FunctionDescription::setFunctionName(const std::string &newName)
{
FunctionName = newName;
}
std::string FunctionDescription::GetFunctionDescription() const
{
return FunctionHelpDescription;
}
const FunctionArgument& FunctionDescription::GetArgument(
unsigned long ArgumentNumber) const
{
return Arguments.at(ArgumentNumber);
}
unsigned long FunctionDescription::NumberOfArguments() const
{
return static_cast<unsigned long>(Arguments.size());
}
FunctionDescription::FunctionDescription(std::string FunctionName_,
std::string FunctionHelpDescription_,
std::string ReturnType_,
const std::string& ExcelKey_,
const std::vector<FunctionArgument>& Arguments_,
bool Volatile_,
bool Time_,
bool Threadsafe_,
std::string helpID_,
bool Asynchronous_,
bool MacroSheet_,
bool ClusterSafe_)
:
FunctionName(FunctionName_),
DisplayName(FunctionName_),
FunctionHelpDescription(FunctionHelpDescription_),
ReturnType(ReturnType_),
ExcelKey(ExcelKey_),
helpID(helpID_),
Arguments(Arguments_),
Volatile(Volatile_),
Time(Time_),
Threadsafe(Threadsafe_),
Asynchronous(Asynchronous_),
MacroSheet(MacroSheet_),
ClusterSafe(ClusterSafe_)
{
}
std::string FunctionDescription::GetExcelKey() const
{
return ExcelKey;
}
std::string FunctionDescription::GetReturnType() const
{
return ReturnType;
}
bool FunctionDescription::GetVolatile() const
{
return Volatile;
}
bool FunctionDescription::DoTime() const
{
return Time;
}
bool FunctionDescription::GetThreadsafe() const
{
return Threadsafe;
}
std::string FunctionDescription::GetHelpID() const
{
return helpID;
}
bool FunctionDescription::GetAsynchronous() const
{
return Asynchronous;
}
bool FunctionDescription::GetMacroSheet() const
{
return MacroSheet;
}
bool FunctionDescription::GetClusterSafe() const
{
return ClusterSafe;
}
#include<iostream>
void FunctionDescription::Transit(const std::vector<FunctionDescription> &source,
std::vector<FunctionDescription> & destination)
{
if(source.size()!=destination.size())
{
throw("number of managed functions and native wrappers not the same");
}
for(size_t i(0); i <destination.size(); ++i)
{
destination[i].Asynchronous = source[i].Asynchronous;
destination[i].ClusterSafe = source[i].ClusterSafe ;
destination[i].DisplayName = source[i].DisplayName ;
destination[i].FunctionHelpDescription = source[i].FunctionHelpDescription ;
destination[i].helpID = source[i].helpID ;
destination[i].MacroSheet = source[i].MacroSheet ;
destination[i].Threadsafe = source[i].Threadsafe ;
destination[i].Time = source[i].Time ;
destination[i].Volatile = source[i].Volatile ;
if(destination[i].FunctionName != source[i].FunctionName)
{
std::cout << destination[i].FunctionName << " : " << source[i].FunctionName << "\n";
throw("unmanaged wrappers must be in same order as manged function");
}
}
}
| 28.526316
| 87
| 0.626468
|
jbriand
|
9dc6aa79772b5cec8310264f1cedb43cc91d9598
| 5,042
|
hpp
|
C++
|
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/Zenject/ConventionBindInfo.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:42 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: Dictionary`2<TKey, TValue>
template<typename TKey, typename TValue>
class Dictionary_2;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
// Forward declaring type: Type
class Type;
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: Assembly
class Assembly;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.ConventionBindInfo
class ConventionBindInfo : public ::Il2CppObject {
public:
// Nested type: Zenject::ConventionBindInfo::$$c__DisplayClass6_0
class $$c__DisplayClass6_0;
// Nested type: Zenject::ConventionBindInfo::$$c__DisplayClass7_0
class $$c__DisplayClass7_0;
// private readonly System.Collections.Generic.List`1<System.Func`2<System.Type,System.Boolean>> _typeFilters
// Offset: 0x10
System::Collections::Generic::List_1<System::Func_2<System::Type*, bool>*>* typeFilters;
// private readonly System.Collections.Generic.List`1<System.Func`2<System.Reflection.Assembly,System.Boolean>> _assemblyFilters
// Offset: 0x18
System::Collections::Generic::List_1<System::Func_2<System::Reflection::Assembly*, bool>*>* assemblyFilters;
// Get static field: static private readonly System.Collections.Generic.Dictionary`2<System.Reflection.Assembly,System.Type[]> _assemblyTypeCache
static System::Collections::Generic::Dictionary_2<System::Reflection::Assembly*, ::Array<System::Type*>*>* _get__assemblyTypeCache();
// Set static field: static private readonly System.Collections.Generic.Dictionary`2<System.Reflection.Assembly,System.Type[]> _assemblyTypeCache
static void _set__assemblyTypeCache(System::Collections::Generic::Dictionary_2<System::Reflection::Assembly*, ::Array<System::Type*>*>* value);
// public System.Void AddAssemblyFilter(System.Func`2<System.Reflection.Assembly,System.Boolean> predicate)
// Offset: 0xD572D0
void AddAssemblyFilter(System::Func_2<System::Reflection::Assembly*, bool>* predicate);
// public System.Void AddTypeFilter(System.Func`2<System.Type,System.Boolean> predicate)
// Offset: 0xD57444
void AddTypeFilter(System::Func_2<System::Type*, bool>* predicate);
// private System.Collections.Generic.IEnumerable`1<System.Reflection.Assembly> GetAllAssemblies()
// Offset: 0xD574AC
System::Collections::Generic::IEnumerable_1<System::Reflection::Assembly*>* GetAllAssemblies();
// private System.Boolean ShouldIncludeAssembly(System.Reflection.Assembly assembly)
// Offset: 0xD574D0
bool ShouldIncludeAssembly(System::Reflection::Assembly* assembly);
// private System.Boolean ShouldIncludeType(System.Type type)
// Offset: 0xD575A4
bool ShouldIncludeType(System::Type* type);
// private System.Type[] GetTypes(System.Reflection.Assembly assembly)
// Offset: 0xD57678
::Array<System::Type*>* GetTypes(System::Reflection::Assembly* assembly);
// public System.Collections.Generic.List`1<System.Type> ResolveTypes()
// Offset: 0xD54BC0
System::Collections::Generic::List_1<System::Type*>* ResolveTypes();
// static private System.Void .cctor()
// Offset: 0xD57778
static void _cctor();
// private System.Collections.Generic.IEnumerable`1<System.Type> <ResolveTypes>b__9_0(System.Reflection.Assembly assembly)
// Offset: 0xD577F0
System::Collections::Generic::IEnumerable_1<System::Type*>* $ResolveTypes$b__9_0(System::Reflection::Assembly* assembly);
// public System.Void .ctor()
// Offset: 0xD54ADC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static ConventionBindInfo* New_ctor();
}; // Zenject.ConventionBindInfo
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::ConventionBindInfo*, "Zenject", "ConventionBindInfo");
#pragma pack(pop)
| 46.256881
| 149
| 0.735026
|
Futuremappermydud
|
9dc97e63f1312f8a4b80091897bc140aa30d23e8
| 2,742
|
cpp
|
C++
|
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
fifa_gp/predict.cpp
|
vittorioorlandi/STA663_FIFA_GP
|
cb5532f8104fa630b8ea6930f414e3228349ae52
|
[
"MIT"
] | null | null | null |
#include <random>
#include <Eigen/Dense>
#include "HODLR_Tree.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <squaredeMat.hpp> //squared exponential kernel
#include <squaredeP1Mat.hpp>
using std::normal_distribution;
namespace py = pybind11;
Eigen::MatrixXd predict(Eigen::MatrixXd X, Eigen::MatrixXd Y, Eigen::MatrixXd Xtest, Eigen::VectorXd sig_samps, Eigen::VectorXd rho_samps, Eigen::VectorXd tau_samps, double multiplier, int M, double tol, int nsamps) {
/*
Sample a draw of the GP function f*|f, sig, rho, tau, x*.
Assume a squared exponential Gaussian Process based on
observed function f at new test points x*.
Temporarily assumes fit method was called with regression = true.
*/
// Create the standard normal generator
normal_distribution<double> norm(0, 1);
std::mt19937 rng;
auto r_std_normal = bind(norm, rng);
int Ntest = Xtest.rows();
int N = X.rows();
int D = X.cols();
// HODLR details
int n_levels = log(N / M) / log(2);
bool is_sym = true;
bool is_pd = true;
double tau;
double rho;
double sig;
double sigsq;
double tmpSSR;
// Allocate space for output
Eigen::MatrixXd fstarsamp(nsamps, Ntest);
Eigen::VectorXd KobsNew(N);
for (int s = 0; s < nsamps; s++) {
sig = sig_samps(s);
tau = tau_samps(s);
rho = rho_samps(s);
sigsq = pow(sig, 2.0);
// HODLR approximation
SQRExponentialP1_Kernel* L = new SQRExponentialP1_Kernel(X, N, sig, rho, tau);
HODLR_Tree* T = new HODLR_Tree(n_levels, tol, L); // With noise (i.e. Sigma + I/tau)
T->assembleTree(is_sym, is_pd);
T->factorize();
for (int i = 0; i < Ntest; i++) {
Eigen::RowVectorXd Xtest_i = Xtest.row(i);
// Get covariance between X and Xtest
for (int j = 0; j < N; j++) {
Eigen::RowVectorXd tmp = X.row(j) - Xtest_i;
tmpSSR = 0.0;
for (int d = 0; d < D; d++) {
tmpSSR = tmpSSR + pow(tmp(d), 2.0);
}
KobsNew(j) = sigsq * exp(- tmpSSR * rho);
}
// Get variance at Xtest
double kNewNew = sigsq + 1e-8;
// Get posterior mean and variance of f* at point xtest(i)
double sdstar = pow(kNewNew - (multiplier * KobsNew.transpose() * T->solve(tau * KobsNew))(0, 0), 0.5);
double mustar = (multiplier * KobsNew.transpose() * T->solve(tau * Y))(0, 0);
auto normal_samp = r_std_normal();
fstarsamp(s, i) = sdstar * normal_samp + mustar;
}
}
return fstarsamp;
}
void predict_module(py::module &m) {
m.def("predict_f", &predict, "predicted samples of f at new X");
}
| 29.804348
| 217
| 0.598833
|
vittorioorlandi
|
9dd2e4bb8318b8f7298242866853681f7f10c2f7
| 8,950
|
cpp
|
C++
|
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/auto/dbus/qdbusservicewatcher/tst_qdbusservicewatcher.cpp
|
zwollerob/PhantomJS_AMR6VL
|
71c126e98a8c32950158d04d0bd75823cd008b99
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtDBus/QDBusServiceWatcher>
#include <QtDBus>
#include <QtTest>
class tst_QDBusServiceWatcher: public QObject
{
Q_OBJECT
QString serviceName;
int testCounter;
public:
tst_QDBusServiceWatcher();
private slots:
void initTestCase();
void init();
void watchForCreation();
void watchForDisappearance();
void watchForOwnerChange();
void modeChange();
};
tst_QDBusServiceWatcher::tst_QDBusServiceWatcher()
: testCounter(0)
{
}
void tst_QDBusServiceWatcher::initTestCase()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
}
void tst_QDBusServiceWatcher::init()
{
// change the service name from test to test
serviceName = "com.example.TestService" + QString::number(testCounter++);
}
void tst_QDBusServiceWatcher::watchForCreation()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForRegistration);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
// unregister it:
con.unregisterService(serviceName);
// and register again
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
}
void tst_QDBusServiceWatcher::watchForDisappearance()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForUnregistration);
watcher.setObjectName("watcher for disappearance");
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceUnregistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
// unregister it:
con.unregisterService(serviceName);
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 0);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
}
void tst_QDBusServiceWatcher::watchForOwnerChange()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForOwnerChange);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
// unregister it:
con.unregisterService(serviceName);
// and register again
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 2);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
QCOMPARE(spyO.at(1).at(0).toString(), serviceName);
QVERIFY(spyO.at(1).at(1).toString().isEmpty());
QCOMPARE(spyO.at(1).at(2).toString(), con.baseService());
}
void tst_QDBusServiceWatcher::modeChange()
{
QDBusConnection con = QDBusConnection::sessionBus();
QVERIFY(con.isConnected());
QDBusServiceWatcher watcher(serviceName, con, QDBusServiceWatcher::WatchForRegistration);
QSignalSpy spyR(&watcher, SIGNAL(serviceRegistered(QString)));
QSignalSpy spyU(&watcher, SIGNAL(serviceUnregistered(QString)));
QSignalSpy spyO(&watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)));
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceRegistered(QString)), SLOT(exitLoop()));
// register a name
QVERIFY(con.registerService(serviceName));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 1);
QCOMPARE(spyR.at(0).at(0).toString(), serviceName);
QCOMPARE(spyU.count(), 0);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QVERIFY(spyO.at(0).at(1).toString().isEmpty());
QCOMPARE(spyO.at(0).at(2).toString(), con.baseService());
spyR.clear();
spyU.clear();
spyO.clear();
watcher.setWatchMode(QDBusServiceWatcher::WatchForUnregistration);
// unregister it:
con.unregisterService(serviceName);
QTestEventLoop::instance().connect(&watcher, SIGNAL(serviceUnregistered(QString)), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(spyR.count(), 0);
QCOMPARE(spyU.count(), 1);
QCOMPARE(spyU.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.count(), 1);
QCOMPARE(spyO.at(0).at(0).toString(), serviceName);
QCOMPARE(spyO.at(0).at(1).toString(), con.baseService());
QVERIFY(spyO.at(0).at(2).toString().isEmpty());
}
QTEST_MAIN(tst_QDBusServiceWatcher)
#include "tst_qdbusservicewatcher.moc"
| 33.395522
| 105
| 0.694637
|
zwollerob
|
9dd2fbd09ba6dcd244a3d62627615d9dee4ca6ac
| 16,202
|
cpp
|
C++
|
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
src/core/commands.cpp
|
sellesoft/deshi
|
0bcd13bce29278f89fe6fe7b6658df349c104ee2
|
[
"Unlicense"
] | null | null | null |
/*Index:
@vars
@add
@run
@init
*/
#include "memory.h"
#define DESHI_CMD_START(name, desc) \
deshi__last_cmd_desc = str8_lit(desc); \
auto deshi__cmd__##name = [](str8* args, u32 arg_count) -> void
#define DESHI_CMD_END_NO_ARGS(name) \
; \
cmd_add(deshi__cmd__##name, str8_lit(#name), deshi__last_cmd_desc, 0, 0)
#define DESHI_CMD_END(name, ...) \
; \
local Type deshi__cmd__##name##args[] = {__VA_ARGS__}; \
cmd_add(deshi__cmd__##name, str8_lit(#name), deshi__last_cmd_desc, deshi__cmd__##name##args, ArrayCount(deshi__cmd__##name##args))
//TODO remove the need for this by having functions take in str8
#define temp_str8_cstr(s) (const char*)str8_copy(s, deshi_temp_allocator).str
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@vars
local array<Command> deshi__cmd_commands(deshi_allocator);
local array<Alias> deshi__cmd_aliases(deshi_allocator);
local str8 deshi__last_cmd_desc;
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@add
void cmd_add(CmdFunc func, str8 name, str8 desc, Type* args, u32 arg_count){
deshi__cmd_commands.add(Command{});
Command* cmd = &deshi__cmd_commands[deshi__cmd_commands.count-1];
cmd->func = func;
cmd->name = name;
cmd->desc = desc;
cmd->args = args;
cmd->arg_count = arg_count;
cmd->min_args = 0;
cmd->max_args = 0;
str8_builder builder;
str8_builder_init(&builder, name, deshi_allocator);
forI(arg_count){
cmd->max_args++;
str8_builder_append(&builder, str8_lit(" "));
if(args[i] & CmdArgument_OPTIONAL){
str8_builder_append(&builder, str8_lit("["));
}else{
str8_builder_append(&builder, str8_lit("<"));
cmd->min_args++;
}
if (args[i] & CmdArgument_S32){
str8_builder_append(&builder, str8_lit("S32"));
}else if(args[i] & CmdArgument_String){
str8_builder_append(&builder, str8_lit("String"));
}else{
Assert(!"unhandled command arguent");
NotImplemented;
}
if(args[i] & CmdArgument_OPTIONAL){
str8_builder_append(&builder, str8_lit("]"));
}else{
str8_builder_append(&builder, str8_lit(">"));
}
}
str8_builder_fit(&builder);
cmd->usage.str = builder.str;
cmd->usage.count = builder.count;
}
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@run
void cmd_run(str8 input){
array<str8> args(deshi_temp_allocator);
//split input by spaces (treating double quoted strings as one item)
//TODO nested aliases
while(input){
str8_advance_while(&input, ' ');
if(!input) break;
str8 word = input;
if(str8_index(word, 0).codepoint == '\"'){
str8_advance(&word);
word = str8_eat_until(word, '\"');
if(word){
args.add(word);
input.str = word.str+word.count+1;
input.count -= word.count+2;
}else{
args.add(input);
break;
}
}else{
word = str8_eat_until(word, ' ');
if(word){
b32 aliased = false;
forE(deshi__cmd_aliases){
if(str8_equal(word, it->alias)){
str8 temp = it->actual;
while(temp){
str8_advance_while(&temp, ' ');
str8 before = temp;
str8_advance_until(&temp, ' ');
args.add(str8{before.str, before.count-temp.count});
}
aliased = true;
break;
}
}
if(!aliased) args.add(word);
input.str = word.str+word.count;
input.count -= word.count;
}else{
b32 aliased = false;
forE(deshi__cmd_aliases){
if(str8_equal(input, it->alias)){
str8 temp = it->actual;
while(temp){
str8_advance_while(&temp, ' ');
str8 before = temp;
str8_advance_until(&temp, ' ');
args.add(str8{before.str, before.count-temp.count});
}
aliased = true;
break;
}
}
if(!aliased) args.add(input);
break;
}
}
}
if(args.count){
u32 args_count = args.count-1;
b32 found = false;
forE(deshi__cmd_commands){
if(str8_equal(args[0], it->name)){
if(it->func){
if(args_count < it->min_args){
LogE("cmd", "Command '",args[0],"' requires at least ",it->min_args," arguments");
}else if(args_count > it->max_args){
LogE("cmd", "Command '",args[0],"' requires at most ",it->max_args," arguments");
}else{
it->func(args.data+1, args_count);
}
}else{
LogE("cmd", "Command '",args[0],"' has no registered function");
}
found = true;
break;
}
}
if(!found){
LogE("cmd", "Unknown command '",args[0],"'");
}
}
}
//-////////////////////////////////////////////////////////////////////////////////////////////////
//@init
void cmd_init(){
DeshiStageInitStart(DS_CMD, DS_MEMORY, "Attempted to initialize Cmd module before initializing Memory module");
DESHI_CMD_START(test, "testing sandbox"){
console_log("{{c=magen}blah blah");
}DESHI_CMD_END_NO_ARGS(test);
DESHI_CMD_START(dir, "List the contents of a directory"){
array<File> files = file_search_directory(args[0]);
char time_str[1024];
if(files.count){
Log("cmd","Directory of '",args[0],"':");
forE(files){
strftime(time_str,1024,"%D %R",localtime((time_t*)&it->last_write_time));
Logf("cmd","%s %s %-30s %lu bytes", time_str,((it->is_directory)?"<DIR> ":"<FILE>"),
(const char*)it->name.str,it->bytes);
}
}
}DESHI_CMD_END(dir, CmdArgument_String);
DESHI_CMD_START(rm, "Remove a file"){
file_delete(args[0]);
}DESHI_CMD_END(rm, CmdArgument_String);
DESHI_CMD_START(file_exists, "Checks if a file exists"){
Log("cmd","File '",args[0],"' ",(file_exists(args[0])) ? "exists." : "does not exist.");
}DESHI_CMD_END(file_exists, CmdArgument_String);
DESHI_CMD_START(rename, "Renames a file"){
file_rename(args[0], args[1]);
}DESHI_CMD_END(rename, CmdArgument_String, CmdArgument_String);
DESHI_CMD_START(add, "Adds two numbers together"){
//TODO rework this to be 'calc' instead of just 'add'
s32 i0 = atoi(temp_str8_cstr(args[0]));
s32 i1 = atoi(temp_str8_cstr(args[1]));
Log("cmd", i0," + ",i1," = ", i0+i1);
}DESHI_CMD_END(add, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(daytime, "Logs the time in day-time format"){
u8 time_buffer[512];
time_t rawtime = time(0);
strftime((char*)time_buffer, 512, "%c", localtime(&rawtime));
Log("cmd",(const char*)time_buffer);
}DESHI_CMD_END_NO_ARGS(daytime);
DESHI_CMD_START(list, "Lists available commands"){
str8_builder builder;
str8_builder_init(&builder, {}, deshi_temp_allocator);
forE(deshi__cmd_commands){
str8_builder_append(&builder, it->name);
str8_builder_append(&builder, str8_lit(": "));
str8_builder_append(&builder, it->desc);
str8_builder_append(&builder, str8_lit("\n"));
}
Log("cmd", (const char*)builder.str);
}DESHI_CMD_END_NO_ARGS(list);
DESHI_CMD_START(help, "Logs description and usage of specified command"){
if(arg_count){
b32 found = false;
forE(deshi__cmd_commands){
if(str8_equal(it->name, args[0])){
Log("cmd", (const char*)it->desc.str);
Log("cmd", (const char*)it->usage.str);
found = true;
break;
}
}
if(!found) LogE("cmd", "Command '",args[0],"' not found");
}else{
Log("cmd", "Use 'help <command>' to get a description and usage of the command");
Log("cmd", "Use 'list' to get a list of all available commands");
Log("cmd", "Usage Format: command <required> [optional]");
}
}DESHI_CMD_END(help, CmdArgument_String|CmdArgument_OPTIONAL);
DESHI_CMD_START(alias, "Gives an alias to specified command and arguments"){
//check that alias' actual won't contain the alias
str8 cursor = args[1];
u32 alias_len = str8_length(args[0]);
u32 prev_codepoint = -1;
while(cursor){
if(args[0].count > cursor.count) break;
if( str8_nequal(cursor, args[0], alias_len)
&& (prev_codepoint == -1 || prev_codepoint == ' ')
&& (cursor.str+args[0].count == cursor.str+cursor.count || str8_index(cursor, alias_len).codepoint == ' ')){
LogE("cmd", "Aliases can't be recursive");
return;
}
prev_codepoint = str8_advance(&cursor).codepoint;
}
//check that alias doesnt start with a number
if(isdigit(str8_index(args[0], 0).codepoint)){
LogE("cmd", "Aliases can't start with a number");
return;
}
//check if name is used by a command
forE(deshi__cmd_commands){
if(str8_equal(it->name, args[0])){
LogE("cmd", "Aliases can't use the same name as an existing command");
return;
}
}
//check if alias already exists
u32 idx = -1;
forE(deshi__cmd_aliases){
if(str8_equal(it->alias, args[0])){
idx = it-it_begin;
break;
}
}
if(idx == -1){
deshi__cmd_aliases.add({str8_copy(args[0], deshi_allocator), str8_copy(args[1], deshi_allocator)});
}else{
memory_zfree(args[1].str);
deshi__cmd_aliases[idx].actual = str8_copy(args[1], deshi_allocator);
}
}DESHI_CMD_END(alias, CmdArgument_String, CmdArgument_String);
DESHI_CMD_START(aliases, "Lists available aliases"){
forE(deshi__cmd_aliases){
Log("cmd", (const char*)it->alias.str,": ",(const char*)it->actual.str);
}
}DESHI_CMD_END_NO_ARGS(aliases);
DESHI_CMD_START(window_display_mode, "Changes whether the window is in windowed(0), borderless(1), or fullscreen(2) mode"){
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
window_display_mode(window_active, DisplayMode_Windowed);
Log("cmd", "Window display mode updated to 'windowed'");
}break;
case 1:{
window_display_mode(window_active, DisplayMode_Borderless);
Log("cmd", "Window display mode updated to 'borderless'");
}break;
case 2:{
window_display_mode(window_active, DisplayMode_BorderlessMaximized);
Log("cmd", "Window display mode updated to 'borderless maximized'");
}break;
case 3:{
window_display_mode(window_active, DisplayMode_Fullscreen);
Log("cmd", "Window display mode updated to 'fullscreen'");
}break;
default:{
Log("cmd", "Display Modes: 0=Windowed, 1=Borderless, 2=Borderless Maximized, 3=Fullscreen");
}break;
}
}DESHI_CMD_END(window_display_mode, CmdArgument_S32);
DESHI_CMD_START(window_title, "Changes the title of the active window"){
window_title(window_active, args[0]);
Log("cmd","Updated active window's title to: ",args[0]);
}DESHI_CMD_END(window_title, CmdArgument_String);
DESHI_CMD_START(window_cursor_mode, "Changes whether the cursor is in default(0), first person(1), or hidden(2) mode"){
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
window_cursor_mode(window_active, CursorMode_Default);
Log("cmd", "Cursor mode updated to 'default'");
}break;
case 1:{
window_cursor_mode(window_active, CursorMode_FirstPerson);
Log("cmd", "Cursor mode updated to 'first person'");
}break;
default:{
Log("cmd", "Cursor Modes: 0=Default, 1=First Person");
}break;
}
}DESHI_CMD_END(window_cursor_mode, CmdArgument_S32);
DESHI_CMD_START(window_raw_input, "Changes whether the window uses raw input"){
LogE("cmd","Raw Input not setup yet");
return;
s32 mode = atoi((const char*)args[0].str);
switch(mode){
case 0:{
//window_active->UpdateRawInput(false);
Log("cmd", "Raw input updated to 'false'");
}break;
case 1:{
//window_active->UpdateRawInput(true);
Log("cmd", "Raw input updated to 'true'");
}break;
default:{
Log("cmd", "Raw Input: 0=False, 1=True");
}break;
}
}DESHI_CMD_END(window_raw_input, CmdArgument_S32);
DESHI_CMD_START(window_info, "Lists window's vars"){
str8 dispMode;
switch(window_active->display_mode){
case(DisplayMode_Windowed): { dispMode = str8_lit("Windowed"); }break;
case(DisplayMode_Borderless): { dispMode = str8_lit("Borderless"); }break;
case(DisplayMode_BorderlessMaximized):{ dispMode = str8_lit("Borderless Maximized"); }break;
case(DisplayMode_Fullscreen): { dispMode = str8_lit("Fullscreen"); }break;
}
str8 cursMode;
switch(window_active->cursor_mode){
case(CursorMode_Default): { cursMode = str8_lit("Default"); }break;
case(CursorMode_FirstPerson):{ cursMode = str8_lit("First Person"); }break;
}
Log("cmd",
"Window Info"
"\n Index: ",window_active->index,
"\n Title: ",window_active->title,
"\n Client Pos: ",window_active->x,",",window_active->y,
"\n Client Dims: ",window_active->width,"x",window_active->height,
"\n Decorated Pos: ",window_active->position_decorated.x,",",window_active->position_decorated.y,
"\n Decorated Dims: ",window_active->dimensions_decorated.x,"x",window_active->dimensions_decorated.y,
"\n Display Mode: ",dispMode,
"\n Cursor Mode: ",cursMode,
"\n Restore Pos: ",window_active->restore.x,",",window_active->restore.y,
"\n Restore Dims: ",window_active->restore.width,"x",window_active->restore.height);
}DESHI_CMD_END_NO_ARGS(window_info);
DESHI_CMD_START(mat_list, "Lists the materials and their info"){
Log("cmd", "Material List:\nName\tShader\tTextures");
forI(Storage::MaterialCount()){
Material* mat = Storage::MaterialAt(i);
str8_builder builder;
str8_builder_init(&builder, str8{(u8*)mat->name, (s64)strlen(mat->name)}, deshi_temp_allocator);
str8_builder_append(&builder, str8_lit("\t"));
str8_builder_append(&builder, ShaderStrings[mat->shader]);
str8_builder_append(&builder, str8_lit("\t"));
forI(mat->textures.count){
str8_builder_append(&builder, str8_lit(" "));
str8_builder_append(&builder, Storage::TextureName(mat->textures[i]));
}
Log("cmd", (const char*)builder.str);
}
}DESHI_CMD_END_NO_ARGS(mat_list);
DESHI_CMD_START(mat_texture, "Changes a texture of a material"){
s32 matID = atoi(temp_str8_cstr(args[0]));
s32 texSlot = atoi(temp_str8_cstr(args[1]));
s32 texID = atoi(temp_str8_cstr(args[2]));
Storage::MaterialAt(matID)->textures[texSlot] = texID;
Log("cmd", "Updated material ",Storage::MaterialName(matID),"'s texture",texSlot," to ",Storage::TextureName(texID));
}DESHI_CMD_END(mat_texture, CmdArgument_S32, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(mat_shader, "Changes the shader of a material"){
s32 matID = atoi(temp_str8_cstr(args[0]));
s32 shader = atoi(temp_str8_cstr(args[1]));
Storage::MaterialAt(matID)->shader = (Shader)shader;
Log("cmd", "Updated material ",Storage::MaterialName(matID),"'s shader to ", ShaderStrings[shader]);
}DESHI_CMD_END(mat_shader, CmdArgument_S32, CmdArgument_S32);
DESHI_CMD_START(shader_reload, "Reloads specified shader"){
s32 id = atoi((const char*)args[0].str);
if(id == -1){
render_reload_all_shaders();
console_log("{{t=CMD,c=magen}Reloaded all shaders");
}else if(id < Shader_COUNT){
render_reload_shader(id);
console_log("{{t=CMD,c=magen}Reloaded '",ShaderStrings[id]);
}else{
LogE("cmd", "There is no shader with id: ",id);
}
}DESHI_CMD_END(shader_reload, CmdArgument_S32);
DESHI_CMD_START(shader_list, "Lists the shaders and their info"){
Log("cmd", "Shader List:\nID\tName");
forI(ArrayCount(ShaderStrings)){
Log("cmd", i,'\t',ShaderStrings[i]);
}
}DESHI_CMD_END_NO_ARGS(shader_list);
DESHI_CMD_START(texture_load, "Loads a specific texture"){
Stopwatch load_stopwatch = start_stopwatch();
TextureType type = TextureType_2D;
if(arg_count == 2) type = (TextureType)atoi(temp_str8_cstr(args[1]));
Storage::CreateTextureFromFile(args[0], ImageFormat_RGBA, type);
Log("cmd", "Loaded texture '",args[0],"' in ",peek_stopwatch(load_stopwatch),"ms");
}DESHI_CMD_END(texture_load, CmdArgument_String, CmdArgument_S32|CmdArgument_OPTIONAL);
DESHI_CMD_START(texture_list, "Lists the textures and their info"){
Log("cmd", "Texture List:\nName\tWidth\tHeight\tDepth\tMipmaps\tType");
forI(Storage::TextureCount()){
Texture* tex = Storage::TextureAt(i);
Log("cmd", '\n',tex->name,'\t',tex->width,'\t',tex->height,'\t',tex->depth, '\t',tex->mipmaps,'\t',TextureTypeStrings[tex->type]);
}
}DESHI_CMD_END_NO_ARGS(texture_list);
DESHI_CMD_START(quit, "Exits the application"){
platform_exit();
}DESHI_CMD_END_NO_ARGS(quit);
DeshiStageInitEnd(DS_CMD);
}
#undef DESHI_CMD_START
#undef DESHI_CMD_END
| 34.545842
| 133
| 0.660351
|
sellesoft
|
9dd39adbcf01df8879247d8e0f45898bc7bd4eea
| 1,628
|
cpp
|
C++
|
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | 5
|
2019-05-11T18:33:32.000Z
|
2019-12-13T09:13:02.000Z
|
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | null | null | null |
LinkedList/0002-Add-Two-Numbers/main.cpp
|
FeiZhao0531/PlayLeetCode
|
ed23477fd6086d5139bda3d93feeabc09b06854d
|
[
"MIT"
] | null | null | null |
/// Source : https://leetcode.com/problems/add-two-numbers/description/
/// Author : Fei
/// Time : Jun-4-2019
#include "../SingleLinkedList.h"
#include "../SingleLinkedList.cpp"
#include <cassert>
using namespace std;
class Solution
{
public:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
assert( l1 && l2);
ListNode* sumHead = new ListNode(0);
ListNode* curr = sumHead;
int carry = 0;
while( l1 || l2 || carry) {
int sum = carry;
if( l1) {
sum += l1->val;
l1 = l1->next;
}
if( l2) {
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
curr->next = new ListNode( sum % 10);
curr = curr->next;
}
ListNode* res = sumHead->next;
delete sumHead;
sumHead = NULL;
return res;
}
};
int main()
{
int arr1[] = {2,4,3,1};
int arr2[] = {5,6,4};
// int arr1[] = {0};
// int arr2[] = {0};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]);
SingleLinkedList mysinglelinkedlist;
ListNode* l1 = mysinglelinkedlist.createSingleLinkedList(arr1, n1);
ListNode* l2 = mysinglelinkedlist.createSingleLinkedList(arr2, n2);
mysinglelinkedlist.printSingleLinkedList(l1);
mysinglelinkedlist.printSingleLinkedList(l2);
ListNode* head = Solution().addTwoNumbers(l1,l2);
mysinglelinkedlist.printSingleLinkedList(head);
mysinglelinkedlist.deleteSingleLinkedList(head);
return 0;
}
| 25.046154
| 71
| 0.565725
|
FeiZhao0531
|
9dd7e968b3ad4c4aa4f1ecf9cae9d75fd798df51
| 1,557
|
cpp
|
C++
|
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | 8
|
2019-06-06T13:31:01.000Z
|
2022-02-09T01:35:48.000Z
|
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | null | null | null |
test/test.cpp
|
jermp/mm_file
|
ed6dbb828d7ed85128241ef6693bf383d7f7cb2d
|
[
"MIT"
] | 1
|
2020-10-30T19:35:30.000Z
|
2020-10-30T19:35:30.000Z
|
#include <iostream>
#include "../include/mm_file/mm_file.hpp"
int main() {
std::string filename("./tmp.bin");
static const size_t n = 13;
{
// write n uint32_t integers
mm::file_sink<uint32_t> fout(filename, n);
std::cout << "mapped " << fout.bytes() << " bytes "
<< "for " << fout.size() << " integers" << std::endl;
auto* data = fout.data();
for (uint32_t i = 0; i != fout.size(); ++i) {
data[i] = i;
std::cout << "written " << data[i] << std::endl;
}
// test iterator
for (auto x : fout) {
std::cout << "written " << x << std::endl;
}
fout.close();
}
{
// instruct the kernel that we will read the content
// of the file sequentially
int advice = mm::advice::sequential;
// read the stream as uint16_t integers
mm::file_source<uint16_t> fin1(filename, advice);
std::cout << "mapped " << fin1.bytes() << " bytes "
<< "for " << fin1.size() << " integers" << std::endl;
auto const* data = fin1.data();
for (uint32_t i = 0; i != fin1.size(); ++i) {
std::cout << "read " << data[i] << std::endl;
}
fin1.close();
// test iterator
mm::file_source<uint16_t> fin2;
fin2.open(filename, advice);
for (auto x : fin2) {
std::cout << "read " << x << std::endl;
}
fin2.close();
}
std::remove(filename.c_str());
return 0;
}
| 27.803571
| 71
| 0.478484
|
jermp
|
9de2b001e9267ff1935a2426223f12bf406b5efe
| 225
|
cpp
|
C++
|
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2019-12-25T13:36:01.000Z
|
2019-12-25T13:36:01.000Z
|
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | null | null | null |
Pack_plugins/Pack_tool/ToolsModel.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2020-08-05T14:05:15.000Z
|
2020-08-05T14:05:15.000Z
|
#include "ToolsModel.h"
#include <QDesktopServices>
#include <QUrl>
ToolsModel::ToolsModel(QObject *parent) : QObject(parent)
{
}
void ToolsModel::openUrl(const QString &url)
{
QDesktopServices::openUrl(QUrl(url));
}
| 16.071429
| 57
| 0.728889
|
GreatCong
|
9de6658e6542fb507a086f453e6e84eafe9c93fa
| 1,155
|
cpp
|
C++
|
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | null | null | null |
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | null | null | null |
c10/10.5.cpp
|
sarthak-gupta-sg/hello-world
|
324f321a5454964b35b8399884d8c99971bd3425
|
[
"Apache-2.0"
] | 1
|
2020-05-30T04:30:16.000Z
|
2020-05-30T04:30:16.000Z
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <cstring>
using namespace std;
int main()
{
vector<const char * > roster1 { "abc", "def", "ghi"};
list<const char * > roster2 { "abc", "def", "ghi"};
//list<const char * > roster2(roster1.cbegin(), roster1.cend());
bool result;
result = equal(roster1.cbegin(), roster1.cend(), roster2.cbegin());
cout << "Your result is: " << result << "\n";
std::cout << (void *) roster1[0] << std::endl;
std::cout << (void *) roster2.front() << std::endl;
char const * c1 = "abcdef";
char const * c2 = "abcdef";
cout << *c1 << "\n";
if(c1 == c2)
{
cout << (void *)c1 << " and " << (void *)c2 << " are equal\n" ;
}
else
{
cout << (void *)c1 << " and " << (void *)c2 << " are not equal" ;
}
cout << "On linux g++ they are equal. On Windows cl.exe they are unequal\n";
cout << "\nstrlen: " << strlen(c1) << " vs sizeof: " << sizeof(c1) << "\n";
char c3[] = "def";
cout << "\nstrlen: " << strlen(c3) << " vs sizeof: " << sizeof(c3) << "\n";
return 0;
}
| 26.25
| 80
| 0.505628
|
sarthak-gupta-sg
|
9df5a52a4836c72b14bdce9701b3cab75024ea52
| 955
|
hpp
|
C++
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/depth/visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_STATE_CORE_DEPTH_STENCIL_DEPTH_VISITOR_HPP_INCLUDED
#define SGE_D3D9_STATE_CORE_DEPTH_STENCIL_DEPTH_VISITOR_HPP_INCLUDED
#include <sge/d3d9/state/render_vector.hpp>
#include <sge/renderer/state/core/depth_stencil/depth/enabled_fwd.hpp>
#include <sge/renderer/state/core/depth_stencil/depth/off_fwd.hpp>
namespace sge
{
namespace d3d9
{
namespace state
{
namespace core
{
namespace depth_stencil
{
namespace depth
{
class visitor
{
public:
typedef sge::d3d9::state::render_vector result_type;
result_type operator()(sge::renderer::state::core::depth_stencil::depth::off const &) const;
result_type operator()(sge::renderer::state::core::depth_stencil::depth::enabled const &) const;
};
}
}
}
}
}
}
#endif
| 21.704545
| 98
| 0.762304
|
cpreh
|
9dfe69429c5cf404fde62bcfe39ee68802b20349
| 1,064
|
hpp
|
C++
|
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
Embedded/terranova_sketch/ImuSensor.hpp
|
dhawkes36/TerraNova
|
8fc460d5f221370c8f0b84851c72432dea148b4e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Arduino.h>
#include <Wire.h>
#include <math.h>
#include "SparkFunLSM9DS1.h"
#define LSM9DS1_M 0x1E // Would be 0x1C if SDO_M is LOW
#define LSM9DS1_AG 0x6B // Would be 0x6A if SDO_AG is LOW
// Earth's magnetic field varies by location. Add or subtract
// a declination to get a more accurate heading. Calculate
// your's here:
// http://www.ngdc.noaa.gov/geomag-web/#declination
#define DECLINATION 12
struct ImuData
{
float gyro_x = NAN;
float gyro_y = NAN;
float gyro_z = NAN;
float accel_x = NAN;
float accel_y = NAN;
float accel_z = NAN;
float mag_x = NAN;
float mag_y = NAN;
float mag_z = NAN;
float pitch = NAN;
float roll = NAN;
float heading = NAN;
};
class ImuSensor
{
public:
ImuSensor():imu_(new LSM9DS1()){};
~ImuSensor(){delete imu_;};
bool init();
ImuData getData();
private:
LSM9DS1 *imu_;
float pitch_;
float roll_;
float heading_;
void calculateAttitude(const float &ax, const float &ay, const float &az, float mx, float my, float mz);
};
| 19.703704
| 108
| 0.668233
|
dhawkes36
|
3b01bb6578e79315fcb1c382fa78278162bf3488
| 885
|
hpp
|
C++
|
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
code/include/common/Mutex.hpp
|
StuntHacks/infinite-dungeons
|
b462dd27c4e0f7285940e45d086b5d022fea23df
|
[
"MIT"
] | null | null | null |
/**
* @file common/Mutex.hpp
* @brief Defines the Mutex class
*/
#pragma once
#ifdef __SWITCH__
#include <sys/lock.h>
#else
#ifdef __PC__
#include <mutex>
#endif
#endif
namespace id {
/**
* @brief A mutex
*/
class Mutex {
public:
/**
* @brief Creates the mutex
*/
Mutex();
/**
* @brief Destructor
*
* This automatically unlocks the mutex
*/
~Mutex();
/**
* @brief Locks the mutex
*/
void lock();
/**
* @brief Unlocks the mutex
*/
void unlock();
private:
/* data */
#ifdef __SWITCH__
_LOCK_RECURSIVE_T m_mutex;
#else
#ifdef __PC__
std::recursive_mutex m_mutex;
#endif
#endif
};
} /* id */
| 16.388889
| 47
| 0.444068
|
StuntHacks
|
3b0498e0685a650933d0c9e4519fc67dc41c8d3b
| 4,840
|
cpp
|
C++
|
tank_demo.cpp
|
alerdenisov/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 13
|
2017-08-02T03:59:45.000Z
|
2021-04-20T04:12:40.000Z
|
tank_demo.cpp
|
philsong/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 1
|
2021-05-11T02:36:30.000Z
|
2021-05-11T02:36:30.000Z
|
tank_demo.cpp
|
philsong/eos-tank-demo
|
9ef62fc22e8998d091d09298b0ffbd321e1f8cc2
|
[
"MIT"
] | 5
|
2017-07-31T05:27:42.000Z
|
2019-03-30T09:58:07.000Z
|
// Copyright (c) 2017 Aler Denisov
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tank_demo/tank_demo.hpp>
#include <tank_demo/checks.hpp>
#include <eoslib/print.hpp>
namespace TankDemo
{
using namespace eos;
/// When storing accounts, check for empty balance and remove account
void save_tank(AccountName owner, const Tank &tank)
{
/// value, scope
Tanks::store(tank, owner);
}
void move_tank(Tank &tank, int32_t new_x, int32_t new_y)
{
int64_t prev_hash = pos_to_hash(tank.x, tank.y);
Positions::remove(tank, prev_hash);
tank.x = new_x;
tank.y = new_y;
int64_t next_hash = pos_to_hash(new_x, new_y);
Positions::store(tank, next_hash);
}
void apply_spawn_tank(const Coordinate &coordinate)
{
requireAuth(coordinate.owner);
auto tank = get_tank(coordinate.owner);
require_true(tank.valid);
require_false(tank.in_game);
auto found = get_at_position(coordinate.x, coordinate.y);
require_false(found.valid);
tank.x = coordinate.x;
tank.y = coordinate.y;
tank.lives = INITIAL_LIVES;
tank.points = MAX_POINT_RECOVER;
int64_t hash = pos_to_hash(tank.x, tank.y);
Positions::store(tank, hash);
save_tank(coordinate.owner, tank);
}
void apply_move_tank(const Coordinate &coordinate)
{
requireAuth(coordinate.owner);
auto tank = get_tank(coordinate.owner);
require_ready(tank);
int32_t distance = get_distance(tank.x, tank.y, coordinate.x, coordinate.y);
require_not_less(int32_t(tank.points), distance);
auto found = get_at_position(coordinate.x, coordinate.y);
require_false(found.valid);
move_tank(tank, coordinate.x, coordinate.y);
tank.points -= distance;
save_tank(coordinate.owner, tank);
}
// execute fire transaction
void apply_fire(const Interact &interaction)
{
requireNotice(interaction.from, interaction.to);
requireAuth(interaction.from);
auto from = get_tank(interaction.from);
auto to = get_tank(interaction.to);
require_ready(from);
require_ready(to);
int32_t distance = get_distance(from.x, from.y, to.x, to.y);
// Check if tank have enough points
int32_t required_points = max(int32_t(1), distance - BASE_SHOT_DISTANCE);
require_not_more(required_points, int32_t(from.points));
from.points -= distance - BASE_SHOT_DISTANCE;
to.lives -= 1;
save_tank(interaction.from, from);
save_tank(interaction.to, to);
}
// execute share trx
void apply_share(const Interact &interaction)
{
requireNotice(interaction.from, interaction.to);
requireAuth(interaction.from);
auto from = get_tank(interaction.from);
auto to = get_tank(interaction.to);
require_ready(from);
require_ready(to);
// check if tank have enough points
require_not_less(from.points, uint32_t(1));
// TODO: check is distance is too far
int32_t distance = get_distance(from.x, from.y, to.x, to.y);
require_not_more(distance, int32_t(3));
from.points -= 1;
to.points += 1;
save_tank(interaction.from, from);
save_tank(interaction.to, to);
}
}
using namespace TankDemo;
extern "C" {
void init()
{
save_tank(N(tank), Tank(int32_t(0), int32_t(0)));
}
/// The apply method implements the dispatch of events to this contract
void apply(uint64_t code, uint64_t action)
{
if (code == N(tank))
{
if (action == N(spawn))
{
TankDemo::apply_spawn_tank(currentMessage<TankDemo::Coordinate>());
}
else if (action == N(move))
{
TankDemo::apply_move_tank(currentMessage<TankDemo::Coordinate>());
}
else if (action == N(fire))
{
TankDemo::apply_fire(currentMessage<TankDemo::Interact>());
}
else if (action == N(share))
{
TankDemo::apply_share(currentMessage<TankDemo::Interact>());
}
else if (action == N(info))
{
// not implemented yet
}
}
else if (code == N(judge))
{
// not implemented yet
}
}
}
| 26.888889
| 81
| 0.718595
|
alerdenisov
|
3b07a3124914a3223202fbd58b1008a8d750950a
| 6,514
|
cpp
|
C++
|
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
widgets/screenshotwidget.cpp
|
JLIT0/GBox
|
f5df851534bfb5cbdf0ae84d25e58a6cfdc69241
|
[
"Apache-2.0"
] | null | null | null |
/***********************************************************************
*Copyright 2010-20XX by 7ymekk
*
* 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.
*
* @author 7ymekk (7ymekk@gmail.com)
*
************************************************************************/
#include "screenshotwidget.h"
#include "ui_screenshotwidget.h"
#include <QMouseEvent>
#include <QFileDialog>
ScreenshotWidget::ScreenshotWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ScreenshotWidget)
{
ui->setupUi(this);
this->rotation = 0;
this->widthScreen = 320;
this->heightScreen = 480;
this->screenshot = QPixmap::fromImage(noScreenshotImage(this->widthScreen, this->heightScreen), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(this->screenshot);
connect(this->ui->buttonSaveScreenshot, SIGNAL(clicked()), this, SLOT(saveScreenshot()));
connect(this->ui->buttonRefreshScreenshot, SIGNAL(clicked()), this, SLOT(refreshScreenshot()));
connect(this->ui->buttonRotateLeft, SIGNAL(clicked()), this, SLOT(rotateLeft()));
connect(this->ui->buttonRotateRight, SIGNAL(clicked()), this, SLOT(rotateRight()));
this->setLayout(ui->layoutScreenshot);
refreshScreenshot();
}
ScreenshotWidget::~ScreenshotWidget()
{
delete ui;
}
void ScreenshotWidget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void ScreenshotWidget::resizeEvent(QResizeEvent * event)
{
Q_UNUSED(event);
QSize scaledSize = this->screenshot.size();
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
if (!this->ui->labelRgb565->pixmap() || scaledSize != this->ui->labelRgb565->pixmap()->size())
updateScreenshotLabel();
}
void ScreenshotWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
this->rotation = 0;
QSize scaledSize = QSize(this->widthScreen, this->heightScreen);
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
QPixmap pix = QPixmap::fromImage(noScreenshotImage(scaledSize.width(), scaledSize.height()), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(pix);
this->takeScreenshot();
}
}
void ScreenshotWidget::refreshScreenshot()
{
this->rotation = 0;
QSize scaledSize = QSize(this->widthScreen, this->heightScreen);
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
QPixmap pix = QPixmap::fromImage(noScreenshotImage(scaledSize.width(), scaledSize.height()), Qt::AutoColor);
this->ui->labelRgb565->setPixmap(pix);
takeScreenshot();
}
void ScreenshotWidget::rotateLeft()
{
QMatrix matrix;
QImage image;
image = this->screenshot.toImage();
this->rotation -= 90;
matrix.rotate(this->rotation);
image = image.transformed(matrix);
this->ui->labelRgb565->setPixmap(
QPixmap::fromImage(image, Qt::AutoColor).scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void ScreenshotWidget::rotateRight()
{
QMatrix matrix;
QImage image;
image = this->screenshot.toImage();
this->rotation += 90;
matrix.rotate(this->rotation);
image = image.transformed(matrix);
this->ui->labelRgb565->setPixmap(
QPixmap::fromImage(image, Qt::AutoColor).scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void ScreenshotWidget::saveScreenshot()
{
QFile plik;
plik.setFileName(QFileDialog::getSaveFileName(this, tr("Save File..."), "./screenshot.png", tr("Png file")+" (*.png)"));
if (plik.fileName().isEmpty())
return;
if (plik.open(QFile::WriteOnly))
{
QMatrix matrix;
matrix.rotate(this->rotation);
QImage image;
image = this->screenshot.toImage();
image = image.transformed(matrix);
image.save(&plik, "PNG");
plik.close();
}
}
void ScreenshotWidget::showScreenshot(QImage image, int width, int height)
{
this->rotation = 0;
QSize scaledSize = QSize(width, height);
scaledSize.scale(this->size(), Qt::KeepAspectRatio);
this->screenshot = QPixmap::fromImage(image, Qt::AutoColor);
this->ui->labelRgb565->setPixmap(this->screenshot.scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
disconnect(this, SLOT(showScreenshot(QImage,int,int)));
}
void ScreenshotWidget::takeScreenshot()
{
threadScreenshot.widthScreen = this->ui->labelRgb565->width();
threadScreenshot.heightScreen = this->ui->labelRgb565->height();
threadScreenshot.start();
connect(&threadScreenshot, SIGNAL(gotScreenshot(QImage, int, int)), this, SLOT(showScreenshot(QImage, int, int)));
}
void ScreenshotWidget::updateScreenshotLabel()
{
QMatrix matrix;
matrix.rotate(this->rotation);
QImage image;
image = this->screenshot.toImage();
image = image.transformed(matrix);
QSize scaledSize = image.size();
scaledSize.scale(this->ui->labelRgb565->size(), Qt::KeepAspectRatio);
this->ui->labelRgb565->setPixmap(QPixmap::fromImage(image.scaled(this->ui->labelRgb565->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation), Qt::AutoColor));
}
| 35.98895
| 125
| 0.600399
|
JLIT0
|
3b086f8c712fea2e9ee0e96726386d77990daf57
| 1,191
|
cpp
|
C++
|
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
src/lib/ConcurrentLib/ConcurrentObjects.cpp
|
Korovasoft/Concurrent-GARTH
|
2f22c464ce30f743b45bbd6c18a8546bee69be93
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////
////////////////////////////////////////
//
// Copyright (C) 2014 Korovasoft, Inc.
//
// File:
// \file ConcurrentObjects.cpp
//
// Description:
// \brief ConcurrentObjects Library implementation.
//
// Author:
// \author J. Caleb Wherry
//
////////////////////////////////////////
////////////////////////////////////////
// Forward declarations:
////
// Local includes:
#include "ConcurrentObjects.h"
// Compiler includes:
#include <stdexcept>
#include <thread>
/// ConcurrentObjects namespace
namespace ConcurrentObjects
{
ConcurrentCounter::ConcurrentCounter()
{
currentCount = 0;
}
ConcurrentCounter::ConcurrentCounter(uint32_t _maxCount):
maxCount(_maxCount),
currentCount(0)
{
// Do nothing.
}
void ConcurrentCounter::increment()
{
// Check to make sure count doesn't go above maxCount. If so, throw error:
if ( (currentCount+1) <= maxCount)
{
currentCount++;
}
else
{
throw std::out_of_range("Can't count that high!");
}
}
uint32_t ConcurrentCounter::getCount()
{
return currentCount;
}
} // ConcurrentObjects namespace
| 17.26087
| 78
| 0.555835
|
Korovasoft
|
3b13b6b256f7e9dd51deb0231598592148539d1c
| 23,624
|
cpp
|
C++
|
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/hardware/interface/linux/GpioDevPort.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2018 Jeff Jackowski
*/
#include <boost/exception/errinfo_file_name.hpp>
#include <boost/exception/errinfo_errno.hpp>
#include <duds/hardware/interface/linux/GpioDevPort.hpp>
#include <duds/hardware/interface/PinConfiguration.hpp>
#include <linux/gpio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
namespace duds { namespace hardware { namespace interface { namespace linux {
/**
* Initializes a gpiohandle_request structure.
* @param req The gpiohandle_request structure to be initialized.
* @param consumer The consumer name to place inside the gpiohandle_request.
*/
static void InitGpioHandleReq(
gpiohandle_request &req,
const std::string &consumer
) {
memset(&req, 0, sizeof(gpiohandle_request));
strcpy(req.consumer_label, consumer.c_str());
}
/**
* Adds a GPIO line offset to a gpiohandle_request object.
* @param req The request object that will hold the offset.
* @param offset The offset to add. It will be placed at the end.
*/
static void AddOffset(gpiohandle_request &req, std::uint32_t offset) {
#ifndef NDEBUG
// check limit on number of lines
assert(req.lines < GPIOHANDLES_MAX);
// ensure the offset is not already present
for (int idx = req.lines - 1; idx >= 0; --idx) {
assert(req.lineoffsets[idx] != offset);
}
#endif
req.lineoffsets[req.lines++] = offset;
}
/**
* Finds the array index that corresponds to the given offset. Useful in cases
* where the two do not match, such as with IoGpioRequest.
* @param req The request object to search.
* @param offset The pin offset to find.
* @return The index into the lineoffsets array in @a req for
* @a offset, or -1 if the offset was not found.
*/
static int FindOffset(gpiohandle_request &req, std::uint32_t offset) {
for (int idx = req.lines - 1; idx >= 0; --idx) {
if (req.lineoffsets[idx] == offset) {
return idx;
}
}
return -1;
}
/**
* Removes a GPIO line offset from a gpiohandle_request object.
* @param req The request object that holds the offset.
* @param offset The offset to remove. The offset at the end will take its
* place.
* @return True if the item was found and removed, false otherwise.
*/
static bool RemoveOffset(gpiohandle_request &req, std::uint32_t offset) {
// non-empty request?
if (req.lines) {
// search for offset
for (int idx = req.lines - 1; idx >= 0; --idx) {
if (req.lineoffsets[idx] == offset) {
// move last offset into spot of offset to remove
req.lineoffsets[idx] = req.lineoffsets[req.lines - 1];
// also move output state value
req.default_values[idx] = req.default_values[req.lines - 1];
// remove last
--req.lines;
return true;
}
}
}
return false;
}
/**
* Closes the file descriptor in the request object if it appears to have a
* file, and then sets the descriptor to zero.
* @param req The request object to modify.
*/
static void CloseIfOpen(gpiohandle_request &req) {
if (req.fd) {
close(req.fd);
req.fd = 0;
}
}
/**
* Requests input states from the kernel.
* If the request for using input rather than output has not yet been made,
* it will be made here. This is because it is valid to have set an input
* state, lose the access object, then create a new access object for the same
* pins, and assume the pins are still inputs. The request to use them as
* inputs, however, must be made again to the kernel.
* @param chipFd The file descriptor for the GPIO device. Needed for the
* GPIO_GET_LINEHANDLE_IOCTL operation that will occur if any
* of the pins has not yet been configured as an input.
* @param result The input states.
* @param req The request object with the input pins.
*/
static void GetInput(int chipFd, gpiohandle_data &result, gpiohandle_request &req) {
assert(req.flags & GPIOHANDLE_REQUEST_INPUT);
assert(req.lines > 0);
if (!req.fd && (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0)) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
assert(req.fd);
if (ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &result) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLineValuesError() <<
boost::errinfo_errno(res)
);
}
}
/**
* Sets the output states for all the pins in the request object.
* If the request for using output rather than input has not yet been made,
* it will be made here. This is because it is valid to have set an output
* state, lose the access object, then create a new access object for the same
* pins, and assume the pins are still outputs. The request to use them as
* outputs, however, must be made again to the kernel.
* @internal
* @param chipFd The file descriptor for the GPIO device. Needed for the
* GPIO_GET_LINEHANDLE_IOCTL operation that will occur if any
* of the pins has not yet been configured as an output.
* @param req The request object with the output pins and states.
* The default_values field is used for the output states,
* even when the pins are already configured as outputs.
*/
static void SetOutput(int chipFd, gpiohandle_request &req) {
assert(req.flags & GPIOHANDLE_REQUEST_OUTPUT);
assert(req.lines > 0);
if (!req.fd) {
// obtain new line handle only when it didn't already exist
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
// else, the above ioctl function succeeded and the output is now set
} else {
// already have line handle
assert(req.fd);
if (ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &(req.default_values)) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevSetLineValuesError() <<
boost::errinfo_errno(res)
);
}
}
}
/**
* An abstraction for using gpiohandle_request object(s).
* @author Jeff Jackowski
*/
class GpioRequest {
public:
virtual ~GpioRequest() { };
/**
* Configures the pin at the given offset as an input.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
*/
virtual void inputOffset(int chipFd, std::uint32_t offset) = 0;
/**
* Configures the pin at the given offset as an output.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
* @param state The output state for the pin.
*/
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) = 0;
/**
* Read from all input pins.
* @param chipFd The file descriptor for the GPIO device.
* @param result The input states.
* @param offsets A pointer to the start of an array with the line
* offset values for identifying where the input source.
* @param length The number of line offsets.
*/
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) = 0;
/**
* Configures pins as outputs and sets their output states.
* @param chipFd The file descriptor for the GPIO device.
*/
virtual void write(int chipFd) = 0;
/**
* Sets the output state of a single output pin.
* @pre The pin is already configured as an output.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
* @param state The output state for the pin.
*/
virtual void write(int chipFd, std::uint32_t offset, bool state) = 0;
/**
* Reads the input state of the indicated pin. Configures the pin as an
* input if not already an input.
* @param chipFd The file descriptor for the GPIO device.
* @param offset The pin offset.
*/
virtual bool inputState(int chipFd, std::uint32_t offset) = 0;
/**
* Sets the output state of a single pin in advance of making the output
* request to the port. Use write(int) to output the data.
* @param offset The pin offset.
* @param state The output state to store for the pin.
*/
virtual void outputState(std::uint32_t offset, bool state) = 0;
};
/**
* Implements using a single gpiohandle_request object for working with a
* single pin.
* @author Jeff Jackowski
*/
class SingleGpioRequest : public GpioRequest {
/**
* The request object.
*/
gpiohandle_request req;
public:
SingleGpioRequest(const std::string &consumer, std::uint32_t offset) {
InitGpioHandleReq(req, consumer);
req.lineoffsets[0] = offset;
req.lines = 1;
}
virtual ~SingleGpioRequest() {
CloseIfOpen(req);
}
virtual void inputOffset(int chipFd, std::uint32_t offset) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.flags = GPIOHANDLE_REQUEST_INPUT;
CloseIfOpen(req);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.flags = GPIOHANDLE_REQUEST_OUTPUT;
CloseIfOpen(req);
req.default_values[0] = state;
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &req) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) {
GetInput(chipFd, result, req);
offsets = req.lineoffsets;
length = 1;
}
virtual void write(int chipFd) {
SetOutput(chipFd, req);
}
virtual void write(int chipFd, std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
// early exit: already outputing the requested state
if (req.fd && (state == (req.default_values[0] > 0))) {
return;
}
// might not yet be an output
if (req.flags != GPIOHANDLE_REQUEST_OUTPUT) {
req.flags = GPIOHANDLE_REQUEST_OUTPUT;
CloseIfOpen(req);
}
req.default_values[0] = state;
SetOutput(chipFd, req);
}
virtual bool inputState(int chipFd, std::uint32_t offset) {
// offset must not change
assert(offset == req.lineoffsets[0]);
gpiohandle_data result;
// might not yet be an input
if (req.flags != GPIOHANDLE_REQUEST_INPUT) {
req.flags = GPIOHANDLE_REQUEST_INPUT;
CloseIfOpen(req);
}
GetInput(chipFd, result, req);
return result.values[0];
}
virtual void outputState(std::uint32_t offset, bool state) {
// offset must not change
assert(offset == req.lineoffsets[0]);
req.default_values[0] = state;
}
};
/**
* Implements using two gpiohandle_requests object for working with multiple
* pins.
* @author Jeff Jackowski
*/
class IoGpioRequest : public GpioRequest {
/**
* Input request.
*/
gpiohandle_request inReq;
/**
* Output request.
*/
gpiohandle_request outReq;
public:
IoGpioRequest(const std::string &consumer) {
InitGpioHandleReq(inReq, consumer);
InitGpioHandleReq(outReq, consumer);
inReq.flags = GPIOHANDLE_REQUEST_INPUT;
outReq.flags = GPIOHANDLE_REQUEST_OUTPUT;
}
virtual ~IoGpioRequest() {
CloseIfOpen(inReq);
CloseIfOpen(outReq);
}
void lastOutputState(bool state) {
outReq.default_values[outReq.lines - 1] = state;
}
/**
* Adds an offset for input use.
* @pre The offset is not in either the input or output set.
*/
void addInputOffset(std::uint32_t offset) {
AddOffset(inReq, offset);
}
/**
* Adds an offset for output use and sets the initial output state.
* @pre The offset is not in either the input or output set.
*/
void addOutputOffset(std::uint32_t offset, bool state) {
AddOffset(outReq, offset);
lastOutputState(state);
}
virtual void inputOffset(int chipFd, std::uint32_t offset) {
bool rem = RemoveOffset(outReq, offset);
assert(rem);
CloseIfOpen(outReq);
AddOffset(inReq, offset);
CloseIfOpen(inReq);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &inReq) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void outputOffset(int chipFd, std::uint32_t offset, bool state) {
bool rem = RemoveOffset(inReq, offset);
assert(rem);
CloseIfOpen(inReq);
AddOffset(outReq, offset);
CloseIfOpen(outReq);
lastOutputState(state);
if (ioctl(chipFd, GPIO_GET_LINEHANDLE_IOCTL, &outReq) < 0) {
int res = errno;
DUDS_THROW_EXCEPTION(GpioDevGetLinehandleError() <<
boost::errinfo_errno(res)
);
}
}
virtual void read(
int chipFd,
gpiohandle_data &result,
std::uint32_t *&offsets,
int &length
) {
GetInput(chipFd, result, inReq);
offsets = inReq.lineoffsets;
length = inReq.lines;
}
virtual void write(int chipFd) {
if (outReq.lines) {
SetOutput(chipFd, outReq);
}
}
virtual void write(int chipFd, std::uint32_t offset, bool state) {
int idx = FindOffset(outReq, offset);
assert(idx >= 0);
// early exit: already outputing the requested state
if (outReq.fd && (state == (outReq.default_values[idx] > 0))) {
return;
}
outReq.default_values[idx] = state;
SetOutput(chipFd, outReq);
}
virtual bool inputState(int chipFd, std::uint32_t offset) {
gpiohandle_data result;
GetInput(chipFd, result, inReq);
int idx = FindOffset(inReq, offset);
assert(idx >= 0);
return result.values[idx] > 0;
}
virtual void outputState(std::uint32_t offset, bool state) {
int idx = FindOffset(outReq, offset);
if (idx < 0) {
bool rem = RemoveOffset(inReq, offset);
// the pin must already be in a request object
assert(rem);
CloseIfOpen(inReq);
AddOffset(outReq, offset);
CloseIfOpen(outReq);
lastOutputState(state);
} else {
outReq.default_values[idx] = state;
}
}
};
// ---------------------------------------------------------------------------
GpioDevPort::GpioDevPort(
const std::string &path,
unsigned int firstid,
const std::string &username
) : DigitalPortIndependentPins(0, firstid), consumer(username), devpath(path) {
chipFd = open(path.c_str(), 0);
if (chipFd < 0) {
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path)
);
}
gpiochip_info cinfo;
if (ioctl(chipFd, GPIO_GET_CHIPINFO_IOCTL, &cinfo) < 0) {
int res = errno;
close(chipFd);
// could improve error reporting, but may not really matter
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path) << boost::errinfo_errno(res)
);
}
name = cinfo.name;
pins.resize(cinfo.lines);
for (std::uint32_t pidx = 0; pidx < cinfo.lines; ++pidx) {
initPin(pidx, pidx);
}
}
GpioDevPort::GpioDevPort(
const std::vector<unsigned int> &ids,
const std::string &path,
unsigned int firstid,
const std::string &username
) : DigitalPortIndependentPins(ids.size(), firstid), consumer(username),
devpath(path) {
chipFd = open(path.c_str(), 0);
if (chipFd < 0) {
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path)
);
}
gpiochip_info cinfo;
if (ioctl(chipFd, GPIO_GET_CHIPINFO_IOCTL, &cinfo) < 0) {
int res = errno;
close(chipFd);
// could improve error reporting, but may not really matter
DUDS_THROW_EXCEPTION(DigitalPortDoesNotExistError() <<
boost::errinfo_file_name(path) << boost::errinfo_errno(res)
);
}
name = cinfo.name;
std::vector<unsigned int>::const_iterator iter = ids.begin();
for (unsigned int pid = 0; iter != ids.end(); ++iter, ++pid) {
initPin(*iter, pid);
}
}
std::shared_ptr<GpioDevPort> GpioDevPort::makeConfiguredPort(
PinConfiguration &pc,
const std::string &name,
const std::string &defaultPath,
bool forceDefault
) {
// find the port's config object
const PinConfiguration::Port &port = pc.port(name);
// work out device file path
std::string path;
if (forceDefault || port.typeval.empty()) {
path = defaultPath;
} else {
path = port.typeval;
}
// enumerate the pins
std::vector<unsigned int> gpios;
unsigned int next = 0;
gpios.reserve(port.pins.size());
for (auto const &pin : port.pidIndex()) {
// pin IDs cannot be assigned arbitrary values
if ((pin.pid + port.idOffset) != pin.gid) {
DUDS_THROW_EXCEPTION(PortBadPinIdError() <<
PortPinId(pin.gid)
);
}
// need empty spots?
if (pin.pid > next) {
// add unavailable pins
gpios.insert(gpios.end(), pin.pid - next, -1);
}
// add available pin
gpios.push_back(pin.pid);
next = pin.pid + 1;
}
std::shared_ptr<GpioDevPort> sp = std::make_shared<GpioDevPort>(
gpios,
path,
port.idOffset
);
try {
pc.attachPort(sp, name);
} catch (PinError &pe) {
pe << boost::errinfo_file_name(path);
throw;
}
return sp;
}
GpioDevPort::~GpioDevPort() {
shutdown();
close(chipFd);
}
void GpioDevPort::initPin(std::uint32_t offset, unsigned int pid) {
if (offset == -1) {
// line cannot be used
pins[pid].markNonexistent();
return;
}
// prepare data for inquiry to kernel
gpioline_info linfo;
memset(&linfo, 0, sizeof(linfo)); // all examples do this; needed?
linfo.line_offset = offset;
// request data from the kernel; check for error
if (ioctl(chipFd, GPIO_GET_LINEINFO_IOCTL, &linfo) < 0) {
int res = errno;
close(chipFd);
DUDS_THROW_EXCEPTION(DigitalPortLacksPinError() <<
PinErrorId(globalId(offset)) << PinErrorPortId(offset) <<
boost::errinfo_errno(res) << boost::errinfo_file_name(devpath)
);
}
// used by kernel?
if (linfo.flags & GPIOLINE_FLAG_KERNEL) {
// line cannot be used
pins[pid].markNonexistent();
} else {
// set configuration to match reported status
if (linfo.flags & GPIOLINE_FLAG_IS_OUT) {
pins[pid].conf.options = DigitalPinConfig::DirOutput;
} else {
pins[pid].conf.options = DigitalPinConfig::DirInput;
}
if (linfo.flags & GPIOLINE_FLAG_OPEN_DRAIN) {
pins[pid].conf.options |= DigitalPinConfig::OutputDriveLow;
} else if (linfo.flags & GPIOLINE_FLAG_OPEN_SOURCE) {
pins[pid].conf.options |= DigitalPinConfig::OutputDriveHigh;
} else if (pins[pid].conf.options & DigitalPinConfig::DirOutput) {
pins[pid].conf.options |= DigitalPinConfig::OutputPushPull;
}
// no data on output currents
pins[pid].conf.minOutputCurrent = pins[pid].conf.maxOutputCurrent = 0;
// Unfortunately, the kernel reports on the current status of the line
// and not the line's capabilities. Report the line can do what the
// kernel supports, and hope this doesn't cause trouble.
pins[pid].cap.capabilities =
DigitalPinCap::Input |
DigitalPinCap::OutputPushPull /*|
DigitalPinCap::EventEdgeFalling | // theses are not yet supported
DigitalPinCap::EventEdgeRising |
DigitalPinCap::EventEdgeChange |
DigitalPinCap::InterruptOnEvent */;
// no data on output currents
pins[pid].cap.maxOutputCurrent = 0;
}
}
bool GpioDevPort::simultaneousOperations() const {
return true;
}
void GpioDevPort::madeAccess(DigitalPinAccess &acc) {
portData(acc).pointer = new SingleGpioRequest(consumer, acc.localId());
}
void GpioDevPort::madeAccess(DigitalPinSetAccess &acc) {
// create the request objects
IoGpioRequest *igr = new IoGpioRequest(consumer);
// fill stuff?
for (auto pid : acc.localIds()) {
const PinEntry &pe = pins[pid];
if (pe.conf.options & DigitalPinConfig::DirInput) {
//AddOffset(hreq->inReq, pid);
igr->addInputOffset(pid);
} else if (pe.conf.options & DigitalPinConfig::DirOutput) {
//AddOffset(hreq->outReq, pid);
igr->addOutputOffset(
pid,
(pe.conf.options & DigitalPinConfig::OutputState) > 0
);
}
assert(pe.conf.options & DigitalPinConfig::DirMask);
}
portData(acc).pointer = igr;
}
void GpioDevPort::retiredAccess(const DigitalPinAccess &acc) noexcept {
SingleGpioRequest *sgr;
portDataPtr(acc, &sgr);
delete sgr;
}
void GpioDevPort::retiredAccess(const DigitalPinSetAccess &acc) noexcept {
IoGpioRequest *igr;
portDataPtr(acc, &igr);
delete igr;
}
void GpioDevPort::configurePort(
unsigned int lid,
const DigitalPinConfig &cfg,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
DigitalPinConfig &dpc = pins[lid].conf;
// change in config?
if (
(dpc.options & DigitalPinConfig::DirMask) !=
(cfg & DigitalPinConfig::DirMask)
) {
if (cfg & DigitalPinConfig::DirInput) {
gr->inputOffset(chipFd, lid);
} else if (cfg & DigitalPinConfig::DirOutput) {
gr->outputOffset(
chipFd,
lid,
dpc.options & DigitalPinConfig::OutputState
);
}
}
} catch (PinError &pe) {
pe << PinErrorId(globalId(lid)) << boost::errinfo_file_name(devpath);
throw;
}
bool GpioDevPort::inputImpl(
unsigned int gid,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
int lid = localId(gid);
bool res = gr->inputState(chipFd, lid);
pins[lid].conf.options.setTo(DigitalPinConfig::InputState, res);
return res;
} catch (PinError &pe) {
pe << PinErrorId(gid) << boost::errinfo_file_name(devpath);
throw;
}
std::vector<bool> GpioDevPort::inputImpl(
const std::vector<unsigned int> &pvec,
DigitalPinAccessBase::PortData *pdata
) try {
GpioRequest *gr = (GpioRequest*)pdata->pointer;
gpiohandle_data result;
std::uint32_t *offsets;
int length;
gr->read(chipFd, result, offsets, length);
assert(length >= pvec.size());
// record input states
for (int idx = 0; idx < length; ++idx) {
pins[offsets[idx]].conf.options.setTo(
DigitalPinConfig::InputState,
result.values[idx] > 0
);
}
// return input states
std::vector<bool> outv(pvec.size());
int idx = 0;
for (const unsigned int &gid : pvec) {
outv[idx++] =
(pins[localId(gid)].conf.options & DigitalPinConfig::InputState) > 0;
}
return outv;
} catch (PinError &pe) {
pe << boost::errinfo_file_name(devpath);
throw;
}
void GpioDevPort::outputImpl(
unsigned int lid,
bool state,
DigitalPinAccessBase::PortData *pdata
) try {
// find the pin configuration
DigitalPinConfig &dpc = pins[lid].conf;
// get the request object to make modifications
GpioRequest *gr = (GpioRequest*)pdata->pointer;
// is output?
if (dpc.options & DigitalPinConfig::DirOutput) {
// set output state
gr->write(chipFd, lid, state);
}
// store new state; no change if error above
dpc.options.setTo(DigitalPinConfig::OutputState, state);
} catch (PinError &pe) {
pe << PinErrorId(globalId(lid)) << boost::errinfo_file_name(devpath);
throw;
}
void GpioDevPort::outputImpl(
const std::vector<unsigned int> &pvec,
const std::vector<bool> &state,
DigitalPinAccessBase::PortData *pdata
) try {
// get the request object to make modifications
GpioRequest *gr = (GpioRequest*)pdata->pointer;
// loop through all pins to alter
std::vector<unsigned int>::const_iterator piter = pvec.begin();
std::vector<bool>::const_iterator siter = state.begin();
int outs = 0;
for (; piter != pvec.end(); ++piter, ++siter) {
// configured for output? might be changing state ahead of config change
if (pins[*piter].conf.options & DigitalPinConfig::DirOutput) {
// configure the port data; no output happens yet
gr->outputState(*piter, *siter);
++outs;
}
// store new state
pins[*piter].conf.options.setTo(DigitalPinConfig::OutputState, *siter);
}
// send output if already in output state
if (outs) {
gr->write(chipFd);
}
} catch (PinError &pe) {
pe << boost::errinfo_file_name(devpath);
throw;
}
} } } } // namespaces
| 30.326059
| 84
| 0.696664
|
jjackowski
|
3b17e9e50f5e642166a51cf5a7d96726f77fd3ed
| 38,117
|
cpp
|
C++
|
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | 1
|
2022-02-15T21:00:31.000Z
|
2022-02-15T21:00:31.000Z
|
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | null | null | null |
src/library/renderbuffer.cpp
|
flubbe/swr
|
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
|
[
"MIT"
] | null | null | null |
/**
* swr - a software rasterizer
*
* frame buffer buffer implementation.
*
* \author Felix Lubbe
* \copyright Copyright (c) 2021
* \license Distributed under the MIT software license (see accompanying LICENSE.txt).
*/
/* user headers. */
#include "swr_internal.h"
namespace swr
{
namespace impl
{
/*
* helper lambdas.
* !!fixme: these are duplicated in fragment.cpp
*/
static auto to_uint32_mask = [](bool b) -> std::uint32_t
{
return ~(static_cast<std::uint32_t>(b) - 1);
};
static auto set_uniform_mask = [](bool mask[4], bool v)
{
mask[0] = mask[1] = mask[2] = mask[3] = v;
};
static auto apply_mask = [](bool mask[4], const auto additional_mask[4])
{
mask[0] &= static_cast<bool>(additional_mask[0]);
mask[1] &= static_cast<bool>(additional_mask[1]);
mask[2] &= static_cast<bool>(additional_mask[2]);
mask[3] &= static_cast<bool>(additional_mask[3]);
};
/*
* attachment_texture.
*/
bool attachment_texture::is_valid() const
{
if(tex_id == default_tex_id || tex == nullptr || info.data_ptr == nullptr)
{
return false;
}
if(level >= tex->data.data_ptrs.size())
{
return false;
}
if(tex_id >= global_context->texture_2d_storage.size())
{
return false;
}
if(!global_context->texture_2d_storage[tex_id])
{
return false;
}
return global_context->texture_2d_storage[tex_id].get() == tex && tex_id == tex->id && info.data_ptr == tex->data.data_ptrs[level];
}
#if defined(SWR_USE_MORTON_CODES) && 0
template<>
void scissor_clear_buffer(ml::vec4 clear_value, attachment_info<ml::vec4>& info, const utils::rect& scissor_box)
{
int x_min = std::min(std::max(0, scissor_box.x_min), info.width);
int x_max = std::max(0, std::min(scissor_box.x_max, info.width));
int y_min = std::min(std::max(0, scissor_box.y_max), info.height);
int y_max = std::max(0, std::min(scissor_box.y_min, info.height));
const auto row_size = x_max - x_min;
const auto skip = info.pitch - row_size;
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
for(int i = 0; i < row_size; ++i)
{
*ptr++ = clear_value;
}
ptr += skip;
}
}
#elif 0
template<typename T>
static void scissor_clear_buffer_morton(T clear_value, attachment_info<T>& info, const utils::rect& scissor_box)
{
int x_min = std::min(std::max(0, scissor_box.x_min), info.width);
int x_max = std::max(0, std::min(scissor_box.x_max, info.width));
int y_min = std::min(std::max(info.height - scissor_box.y_max, 0), info.height);
int y_max = std::max(0, std::min(info.height - scissor_box.y_min, info.height));
for(int y = y_min; y < y_max; ++y)
{
for(int x = x_min; x < x_max; ++x)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_value;
}
}
}
#endif
/*
* default framebuffer.
*/
void default_framebuffer::clear_color(uint32_t attachment, ml::vec4 clear_color)
{
if(attachment == 0)
{
auto& info = color_buffer.info;
utils::memset32(info.data_ptr, color_buffer.converter.to_pixel(clear_color), info.pitch * info.height);
}
}
void default_framebuffer::clear_color(uint32_t attachment, ml::vec4 clear_color, const utils::rect& rect)
{
if(attachment == 0)
{
auto clear_value = color_buffer.converter.to_pixel(clear_color);
int x_min = std::min(std::max(0, rect.x_min), color_buffer.info.width);
int x_max = std::max(0, std::min(rect.x_max, color_buffer.info.width));
int y_min = std::min(std::max(color_buffer.info.height - rect.y_max, 0), color_buffer.info.height);
int y_max = std::max(0, std::min(color_buffer.info.height - rect.y_min, color_buffer.info.height));
const auto row_size = (x_max - x_min) * sizeof(uint32_t);
auto ptr = reinterpret_cast<uint8_t*>(color_buffer.info.data_ptr) + y_min * color_buffer.info.pitch + x_min * sizeof(uint32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_value), row_size);
ptr += color_buffer.info.pitch;
}
}
}
void default_framebuffer::clear_depth(ml::fixed_32_t clear_depth)
{
auto& info = depth_buffer.info;
if(info.data_ptr)
{
utils::memset32(reinterpret_cast<uint32_t*>(info.data_ptr), ml::unwrap(clear_depth), info.pitch * info.height);
}
}
void default_framebuffer::clear_depth(ml::fixed_32_t clear_depth, const utils::rect& rect)
{
int x_min = std::min(std::max(0, rect.x_min), depth_buffer.info.width);
int x_max = std::max(0, std::min(rect.x_max, depth_buffer.info.width));
int y_min = std::min(std::max(depth_buffer.info.height - rect.y_max, 0), depth_buffer.info.height);
int y_max = std::max(0, std::min(depth_buffer.info.height - rect.y_min, depth_buffer.info.height));
const auto row_size = (x_max - x_min) * sizeof(ml::fixed_32_t);
auto ptr = reinterpret_cast<uint8_t*>(depth_buffer.info.data_ptr) + y_min * depth_buffer.info.pitch + x_min * sizeof(ml::fixed_32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_depth), row_size);
ptr += depth_buffer.info.pitch;
}
}
void default_framebuffer::merge_color(uint32_t attachment, int x, int y, const fragment_output& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment != 0)
{
return;
}
if(frag.write_flags & fragment_output::fof_write_color)
{
// convert color to output format.
uint32_t write_color = color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color));
// alpha blending.
uint32_t* color_buffer_ptr = color_buffer.info.data_ptr + y * color_buffer.info.width + x;
if(do_blend)
{
write_color = swr::output_merger::blend(color_buffer.converter, blend_src, blend_dst, write_color, *color_buffer_ptr);
}
// write color.
*color_buffer_ptr = write_color;
}
}
void default_framebuffer::merge_color_block(uint32_t attachment, int x, int y, const fragment_output_block& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment != 0)
{
return;
}
// generate write mask.
uint32_t color_write_mask[4] = {to_uint32_mask(frag.write_color[0]), to_uint32_mask(frag.write_color[1]), to_uint32_mask(frag.write_color[2]), to_uint32_mask(frag.write_color[3])};
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
if(frag.write_color[0] || frag.write_color[1] || frag.write_color[2] || frag.write_color[3])
{
// convert color to output format.
DECLARE_ALIGNED_ARRAY4(uint32_t, write_color) = {
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[0])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[1])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[2])),
color_buffer.converter.to_pixel(ml::clamp_to_unit_interval(frag.color[3]))};
// alpha blending.
uint32_t* color_buffer_ptr[4] = {
color_buffer.info.data_ptr + coords[0].y * color_buffer.info.width + coords[0].x,
color_buffer.info.data_ptr + coords[1].y * color_buffer.info.width + coords[1].x,
color_buffer.info.data_ptr + coords[2].y * color_buffer.info.width + coords[2].x,
color_buffer.info.data_ptr + coords[3].y * color_buffer.info.width + coords[3].x};
DECLARE_ALIGNED_ARRAY4(uint32_t, color_buffer_values) = {
*color_buffer_ptr[0], *color_buffer_ptr[1], *color_buffer_ptr[2], *color_buffer_ptr[3]};
if(do_blend)
{
// note: when compiling with SSE/SIMD enabled, make sure that src/dest/out are aligned on 16-byte boundaries.
swr::output_merger::blend_block(color_buffer.converter, blend_src, blend_dst, write_color, color_buffer_values, write_color);
}
// write color.
*(color_buffer_ptr[0]) = (color_buffer_values[0] & ~color_write_mask[0]) | (write_color[0] & color_write_mask[0]);
*(color_buffer_ptr[1]) = (color_buffer_values[1] & ~color_write_mask[1]) | (write_color[1] & color_write_mask[1]);
*(color_buffer_ptr[2]) = (color_buffer_values[2] & ~color_write_mask[2]) | (write_color[2] & color_write_mask[2]);
*(color_buffer_ptr[3]) = (color_buffer_values[3] & ~color_write_mask[3]) | (write_color[3] & color_write_mask[3]);
}
}
void default_framebuffer::depth_compare_write(int x, int y, float depth_value, comparison_func depth_func, bool write_depth, bool& write_mask)
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
write_mask = false;
return;
}
write_mask = write_depth;
// if no depth buffer was created, accept.
if(!depth_buffer.info.data_ptr)
{
return;
}
// read and compare depth buffer.
ml::fixed_32_t* depth_buffer_ptr = depth_buffer.info.data_ptr + y * depth_buffer.info.width + x;
ml::fixed_32_t old_depth_value = *depth_buffer_ptr;
ml::fixed_32_t new_depth_value{depth_value};
// basic comparisons for depth test.
bool depth_compare[] = {
true, /* pass */
false, /* fail */
new_depth_value == old_depth_value, /* equal */
false, /* not_equal */
new_depth_value < old_depth_value, /* less */
false, /* less_equal */
false, /* greater */
false /* greater_equal */
};
// compound comparisons for depth test.
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
// generate write mask for this fragment.
write_mask &= depth_compare[static_cast<std::uint32_t>(depth_func)];
// write depth value.
uint32_t depth_write_mask = to_uint32_mask(write_depth && write_mask);
*depth_buffer_ptr = ml::wrap((ml::unwrap(*depth_buffer_ptr) & ~depth_write_mask) | (ml::unwrap(new_depth_value) & depth_write_mask));
}
void default_framebuffer::depth_compare_write_block(int x, int y, float depth_value[4], comparison_func depth_func, bool write_depth, bool write_mask[4])
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
set_uniform_mask(write_mask, false);
return;
}
// if no depth buffer was created, accept.
if(!depth_buffer.info.data_ptr)
{
// the write mask is initialized with "accept all".
return;
}
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// read and compare depth buffer.
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_buffer.info.data_ptr + coords[0].y * depth_buffer.info.width + coords[0].x,
depth_buffer.info.data_ptr + coords[1].y * depth_buffer.info.width + coords[1].x,
depth_buffer.info.data_ptr + coords[2].y * depth_buffer.info.width + coords[2].x,
depth_buffer.info.data_ptr + coords[3].y * depth_buffer.info.width + coords[3].x};
ml::fixed_32_t old_depth_value[4] = {*depth_buffer_ptr[0], *depth_buffer_ptr[1], *depth_buffer_ptr[2], *depth_buffer_ptr[3]};
ml::fixed_32_t new_depth_value[4] = {depth_value[0], depth_value[1], depth_value[2], depth_value[3]};
// basic comparisons for depth test.
bool depth_compare[][4] = {
{true, true, true, true}, /* pass */
{false, false, false, false}, /* fail */
{new_depth_value[0] == old_depth_value[0], new_depth_value[1] == old_depth_value[1], new_depth_value[2] == old_depth_value[2], new_depth_value[3] == old_depth_value[3]}, /* equal */
{false, false, false, false}, /* not_equal */
{new_depth_value[0] < old_depth_value[0], new_depth_value[1] < old_depth_value[1], new_depth_value[2] < old_depth_value[2], new_depth_value[3] < old_depth_value[3]}, /* less */
{false, false, false, false}, /* less -<equal */
{false, false, false, false}, /* greater */
{false, false, false, false} /* greater_equal */
};
// compound comparisons for depth test.
for(int k = 0; k < 4; ++k)
{
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)][k] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
}
bool depth_mask[4] = {
depth_compare[static_cast<std::uint32_t>(depth_func)][0], depth_compare[static_cast<std::uint32_t>(depth_func)][1], depth_compare[static_cast<std::uint32_t>(depth_func)][2], depth_compare[static_cast<std::uint32_t>(depth_func)][3]};
apply_mask(write_mask, depth_mask);
// write depth.
uint32_t depth_write_mask[4] = {to_uint32_mask(write_mask[0] && write_depth), to_uint32_mask(write_mask[1] && write_depth), to_uint32_mask(write_mask[2] && write_depth), to_uint32_mask(write_mask[3] && write_depth)};
*(depth_buffer_ptr[0]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[0])) & ~depth_write_mask[0]) | (ml::unwrap(new_depth_value[0]) & depth_write_mask[0]));
*(depth_buffer_ptr[1]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[1])) & ~depth_write_mask[1]) | (ml::unwrap(new_depth_value[1]) & depth_write_mask[1]));
*(depth_buffer_ptr[2]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[2])) & ~depth_write_mask[2]) | (ml::unwrap(new_depth_value[2]) & depth_write_mask[2]));
*(depth_buffer_ptr[3]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[3])) & ~depth_write_mask[3]) | (ml::unwrap(new_depth_value[3]) & depth_write_mask[3]));
}
/*
* framebuffer_object
*/
void framebuffer_object::clear_color(uint32_t attachment, ml::vec4 clear_color)
{
if(attachment < color_attachments.size() && color_attachments[attachment])
{
// this also clears mipmaps, if present
auto& info = color_attachments[attachment]->info;
#ifdef SWR_USE_SIMD
utils::memset128(info.data_ptr, *reinterpret_cast<__m128i*>(&clear_color.data), info.pitch * info.height * sizeof(__m128));
#else /* SWR_USE_SIMD */
std::fill_n(info.data_ptr, info.pitch * info.height, clear_color);
#endif /* SWR_USE_SIMD */
}
}
void framebuffer_object::clear_color(uint32_t attachment, ml::vec4 clear_color, const utils::rect& rect)
{
if(attachment < color_attachments.size() && color_attachments[attachment])
{
#ifdef SWR_USE_MORTON_CODES
auto& info = color_attachments[attachment]->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(0, rect.y_min), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
for(int x = x_min; x < x_max; ++x)
{
for(int y = y_min; y < y_max; ++y)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_color;
}
}
#else
auto& info = color_attachments[attachment]->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(0, rect.y_min), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
const auto row_size = x_max - x_min;
# ifdef SWR_USE_SIMD
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
utils::memset128(ptr, *reinterpret_cast<__m128i*>(&clear_color.data), row_size * sizeof(__m128));
ptr += info.pitch;
}
# else /* SWR_USE_SIMD */
const auto skip = info.pitch - row_size;
auto ptr = info.data_ptr + y_min * info.pitch + x_min;
for(int y = y_min; y < y_max; ++y)
{
for(int i = 0; i < row_size; ++i)
{
*ptr++ = clear_color;
}
ptr += skip;
}
# endif /* SWR_USE_SIMD */
#endif /* SWR_USE_MORTON_CODES */
}
}
void framebuffer_object::clear_depth(ml::fixed_32_t clear_depth)
{
if(depth_attachment)
{
auto& info = depth_attachment->info;
utils::memset32(reinterpret_cast<uint32_t*>(info.data_ptr), ml::unwrap(clear_depth), info.pitch * info.height);
}
}
void framebuffer_object::clear_depth(ml::fixed_32_t clear_depth, const utils::rect& rect)
{
if(depth_attachment)
{
#ifdef SWR_USE_MORTON_CODES
auto& info = depth_attachment->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(rect.y_min, 0), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
for(int x = x_min; x < x_max; ++x)
{
for(int y = y_min; y < y_max; ++y)
{
*(info.data_ptr + libmorton::morton2D_32_encode(x, y)) = clear_depth;
}
}
#else
auto& info = depth_attachment->info;
int x_min = std::min(std::max(0, rect.x_min), info.width);
int x_max = std::max(0, std::min(rect.x_max, info.width));
int y_min = std::min(std::max(rect.y_min, 0), info.height);
int y_max = std::max(0, std::min(rect.y_max, info.height));
const auto row_size = (x_max - x_min) * sizeof(ml::fixed_32_t);
auto ptr = reinterpret_cast<uint8_t*>(info.data_ptr) + y_min * info.pitch + x_min * sizeof(ml::fixed_32_t);
for(int y = y_min; y < y_max; ++y)
{
utils::memset32(ptr, *reinterpret_cast<uint32_t*>(&clear_depth), row_size);
ptr += info.pitch;
}
#endif /* SWR_USE_MORTON_CODES */
}
}
void framebuffer_object::merge_color(uint32_t attachment, int x, int y, const fragment_output& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment > color_attachments.size() || !color_attachments[attachment])
{
return;
}
if(frag.write_flags & fragment_output::fof_write_color)
{
ml::vec4 write_color{ml::clamp_to_unit_interval(frag.color)};
ml::vec4* data_ptr = color_attachments[attachment]->info.data_ptr;
#ifndef SWR_USE_MORTON_CODES
int pitch = color_attachments[attachment]->info.pitch;
#endif
// alpha blending.
#ifdef SWR_USE_MORTON_CODES
ml::vec4* color_buffer_ptr = data_ptr + libmorton::morton2D_32_encode(x, y);
#else
ml::vec4* color_buffer_ptr = data_ptr + y * pitch + x;
#endif
if(do_blend)
{
write_color = swr::output_merger::blend(blend_src, blend_dst, write_color, *color_buffer_ptr);
}
// write color.
*color_buffer_ptr = write_color;
}
}
void framebuffer_object::merge_color_block(uint32_t attachment, int x, int y, const fragment_output_block& frag, bool do_blend, blend_func blend_src, blend_func blend_dst)
{
if(attachment > color_attachments.size() || !color_attachments[attachment])
{
return;
}
if(frag.write_color[0] || frag.write_color[1] || frag.write_color[2] || frag.write_color[3])
{
// convert color to output format.
ml::vec4 write_color[4] = {
ml::clamp_to_unit_interval(frag.color[0]),
ml::clamp_to_unit_interval(frag.color[1]),
ml::clamp_to_unit_interval(frag.color[2]),
ml::clamp_to_unit_interval(frag.color[3])};
ml::vec4* data_ptr = color_attachments[attachment]->info.data_ptr;
#ifndef SWR_USE_MORTON_CODES
int pitch = color_attachments[attachment]->info.pitch;
#endif
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// alpha blending.
#ifdef SWR_USE_MORTON_CODES
ml::vec4* color_buffer_ptrs[4] = {
data_ptr + libmorton::morton2D_32_encode(coords[0].x, coords[0].y),
data_ptr + libmorton::morton2D_32_encode(coords[1].x, coords[1].y),
data_ptr + libmorton::morton2D_32_encode(coords[2].x, coords[2].y),
data_ptr + libmorton::morton2D_32_encode(coords[3].x, coords[3].y)};
#else
ml::vec4* color_buffer_ptrs[4] = {
data_ptr + coords[0].y * pitch + coords[0].x,
data_ptr + coords[1].y * pitch + coords[1].x,
data_ptr + coords[2].y * pitch + coords[2].x,
data_ptr + coords[3].y * pitch + coords[3].x};
#endif
ml::vec4 color_buffer_values[4] = {
*color_buffer_ptrs[0], *color_buffer_ptrs[1], *color_buffer_ptrs[2], *color_buffer_ptrs[3]};
if(do_blend)
{
swr::output_merger::blend_block(blend_src, blend_dst, write_color, color_buffer_values, write_color);
}
// write color.
#define CONDITIONAL_WRITE(condition, write_target, write_source) \
if(condition) \
{ \
write_target = write_source; \
}
CONDITIONAL_WRITE(frag.write_color[0], *(color_buffer_ptrs[0]), write_color[0]);
CONDITIONAL_WRITE(frag.write_color[1], *(color_buffer_ptrs[1]), write_color[1]);
CONDITIONAL_WRITE(frag.write_color[2], *(color_buffer_ptrs[2]), write_color[2]);
CONDITIONAL_WRITE(frag.write_color[3], *(color_buffer_ptrs[3]), write_color[3]);
#undef CONDITIONAL_WRITE
}
}
//!!fixme: this is almost exactly the same as default_framebuffer::depth_compare_write.
void framebuffer_object::depth_compare_write(int x, int y, float depth_value, comparison_func depth_func, bool write_depth, bool& write_mask)
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
write_mask = false;
return;
}
write_mask = true;
// if no depth buffer was created, accept.
if(!depth_attachment || !depth_attachment->info.data_ptr)
{
return;
}
// read and compare depth buffer.
#ifdef SWR_USE_MORTON_CODES
ml::fixed_32_t* depth_buffer_ptr = depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(x, y);
#else
ml::fixed_32_t* depth_buffer_ptr = depth_attachment->info.data_ptr + y * depth_attachment->info.width + x;
#endif
ml::fixed_32_t old_depth_value = *depth_buffer_ptr;
ml::fixed_32_t new_depth_value{depth_value};
// basic comparisons for depth test.
bool depth_compare[] = {
true, /* pass */
false, /* fail */
new_depth_value == old_depth_value, /* equal */
false, /* not_equal */
new_depth_value < old_depth_value, /* less */
false, /* less_equal */
false, /* greater */
false /* greater_equal */
};
// compound comparisons for depth test.
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)];
// generate write mask for this fragment.
write_mask &= depth_compare[static_cast<std::uint32_t>(depth_func)];
// write depth value.
uint32_t depth_write_mask = to_uint32_mask(write_depth && write_mask);
*depth_buffer_ptr = ml::wrap((ml::unwrap(*depth_buffer_ptr) & ~depth_write_mask) | (ml::unwrap(new_depth_value) & depth_write_mask));
}
//!!fixme: this is almost exactly the same as default_framebuffer::depth_compare_write_block.
void framebuffer_object::depth_compare_write_block(int x, int y, float depth_value[4], comparison_func depth_func, bool write_depth, bool write_mask[4])
{
// discard fragment if depth testing is always failing.
if(depth_func == swr::comparison_func::fail)
{
set_uniform_mask(write_mask, false);
return;
}
// if no depth buffer was created, accept.
if(!depth_attachment || !depth_attachment->info.data_ptr)
{
// the write mask is initialized with "accept all".
return;
}
// block coordinates
const ml::tvec2<int> coords[4] = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};
// read and compare depth buffer.
#ifdef SWR_USE_MORTON_CODES
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[0].x, coords[0].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[1].x, coords[1].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[2].x, coords[2].y),
depth_attachment->info.data_ptr + libmorton::morton2D_32_encode(coords[3].x, coords[3].y)};
#else
ml::fixed_32_t* depth_buffer_ptr[4] = {
depth_attachment->info.data_ptr + coords[0].y * depth_attachment->info.width + coords[0].x,
depth_attachment->info.data_ptr + coords[1].y * depth_attachment->info.width + coords[1].x,
depth_attachment->info.data_ptr + coords[2].y * depth_attachment->info.width + coords[2].x,
depth_attachment->info.data_ptr + coords[3].y * depth_attachment->info.width + coords[3].x};
#endif
ml::fixed_32_t old_depth_value[4] = {*depth_buffer_ptr[0], *depth_buffer_ptr[1], *depth_buffer_ptr[2], *depth_buffer_ptr[3]};
ml::fixed_32_t new_depth_value[4] = {depth_value[0], depth_value[1], depth_value[2], depth_value[3]};
// basic comparisons for depth test.
bool depth_compare[][4] = {
{true, true, true, true}, /* pass */
{false, false, false, false}, /* fail */
{new_depth_value[0] == old_depth_value[0], new_depth_value[1] == old_depth_value[1], new_depth_value[2] == old_depth_value[2], new_depth_value[3] == old_depth_value[3]}, /* equal */
{false, false, false, false}, /* not_equal */
{new_depth_value[0] < old_depth_value[0], new_depth_value[1] < old_depth_value[1], new_depth_value[2] < old_depth_value[2], new_depth_value[3] < old_depth_value[3]}, /* less */
{false, false, false, false}, /* less -<equal */
{false, false, false, false}, /* greater */
{false, false, false, false} /* greater_equal */
};
// compound comparisons for depth test.
for(int k = 0; k < 4; ++k)
{
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::not_equal)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less)][k] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)][k] = !depth_compare[static_cast<std::uint32_t>(swr::comparison_func::less_equal)][k];
depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater_equal)][k] = depth_compare[static_cast<std::uint32_t>(swr::comparison_func::greater)] || depth_compare[static_cast<std::uint32_t>(swr::comparison_func::equal)][k];
}
bool depth_mask[4] = {
depth_compare[static_cast<std::uint32_t>(depth_func)][0], depth_compare[static_cast<std::uint32_t>(depth_func)][1], depth_compare[static_cast<std::uint32_t>(depth_func)][2], depth_compare[static_cast<std::uint32_t>(depth_func)][3]};
apply_mask(write_mask, depth_mask);
// write depth.
uint32_t depth_write_mask[4] = {to_uint32_mask(write_mask[0] && write_depth), to_uint32_mask(write_mask[1] && write_depth), to_uint32_mask(write_mask[2] && write_depth), to_uint32_mask(write_mask[3] && write_depth)};
*(depth_buffer_ptr[0]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[0])) & ~depth_write_mask[0]) | (ml::unwrap(new_depth_value[0]) & depth_write_mask[0]));
*(depth_buffer_ptr[1]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[1])) & ~depth_write_mask[1]) | (ml::unwrap(new_depth_value[1]) & depth_write_mask[1]));
*(depth_buffer_ptr[2]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[2])) & ~depth_write_mask[2]) | (ml::unwrap(new_depth_value[2]) & depth_write_mask[2]));
*(depth_buffer_ptr[3]) = ml::wrap((ml::unwrap(*(depth_buffer_ptr[3])) & ~depth_write_mask[3]) | (ml::unwrap(new_depth_value[3]) & depth_write_mask[3]));
}
} /* namespace impl */
/*
* framebuffer object interface.
*/
/** the default framebuffer has id 0. this constant is mostly here to make the code below more readable. */
constexpr uint32_t default_framebuffer_id = 0;
/** two more functions for handling the default_framebuffer_id case. */
static auto id_to_slot = [](std::uint32_t id) -> std::uint32_t
{ return id - 1; };
static auto slot_to_id = [](std::uint32_t slot) -> std::uint32_t
{ return slot + 1; };
uint32_t CreateFramebufferObject()
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
// set up a new framebuffer.
auto slot = context->framebuffer_objects.push({});
auto* new_fbo = &context->framebuffer_objects[slot];
new_fbo->reset(slot);
return slot_to_id(slot);
}
void ReleaseFramebufferObject(uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// do not release default framebuffer.
return;
}
auto slot = id_to_slot(id);
if(slot < context->framebuffer_objects.size() && !context->framebuffer_objects.is_free(slot))
{
// check if we are bound to a target and reset the target if necessary.
if(context->states.draw_target == &context->framebuffer_objects[slot])
{
context->states.draw_target = &context->framebuffer;
}
// release framebuffer object.
context->framebuffer_objects[slot].reset();
context->framebuffer_objects.free(slot);
}
}
void BindFramebufferObject(framebuffer_target target, uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// bind the default framebuffer.
if(target == framebuffer_target::draw || target == framebuffer_target::draw_read)
{
context->states.draw_target = &context->framebuffer;
}
if(target == framebuffer_target::read || target == framebuffer_target::draw_read)
{
/* unimplemented. */
}
return;
}
// check that the id is valid.
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_operation;
return;
}
if(target == framebuffer_target::draw || target == framebuffer_target::draw_read)
{
context->states.draw_target = &context->framebuffer_objects[slot];
}
if(target == framebuffer_target::read || target == framebuffer_target::draw_read)
{
/* unimplemented. */
}
}
void FramebufferTexture(uint32_t id, framebuffer_attachment attachment, uint32_t attachment_id, uint32_t level)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// textures cannot be bound to the default framebuffer.
context->last_error = error::invalid_value;
return;
}
int numeric_attachment = static_cast<int>(attachment);
if(numeric_attachment >= static_cast<int>(framebuffer_attachment::color_attachment_0) && numeric_attachment <= static_cast<int>(framebuffer_attachment::color_attachment_7))
{
// use texture as color buffer.
// get framebuffer object.
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_value;
return;
}
auto fbo = &context->framebuffer_objects[slot];
// get texture.
auto tex_id = attachment_id;
if(tex_id >= context->texture_2d_storage.size() || context->texture_2d_storage.is_free(tex_id))
{
context->last_error = error::invalid_value;
return;
}
// associate texture to fbo.
fbo->attach_texture(attachment, context->texture_2d_storage[tex_id].get(), level);
}
else
{
// unknown attachment.
context->last_error = error::invalid_value;
}
}
uint32_t CreateDepthRenderbuffer(uint32_t width, uint32_t height)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
auto slot = context->depth_attachments.push({});
context->depth_attachments[slot].allocate(width, height);
return slot;
}
void ReleaseDepthRenderbuffer(uint32_t id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id < context->depth_attachments.size() && !context->depth_attachments.is_free(id))
{
context->depth_attachments.free(id);
}
}
void FramebufferRenderbuffer(uint32_t id, framebuffer_attachment attachment, uint32_t attachment_id)
{
ASSERT_INTERNAL_CONTEXT;
impl::render_device_context* context = impl::global_context;
if(id == default_framebuffer_id)
{
// don't operate on the default framebuffer.
context->last_error = error::invalid_value;
return;
}
if(attachment != framebuffer_attachment::depth_attachment)
{
// currently only depth attachments are supported.
context->last_error = error::invalid_value;
return;
}
if(attachment_id >= context->depth_attachments.size() || context->depth_attachments.is_free(attachment_id))
{
context->last_error = error::invalid_value;
return;
}
auto slot = id_to_slot(id);
if(slot >= context->framebuffer_objects.size() || context->framebuffer_objects.is_free(slot))
{
context->last_error = error::invalid_value;
return;
}
auto& fbo = context->framebuffer_objects[slot];
fbo.attach_depth(&context->depth_attachments[attachment_id]);
}
} /* namespace swr */
| 42.541295
| 242
| 0.626859
|
flubbe
|
3b19c39ea419dc6a928525f68a89e55b9e06fff5
| 1,549
|
cpp
|
C++
|
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | 2
|
2015-01-07T18:36:39.000Z
|
2015-01-08T13:54:43.000Z
|
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | null | null | null |
pihud/src/Event.cpp
|
maximaximal/piga
|
54530c208e59eaaf8d44c1f8d640f5ec028d4126
|
[
"Zlib"
] | null | null | null |
#include <pihud/Event.hpp>
namespace PiH
{
Event::Event()
{
type = EventType::NotSet;
}
Event::Event(const InputEvent &inputEvent, int playerID)
{
type = EventType::Input;
input = inputEvent;
this->playerID = playerID;
}
Event::Event(const FocusEvent &focusEvent, int playerID)
{
type = EventType::Focus;
focus = focusEvent;
this->playerID = playerID;
}
Event::Event(const PigaEvent &pigaEvent, int playerID)
{
type = EventType::Piga;
piga = pigaEvent;
this->playerID = playerID;
}
Event::Event(const piga::GameEvent &gameEvent, bool focusEvent)
{
playerID = gameEvent.playerID();
if(gameEvent.type() == piga::GameEvent::GameInput && !focusEvent)
{
PigaEvent pigaEvent(gameEvent.gameInput.control(), gameEvent.gameInput.state());
type = EventType::Piga;
piga = pigaEvent;
}
else if(gameEvent.type() == piga::GameEvent::GameInput)
{
if((gameEvent.gameInput.control() == piga::DOWN
|| gameEvent.gameInput.control() == piga::LEFT
|| gameEvent.gameInput.control() == piga::RIGHT
|| gameEvent.gameInput.control() == piga::UP)
&& focusEvent)
{
type = EventType::Focus;
FocusEvent focusEvent(gameEvent);
focus = focusEvent;
}
}
}
Event::~Event()
{
}
}
| 28.163636
| 92
| 0.534538
|
maximaximal
|
3b226b50358c2dc65cb80efd38d9658b043f2ac0
| 1,114
|
cpp
|
C++
|
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 47
|
2016-05-20T08:49:47.000Z
|
2022-01-03T01:17:07.000Z
|
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | null | null | null |
utility/addressof.cpp
|
MaxHonggg/professional_boost
|
6fff73d3b9832644068dc8fe0443be813c7237b4
|
[
"BSD-2-Clause"
] | 37
|
2016-07-25T04:52:08.000Z
|
2022-02-14T03:55:08.000Z
|
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;
#include <boost/utility/addressof.hpp>
using namespace boost;
///////////////////////////////////////
void case1()
{
int i;
string s;
assert(&i == boost::addressof(i));
assert(&s == boost::addressof(s));
int a[10];
assert(&a == boost::addressof(a));
assert(a + 1 == boost::addressof(a[1]));
assert(&printf == boost::addressof(printf));
}
///////////////////////////////////////
class dont_do_this
{
public:
int x,y;
size_t operator&() const
{ return (size_t)&y; }
};
void case2()
{
dont_do_this d;
assert(&d != (size_t)boost::addressof(d));
assert(&d == (size_t)&d.y);
dont_do_this *p = boost::addressof(d);
p->x = 1;
}
///////////////////////////////////////
class danger_class
{
void operator&() const;
};
void case3()
{
danger_class d;
// cout << &d;
cout << boost::addressof(d);
}
///////////////////////////////////////
int main()
{
std::cout << "hello addressof" << std::endl;
case1();
case2();
case3();
}
| 15.914286
| 48
| 0.487433
|
MaxHonggg
|
3b26b2e687ade339b075dcd2ff136e1fb3236ecb
| 2,434
|
hpp
|
C++
|
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | 2
|
2015-10-15T19:32:42.000Z
|
2021-12-20T15:56:04.000Z
|
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | null | null | null |
gcpp/classes/opathspec.hpp
|
razzlefratz/MotleyTools
|
3c69c574351ce6f4b7e687c13278d4b6cbb200f3
|
[
"0BSD"
] | null | null | null |
/*====================================================================*
*
* opathspec.hpp - interface for the opathspec class.
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef oPATH_HEADER
#define oPATH_HEADER
/*====================================================================*
* system header files;
*--------------------------------------------------------------------*/
#include <sys/stat.h>
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/stdafx.hpp"
#include "../classes/owildcard.hpp"
/*====================================================================*
*
*--------------------------------------------------------------------*/
class __declspec (dllexport) opathspec: private owildcard
{
public:
opathspec ();
virtual ~ opathspec ();
bool isdotdir (char const * filename);
bool exists (char const * pathname);
bool infolder (char fullname [], char const * wildcard, bool recurse);
bool instring (char fullname [], char const * pathname, char const * filename);
bool instring (char fullname [], char const * pathname, char const * filename, bool recurse);
bool invector (char fullname [], char const * pathname [], char const * filename);
bool invector (char fullname [], char const * pathname [], char const * filename, bool recurse);
char const * dirname (char const * filespec);
char const * basename (char const * filespec);
void fullpath (char fullname [], char const * filespec);
void makepath (char fullname [], char const * pathname, char const * filename);
void findpath (char const * fullname, char pathname [], char filename []);
void partpath (char const * fullname, char pathname [], char filename []);
void partfile (char const * filename, char basename [], char extender []);
private:
struct stat mstatinfo;
void splitpath (char * filespec);
void mergepath ();
char ** mstack;
unsigned mindex;
unsigned mstart;
unsigned mlevel;
unsigned mcount;
unsigned mlimit;
};
/*====================================================================*
*
*--------------------------------------------------------------------*/
#endif
| 34.28169
| 97
| 0.497124
|
razzlefratz
|
3b281d2749fc00e1bb7f10dea504edd642437cea
| 1,026
|
hpp
|
C++
|
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
src/lib/builders/interpretable.hpp
|
bunsanorg/bacs_system
|
22149ecfaac913b820dbda52933bf8ea9fecd723
|
[
"Apache-2.0"
] | null | null | null |
#include "compilable.hpp"
namespace bacs {
namespace system {
namespace builders {
class interpretable : public compilable {
protected:
name_type name(const bacs::process::Source &source) override;
};
class interpretable_executable : public compilable_executable {
public:
interpretable_executable(const ContainerPointer &container,
bunsan::tempfile &&tmpdir,
const compilable::name_type &name,
const boost::filesystem::path &executable,
const std::vector<std::string> &flags_ = {});
ProcessPointer create(const ProcessGroupPointer &process_group,
const ProcessArguments &arguments) override;
protected:
virtual std::vector<std::string> arguments() const;
virtual std::vector<std::string> flags() const;
private:
const boost::filesystem::path m_executable;
const std::vector<std::string> m_flags;
};
} // namespace builders
} // namespace system
} // namespace bacs
| 29.314286
| 72
| 0.662768
|
bunsanorg
|
3b2958e86930fc17a868e5f4663e908315b57621
| 28,856
|
cpp
|
C++
|
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 17
|
2020-11-23T07:24:16.000Z
|
2022-03-28T10:29:06.000Z
|
ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.cpp
|
urgu00/QuantLib
|
fecce0abb0ff3d50da29c129f8f9e73176e20ab9
|
[
"BSD-3-Clause"
] | 7
|
2017-04-24T08:28:43.000Z
|
2022-03-15T08:59:54.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2018 Sebastian Schlenkrich
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <sstream>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/experimental/vanillalocalvolmodel/vanillalocalvolmodel.hpp>
namespace {
// we need to calculate the cumulative normal distribution function (and derivative)
// in various places
QuantLib::CumulativeNormalDistribution Phi;
// we need to convert numbers to strings for logging
template <typename T>
std::string to_string(T val) {
std::stringstream stream;
stream << val;
return stream.str();
}
}
namespace QuantLib {
// we have two constructors and want to make sure the setup is consistent
void VanillaLocalVolModel::initializeDeepInTheModelParameters() {
straddleATM_ = sigmaATM_ * sqrt(T_) * M_1_SQRTPI * M_SQRT_2 * 2.0;
if (useInitialMu_) mu_ = initialMu_;
else mu_ = -(Mm_[0] + Mp_[0]) / 4.0 * T_; // this should be exact for shifted log-normal models
alpha_ = 1.0;
nu_ = 0.0;
extrapolationStdevs_ = 10.0;
sigma0Tol_ = 1.0e-12;
S0Tol_ = 1.0e-12;
}
Real VanillaLocalVolModel::localVol(const bool isRightWing, const Size k, const Real S) {
// this is an unsafe method specifying the vol function sigma(S) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
return sigma0 + Mp_[k] * (S - S0);
} else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
return sigma0 + Mm_[k] * (S - S0);
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::underlyingS(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the underlying level S(x) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real deltaS = (Mp_[k] == 0.0) ? (sigma0*(x - x0)) : (sigma0 / Mp_[k] * (exp(Mp_[k] * (x - x0)) - 1.0));
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
return S0 + deltaS;
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real deltaS = (Mm_[k] == 0.0) ? (sigma0*(x - x0)) : (sigma0 / Mm_[k] * (exp(Mm_[k] * (x - x0)) - 1.0));
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
return S0 + deltaS;
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::underlyingX(const bool isRightWing, const Size k, const Real S) {
// this is an unsafe method specifying the underlying level x(S) on the individual segments
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 > 0.0, "sigma0 > 0.0 required");
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real S0 = (k > 0) ? Sp_[k - 1] : S0_;
Real deltaX = (Mp_[k] == 0.0) ? ((S - S0) / sigma0) : (log(1.0 + Mp_[k] / sigma0*(S - S0)) / Mp_[k]);
return x0 + deltaX;
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 > 0.0, "sigma0 > 0.0 required");
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real S0 = (k > 0) ? Sm_[k - 1] : S0_;
Real deltaX = (Mm_[k] == 0.0) ? ((S - S0) / sigma0) : (log(1.0 + Mm_[k] / sigma0*(S - S0)) / Mm_[k]);
return x0 + deltaX;
}
return 0.0; // this should never be reached
}
Real VanillaLocalVolModel::primitiveF(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the primitive function F(x) = \int [alpha S(x) + nu] p(x) dx
// on the individual segments
Real sigma0, x0, S0, m0;
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
x0 = (k > 0) ? Xp_[k - 1] : 0.0;
S0 = (k > 0) ? Sp_[k - 1] : S0_;
m0 = Mp_[k];
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
x0 = (k > 0) ? Xm_[k - 1] : 0.0;
S0 = (k > 0) ? Sm_[k - 1] : S0_;
m0 = Mm_[k];
}
Real y0 = (x0 - mu_) / sqrt(T_);
Real y1 = (x - mu_) / sqrt(T_);
Real h = m0 * sqrt(T_);
Real Ny = Phi(y1);
Real term1, term2;
if (m0 == 0.0) {
term1 = (S0 + nu_ / alpha_ - sigma0 * sqrt(T_) * y0) * Ny;
term2 = sigma0 * sqrt(T_) * Phi.derivative(y1); // use dN/dx = dN/dy / sqrt(T)
}
else {
Real NyMinush = Phi(y1 - h);
term1 = exp(h*h / 2.0 - h*y0)*sigma0 / m0 * NyMinush;
term2 = (sigma0 / m0 - (S0 + nu_ / alpha_)) * Ny;
}
return alpha_ * (term1 - term2);
}
Real VanillaLocalVolModel::primitiveFSquare(const bool isRightWing, const Size k, const Real x) {
// this is an unsafe method specifying the primitive function F(x) = \int [alpha S(x) + nu]^2 p(x) dx
// on the individual segments
Real sigma0, x0, S0, m0;
if (isRightWing) {
QL_REQUIRE(k < sigmaP_.size(), "k < sigmaP_.size() required.");
sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
x0 = (k > 0) ? Xp_[k - 1] : 0.0;
S0 = (k > 0) ? Sp_[k - 1] : S0_;
m0 = Mp_[k];
}
else {
QL_REQUIRE(k < sigmaM_.size(), "k < sigmaM_.size() required.");
sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
x0 = (k > 0) ? Xm_[k - 1] : 0.0;
S0 = (k > 0) ? Sm_[k - 1] : S0_;
m0 = Mm_[k];
}
Real y0 = (x0 - mu_) / sqrt(T_);
Real y1 = (x - mu_) / sqrt(T_);
Real h = m0 * sqrt(T_);
Real Ny = Phi(y1);
Real sum = 0;
if (m0 == 0.0) {
Real K3 = S0 + nu_ / alpha_ - sigma0 * sqrt(T_) * y0;
Real term1 = (K3 * K3 + sigma0 * sigma0 * T_) * Ny;
Real term2 = 2.0 * sigma0 * sqrt(T_) * K3 + sigma0 * sigma0 * T_ * y1;
term2 *= Phi.derivative(y1); // use dN/dx = dN/dy / sqrt(T)
sum = term1 - term2;
}
else {
Real NyMinush = Phi(y1 - h);
Real NyMinus2h = Phi(y1 - 2.0*h);
Real K1 = sigma0 / m0 * exp(h*(h - y0));
Real K2 = S0 + nu_ / alpha_ - sigma0 / m0;
Real term1 = K2 * K2 * Ny;
Real term2 = 2.0 * K1 * K2 * exp(-h*h / 2.0) * NyMinush;
Real term3 = K1 * K1 * NyMinus2h;
sum = term1 + term2 + term3;
}
return alpha_ * alpha_ * sum;
}
void VanillaLocalVolModel::calculateSGrid() {
// this is an unsafe method to calculate the S-grid for a given x-grid
// it is intended as a preprocessing step in conjunction with smile interplation
// validity of the model is ensured by proceeding it with updateLocalVol()
for (Size k = 0; k < Xp_.size(); ++k) { // right wing calculations
Sp_[k] = underlyingS(true, k, Xp_[k]);
sigmaP_[k] = localVol(true, k, Sp_[k]);
}
for (Size k = 0; k < Sm_.size(); ++k) { // left wing calculations
Sm_[k] = underlyingS(false, k, Xm_[k]);
sigmaM_[k] = localVol(false, k, Sm_[k]);
}
}
void VanillaLocalVolModel::updateLocalVol() {
// use ODE solution to determine x-grid and sigma-grid taking into account constraints of
// positive local volatility and local vol extrapolation
for (Size k = 0; k < Sp_.size(); ++k) { // right wing calculations
Real x0 = (k > 0) ? Xp_[k - 1] : 0.0;
Real sigma0 = (k > 0) ? sigmaP_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 >= 0.0, "sigma0 >= 0.0 required.");
if ((k == Sp_.size() - 1)||(localVol(true, k, Sp_[k])<=0.0)||(underlyingX(true, k, Sp_[k])>upperBoundX())) { // right wing extrapolation, maybe better use some epsilon here
Real XRight = upperBoundX(); // mu might not yet be calibrated
QL_REQUIRE(XRight >= x0, "XRight >= x0 required.");
Xp_[k] = XRight;
Sp_[k] = underlyingS(true, k, XRight);
sigmaP_[k] = localVol(true, k, Sp_[k]);
if (k < Sp_.size() - 1) Mp_[k + 1] = Mp_[k]; // we need to make sure vol doesn't go up again
continue;
}
sigmaP_[k] = localVol(true, k, Sp_[k]);
QL_REQUIRE(sigmaP_[k] > 0.0, "sigmaP_[k] > 0.0 required.");
Xp_[k] = underlyingX(true, k, Sp_[k]);
}
for (Size k = 0; k < Sm_.size(); ++k) { // left wing calculations
Real x0 = (k > 0) ? Xm_[k - 1] : 0.0;
Real sigma0 = (k > 0) ? sigmaM_[k - 1] : sigma0_;
QL_REQUIRE(sigma0 >= 0.0, "sigma0 >= 0.0 required.");
if ((k == Sm_.size() - 1)||(localVol(false, k, Sm_[k]) <= 0.0)||(underlyingX(false, k, Sm_[k])<lowerBoundX())) { // left wing extrapolation, maybe better use some epsilon here
Real XLeft = lowerBoundX(); // mu might not yet be calibrated
QL_REQUIRE(XLeft <= x0, "XLeft <= x0 required.");
Xm_[k] = XLeft;
Sm_[k] = underlyingS(false, k, XLeft);
sigmaM_[k] = localVol(false, k, Sm_[k]);
if (k < Sm_.size() - 1) Mm_[k + 1] = Mm_[k]; // we need to make sure vol doesn't go up again
continue;
}
sigmaM_[k] = localVol(false, k, Sm_[k]);
QL_REQUIRE(sigmaM_[k] > 0.0, "sigmaM_[k] > 0.0 required.");
Xm_[k] = underlyingX(false, k, Sm_[k]);
}
}
void VanillaLocalVolModel::calibrateATM() {
Real straddleVega = straddleATM_ / sigmaATM_;
Real forwardMinusStrike0, forwardMinusStrike1, straddleMinusATM0, straddleMinusATM1, dmu, dlogSigma0;
Real dfwd_dmu, dstr_dlogSigma0, logSigma0=log(sigma0_);
for (Size k = 0; k < maxCalibrationIters_; ++k) {
Real call = expectation(true, S0_);
Real put = expectation(false, S0_);
forwardMinusStrike1 = call - put;
straddleMinusATM1 = call + put - straddleATM_;
if (k > 0) { // perform line search
Real num = forwardMinusStrike0*(forwardMinusStrike1 - forwardMinusStrike0) +
straddleMinusATM0*(straddleMinusATM1 - straddleMinusATM0);
Real den = (forwardMinusStrike1 - forwardMinusStrike0)*(forwardMinusStrike1 - forwardMinusStrike0) +
(straddleMinusATM1 - straddleMinusATM0)*(straddleMinusATM1 - straddleMinusATM0);
Real lambda = -num / den;
Real eps = 1.0e-6; // see Griewank '86
if (lambda < -0.5 - eps) lambda = -0.5;
else if (lambda < -eps); // lambda = lambda;
else if (lambda < 0.0) lambda = -eps;
else if (lambda <= eps) lambda = eps;
else if (lambda <= 0.5 + eps); // lambda = lambda;
else lambda = 1.0;
if (lambda < 1.0) { // reject the step and calculate a new try
// x = x - dx + lambda dx = x + (lambda - 1.0) dx
mu_ += (lambda - 1.0) * dmu;
logSigma0 += (lambda - 1.0) * dlogSigma0;
dmu *= lambda;
dlogSigma0 *= lambda;
sigma0_ = exp(logSigma0);
updateLocalVol();
if (enableLogging_) logging_.push_back("k: " + to_string(k) +
"; C: " + to_string(call) +
"; P: " + to_string(put) +
"; S: " + to_string(straddleATM_) +
"; lambda: " + to_string(lambda) +
"; dmu: " + to_string(dmu) +
"; dlogSigma0: " + to_string(dlogSigma0));
continue; // don't update derivatives and step direction for rejected steps
}
}
if (k == 0) {
dfwd_dmu = sigma0_; // this is an estimate based on dS/dX at ATM
dstr_dlogSigma0 = straddleVega * sigma0_; // this is an estimate based on dsigmaATM / dsigma0 =~ 1
}
if (k>0) { // we use secant if available
// only update derivative if we had a step, otherwise use from previous iteration
// also avoid division by zero and zero derivative
Real eps = 1.0e-12; // we aim at beeing a bit more robust
if ((fabs(forwardMinusStrike1 - forwardMinusStrike0) > eps) && (fabs(dmu) > eps)) {
dfwd_dmu = (forwardMinusStrike1 - forwardMinusStrike0) / dmu;
}
if ((fabs(straddleMinusATM1 - straddleMinusATM0) > eps) && (fabs(dlogSigma0) > eps)) {
dstr_dlogSigma0 = (straddleMinusATM1 - straddleMinusATM0) / dlogSigma0;
}
}
dmu = -forwardMinusStrike1 / dfwd_dmu;
if (k < onlyForwardCalibrationIters_) dlogSigma0 = 0.0; // keep sigma0 fixed and only calibrate forward
else dlogSigma0 = -straddleMinusATM1 / dstr_dlogSigma0;
if (dmu <= -0.9*upperBoundX()) dmu = -0.5*upperBoundX(); // make sure 0 < eps < upperBoundX() in next update
if (dmu >= -0.9*lowerBoundX()) dmu = -0.5*lowerBoundX(); // make sure 0 > eps > lowerBoundX() in next update
// maybe some line search could improve convergence...
mu_ += dmu;
logSigma0 += dlogSigma0;
sigma0_ = exp(logSigma0); // ensure sigma0 > 0
updateLocalVol();
// prepare for next iteration
forwardMinusStrike0 = forwardMinusStrike1;
straddleMinusATM0 = straddleMinusATM1;
if (enableLogging_) logging_.push_back("k: " + to_string(k) +
"; C: " + to_string(call) +
"; P: " + to_string(put) +
"; S: " + to_string(straddleATM_) +
"; dfwd_dmu: " + to_string(dfwd_dmu) +
"; dstr_dlogSigma0: " + to_string(dstr_dlogSigma0) +
"; dmu: " + to_string(dmu) +
"; dlogSigma0: " + to_string(dlogSigma0));
if ((fabs(forwardMinusStrike0) < S0Tol_) && (fabs(sigma0_*dlogSigma0) < sigma0Tol_)) break;
}
}
void VanillaLocalVolModel::adjustATM() {
// reset adjusters in case this method is invoked twice
alpha_ = 1.0;
nu_ = 0.0;
Real call0 = expectation(true, S0_);
Real put0 = expectation(false, S0_);
nu_ = put0 - call0;
if (enableLogging_) logging_.push_back("C0: " + to_string(call0) + "; P0: " + to_string(put0) + "; nu: " + to_string(nu_));
Real call1 = expectation(true, S0_);
Real put1 = expectation(false, S0_);
alpha_ = straddleATM_ / (call1 + put1);
nu_ = alpha_*nu_ + (1.0 - alpha_)*S0_;
if (enableLogging_) logging_.push_back("C1: " + to_string(call1) + "; P1: " + to_string(put1) + "; alpha_: " + to_string(alpha_) + "; nu_: " + to_string(nu_));
}
// construct model based on S-grid
VanillaLocalVolModel::VanillaLocalVolModel(
const Time T,
const Real S0,
const Real sigmaATM,
const std::vector<Real>& Sp,
const std::vector<Real>& Sm,
const std::vector<Real>& Mp,
const std::vector<Real>& Mm,
// controls for calibration
const Size maxCalibrationIters,
const Size onlyForwardCalibrationIters,
const bool adjustATMFlag,
const bool enableLogging,
const bool useInitialMu,
const Real initialMu)
: T_(T), S0_(S0), sigmaATM_(sigmaATM), Sp_(Sp), Sm_(Sm), Mp_(Mp), Mm_(Mm), sigma0_(sigmaATM),
maxCalibrationIters_(maxCalibrationIters), onlyForwardCalibrationIters_(onlyForwardCalibrationIters),
adjustATM_(adjustATMFlag), useInitialMu_(useInitialMu), initialMu_(initialMu), enableLogging_(enableLogging) {
// some basic sanity checks come here to avoid the need for taking care of it later on
QL_REQUIRE(T_ > 0, "T_ > 0 required.");
QL_REQUIRE(sigmaATM_ > 0, "sigmaATM_ > 0 required.");
QL_REQUIRE(Sp_.size() > 0, "Sp_.size() > 0 required.");
QL_REQUIRE(Sm_.size() > 0, "Sm_.size() > 0 required.");
QL_REQUIRE(Mp_.size() == Sp_.size(), "Mp_.size() == Sp_.size() required.");
QL_REQUIRE(Mm_.size() == Sm_.size(), "Mm_.size() == Sm_.size() required.");
// check for monotonicity
QL_REQUIRE(Sp_[0] > S0_, "Sp_[0] > S0_ required.");
for (Size k=1; k<Sp_.size(); ++k) QL_REQUIRE(Sp_[k] > Sp_[k-1], "Sp_[k] > Sp_[k-1] required.");
QL_REQUIRE(Sm_[0] < S0_, "Sm_[0] < S0_ required.");
for (Size k = 1; k<Sm_.size(); ++k) QL_REQUIRE(Sm_[k] < Sm_[k-1], "Sm_[k] < Sm_[k-1] required.");
// now it makes sense to allocate memory
sigmaP_.resize(Sp_.size());
sigmaM_.resize(Sm_.size());
Xp_.resize(Sp_.size());
Xm_.resize(Sm_.size());
// initialize deep-in-the-model parameters
initializeDeepInTheModelParameters();
// now we may calculate local volatility
updateLocalVol();
calibrateATM();
if (adjustATM_) adjustATM();
}
// construct model based on x-grid
VanillaLocalVolModel::VanillaLocalVolModel(
const Time T,
const Real S0,
const Real sigmaATM,
const Real sigma0,
const std::vector<Real>& Xp,
const std::vector<Real>& Xm,
const std::vector<Real>& Mp,
const std::vector<Real>& Mm,
// controls for calibration
const Size maxCalibrationIters,
const Size onlyForwardCalibrationIters,
const bool adjustATMFlag,
const bool enableLogging,
const bool useInitialMu,
const Real initialMu)
: T_(T), S0_(S0), sigmaATM_(sigmaATM), Mp_(Mp), Mm_(Mm), sigma0_(sigma0), Xp_(Xp), Xm_(Xm),
maxCalibrationIters_(maxCalibrationIters), onlyForwardCalibrationIters_(onlyForwardCalibrationIters),
adjustATM_(adjustATMFlag), useInitialMu_(useInitialMu), initialMu_(initialMu), enableLogging_(enableLogging) {
// some basic sanity checks come here to avoid the need for taking care of it later on
QL_REQUIRE(T_ > 0, "T_ > 0 required.");
QL_REQUIRE(sigmaATM_ > 0, "sigmaATM_ > 0 required.");
QL_REQUIRE(sigma0_ > 0, "sigma0_ > 0 required.");
QL_REQUIRE(Xp_.size() > 0, "Xp_.size() > 0 required.");
QL_REQUIRE(Xm_.size() > 0, "Xm_.size() > 0 required.");
QL_REQUIRE(Mp_.size() == Xp_.size(), "Mp_.size() == Xp_.size() required.");
QL_REQUIRE(Mm_.size() == Xm_.size(), "Mm_.size() == Xm_.size() required.");
// check for monotonicity
QL_REQUIRE(Xp_[0] > 0.0, "Xp_[0] > 0.0 required.");
for (Size k = 1; k<Xp_.size(); ++k) QL_REQUIRE(Xp_[k] > Xp_[k - 1], "Xp_[k] > Xp_[k-1] required.");
QL_REQUIRE(Xm_[0] < 0.0, "Xm_[0] < 0.0 required.");
for (Size k = 1; k<Xm_.size(); ++k) QL_REQUIRE(Xm_[k] < Xm_[k - 1], "Xm_[k] < Xm_[k-1] required.");
// now it makes sense to allocate memory
sigmaP_.resize(Xp_.size());
sigmaM_.resize(Xm_.size());
Sp_.resize(Xp_.size());
Sm_.resize(Xm_.size());
// initialize deep-in-the-model parameters
initializeDeepInTheModelParameters();
// now we may calculate local volatility
calculateSGrid(); // we need this preprocessing step since we only input x instead of S
updateLocalVol();
calibrateATM();
if (adjustATM_) adjustATM();
}
// attributes in more convenient single-vector format
const std::vector<Real> VanillaLocalVolModel::underlyingX() {
std::vector<Real> X(Xm_.size() + Xp_.size() + 1);
for (Size k = 0; k < Xm_.size(); ++k) X[k] = Xm_[Xm_.size() - k - 1];
X[Xm_.size()] = 0.0;
for (Size k = 0; k < Xp_.size(); ++k) X[Xm_.size() + 1 + k] = Xp_[k];
return X;
}
const std::vector<Real> VanillaLocalVolModel::underlyingS() {
std::vector<Real> S(Sm_.size() + Sp_.size() + 1);
for (Size k = 0; k < Sm_.size(); ++k) S[k] = Sm_[Sm_.size() - k - 1];
S[Sm_.size()] = S0_;
for (Size k = 0; k < Sp_.size(); ++k) S[Sm_.size() + 1 + k] = Sp_[k];
return S;
}
const std::vector<Real> VanillaLocalVolModel::localVol() {
std::vector<Real> sigma(sigmaM_.size() + sigmaP_.size() + 1);
for (Size k = 0; k < sigmaM_.size(); ++k) sigma[k] = sigmaM_[sigmaM_.size() - k - 1];
sigma[sigmaM_.size()] = sigma0_;
for (Size k = 0; k < sigmaP_.size(); ++k) sigma[sigmaM_.size() + 1 + k] = sigmaP_[k];
return sigma;
}
const std::vector<Real> VanillaLocalVolModel::localVolSlope() {
std::vector<Real> m(Mm_.size() + Mp_.size() + 1);
for (Size k = 0; k < Mm_.size(); ++k) m[k] = Mm_[Mm_.size() - k - 1];
m[Mm_.size()] = 0.0; // undefined
for (Size k = 0; k < Mp_.size(); ++k) m[Mm_.size() + 1 + k] = Mp_[k];
return m;
}
// model function evaluations
const Real VanillaLocalVolModel::localVol(Real S) {
bool isRightWing = (S >= S0_) ? true : false;
Size idx = 0;
if (isRightWing) while ((idx < Sp_.size() - 1) && (Sp_[idx] < S)) ++idx;
else while ((idx < Sm_.size() - 1) && (Sm_[idx] > S)) ++idx;
return localVol(isRightWing, idx, S);
}
const Real VanillaLocalVolModel::underlyingS(Real x) {
bool isRightWing = (x >= 0.0) ? true : false;
Size idx = 0;
if (isRightWing) while ((idx < Xp_.size() - 1) && (Xp_[idx] < x)) ++idx;
else while ((idx < Xm_.size() - 1) && (Xm_[idx] > x)) ++idx;
return underlyingS(isRightWing, idx, x);
}
// calculating expectations - that is the actual purpose of that model
const Real VanillaLocalVolModel::expectation(bool isRightWing, Real strike) {
// calculate the forward price of an OTM option
Size idx = 0;
if (isRightWing) {
QL_REQUIRE(strike >= S0_, "strike >= S0_ required");
while ((idx < Sp_.size()) && (Sp_[idx] <= strike)) ++idx; // make sure strike < Sp_[idx]
if (idx == Sp_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xp_[idx - 1] : 0.0;
QL_REQUIRE((x0 <= strikeX) && (strikeX <= Xp_[idx]), "(x0 <= strikeX) && (strikeX <= Xp_[idx]) required");
Real intS = 0.0;
for (Size k = idx; k < Sp_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xp_[k - 1];
intS += (primitiveF(isRightWing, k, Xp_[k]) - primitiveF(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xp_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS - strike * intK;
}
else {
QL_REQUIRE(strike <= S0_, "strike <= S0_ required");
while ((idx < Sm_.size()) && (Sm_[idx] >= strike)) ++idx; // make sure Sm_[idx] < strke
if (idx == Sm_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xm_[idx - 1] : 0.0;
QL_REQUIRE((x0 >= strikeX) && (strikeX >= Xm_[idx]), "(x0 >= strikeX) && (strikeX >= Xm_[idx]) required");
Real intS = 0.0;
for (Size k = idx; k < Sm_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xm_[k - 1];
intS += (primitiveF(isRightWing, k, Xm_[k]) - primitiveF(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xm_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS - strike * intK;
}
}
const Real VanillaLocalVolModel::variance(bool isRightWing, Real strike) {
// calculate the forward price of an OTM power option with payoff 1_{S>K}(S-K)^2
Size idx = 0;
if (isRightWing) {
QL_REQUIRE(strike >= S0_, "strike >= S0_ required");
while ((idx < Sp_.size()) && (Sp_[idx] <= strike)) ++idx; // make sure strike < Sp_[idx]
if (idx == Sp_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xp_[idx - 1] : 0.0;
QL_REQUIRE((x0 <= strikeX) && (strikeX <= Xp_[idx]), "(x0 <= strikeX) && (strikeX <= Xp_[idx]) required");
Real intS=0.0, intS2 = 0.0;
for (Size k = idx; k < Sp_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xp_[k - 1];
intS += (primitiveF(isRightWing, k, Xp_[k]) - primitiveF(isRightWing, k, xStart));
intS2 += (primitiveFSquare(isRightWing, k, Xp_[k]) - primitiveFSquare(isRightWing, k, xStart));
}
// we need to adjust for the Vanilla and strike integral
Real xEnd = Xp_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return intS2 - 2.0 * strike * intS + strike * strike * intK;
}
else {
QL_REQUIRE(strike <= S0_, "strike <= S0_ required");
while ((idx < Sm_.size()) && (Sm_[idx] >= strike)) ++idx; // make sure Sm_[idx] < strke
if (idx == Sm_.size()) return 0.0; // we are beyond exrapolation
Real strikeX = underlyingX(isRightWing, idx, strike);
Real x0 = (idx > 0) ? Xm_[idx - 1] : 0.0;
QL_REQUIRE((x0 >= strikeX) && (strikeX >= Xm_[idx]), "(x0 >= strikeX) && (strikeX >= Xm_[idx]) required");
Real intS = 0.0, intS2 = 0.0;
for (Size k = idx; k < Sm_.size(); ++k) {
Real xStart = (k == idx) ? strikeX : Xm_[k - 1];
intS += (primitiveF(isRightWing, k, Xm_[k]) - primitiveF(isRightWing, k, xStart));
intS2 += (primitiveFSquare(isRightWing, k, Xm_[k]) - primitiveFSquare(isRightWing, k, xStart));
}
// we need to adjust for the strike integral
Real xEnd = Xm_.back();
Real intK = Phi((xEnd - mu_) / sqrt(T_)) - Phi((strikeX - mu_) / sqrt(T_));
return -(intS2 - 2.0 * strike * intS + strike * strike * intK);
}
}
} // namespace QauntLib
| 50.802817
| 187
| 0.525818
|
urgu00
|
3b2aa11f7e5dfaf5db22d5b8c854b65e354fa357
| 1,758
|
cpp
|
C++
|
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
bzoj/1057.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
// Copy from luogu1169
#include <iostream>
#include <algorithm>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <queue>
#include <cmath>
#include <math.h>
#include <vector>
#include <iostream>
#include <cstdio>
#include <ctime>
#include <set>
#include <map>
#include <fstream>
#include <bits/stdc++.h>
#define ll long long
#define oo 1<<30
#define ESP 1e-9
#define read(a) scanf("%d", &a)
#define writeln(a) printf("%d\n", a)
#define write(a) printf("%d", a)
#define mst(a, b) memset(a, b, sizeof a)
#define rep(a, b, c) for(int a = b; a < c; a ++)
#define reps(a, b, c) for(int a = b; a <= c; a ++)
#define repx(a, b, c) for(int a = b, a > c; a --)
#define repxs(a, b, c) for(int a = b; a >= c; a --)
#define MOD 1000000007
#define MAXN 805
using namespace std;
const int mxn=2005;
int n,m,ans1,ans2;
int h[mxn][mxn],l[mxn],r[mxn],s[mxn];
bool a[mxn][mxn];
inline void find(bool flag)
{
memset(h,0,sizeof h);
reps(i,1,n) reps(j,1,m) if(a[i][j]==flag) h[i][j]=h[i-1][j]+1;
reps( i,1,n)
{
int top=0;
s[top]=0;
reps( j,1,m)
{
while(h[i][s[top]]>=h[i][j] && top) top--;
l[j]=s[top]+1;
s[++top]=j;
}
top=0;s[0]=m+1;
repxs(j,m,1)
{
while(h[i][s[top]]>=h[i][j] && top) top--;
r[j]=s[top]-1;
s[++top]=j;
ans2=max(ans2,(r[j]-l[j]+1)*h[i][j]);
if(r[j]-l[j]+1>=h[i][j]) ans1=max(ans1,h[i][j]*h[i][j]);
}
}
}
int main (){
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++){
cin >> a[i][j];
a[i][j] = (a[i][j] == (i % 2) ^ (j % 2));
}
find(0);
find(1);
cout << ans1 << "\n" << ans2;
return 0;
}
| 22.253165
| 68
| 0.497156
|
swwind
|
3b3e7f7492f7cda4e0c6f4a931e32e1ddcd04e79
| 239
|
cpp
|
C++
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 32
|
2018-06-16T20:50:15.000Z
|
2022-03-26T16:57:15.000Z
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 2
|
2018-10-07T17:41:39.000Z
|
2021-01-08T03:14:19.000Z
|
src/Rendering/Lighting/CompositeLight.cpp
|
Tristeon/Tristeon2D
|
9052e87b743f1122ed4c81952f2bffda96599447
|
[
"MIT"
] | 9
|
2018-06-12T21:00:58.000Z
|
2021-01-08T02:18:30.000Z
|
#include "CompositeLight.h"
#include <Collector.h>
namespace Tristeon
{
CompositeLight::CompositeLight()
{
Collector<CompositeLight>::add(this);
}
CompositeLight::~CompositeLight()
{
Collector<CompositeLight>::remove(this);
}
}
| 15.933333
| 42
| 0.732218
|
Tristeon
|
3b3f290de42e2598a981357d8ebfeacff5adc4ce
| 1,420
|
cpp
|
C++
|
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | 1
|
2019-06-24T11:34:23.000Z
|
2019-06-24T11:34:23.000Z
|
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | null | null | null |
17-Hash-Tables/Source.cpp
|
InamTaj/data-structures
|
7a662a8e635402bab3481d69d8df9164499da6b4
|
[
"Apache-2.0"
] | 1
|
2020-11-23T03:28:52.000Z
|
2020-11-23T03:28:52.000Z
|
//Inamullah Taj - 1446
// OBJECTIVE: Implement a Class of Static Graph
#include "HashTableHeader.h"
#include <conio.h>
#include <iostream>
using namespace std;
void main()
{
char ext;
int choice, size, value;
cout<<"\t \t \t>>-> HASH TABLES <-<<\n\n";
cout<<"\n\t\tEnter Size of Table = "; cin>>size;
HashTable<int> mytable(size);
do
{
cout<<"\n\tWhat to do?\n1 -> Insert key\n2 -> Search Key\n3 -> Delete Key\n4 -> Show Table\n0 -> EXIT\n\t\tYour Choice = "; cin>>choice; cout<<endl;
if(choice==1)
{
cout<<"Enter Value to insert = "; cin>>value;
mytable.Insert(value);
}
else if(choice==2)
{
cout<<"Enter Value to search = "; cin>>value;
int status = mytable.Search(value);
if(status != 0)
{ cout<<"\n\tValue "<<value<<" is at Index "<<status; }
else if(status == 0)
{ cout<<"\n\tERROR:: Value not Found in Table!"; }
}
else if(choice==3)
{
cout<<"Enter Value to Delete = "; cin>>value;
int stat = mytable.GetKey(value);
if(stat!=0)
{ cout<<"\n\tValue "<<value<<" Deleted from Table!"; }
else
{ cout<<"\n\tERROR:: Value not Found in Table!"; }
}
else if (choice==4)
{
mytable.ShowTable();
}
else if (choice==0)
{ break; }
else
{ cout<<"\n\tERROR:: Wrong Choice! Try Again.."; }
cout<<"\n\n\t\t\tENTER to Continue | ESc to Exit.."; ext = _getch();
}
while(ext!=27);
}
| 26.792453
| 151
| 0.569014
|
InamTaj
|
3b42d88f49debe20d42ab1933f021c6361e0b810
| 1,266
|
hpp
|
C++
|
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
include/copr/sequence/fft.hpp
|
orisano/copr
|
3c1018edcc20e0f855ec614b2ddf579f8f81cd72
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include <complex>
#include <vector>
template <typename T>
inline std::complex<T> cmul(const std::complex<T>& a, const std::complex<T>& b) {
return std::complex<T>(a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real());
}
template <typename T>
void fft(std::vector<std::complex<T>>& a, int sign = +1) {
const int N = a.size();
assert(N == (N & -N));
const T theta = 8 * sign * std::atan(1.0) / N;
for (int i = 0, j = 1; j < N - 1; ++j) {
for (int k = N >> 1; k > (i ^= k);) k >>= 1;
if (j < i) std::swap(a[i], a[j]);
}
for (int m, mh = 1; (m = mh << 1) <= N; mh = m) {
int irev = 0;
for (int i = 0; i < N; i += m) {
auto w = std::exp(std::complex<T>(0, theta * irev));
for (int k = N >> 2; k > (irev ^= k);) k >>= 1;
for (int j = i; j < mh + i; ++j) {
int k = j + mh;
auto x = a[j] - a[k];
a[j] += a[k];
a[k] = cmul(w, x);
}
}
}
}
template <typename T>
void ifft(std::vector<std::complex<T>>& a) {
const int N = a.size();
assert(N == (N & -N));
fft(a, -1);
const T inv = 1.0 / N;
for (int i = 0; i < N; ++i) {
a[i] *= inv;
}
}
| 25.32
| 81
| 0.460506
|
orisano
|
3b4581ebe1400cc04822f68b1ab6ed506e54ce8e
| 3,586
|
cpp
|
C++
|
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
timer/Utility/CollisionUtilities.cpp
|
MaticVrtacnik/ProceduralnaAnimacija
|
bc47ccc721d1bedb31ed5949eb740892f094897a
|
[
"MIT"
] | null | null | null |
/*
MIT License
Copyright (c) 2019 MaticVrtacnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "CollisionUtilities.hpp"
#include <utility>
#include <glm\gtc\type_ptr.hpp>
#include <BulletCollision\CollisionShapes\btCollisionShape.h>
#include "../Define/PrintDefines.hpp"
namespace Engine{
namespace Physics{
btVector3 convertVec3(const glm::vec3 &vector){
return btVector3(vector.x, vector.y, vector.z);
}
btVector3 convertVec3(glm::vec3 &&vector){
return btVector3(std::move(vector.x), std::move(vector.y), std::move(vector.z));
}
glm::vec3 convertVec3(const btVector3 &vector){
return glm::vec3(vector.getX(), vector.getY(), vector.getZ());
}
/*glm::vec3 convertVec3(btVector3 &&vector){
return glm::vec3(std::move(vector)); //TODO FIXXXXXX
}*/
btQuaternion convertQuat(const glm::quat &quaternion){
return btQuaternion(
quaternion.x, quaternion.y,
quaternion.z, quaternion.w
);
}
btQuaternion convertQuat(glm::quat &&quaternion){
return btQuaternion(
std::move(quaternion.x), std::move(quaternion.y),
std::move(quaternion.z), std::move(quaternion.w)
);
}
glm::quat convertQuat(const btQuaternion &quaternion){
return glm::quat(quaternion.w(), quaternion.x(), quaternion.y(), quaternion.z());
}
/*
glm::quat convertQuat(btQuaternion &&quaternion){
return glm::quat(
quaternion.w(), quaternion.x(),
quaternion.y(), quaternion.z()
);
}
*/
btTransform convertMat4(const glm::mat4 &transform){
/*if (glm::length(glm::vec3(transform[0])) != 1.0f)
WARNING("BulletPhysics Matrix X-axis scale not 1.0");
if (glm::length(glm::vec3(transform[1])) != 1.0f)
WARNING("BulletPhysics Matrix Y-axis scale not 1.0");
if (glm::length(glm::vec3(transform[2])) != 1.0f)
WARNING("BulletPhysics Matrix Z-axis scale not 1.0");*/
btTransform _transform = btTransform::getIdentity();
_transform.setFromOpenGLMatrix(glm::value_ptr(transform));
return _transform;
}
glm::mat4 convertMat4(const btTransform &transform){
glm::mat4 _transform;
transform.getOpenGLMatrix(glm::value_ptr(_transform));
return _transform;
}
glm::vec3 getBodyScale(btRigidBody &body){
btVector3 _aabbMin, _aabbMax;
body.getAabb(_aabbMin, _aabbMax);
return glm::abs(Physics::convertVec3(_aabbMax - _aabbMin));
}
glm::mat2x3 getBoundingBox(btCollisionShape *collisionShape){
btVector3 _aabbMin, _aabbMax;
collisionShape->getAabb(btTransform::getIdentity(), _aabbMin, _aabbMax);
return glm::mat2x3(convertVec3(_aabbMin), convertVec3(_aabbMax));
}
}
}
| 29.393443
| 84
| 0.726715
|
MaticVrtacnik
|
8dc922b8b29873463fb27cc57301a26a9b2ba1f3
| 21,764
|
cc
|
C++
|
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
ggadget/clutter/view_actor_binder.cc
|
meego-netbook-ux/google-gadgets-meego
|
89af89796bca073e95f44d43c9d81407caabedf0
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Portions:
Copyright 2008-2010 Intel Corp.
Authors:
Iain Holmes <iain@linux.intel.com>
Roger WANG <roger.wang@intel.com>
*/
#include <algorithm>
#include <string>
#include <vector>
#include <cairo.h>
#include <clutter/clutter.h>
#include "view_actor_binder.h"
#include <ggadget/common.h>
#include <ggadget/logger.h>
#include <ggadget/event.h>
#include <ggadget/main_loop_interface.h>
#include <ggadget/view_interface.h>
#include <ggadget/view_host_interface.h>
#include <ggadget/clip_region.h>
#include <ggadget/math_utils.h>
#include <ggadget/string_utils.h>
#include "cairo_canvas.h"
#include "cairo_graphics.h"
#include "key_convert.h"
#include "utilities.h"
#define GRAB_POINTER_EXPLICITLY
namespace ggadget {
namespace clutter {
// A small motion threshold to prevent a click with tiny mouse move from being
// treated as window move or resize.
static const double kDragThreshold = 3;
// Minimal interval between self draws.
static const unsigned int kSelfDrawInterval = 40;
class ViewActorBinder::Impl {
public:
Impl(ViewInterface *view,
ViewHostInterface *host, ClutterActor *actor)
: view_(view),
host_(host),
actor_(actor),
handlers_(new gulong[kEventHandlersNum]),
on_zoom_connection_(NULL),
dbl_click_(false),
focused_(false),
button_pressed_(false),
#ifdef GRAB_POINTER_EXPLICITLY
pointer_grabbed_(false),
#endif
zoom_(1.0),
mouse_down_x_(-1),
mouse_down_y_(-1),
mouse_down_hittest_(ViewInterface::HT_CLIENT),
self_draw_(false),
self_draw_timer_(0),
last_self_draw_time_(0),
freeze_updates_(false) {
ASSERT(view);
ASSERT(host);
g_object_ref(G_OBJECT(actor_));
for (size_t i = 0; i < kEventHandlersNum; ++i) {
handlers_[i] = g_signal_connect(G_OBJECT(actor_),
kEventHandlers[i].event,
kEventHandlers[i].handler,
this);
}
CairoGraphics *gfx= down_cast<CairoGraphics *>(view_->GetGraphics());
ASSERT(gfx);
zoom_ = gfx->GetZoom();
on_zoom_connection_ = gfx->ConnectOnZoom(NewSlot(this, &Impl::OnZoom));
}
~Impl() {
view_ = NULL;
if (self_draw_timer_) {
g_source_remove(self_draw_timer_);
self_draw_timer_ = 0;
}
for (size_t i = 0; i < kEventHandlersNum; ++i) {
if (handlers_[i] > 0)
g_signal_handler_disconnect(G_OBJECT(actor_), handlers_[i]);
else
DLOG("Handler %s was not connected.", kEventHandlers[i].event);
}
delete[] handlers_;
handlers_ = NULL;
if (on_zoom_connection_) {
on_zoom_connection_->Disconnect();
on_zoom_connection_ = NULL;
}
g_object_unref(G_OBJECT(actor_));
}
void OnZoom(double zoom) {
zoom_ = zoom;
}
static gboolean ButtonPressHandler(ClutterActor *actor,
ClutterButtonEvent *event,
gpointer user_data) {
DLOG("ButtonPressHandler.");
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
impl->button_pressed_ = true;
impl->host_->ShowTooltip("");
if (!impl->focused_) {
impl->focused_ = true;
SimpleEvent e(Event::EVENT_FOCUS_IN);
// Ignore the result.
impl->view_->OnOtherEvent(e);
}
// This will break I suppose if there's more than one stage
clutter_stage_set_key_focus (CLUTTER_STAGE(clutter_stage_get_default()),
actor);
int mod = ConvertClutterModifierToModifier(event->modifier_state);
int button = event->button == 1 ? MouseEvent::BUTTON_LEFT :
event->button == 2 ? MouseEvent::BUTTON_MIDDLE :
event->button == 3 ? MouseEvent::BUTTON_RIGHT :
MouseEvent::BUTTON_NONE;
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, event->x,
event->y,
&actor_x, &actor_y);
Event::Type type = Event::EVENT_INVALID;
if (event->click_count == 1) {
type = Event::EVENT_MOUSE_DOWN;
impl->mouse_down_x_ = actor_x;
impl->mouse_down_y_ = actor_y;
} else if (event->click_count == 2) {
impl->dbl_click_ = true;
if (button == MouseEvent::BUTTON_LEFT)
type = Event::EVENT_MOUSE_DBLCLICK;
else if (button == MouseEvent::BUTTON_RIGHT)
type = Event::EVENT_MOUSE_RDBLCLICK;
}
if (button != MouseEvent::BUTTON_NONE && type != Event::EVENT_INVALID) {
MouseEvent e(type, (actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod, event);
result = impl->view_->OnMouseEvent(e);
impl->mouse_down_hittest_ = impl->view_->GetHitTest();
// If the View's hittest represents a special button, then handle it
// here.
if (result == EVENT_RESULT_UNHANDLED &&
button == MouseEvent::BUTTON_LEFT &&
type == Event::EVENT_MOUSE_DOWN) {
if (impl->mouse_down_hittest_ == ViewInterface::HT_MENU) {
impl->host_->ShowContextMenu(button);
} else if (impl->mouse_down_hittest_ == ViewInterface::HT_CLOSE) {
impl->host_->CloseView();
}
result = EVENT_RESULT_HANDLED;
}
}
return result != EVENT_RESULT_UNHANDLED;
}
static gboolean ButtonReleaseHandler(ClutterActor *actor,
ClutterButtonEvent *event,
gpointer user_data) {
DLOG("ButtonReleaseHandler.");
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
EventResult result2 = EVENT_RESULT_UNHANDLED;
if (impl->button_pressed_ == false)
return false;
impl->button_pressed_ = false;
impl->host_->ShowTooltip("");
#ifdef GRAB_POINTER_EXPLICITLY
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
int mod = ConvertClutterModifierToModifier(event->modifier_state);
int button = event->button == 1 ? MouseEvent::BUTTON_LEFT :
event->button == 2 ? MouseEvent::BUTTON_MIDDLE :
event->button == 3 ? MouseEvent::BUTTON_RIGHT :
MouseEvent::BUTTON_NONE;
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
if (button != MouseEvent::BUTTON_NONE) {
MouseEvent e(Event::EVENT_MOUSE_UP,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod, event);
result = impl->view_->OnMouseEvent(e);
if (!impl->dbl_click_) {
MouseEvent e2(button == MouseEvent::BUTTON_LEFT ?
Event::EVENT_MOUSE_CLICK : Event::EVENT_MOUSE_RCLICK,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
result2 = impl->view_->OnMouseEvent(e2);
} else {
impl->dbl_click_ = false;
}
}
impl->mouse_down_x_ = -1;
impl->mouse_down_y_ = -1;
impl->mouse_down_hittest_ = ViewInterface::HT_CLIENT;
return result != EVENT_RESULT_UNHANDLED ||
result2 != EVENT_RESULT_UNHANDLED;
}
static gboolean KeyPressHandler(ClutterActor *actor,
ClutterKeyEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
EventResult result2 = EVENT_RESULT_UNHANDLED;
impl->host_->ShowTooltip("");
int mod = ConvertClutterModifierToModifier(event->modifier_state);
unsigned int key_code = ConvertClutterKeyvalToKeyCode(event->keyval);
if (key_code) {
KeyboardEvent e(Event::EVENT_KEY_DOWN, key_code, mod, event);
result = impl->view_->OnKeyEvent(e);
} else {
LOG("Unknown key: 0x%x", event->keyval);
}
guint32 key_char = 0;
if ((event->modifier_state & (CLUTTER_CONTROL_MASK | CLUTTER_MOD1_MASK)) == 0) {
if (key_code == KeyboardEvent::KEY_ESCAPE ||
key_code == KeyboardEvent::KEY_RETURN ||
key_code == KeyboardEvent::KEY_BACK ||
key_code == KeyboardEvent::KEY_TAB) {
// gdk_keyval_to_unicode doesn't support the above keys.
key_char = key_code;
} else {
key_char = clutter_keysym_to_unicode(event->keyval);
}
} else if ((event->modifier_state & CLUTTER_CONTROL_MASK) &&
key_code >= 'A' && key_code <= 'Z') {
// Convert CTRL+(A to Z) to key press code for compatibility.
key_char = key_code - 'A' + 1;
}
if (key_char) {
// Send the char code in KEY_PRESS event.
KeyboardEvent e2(Event::EVENT_KEY_PRESS, key_char, mod, event);
result2 = impl->view_->OnKeyEvent(e2);
}
return result != EVENT_RESULT_UNHANDLED ||
result2 != EVENT_RESULT_UNHANDLED;
}
static gboolean KeyReleaseHandler(ClutterActor *actor,
ClutterKeyEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
EventResult result = EVENT_RESULT_UNHANDLED;
int mod = ConvertClutterModifierToModifier(event->modifier_state);
unsigned int key_code = ConvertClutterKeyvalToKeyCode(event->keyval);
if (key_code) {
KeyboardEvent e(Event::EVENT_KEY_UP, key_code, mod, event);
result = impl->view_->OnKeyEvent(e);
} else {
LOG("Unknown key: 0x%x", event->keyval);
}
return result != EVENT_RESULT_UNHANDLED;
}
void Redraw() {
if (freeze_updates_)
return;
view_->Layout ();
cairo_t *cr = NULL;
const ClipRegion *view_region = view_->GetClipRegion();
size_t count = view_region->GetRectangleCount();
DLOG(" == actor update region == ");
view_region->PrintLog();
if (count) {
Rectangle rect, union_rect;
for (size_t i = 0; i < count; ++i) {
rect = view_region->GetRectangle(i);
if (zoom_ != 1.0) {
rect.Zoom(zoom_);
rect.Integerize(true);
}
union_rect.Union (rect);
}
cr = clutter_cairo_texture_create_region (CLUTTER_CAIRO_TEXTURE(actor_),
union_rect.x, union_rect.y,
union_rect.w, union_rect.h);
}else{
cr = clutter_cairo_texture_create (CLUTTER_CAIRO_TEXTURE(actor_));
}
if (!cr)
return;
cairo_operator_t op = cairo_get_operator(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_paint(cr);
cairo_set_operator(cr, op);
CairoCanvas *canvas = new CairoCanvas(cr,
view_->GetGraphics()->GetZoom(),
view_->GetWidth(),
view_->GetHeight());
DLOG ("redraw");
view_->Draw(canvas);
canvas->Destroy();
cairo_destroy(cr);
}
static gboolean MotionNotifyHandler(ClutterActor *actor,
ClutterMotionEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
int button = ConvertClutterModifierToButton(event->modifier_state);
int mod = ConvertClutterModifierToModifier(event->modifier_state);
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_MOVE,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
#ifdef GRAB_POINTER_EXPLICITLY
if (button != MouseEvent::BUTTON_NONE && !impl->pointer_grabbed_) {
// Grab the cursor to prevent losing events.
clutter_grab_pointer(actor);
impl->pointer_grabbed_ = true;
}
#endif
EventResult result = impl->view_->OnMouseEvent(e);
if (result == EVENT_RESULT_UNHANDLED && button != MouseEvent::BUTTON_NONE &&
impl->mouse_down_x_ >= 0 && impl->mouse_down_y_ >= 0 &&
(std::abs((actor_x) - impl->mouse_down_x_) > kDragThreshold ||
std::abs((actor_y) - impl->mouse_down_y_) > kDragThreshold ||
impl->mouse_down_hittest_ != ViewInterface::HT_CLIENT)) {
impl->button_pressed_ = false;
// Send fake mouse up event to the view so that we can start to drag
// the window. Note: no mouse click event is sent in this case, to prevent
// unwanted action after window move.
MouseEvent e(Event::EVENT_MOUSE_UP,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
0, 0, button, mod);
// Ignore the result of this fake event.
impl->view_->OnMouseEvent(e);
ViewInterface::HitTest hittest = impl->mouse_down_hittest_;
bool resize_drag = false;
// Determine the resize drag edge.
if (hittest == ViewInterface::HT_LEFT ||
hittest == ViewInterface::HT_RIGHT ||
hittest == ViewInterface::HT_TOP ||
hittest == ViewInterface::HT_BOTTOM ||
hittest == ViewInterface::HT_TOPLEFT ||
hittest == ViewInterface::HT_TOPRIGHT ||
hittest == ViewInterface::HT_BOTTOMLEFT ||
hittest == ViewInterface::HT_BOTTOMRIGHT) {
resize_drag = true;
}
#ifdef GRAB_POINTER_EXPLICITLY
// ungrab the pointer before starting move/resize drag.
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
impl->mouse_down_stage_x_ = event->x;
impl->mouse_down_stage_y_ = event->y;
if (resize_drag) {
impl->host_->BeginResizeDrag(button, hittest);
} else {
impl->host_->BeginMoveDrag(button);
}
impl->mouse_down_x_ = -1;
impl->mouse_down_y_ = -1;
impl->mouse_down_hittest_ = ViewInterface::HT_CLIENT;
impl->mouse_down_stage_x_ = 0;
impl->mouse_down_stage_y_ = 0;
}
return result != EVENT_RESULT_UNHANDLED;
}
static gboolean ScrollHandler(ClutterActor *actor,
ClutterScrollEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
int delta_x = 0, delta_y = 0;
if (event->direction == CLUTTER_SCROLL_UP) {
delta_y = MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_DOWN) {
delta_y = -MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_LEFT) {
delta_x = MouseEvent::kWheelDelta;
} else if (event->direction == CLUTTER_SCROLL_RIGHT) {
delta_x = -MouseEvent::kWheelDelta;
}
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, event->x,
event->y,
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_WHEEL,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_,
delta_x, delta_y,
ConvertClutterModifierToButton(event->modifier_state),
ConvertClutterModifierToModifier(event->modifier_state));
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean LeaveNotifyHandler(ClutterActor *actor,
ClutterCrossingEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
// Don't send mouse out event if the mouse is grabbed.
if (impl->button_pressed_)
return FALSE;
impl->host_->ShowTooltip("");
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_OUT,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_, 0, 0,
MouseEvent::BUTTON_NONE,
Event::MOD_NONE);
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean EnterNotifyHandler(ClutterActor *actor,
ClutterCrossingEvent *event,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
impl->host_->ShowTooltip("");
gfloat actor_x, actor_y;
clutter_actor_transform_stage_point(actor, (event->x),
(event->y),
&actor_x, &actor_y);
MouseEvent e(Event::EVENT_MOUSE_OVER,
(actor_x) / impl->zoom_,
(actor_y) / impl->zoom_, 0, 0,
MouseEvent::BUTTON_NONE,
Event::MOD_NONE);
return impl->view_->OnMouseEvent(e) != EVENT_RESULT_UNHANDLED;
}
static gboolean FocusInHandler(ClutterActor *actor,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
if (!impl->focused_) {
impl->focused_ = true;
SimpleEvent e(Event::EVENT_FOCUS_IN);
return impl->view_->OnOtherEvent(e) != EVENT_RESULT_UNHANDLED;
}
return FALSE;
}
static gboolean FocusOutHandler(ClutterActor *actor,
gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
if (impl->focused_) {
impl->focused_ = false;
SimpleEvent e(Event::EVENT_FOCUS_OUT);
#ifdef GRAB_POINTER_EXPLICITLY
// Ungrab the pointer if the focus is lost.
if (impl->pointer_grabbed_) {
clutter_ungrab_pointer();
impl->pointer_grabbed_ = false;
}
#endif
return impl->view_->OnOtherEvent(e) != EVENT_RESULT_UNHANDLED;
}
return FALSE;
}
static gboolean SelfDrawHandler(gpointer user_data) {
Impl *impl = reinterpret_cast<Impl *>(user_data);
impl->self_draw_timer_ = 0;
impl->Redraw();
return FALSE;
}
ViewInterface *view_;
ViewHostInterface *host_;
ClutterActor *actor_;
gulong *handlers_;
Connection *on_zoom_connection_;
bool dbl_click_;
bool focused_;
bool button_pressed_;
#ifdef GRAB_POINTER_EXPLICITLY
bool pointer_grabbed_;
#endif
double zoom_;
double mouse_down_x_;
double mouse_down_y_;
int mouse_down_stage_x_;
int mouse_down_stage_y_;
ViewInterface::HitTest mouse_down_hittest_;
bool self_draw_;
guint self_draw_timer_;
uint64_t last_self_draw_time_;
bool freeze_updates_;
struct EventHandlerInfo {
const char *event;
void (*handler)(void);
};
static EventHandlerInfo kEventHandlers[];
static const size_t kEventHandlersNum;
};
ViewActorBinder::Impl::EventHandlerInfo
ViewActorBinder::Impl::kEventHandlers[] = {
{ "button-press-event", G_CALLBACK(ButtonPressHandler) },
{ "button-release-event", G_CALLBACK(ButtonReleaseHandler) },
{ "enter-event", G_CALLBACK(EnterNotifyHandler) },
/* { "expose-event", G_CALLBACK(ExposeHandler) },*/
{ "key-focus-in", G_CALLBACK(FocusInHandler) },
{ "key-focus-out", G_CALLBACK(FocusOutHandler) },
{ "key-press-event", G_CALLBACK(KeyPressHandler) },
{ "key-release-event", G_CALLBACK(KeyReleaseHandler) },
{ "leave-event", G_CALLBACK(LeaveNotifyHandler) },
{ "motion-event", G_CALLBACK(MotionNotifyHandler) },
{ "scroll-event", G_CALLBACK(ScrollHandler) },
};
const size_t ViewActorBinder::Impl::kEventHandlersNum =
arraysize(ViewActorBinder::Impl::kEventHandlers);
ViewActorBinder::ViewActorBinder(ViewInterface *view,
ViewHostInterface *host, ClutterActor *actor)
: impl_(new Impl(view, host, actor)) {
}
ViewActorBinder::~ViewActorBinder() {
delete impl_;
impl_ = NULL;
}
void ViewActorBinder::Redraw() {
impl_->Redraw();
}
void ViewActorBinder::QueueDraw() {
if (!impl_->self_draw_timer_) {
uint64_t current_time = GetCurrentTime();
if (current_time - impl_->last_self_draw_time_ >= kSelfDrawInterval) {
impl_->self_draw_timer_ =
g_idle_add_full(CLUTTER_PRIORITY_REDRAW, Impl::SelfDrawHandler,
impl_, NULL);
} else {
impl_->self_draw_timer_ =
g_timeout_add(kSelfDrawInterval -
(current_time - impl_->last_self_draw_time_),
Impl::SelfDrawHandler, impl_);
}
}
}
int ViewActorBinder::GetPointerX() {
return impl_->mouse_down_stage_x_;
}
int ViewActorBinder::GetPointerY() {
return impl_->mouse_down_stage_y_;
}
void ViewActorBinder::FreezeUpdates() {
impl_->freeze_updates_ = true;
}
void ViewActorBinder::ThawUpdates() {
impl_->freeze_updates_ = false;
}
} // namespace clutter
} // namespace ggadget
| 33.32925
| 84
| 0.612617
|
meego-netbook-ux
|
8dcce9bc595ba11809680515c9373c5e627702dc
| 54,578
|
cpp
|
C++
|
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | 2
|
2021-10-09T03:47:42.000Z
|
2022-02-06T06:34:31.000Z
|
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | null | null | null |
Examples/AEGP/Artie/Artie.cpp
|
richardlalancette/AfterEffectsExperimentations
|
5eae44e81c867ee44d00f88aaefaef578f7c3de7
|
[
"MIT"
] | null | null | null |
/*******************************************************************/
/* */
/* ADOBE CONFIDENTIAL */
/* _ _ _ _ _ _ _ _ _ _ _ _ _ */
/* */
/* Copyright 2007 Adobe Systems Incorporated */
/* All Rights Reserved. */
/* */
/* NOTICE: All information contained herein is, and remains the */
/* property of Adobe Systems Incorporated and its suppliers, if */
/* any. The intellectual and technical concepts contained */
/* herein are proprietary to Adobe Systems Incorporated and its */
/* suppliers and may be covered by U.S. and Foreign Patents, */
/* patents in process, and are protected by trade secret or */
/* copyright law. Dissemination of this information or */
/* reproduction of this material is strictly forbidden unless */
/* prior written permission is obtained from Adobe Systems */
/* Incorporated. */
/* */
/*******************************************************************/
#include "Artie.h"
static AEGP_PluginID S_aegp_plugin_id;
static SPBasicSuite *S_sp_basic_suiteP;
static A_Err
Artie_DisposeLights(
const PR_InData *in_dataP,
AEGP_MemHandle lightsH)
{
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
return suites.MemorySuite1()->AEGP_FreeMemHandle(lightsH);
}
static A_Err
Artie_GetPlaneEquation(
Artie_Poly *polyP,
A_FpLong *aFP,
A_FpLong *bFP,
A_FpLong *cFP,
A_FpLong *dFP)
{
A_Err err = A_Err_NONE;
A_FpLong sum_x = 0,
sum_y = 0,
sum_z = 0;
for (A_long iL = 0; iL < 4; iL++) {
sum_x += polyP->vertsA[iL].coord.P[0];
sum_y += polyP->vertsA[iL].coord.P[1];
sum_z += polyP->vertsA[iL].coord.P[2];
}
sum_x *= 0.25;
sum_y *= 0.25;
sum_z *= 0.25;
*aFP = polyP->normal.V[0];
*bFP = polyP->normal.V[1];
*cFP = polyP->normal.V[2];
*dFP = -(sum_x * (*aFP) + sum_y * (*bFP) + sum_z * (*cFP));
return err;
}
static A_Err
Artie_RayIntersectPlane(
Artie_Poly *polyP,
Ray *rayP,
A_FpLong *tPF)
{
A_Err err = A_Err_NONE;
A_FpLong topF = 0.0,
bottomF = 0.0,
aFP = 0.0,
bFP = 0.0,
cFP = 0.0,
dFP = 0.0;
VectorType4D dir;
ERR(Artie_GetPlaneEquation(polyP, &aFP, &bFP, &cFP, &dFP));
if (!err) {
dir = Pdiff(rayP->P1, rayP->P0);
bottomF = aFP * dir.V[0] +bFP * dir.V[1] + cFP * dir.V[2];
if (bottomF){
topF = -(dFP + aFP*rayP->P0.P[0] + bFP*rayP->P0.P[1] + cFP*rayP->P0.P[2]);
*tPF = topF / bottomF;
} else {
*tPF = Artie_MISS;
}
}
return err;
}
static A_Err
Artie_RayIntersectLayer(
Artie_Poly *polyP,
Ray *rayP,
A_FpLong *tPF,
A_FpLong *uPF,
A_FpLong *vPF)
{
A_Err err = A_Err_NONE;
A_FpLong u0F = 0.0,
v0F = 0.0,
u1F = 0.0,
v1F = 0.0,
u2F = 0.0,
v2F = 0.0,
alphaF = 0.0,
betaF = 0.0,
gammaF = 0.0;
A_Boolean insideB = FALSE;
A_long i1L = 0,
i2 = 0,
kL = 0;
PointType4D P;
VectorType4D dir;
*uPF = *vPF = -1;
ERR(Artie_RayIntersectPlane(polyP, rayP, tPF));
if ( *tPF != Artie_MISS) {
// find uv-coords
dir = Pdiff(rayP->P1, rayP->P0);
P.P[0] = rayP->P0.P[0] + dir.V[0] * *tPF;
P.P[1] = rayP->P0.P[1] + dir.V[1] * *tPF;
P.P[2] = rayP->P0.P[2] + dir.V[2] * *tPF;
if (0 == polyP->dominant) {
i1L = 1;
i2 = 2;
} else if ( 1 == polyP->dominant) {
i1L = 0;
i2 = 2;
} else {
i1L = 0;
i2 = 1;
}
u0F = P.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v0F = P.P[i2] - polyP->vertsA[0].coord.P[i2];
kL = 2;
do{
u1F = polyP->vertsA[kL-1].coord.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v1F = polyP->vertsA[kL-1].coord.P[i2] - polyP->vertsA[0].coord.P[i2];
u2F = polyP->vertsA[kL ].coord.P[i1L] - polyP->vertsA[0].coord.P[i1L];
v2F = polyP->vertsA[kL ].coord.P[i2] - polyP->vertsA[0].coord.P[i2];
if (u1F == 0){
betaF = u0F/u2F;
if (betaF >= 0.0 && betaF <= 1.0){
alphaF = (v0F - betaF*v2F)/v1F;
insideB = ((alphaF>=0.) && (alphaF + betaF) <= 1);
}
} else {
betaF = (v0F * u1F - u0F * v1F)/(v2F * u1F - u2F * v1F);
if (betaF >= 0. && betaF <= 1.) {
alphaF = (u0F - betaF*u2F) / u1F;
insideB = ((alphaF >= 0.) && (alphaF + betaF) <= 1);
}
}
} while (!insideB && (++kL < 4));
if (insideB){
gammaF = 1.0 - alphaF - betaF;
*uPF = gammaF * polyP->vertsA[0].txtur[0] + alphaF * polyP->vertsA[kL-1].txtur[0] + betaF * polyP->vertsA[kL].txtur[0];
*vPF = gammaF * polyP->vertsA[0].txtur[1] + alphaF * polyP->vertsA[kL-1].txtur[1] + betaF * polyP->vertsA[kL].txtur[1];
} else {
*tPF = Artie_MISS;
}
}
return err;
}
static A_Err
Artie_FillIntersection(
Ray *rayP,
Artie_Poly *polyP,
A_FpLong t,
A_FpLong u,
A_FpLong v,
Intersection *intersectionP)
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(S_sp_basic_suiteP);
AEGP_WorldSuite2 *wsP = suites.WorldSuite2();
A_long widthL = 0,
heightL = 0;
A_u_long rowbytesLu = 0;
PF_Pixel8* baseP = NULL;
ERR(wsP->AEGP_GetSize(polyP->texture, &widthL, &heightL));
ERR(wsP->AEGP_GetBaseAddr8(polyP->texture, &baseP));
ERR(wsP->AEGP_GetRowBytes(polyP->texture, &rowbytesLu));
if ( t != Artie_MISS) {
intersectionP->hitB = TRUE;
intersectionP->intersect_point_coord_on_ray = t;
// build reflected ray
VectorType4D dir, reflected_dir;
A_FpLong dotF;
dir = Pdiff(rayP->P1, rayP->P0);
dotF = Dot4D(dir, polyP->normal);
reflected_dir = Vadd(polyP->normal, Vscale(-2.0, dir));
intersectionP->ray.P0 = PVadd(rayP->P0, Vscale(t, dir));
intersectionP->ray.P0 = PVadd(intersectionP->ray.P0, Vscale(0.0001, reflected_dir));
intersectionP->ray.P1 = PVadd(intersectionP->ray.P0, reflected_dir);
intersectionP->ray.depth = rayP->depth + 1;
intersectionP->ray.contribution = rayP->contribution * polyP->material.ksF;
intersectionP->reflectance_percentF = polyP->material.ksF;
if ( u >= 0 && v >= 0 && u <= 1 && v <= 1) {
A_long iL = static_cast<A_long>(u * (widthL-1));
A_long j = static_cast<A_long>(v * (heightL-1));
PF_Pixel8 *pP = baseP + iL;
intersectionP->color_struck_surface = *(PF_Pixel *)((char *)pP + j * rowbytesLu);
}
}
return err;
}
static
Intersection
SceneIntersection(
Artie_Scene *sceneP,
Ray *rayP)
{
A_Err err = A_Err_NONE;
Intersection returned_I,
I[Artie_MAX_POLYGONS];
A_FpLong u = 0.0,
v = 0.0;
returned_I.hitB = FALSE;
returned_I.intersect_point_coord_on_ray = Artie_MISS;
returned_I.reflectance_percentF = 0.0;
for(A_long iL = 0; iL < sceneP->num_polysL; ++iL){
I[iL].hitB = 0;
err = Artie_RayIntersectLayer(&sceneP->polygons[iL], rayP, &I[iL].intersect_point_coord_on_ray, &u, &v);
if (!err && I[iL].intersect_point_coord_on_ray != Artie_MISS){
I[iL].hitB = 1;
}
}
if (!err) {
for(A_long iL = 0; iL < sceneP->num_polysL; iL++) {
if (I[iL].hitB) {
if (I[iL].intersect_point_coord_on_ray < returned_I.intersect_point_coord_on_ray && I[iL].intersect_point_coord_on_ray > 0){
err = Artie_FillIntersection( rayP,
&sceneP->polygons[iL],
I[iL].intersect_point_coord_on_ray,
u,
v,
&returned_I);
}
}
}
}
return returned_I;
}
static A_Err
Artie_DoInstanceDialog(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_DialogResult *resultP) /* << */
{
A_Err err = A_Err_NONE;
in_dataP->msg_func(0, "Add any options for your Artisan here.");
*resultP = PR_DialogResult_NO_CHANGE;
return err;
}
/* allocate flat handle and write flatten instance data into it */
static A_Err
Artie_FlattenInstance(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_FlatHandle *flatPH) /* << */
{
return A_Err_NONE;
}
/* dispose of render data */
static A_Err
Artie_FrameSetdown(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH render_dataH) /* << */
{
return A_Err_NONE;
}
/* Called immediately before rendering; allocate any render data here */
static A_Err
Artie_FrameSetup(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH *render_dataPH) /* << */
{
return A_Err_NONE;
}
static A_Err
Artie_GlobalDoAbout(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH global_dataH) /* <> */
{
A_Err err = A_Err_NONE;
in_dataP->msg_func(err, "Artie the Artisan.");
return err;
}
static A_Err
Artie_GlobalSetdown(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH global_dataH) /* <> */ // must be disposed by plugin
{
return A_Err_NONE;
}
/* allocate global data here. */
static A_Err
Artie_GlobalSetup(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_GlobalDataH *global_dataPH) /* << */
{
return A_Err_NONE;
}
/* create instance data, using flat_data if supplied */
static A_Err
Artie_SetupInstance(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* >> */
PR_InstanceFlags flags,
PR_FlatHandle flat_dataH0, /* >> */
PR_InstanceDataH *instance_dataPH) /* << */
{
return A_Err_NONE;
}
/* deallocate your instance data */
static A_Err
Artie_SetdownInstance(
const PR_InData *in_dataP, /* >> */
const PR_GlobalContextH global_contextH, /* >> */
const PR_InstanceContextH instance_contextH, /* >> */
PR_GlobalDataH global_dataH, /* >> */
PR_InstanceDataH instance_dataH) /* >> */ // must be disposed by plugin
{
return A_Err_NONE;
}
static A_Err
Artie_Query(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_QueryContextH query_contextH, /* <> */
PR_QueryType query_type, /* >> */
PR_GlobalDataH global_data, /* >> */
PR_InstanceDataH instance_dataH) /* >> */
{
return A_Err_NONE;
}
static A_Err
Artie_DeathHook(
AEGP_GlobalRefcon plugin_refconP,
AEGP_DeathRefcon refconP)
{
return A_Err_NONE;
}
static A_Err
Artie_BuildLight(
const PR_InData *in_dataP, /* >> */
PR_RenderContextH render_contextH, /* >> */
AEGP_LayerH layerH, /* >> */
Artie_Light *lightP) /* <> */
{
A_Err err = A_Err_NONE;
A_Time comp_time, comp_time_step;
AEGP_StreamVal stream_val;
Artie_Light light;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LightSuite2()->AEGP_GetLightType(layerH, &lightP->type));
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_COLOR,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.color.alpha = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.alphaF + 0.5);
light.color.red = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.redF + 0.5);
light.color.green = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.greenF + 0.5);
light.color.blue = (A_u_char)(PF_MAX_CHAN8 * stream_val.color.blueF + 0.5);
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_INTENSITY,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err){
light.intensityF = stream_val.one_d;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CASTS_SHADOWS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.casts_shadowsB = (stream_val.one_d != 0.0);
}
// Normalize intensity
if (!err){
lightP->intensityF *= 0.01;
light.direction.x = 0;
light.direction.y = 0;
light.direction.z = 1;
light.position.x = 0;
light.position.y = 0;
light.position.z = 0;
// GetLightAttenuation was also unimplemented and only returned this constant.
light.attenuation.x = 1;
light.attenuation.y = 0;
light.attenuation.z = 0;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CONE_ANGLE,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.cone_angleF = stream_val.one_d;
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_CONE_FEATHER,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.spot_exponentF = stream_val.one_d;
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform( layerH,
&comp_time,
&light.light_to_world_matrix));
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SHADOW_DARKNESS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
light.shadow_densityF = stream_val.one_d;
if (!err) {
light.shadow_densityF *= 0.01;
}
if (!err && light.type != AEGP_LightType_PARALLEL) {
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SHADOW_DIFFUSION,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
light.radiusF = stream_val.one_d;
}
}
return err;
}
static A_Err
Artie_BuildLights(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle *lightsPH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
A_long layers_to_renderL = 0;
Artie_Light *lightP = NULL;
A_Boolean is_activeB = FALSE;
AEGP_LayerH layerH = NULL;;
A_Time comp_time = {0, 1},
comp_time_step = {0, 1};
AEGP_CompH compH = NULL;
AEGP_ObjectType layer_type = AEGP_ObjectType_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( S_aegp_plugin_id,
"Light Data",
sizeof(Artie_Light),
AEGP_MemFlag_CLEAR,
lightsPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*lightsPH, reinterpret_cast<void**>(&lightP)));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.LayerSuite5()->AEGP_GetCompNumLayers(compH, &layers_to_renderL));
for (A_long iL = 0; !err && iL < layers_to_renderL && iL < Artie_MAX_LIGHTS; iL++){
ERR(suites.LayerSuite5()->AEGP_GetCompLayerByIndex(compH, iL, &layerH));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LayerSuite5()->AEGP_IsVideoActive(layerH,
AEGP_LTimeMode_CompTime,
&comp_time,
&is_activeB));
ERR(suites.LayerSuite5()->AEGP_GetLayerObjectType(layerH, &layer_type));
if (!err && (AEGP_ObjectType_LIGHT == layer_type) && is_activeB){
err = Artie_BuildLight(in_dataP, render_contextH, layerH, lightP);
}
if (!err){
lightP->num_lightsL++;
}
}
if (lightP){
ERR(suites.MemorySuite1()->AEGP_UnlockMemHandle(*lightsPH));
}
if (lightsPH){
ERR2(Artie_DisposeLights(in_dataP, *lightsPH));
}
return err;
}
static A_Err
Artie_CompositeImage(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_LayerQuality quality,
AEGP_WorldH *srcP,
AEGP_WorldH *dstP)
{
A_Err err = A_Err_NONE;
PF_CompositeMode comp_mode;
PF_Quality pf_quality = PF_Quality_HI;
PF_Pixel8 *src_pixelsP = NULL;
PF_Pixel8 *dst_pixelsP = NULL;
PF_EffectWorld src_effect_world;
PF_EffectWorld dst_effect_world;
A_long src_widthL = 0,
src_heightL = 0,
dst_widthL = 0,
dst_heightL = 0;
A_Rect src_rect = {0, 0, 0, 0};
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
A_u_long src_rowbytesLu = 0,
dst_rowbytesLu = 0;
PF_Pixel8 *src_baseP = 0,
*dst_baseP = 0;
ERR(suites.WorldSuite3()->AEGP_GetSize(*srcP, &src_widthL, &src_heightL));
ERR(suites.WorldSuite3()->AEGP_GetSize(*dstP, &dst_widthL, &dst_heightL));
src_rect.bottom = static_cast<A_short>(src_heightL);
src_rect.right = static_cast<A_short>(src_widthL);
comp_mode.xfer = PF_Xfer_IN_FRONT;
comp_mode.rand_seed = 3141;
comp_mode.opacity = 255;
comp_mode.rgb_only = FALSE;
ERR(suites.WorldSuite3()->AEGP_FillOutPFEffectWorld(*srcP, &src_effect_world));
ERR(suites.WorldSuite3()->AEGP_FillOutPFEffectWorld(*dstP, &dst_effect_world));
ERR(suites.CompositeSuite2()->AEGP_TransferRect(pf_quality,
PF_MF_Alpha_STRAIGHT,
PF_Field_FRAME,
&src_rect,
&src_effect_world,
&comp_mode,
NULL,
NULL,
dst_widthL,
dst_heightL,
&dst_effect_world));
return err;
}
static PF_Pixel
Raytrace(
const PR_InData *in_dataP,
Artie_Scene *sceneP,
Ray *rayP)
{
Intersection I;
VectorType4D Nhat,Rvec, Rrefl;
Ray RefRay;
PF_Pixel cFP, crefl;
A_FpLong cosThetaI;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (rayP->contribution < Artie_RAYTRACE_THRESHOLD){
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
return cFP;
}
if (rayP->depth > Artie_MAX_RAY_DEPTH) {
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
return cFP;
}
I = SceneIntersection(sceneP, rayP);
if (I.hitB){
cFP.red = I.color_struck_surface.red;
cFP.green = I.color_struck_surface.green;
cFP.blue = I.color_struck_surface.blue;
cFP.alpha = I.color_struck_surface.alpha;
Nhat = Normalize(suites.ANSICallbacksSuite1()->sqrt, Pdiff(I.ray.P1, I.ray.P0));
Rvec = Normalize(suites.ANSICallbacksSuite1()->sqrt, Pdiff(rayP->P1, rayP->P0));
/* Compute the direction of the reflected ray */
cosThetaI = -Dot4D(Rvec, Nhat);
Rrefl = Vadd(Rvec, Vscale(2.0 * cosThetaI, Nhat));
if (I.reflectance_percentF){
/* Cast aFP reflected ray */
RefRay = CreateRay(I.ray.P0, PVadd(I.ray.P0, Rrefl));
RefRay.contribution = rayP->contribution * I.reflectance_percentF;
RefRay.depth = rayP->depth + 1;
crefl = Raytrace(in_dataP, sceneP, &RefRay);
cFP.red += (A_u_char)(I.reflectance_percentF * crefl.red);
cFP.green += (A_u_char)(I.reflectance_percentF * crefl.green);
cFP.blue += (A_u_char)(I.reflectance_percentF * crefl.blue);
}
} else {
cFP.red = 0;
cFP.green = 0;
cFP.blue = 0;
cFP.alpha = 0;
}
return cFP;
}
static
PF_Pixel ThrowRay(
const PR_InData *in_dataP,
Artie_Scene *sceneP,
A_FpLong xF,
A_FpLong yF,
A_FpLong zF)
{
Ray R;
PointType4D P0, P1;
P0.P[X] = 0;
P0.P[Y] = 0;
P0.P[Z] = 0;
P0.P[W] = 1;
P1.P[X] = xF;
P1.P[Y] = yF;
P1.P[Z] = zF;
P1.P[W] = 1;
R = CreateRay(P0, P1);
R.contribution = 1.0;
R.depth = 0;
return Raytrace(in_dataP, sceneP, &R);
}
static A_Err
Artie_SampleImage(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Scene *sceneP,
Artie_Camera *cameraP,
AEGP_WorldH *rwP)
{
A_Err err = A_Err_NONE;
A_FpLong x = 0,
y = 0,
z = cameraP->focal_lengthF;
PF_Pixel8 *pixelP = NULL,
*baseP = NULL;
A_long widthL = 0,
heightL = 0;
A_u_long rowbytesLu = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.WorldSuite2()->AEGP_GetSize(*rwP, &widthL, &heightL));
ERR(suites.WorldSuite2()->AEGP_GetBaseAddr8(*rwP, &baseP));
ERR(suites.WorldSuite2()->AEGP_GetRowBytes(*rwP, &rowbytesLu));
if (z < 0){
z *= -1;
}
for (A_long iL = 0; iL < heightL; iL++) {
y = -heightL/2.0 + iL + 0.5;
pixelP = (PF_Pixel8*)( (char *)baseP + iL * rowbytesLu);
for (A_long jL = 0; jL < widthL; jL++){
x = -widthL / 2.0 + jL + 0.5;
*pixelP++ = ThrowRay( in_dataP, sceneP, x, y, z);
}
}
return err;
}
static A_Err
Artie_TransformPolygon(
Artie_Poly *polyP,
const A_Matrix4 *xformP)
{
A_Err err = A_Err_NONE;
A_Matrix4 inverse,
normal_xformP;
for(A_long iL = 0; iL < 4; iL++) {
ERR(TransformPoint4(&polyP->vertsA[iL].coord, xformP, &polyP->vertsA[iL].coord));
}
ERR(InverseMatrix4(xformP, &inverse));
ERR(TransposeMatrix4(&inverse, &normal_xformP));
ERR(TransformVector4(&polyP->normal, &normal_xformP, &polyP->normal));
if (!err){
// find dominant axis;
polyP->dominant = 2;
if (ABS(polyP->normal.V[0]) > ABS(polyP->normal.V[1])) {
if (ABS(polyP->normal.V[0]) > ABS(polyP->normal.V[2])) {
polyP->dominant = 0;
} else {
polyP->dominant = 2;
}
} else if (ABS(polyP->normal.V[1]) > ABS(polyP->normal.V[2])) {
polyP->dominant = 1;
} else {
polyP->dominant = 2;
}
}
return err;
}
static A_Err
Artie_TransformScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Scene *sceneP,
Artie_Camera *cameraP)
{
A_Err err = A_Err_NONE;
A_Matrix4 composite,
up_sample,
world,
view,
down_sample;
ERR(ScaleMatrix4( cameraP->dsf.xS, cameraP->dsf.yS, 1.0, &up_sample));
ERR(ScaleMatrix4( 1.0 / cameraP->dsf.xS, 1.0 / cameraP->dsf.yS, 1.0, &down_sample));
if (!err){
view = cameraP->view_matrix;
}
for(A_long iL = 0; iL < sceneP->num_polysL; iL++) {
world = sceneP->polygons[iL].world_matrix;
ERR(MultiplyMatrix4(&up_sample, &world, &composite));
ERR(MultiplyMatrix4(&composite, &view, &composite));
ERR(MultiplyMatrix4(&composite, &down_sample, &composite));
ERR(Artie_TransformPolygon(&sceneP->polygons[iL], &composite));
}
return err;
}
static A_Err
Artie_Paint(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle sceneH,
AEGP_MemHandle cameraH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
Artie_Camera *cameraP = NULL;
AEGP_WorldH render_world;
AEGP_WorldH dst;
AEGP_CompH compH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
A_long widthL = 0,
heightL = 0;
AEGP_ItemH comp_itemH = NULL;
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(cameraH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &comp_itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(comp_itemH, &widthL, &heightL));
ERR(suites.CanvasSuite5()->AEGP_GetCompDestinationBuffer(render_contextH, compH, &dst));
ERR(suites.WorldSuite2()->AEGP_New( S_aegp_plugin_id,
AEGP_WorldType_8,
widthL,
heightL,
&render_world));
ERR(Artie_TransformScene( in_dataP,
render_contextH,
sceneP,
cameraP));
ERR(Artie_SampleImage( in_dataP,
render_contextH,
sceneP,
cameraP,
&render_world));
ERR(Artie_CompositeImage( in_dataP,
render_contextH,
0,
&render_world,
&dst));
if (dst){
ERR2(suites.WorldSuite2()->AEGP_Dispose(render_world));
}
if (sceneP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(sceneH));
}
if (cameraP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(cameraH));
}
return err;
}
static A_Err
Artie_CreateListOfLayerContexts(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
A_long *num_layersPL,
Artie_LayerContexts *layer_contexts)
{
A_Err err = A_Err_NONE;
AEGP_RenderLayerContextH layer_contextH = NULL;
A_long local_layers_to_renderL = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEGP_CanvasSuite5 *csP = suites.CanvasSuite5();
*num_layersPL = 0;
err = csP->AEGP_GetNumLayersToRender(render_contextH, &local_layers_to_renderL);
if (!err) {
for(A_long iL = 0; (!err && (iL < local_layers_to_renderL) && (iL < Artie_MAX_POLYGONS)); iL++){
ERR(csP->AEGP_GetNthLayerContextToRender(render_contextH, iL, &layer_contextH));
if (!err){
layer_contexts->layer_contexts[iL] = layer_contextH;
layer_contexts->count++;
}
}
*num_layersPL = local_layers_to_renderL;
}
return err;
}
static A_Err
Artie_GetSourceLayerSize(
const PR_InData *in_dataP, /* >> */
PR_RenderContextH render_contextH, /* >> */
AEGP_LayerH layerH, /* >> */
A_FpLong *widthPF, /* << */
A_FpLong *heightPF, /* << */
AEGP_DownsampleFactor *dsfP)
{
A_Err err = A_Err_NONE;
AEGP_ItemH source_itemH = NULL;
AEGP_DownsampleFactor dsf = {1, 1};
A_long widthL = 0,
heightL = 0;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (widthPF == NULL ||
heightPF == NULL ||
dsfP == NULL){
err = A_Err_PARAMETER;
}
if (!err){
if (widthPF){
*widthPF = 0.0;
}
if (heightPF){
*heightPF = 0.0;
}
if (dsfP) {
dsfP->xS =
dsfP->yS = 1;
}
// This doesn't return a valid item if the layer is a text layer
// Use AEGP_GetCompRenderTime, AEGP_GetRenderLayerBounds, AEGP_GetRenderDownsampleFactor instead?
ERR(suites.LayerSuite5()->AEGP_GetLayerSourceItem(layerH, &source_itemH));
if (!err && source_itemH){
err = suites.ItemSuite6()->AEGP_GetItemDimensions(source_itemH, &widthL, &heightL);
if (!err){
*widthPF = widthL / (A_FpLong)dsf.xS;
*heightPF = heightL / (A_FpLong)dsf.yS;
ERR(suites.CanvasSuite5()->AEGP_GetRenderDownsampleFactor(render_contextH, &dsf));
if (!err && dsfP){
*dsfP = dsf;
}
}
}
}
return err;
}
static A_Err
Artie_DisposePolygonTexture(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
Artie_Poly *polygonP)
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEGP_CanvasSuite5 *canP = suites.CanvasSuite5();
if (polygonP->texture){
err = canP->AEGP_DisposeTexture(render_contextH, polygonP->layer_contextH, polygonP->texture);
}
return err;
}
/**
** get the pixels and the vertices
** if quality = wireframe, just get the dimensions
**
** we wait until this routine to get the layer dimension as its height and width
** may change with buffer expanding effects applied.
**/
static A_Err
Artie_GetPolygonTexture(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_RenderHints render_hints,
A_Boolean *is_visiblePB,
Artie_Poly *polygonP)
{
A_Err err = A_Err_NONE;
A_FpLong widthF = 0.0, heightF = 0.0;
AEGP_DownsampleFactor dsf = {1, 1};
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*is_visiblePB = FALSE;
if (!polygonP->texture){
// no texture map yet
// if we're in wireframe, there is no texture.
// we still need the dimensions, so we'll get the layers source dimensions and use that.
// we'll also need to correct for the comp down sampling as all textures have this correction
if ( polygonP->aegp_quality == AEGP_LayerQual_WIREFRAME){
ERR(Artie_GetSourceLayerSize( in_dataP,
render_contextH,
polygonP->layerH,
&widthF,
&heightF,
&dsf));
if (!err){
polygonP->origin.x = 0;
polygonP->origin.y = 0;
}
} else {
ERR(suites.CanvasSuite5()->AEGP_RenderTexture( render_contextH,
polygonP->layer_contextH,
AEGP_RenderHints_NONE,
NULL,
NULL,
NULL,
&polygonP->texture));
}
if (!err && polygonP->texture) {
*is_visiblePB = TRUE;
}
if (!err && *is_visiblePB){
A_FpLong widthL = 0,
heightL = 0;
err = Artie_GetSourceLayerSize( in_dataP,
render_contextH,
polygonP->layerH,
&widthL,
&heightL,
&dsf);
if (!err){
polygonP->origin.x /= (A_FpLong)dsf.xS;
polygonP->origin.y /= (A_FpLong)dsf.yS;
}
}
// construct the polygon vertices in local ( pixel) space.
if (!err && *is_visiblePB) {
A_long widthL = 0, heightL = 0;
ERR(suites.WorldSuite2()->AEGP_GetSize(polygonP->texture, &widthL, &heightL));
widthF = static_cast<A_FpLong>(widthL);
heightF = static_cast<A_FpLong>(heightL);
// counterclockwise specification -- for texture map
//vertex 0
polygonP->vertsA[0].coord.P[0] = -polygonP->origin.x;
polygonP->vertsA[0].coord.P[1] = -polygonP->origin.y;
polygonP->vertsA[0].coord.P[2] = 0;
polygonP->vertsA[0].coord.P[3] = 1;
polygonP->vertsA[0].txtur[0] = 0.0;
polygonP->vertsA[0].txtur[1] = 0.0;
polygonP->vertsA[0].txtur[2] = 1;
// vertex 1
polygonP->vertsA[1].coord.P[0] = -polygonP->origin.x;
polygonP->vertsA[1].coord.P[1] = heightF - polygonP->origin.y;
polygonP->vertsA[1].coord.P[2] = 0.0;
polygonP->vertsA[1].coord.P[3] = 1;
polygonP->vertsA[1].txtur[0] = 0.0;
polygonP->vertsA[1].txtur[1] = 1.0;
polygonP->vertsA[1].txtur[2] = 1;
//vertex 2
polygonP->vertsA[2].coord.P[0] = widthF - polygonP->origin.x ;
polygonP->vertsA[2].coord.P[1] = heightF - polygonP->origin.y ;
polygonP->vertsA[2].coord.P[2] = 0;
polygonP->vertsA[2].coord.P[3] = 1;
polygonP->vertsA[2].txtur[0] = 1.0;
polygonP->vertsA[2].txtur[1] = 1.0;
polygonP->vertsA[2].txtur[2] = 1;
// vertex 3
polygonP->vertsA[3].coord.P[0] = (widthF - polygonP->origin.x);
polygonP->vertsA[3].coord.P[1] = -polygonP->origin.y;
polygonP->vertsA[3].coord.P[2] = 0;
polygonP->vertsA[3].coord.P[3] = 1;
polygonP->vertsA[3].txtur[0] = 1.0;
polygonP->vertsA[3].txtur[1] = 0.0;
polygonP->vertsA[3].txtur[2] = 1;
}
}
return err;
}
static A_Err
Artie_BuildPolygon(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_RenderLayerContextH layer_contextH,
AEGP_LayerH layerH,
A_Matrix4 *xform,
A_FpLong widthF,
A_FpLong heightF,
PF_CompositeMode *composite_mode,
Artie_Material *material,
AEGP_TrackMatte *track_matte,
AEGP_LayerQuality *aegp_quality,
Artie_Poly *polygonP) /* <> */
{
A_Err err = A_Err_NONE;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
AEFX_CLR_STRUCT(*polygonP);
polygonP->aegp_quality = *aegp_quality;
polygonP->layerH = layerH;
polygonP->layer_contextH = layer_contextH;
polygonP->normal.V[X] = 0;
polygonP->normal.V[Y] = 0;
polygonP->normal.V[Z] = -1;
polygonP->normal.V[W] = 0;
polygonP->material = *material;
polygonP->world_matrix = *xform;
// fill in vertices and texture map
err = Artie_GetPolygonTexture( in_dataP,
render_contextH,
AEGP_RenderHints_NONE,
&polygonP->is_visibleB,
polygonP);
return err;
}
static A_Err
Artie_AddPolygonToScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
A_long indexL,
AEGP_RenderLayerContextH layer_contextH,
AEGP_LayerH layerH,
AEGP_MemHandle sceneH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
PF_CompositeMode composite_mode;
AEGP_TrackMatte track_matte;
A_Matrix4 xform;
AEGP_LayerQuality aegp_quality;
AEGP_LayerFlags layer_flags;
AEGP_LayerTransferMode layer_transfer_mode;
Artie_Poly poly;
A_FpLong opacityF = 0.0,
widthF = 0.0,
heightF = 0.0;
A_long seedL = 0;
Artie_Material material;
A_Time comp_time = {0,1},
comp_time_step = {0,1};
AEGP_StreamVal stream_val;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
ERR(suites.LayerSuite5()->AEGP_GetLayerFlags(layerH, &layer_flags));
ERR(suites.LayerSuite5()->AEGP_GetLayerTransferMode(layerH, &layer_transfer_mode));
ERR(suites.LayerSuite5()->AEGP_GetLayerQuality(layerH, &aegp_quality));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform(layerH, &comp_time, &xform));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &comp_time, &comp_time_step));
ERR(suites.CanvasSuite5()->AEGP_GetRenderOpacity(render_contextH, layer_contextH, &comp_time, &opacityF));
ERR(suites.LayerSuite5()->AEGP_GetLayerDancingRandValue(layerH, &comp_time, &seedL));
if (!err) {
composite_mode.xfer = layer_transfer_mode.mode;
composite_mode.rand_seed = seedL;
composite_mode.opacity = (unsigned char) (255.0 * opacityF / 100.0 + 0.5);
composite_mode.rgb_only = (layer_transfer_mode.flags & AEGP_TransferFlag_PRESERVE_ALPHA) != 0;
track_matte = layer_transfer_mode.track_matte;
}
// get polygon material
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_AMBIENT_COEFF,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err){
material.kaF = stream_val.one_d;
err = suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_DIFFUSE_COEFF,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL);
material.kdF = stream_val.one_d;
}
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue( layerH,
AEGP_LayerStream_SPECULAR_INTENSITY,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
// Normalize coeffs
if (!err) {
material.ksF = stream_val.one_d;
material.kaF *= 0.01;
material.kdF *= 0.01;
material.ksF *= 0.01;
}
ERR(suites.StreamSuite2()->AEGP_GetLayerStreamValue(layerH,
AEGP_LayerStream_SPECULAR_SHININESS,
AEGP_LTimeMode_CompTime,
&comp_time,
FALSE,
&stream_val,
NULL));
if (!err) {
material.specularF = stream_val.one_d;
AEGP_DownsampleFactor dsf = {1,1};
err = Artie_GetSourceLayerSize( in_dataP,
render_contextH,
layerH,
&widthF,
&heightF,
&dsf);
}
ERR(Artie_BuildPolygon( in_dataP,
render_contextH,
layer_contextH,
layerH,
&xform,
widthF,
heightF,
&composite_mode,
&material,
&track_matte,
&aegp_quality,
&poly));
if (!err) {
sceneP->polygons[indexL] = poly;
sceneP->num_polysL++;
}
if (sceneP) {
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(sceneH));
}
return err;
}
static A_Err
Artie_DisposeScene(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle sceneH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (sceneH) {
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(sceneH, reinterpret_cast<void**>(&sceneP)));
if (!err) {
for(A_long iL = 0; iL< sceneP->num_polysL; iL++){
ERR(Artie_DisposePolygonTexture(in_dataP, render_contextH, &sceneP->polygons[iL]));
}
}
ERR2(suites.MemorySuite1()->AEGP_FreeMemHandle(sceneH));
}
return err;
}
static A_Err
Artie_BuildScene(
const PR_InData *in_dataP,
Artie_LayerContexts layer_contexts,
PR_RenderContextH render_contextH,
AEGP_MemHandle *scenePH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Scene *sceneP = NULL;
AEGP_LayerH layerH = NULL;
AEGP_CompH compH = NULL;
AEGP_ItemH source_itemH = NULL;
AEGP_ItemFlags item_flags = 0;
A_long layers_to_renderL = 0;
AEGP_MemHandle lightsH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Scene Data",
sizeof(Artie_Scene),
AEGP_MemFlag_CLEAR,
scenePH));
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(Artie_CreateListOfLayerContexts(in_dataP,
render_contextH,
&layers_to_renderL,
&layer_contexts));
ERR(Artie_BuildLights(in_dataP, render_contextH, &lightsH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*scenePH, reinterpret_cast<void**>(&sceneP)));
for(A_long iL = 0; iL < layers_to_renderL; iL++){
ERR(suites.CanvasSuite5()->AEGP_GetLayerFromLayerContext( render_contextH,
layer_contexts.layer_contexts[iL],
&layerH));
ERR(suites.LayerSuite5()->AEGP_GetLayerSourceItem(layerH, &source_itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemFlags(source_itemH, &item_flags));
if (item_flags & AEGP_ItemFlag_HAS_VIDEO){
ERR(Artie_AddPolygonToScene( in_dataP,
render_contextH,
iL,
layer_contexts.layer_contexts[iL],
layerH,
*scenePH));
}
}
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(*scenePH));
return err;
}
static A_Err
Artie_DisposeCamera(
const PR_InData *in_dataP,
AEGP_MemHandle cameraH)
{
A_Err err = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
if (!cameraH) {
err = PF_Err_UNRECOGNIZED_PARAM_TYPE;
in_dataP->msg_func(err, "Trying to dispose NULL camera");
}
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(cameraH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.MemorySuite1()->AEGP_FreeMemHandle(cameraH));
return err;
}
static A_Err
Artie_CreateDefaultCamera(
const PR_InData *in_dataP,
AEGP_CompH compH,
AEGP_DownsampleFactor *dsfP,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_ItemH itemH = NULL;
A_long widthL = 0,
heightL = 0;
A_FpLong comp_origin_xF = 0.0,
comp_origin_yF = 0.0,
min_dimensionF = 0.0;
A_Matrix4 matrix;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*cameraPH = NULL;
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Camera Data",
sizeof(Artie_Camera),
AEGP_MemFlag_CLEAR,
cameraPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*cameraPH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(itemH, &widthL, &heightL));
// comp origin is the middle of the comp in x and y, and z = 0.
if (!err){
comp_origin_xF = widthL / 2.0;
comp_origin_yF = heightL / 2.0;
min_dimensionF = MIN(comp_origin_xF, comp_origin_yF);
A_FpLong tanF = suites.ANSICallbacksSuite1()->tan(0.5 * Artie_DEFAULT_FIELD_OF_VIEW);
cameraP->type = AEGP_CameraType_PERSPECTIVE;
cameraP->res_xLu = static_cast<A_u_long>(widthL);
cameraP->res_yLu = static_cast<A_u_long>(heightL);
cameraP->focal_lengthF = min_dimensionF / tanF;
cameraP->dsf = *dsfP;
ERR(IdentityMatrix4(&matrix));
ERR(TranslateMatrix4(comp_origin_xF,
comp_origin_yF,
-cameraP->focal_lengthF,
&matrix));
ERR(InverseMatrix4(&matrix, &cameraP->view_matrix));
ERR(suites.MemorySuite1()->AEGP_UnlockMemHandle(*cameraPH));
}
return err;
}
static A_Err
Artie_CreateLayerCamera(
const PR_InData *in_dataP,
AEGP_CompH compH,
AEGP_DownsampleFactor *dsfP,
A_Time comp_time,
A_Rect *roiRP0,
AEGP_LayerH camera_layerH,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
Artie_Camera *cameraP = NULL;
AEGP_ItemH itemH = NULL;
A_long widthL = 0,
heightL = 0;
A_Ratio pix_aspectR = {1,1};
A_FpLong comp_origin_xF = 0.0,
comp_origin_yF = 0.0;
A_Matrix4 matrix;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
*cameraPH = NULL;
ERR(suites.MemorySuite1()->AEGP_NewMemHandle( in_dataP->aegp_plug_id,
"Camera Data",
sizeof(Artie_Camera),
AEGP_MemFlag_CLEAR,
cameraPH));
ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*cameraPH, reinterpret_cast<void**>(&cameraP)));
ERR(suites.CompSuite4()->AEGP_GetItemFromComp(compH, &itemH));
ERR(suites.ItemSuite6()->AEGP_GetItemDimensions(itemH, &widthL, &heightL));
ERR(suites.ItemSuite6()->AEGP_GetItemPixelAspectRatio(itemH, &pix_aspectR));
// comp origin is the middle of the comp in x and y, and z = 0.
if (!err) {
comp_origin_xF = widthL / 2.0;
comp_origin_yF = heightL / 2.0;
cameraP->view_aspect_ratioF = widthL / heightL;
cameraP->pixel_aspect_ratioF = pix_aspectR.num / pix_aspectR.den;
cameraP->dsf = *dsfP;
}
ERR(suites.LayerSuite5()->AEGP_GetLayerToWorldXform(camera_layerH, &comp_time, &matrix));
ERR(InverseMatrix4(&matrix, &cameraP->view_matrix));
ERR(suites.CameraSuite2()->AEGP_GetCameraType(camera_layerH, &cameraP->type));
if (!err) {
cameraP->res_xLu = (unsigned long) widthL;
cameraP->res_yLu = (unsigned long) heightL;
cameraP->dsf = *dsfP;
if (roiRP0){
cameraP->roiR = *roiRP0;
}
}
if (cameraP){
ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(*cameraPH));
}
if (*cameraPH){
ERR2(Artie_DisposeCamera(in_dataP, *cameraPH));
*cameraPH = NULL;
}
return err;
}
static A_Err
Artie_BuildCamera(
const PR_InData *in_dataP,
PR_RenderContextH render_contextH,
AEGP_MemHandle *cameraPH)
{
A_Err err = A_Err_NONE;
AEGP_LayerH camera_layerH = NULL;
A_Time render_time = {0,1},
time_step = {0,1};
AEGP_DownsampleFactor dsf = {1,1};
AEGP_CompH compH = NULL;
A_LegacyRect roiLR = {0,0,0,0};
A_Rect roiR = {0,0,0,0};
*cameraPH = NULL;
AEGP_SuiteHandler suites(in_dataP->pica_basicP);
ERR(suites.CanvasSuite5()->AEGP_GetCompToRender(render_contextH, &compH));
ERR(suites.CanvasSuite5()->AEGP_GetRenderDownsampleFactor(render_contextH, &dsf));
ERR(suites.CanvasSuite5()->AEGP_GetCompRenderTime(render_contextH, &render_time, &time_step));
ERR(suites.CameraSuite2()->AEGP_GetCamera(render_contextH, &render_time, &camera_layerH));
ERR(suites.CanvasSuite5()->AEGP_GetROI(render_contextH, &roiLR));
if (!err && !camera_layerH){
ERR(Artie_CreateDefaultCamera(in_dataP, compH, &dsf, cameraPH));
} else {
roiR.top = roiLR.top;
roiR.left = roiLR.left;
roiR.right = roiLR.right;
roiR.bottom = roiLR.bottom;
ERR(Artie_CreateLayerCamera( in_dataP,
compH,
&dsf,
render_time,
&roiR,
camera_layerH,
cameraPH));
}
return err;
}
static A_Err
Artie_Render(
const PR_InData *in_dataP, /* >> */
PR_GlobalContextH global_contextH, /* >> */
PR_InstanceContextH instance_contextH, /* >> */
PR_RenderContextH render_contextH, /* >> */
PR_GlobalDataH global_dataH, /* <> */
PR_InstanceDataH instance_dataH, /* <> */
PR_RenderDataH render_dataH)
{
A_Err err = A_Err_NONE,
err2 = A_Err_NONE;
AEGP_MemHandle cameraH = NULL;
AEGP_MemHandle sceneH = NULL;
Artie_LayerContexts layer_contexts;
AEFX_CLR_STRUCT(layer_contexts);
ERR(Artie_BuildCamera(in_dataP, render_contextH, &cameraH));
if (cameraH){
ERR(Artie_BuildScene(in_dataP, layer_contexts, render_contextH, &sceneH));
if (sceneH){
ERR(Artie_Paint(in_dataP, render_contextH, sceneH, cameraH));
ERR2(Artie_DisposeScene(in_dataP, render_contextH, sceneH));
ERR2(Artie_DisposeCamera(in_dataP, cameraH));
}
}
return err;
}
A_Err
EntryPointFunc(
struct SPBasicSuite *pica_basicP, /* >> */
A_long major_versionL, /* >> */
A_long minor_versionL, /* >> */
AEGP_PluginID aegp_plugin_id, /* >> */
AEGP_GlobalRefcon *plugin_refconP) /* << */
{
A_Err err = A_Err_NONE;
A_Version api_version;
A_Version artisan_version;
char match_nameA[PR_PUBLIC_MATCH_NAME_LEN];
char artisan_nameA[PR_PUBLIC_ARTISAN_NAME_LEN];
PR_ArtisanEntryPoints entry_funcs;
AEGP_SuiteHandler suites(pica_basicP);
api_version.majorS = PR_ARTISAN_API_VERSION_MAJOR;
api_version.minorS = PR_ARTISAN_API_VERSION_MINOR;
artisan_version.majorS = Artie_MAJOR_VERSION;
artisan_version.minorS = Artie_MAJOR_VERSION;
S_aegp_plugin_id = aegp_plugin_id;
S_sp_basic_suiteP = pica_basicP;
suites.ANSICallbacksSuite1()->strcpy(match_nameA, Artie_ARTISAN_MATCH_NAME);
suites.ANSICallbacksSuite1()->strcpy(artisan_nameA, Artie_ARTISAN_NAME);
// 0 at the end of the name means optional function
// only render_func is not optional.
try {
entry_funcs.do_instance_dialog_func0 = Artie_DoInstanceDialog;
entry_funcs.flatten_instance_func0 = Artie_FlattenInstance;
entry_funcs.frame_setdown_func0 = Artie_FrameSetdown;
entry_funcs.frame_setup_func0 = Artie_FrameSetup;
entry_funcs.global_do_about_func0 = Artie_GlobalDoAbout;
entry_funcs.global_setdown_func0 = Artie_GlobalSetdown;
entry_funcs.global_setup_func0 = Artie_GlobalSetup;
entry_funcs.render_func = Artie_Render;
entry_funcs.setup_instance_func0 = Artie_SetupInstance;
entry_funcs.setdown_instance_func0 = Artie_SetdownInstance;
entry_funcs.query_func0 = Artie_Query;
#ifdef DEBUG
ERR(suites.MemorySuite1()->AEGP_SetMemReportingOn(TRUE));
#endif
ERR(suites.RegisterSuite5()->AEGP_RegisterArtisan( api_version,
artisan_version,
aegp_plugin_id,
plugin_refconP,
match_nameA,
artisan_nameA,
&entry_funcs));
ERR(suites.RegisterSuite5()->AEGP_RegisterDeathHook( S_aegp_plugin_id,
Artie_DeathHook,
NULL));
} catch (A_Err &thrown_err){
err = thrown_err;
}
return err;
}
/* Everything below this line is specific to Artie's implementation, and
has little to do with the Artisan interface. Hopefully, your plug-in
does something more exciting than basic raytracing.
*/
static void
NormalizePoint(
PointType4D *P1)
{
register double *p = P1->P;
register double w = p[W];
if (w != 1.0){
/* We are assuming that the order in P is: X, Y, Z, W */
*p++ /= w;
*p++ /= w;
*p++ /= w;
*p = 1.0;
}
}
static VectorType4D
Normalize(
A_FpLong (*sqrt)(A_FpLong),
VectorType4D v)
{
VectorType4D vout;
A_FpLong l = sqrt( v.V[0]*v.V[0] + v.V[1]*v.V[1] + v.V[2]*v.V[2]);
if (l < Artie_EPSILON){
vout = v;
} else {
vout.V[0] = v.V[0]/l;
vout.V[1] = v.V[1]/l;
vout.V[2] = v.V[2]/l;
vout.V[3] = 0.0;
}
return vout;
}
/* Return the vector V=P1-P0. */
static VectorType4D
Pdiff(
PointType4D P1,
PointType4D P0)
{
VectorType4D V;
NormalizePoint(&P0);
NormalizePoint(&P1);
V.V[0] = P1.P[0] - P0.P[0];
V.V[1] = P1.P[1] - P0.P[1];
V.V[2] = P1.P[2] - P0.P[2];
V.V[3] = 0.0;
return V;
}
/* Return the vector s*V. */
static VectorType4D
Vscale(
PF_FpLong sF,
VectorType4D V)
{
V.V[X] *= sF;
V.V[Y] *= sF;
V.V[Z] *= sF;
V.V[W] = 0.0;
return V;
}
/* Return the vector V1+V1. */
VectorType4D
Vadd(
VectorType4D V1,
VectorType4D V2)
{
VectorType4D V;
V.V[X] = V1.V[X] + V2.V[X];
V.V[Y] = V1.V[Y] + V2.V[Y];
V.V[Z] = V1.V[Z] + V2.V[Z];
V.V[W] = 0.0;
return V;
}
/* Return the point P+V. */
PointType4D
PVadd(
PointType4D P,
VectorType4D V)
{
PointType4D p;
NormalizePoint(&P);
p.P[X] = P.P[X] + V.V[X];
p.P[Y] = P.P[Y] + V.V[Y];
p.P[Z] = P.P[Z] + V.V[Z];
p.P[W] = 1.0;
return p;
}
/* Return the negative of vector V */
VectorType4D
Vneg(
VectorType4D V)
{
V.V[X] = -V.V[X];
V.V[Y] = -V.V[Y];
V.V[Z] = -V.V[Z];
/* since V is aFP vector, V.V[W] is always 0. */
return V;
}
A_FpLong
Dot4D(
VectorType4D v1F,
VectorType4D v2F)
{
return v1F.V[0] * v2F.V[0] + v1F.V[1] * v2F.V[1] + v1F.V[2] * v2F.V[2];
}
A_Err
IdentityMatrix4(
A_Matrix4 *matrixP)
{
AEFX_CLR_STRUCT(*matrixP);
matrixP->mat[0][0] = 1.0;
matrixP->mat[1][1] = 1.0;
matrixP->mat[2][2] = 1.0;
matrixP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
TranslateMatrix4(
A_FpLong x,
A_FpLong y,
A_FpLong z,
A_Matrix4 *resultP)
{
IdentityMatrix4(resultP);
resultP->mat[3][0] = x;
resultP->mat[3][1] = y;
resultP->mat[3][2] = z;
resultP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
ScaleMatrix4(
A_FpLong x,
A_FpLong y,
A_FpLong z,
A_Matrix4 *resultP)
{
IdentityMatrix4(resultP);
resultP->mat[0][0] = x;
resultP->mat[1][1] = y;
resultP->mat[2][2] = z;
resultP->mat[3][3] = 1.0;
return A_Err_NONE;
}
A_Err
TransposeMatrix4(
const A_Matrix4 *matrix1,
A_Matrix4 *resultP)
{
register A_u_long iLu, jLu;
A_Matrix4 tmp;
for (iLu = 0 ; iLu < 4 ; iLu++){
for (jLu = 0 ; jLu < 4 ; jLu++) {
tmp.mat[iLu][jLu] = matrix1->mat[jLu][iLu];
}
}
AEFX_COPY_STRUCT(tmp, *resultP);
return A_Err_NONE;
}
/* compute inverse, if no inverse, return adjoint */
A_Err
InverseMatrix4(
const A_Matrix4 *m,
A_Matrix4 *resultP)
{
A_Err err = A_Err_NONE;
A_FpLong d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33,
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33,
D;
m00 = m->mat[0][0]; m01 = m->mat[0][1]; m02 = m->mat[0][2]; m03 = m->mat[0][3];
m10 = m->mat[1][0]; m11 = m->mat[1][1]; m12 = m->mat[1][2]; m13 = m->mat[1][3];
m20 = m->mat[2][0]; m21 = m->mat[2][1]; m22 = m->mat[2][2]; m23 = m->mat[2][3];
m30 = m->mat[3][0]; m31 = m->mat[3][1]; m32 = m->mat[3][2]; m33 = m->mat[3][3];
d00 = m11*m22*m33 + m12*m23*m31 + m13*m21*m32 - m31*m22*m13 - m32*m23*m11 - m33*m21*m12;
d01 = m10*m22*m33 + m12*m23*m30 + m13*m20*m32 - m30*m22*m13 - m32*m23*m10 - m33*m20*m12;
d02 = m10*m21*m33 + m11*m23*m30 + m13*m20*m31 - m30*m21*m13 - m31*m23*m10 - m33*m20*m11;
d03 = m10*m21*m32 + m11*m22*m30 + m12*m20*m31 - m30*m21*m12 - m31*m22*m10 - m32*m20*m11;
d10 = m01*m22*m33 + m02*m23*m31 + m03*m21*m32 - m31*m22*m03 - m32*m23*m01 - m33*m21*m02;
d11 = m00*m22*m33 + m02*m23*m30 + m03*m20*m32 - m30*m22*m03 - m32*m23*m00 - m33*m20*m02;
d12 = m00*m21*m33 + m01*m23*m30 + m03*m20*m31 - m30*m21*m03 - m31*m23*m00 - m33*m20*m01;
d13 = m00*m21*m32 + m01*m22*m30 + m02*m20*m31 - m30*m21*m02 - m31*m22*m00 - m32*m20*m01;
d20 = m01*m12*m33 + m02*m13*m31 + m03*m11*m32 - m31*m12*m03 - m32*m13*m01 - m33*m11*m02;
d21 = m00*m12*m33 + m02*m13*m30 + m03*m10*m32 - m30*m12*m03 - m32*m13*m00 - m33*m10*m02;
d22 = m00*m11*m33 + m01*m13*m30 + m03*m10*m31 - m30*m11*m03 - m31*m13*m00 - m33*m10*m01;
d23 = m00*m11*m32 + m01*m12*m30 + m02*m10*m31 - m30*m11*m02 - m31*m12*m00 - m32*m10*m01;
d30 = m01*m12*m23 + m02*m13*m21 + m03*m11*m22 - m21*m12*m03 - m22*m13*m01 - m23*m11*m02;
d31 = m00*m12*m23 + m02*m13*m20 + m03*m10*m22 - m20*m12*m03 - m22*m13*m00 - m23*m10*m02;
d32 = m00*m11*m23 + m01*m13*m20 + m03*m10*m21 - m20*m11*m03 - m21*m13*m00 - m23*m10*m01;
d33 = m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m20*m11*m02 - m21*m12*m00 - m22*m10*m01;
D = m00*d00 - m01*d01 + m02*d02 - m03*d03;
if (D) {
resultP->mat[0][0] = d00/D; resultP->mat[0][1] = -d10/D; resultP->mat[0][2] = d20/D; resultP->mat[0][3] = -d30/D;
resultP->mat[1][0] = -d01/D; resultP->mat[1][1] = d11/D; resultP->mat[1][2] = -d21/D; resultP->mat[1][3] = d31/D;
resultP->mat[2][0] = d02/D; resultP->mat[2][1] = -d12/D; resultP->mat[2][2] = d22/D; resultP->mat[2][3] = -d32/D;
resultP->mat[3][0] = -d03/D; resultP->mat[3][1] = d13/D; resultP->mat[3][2] = -d23/D; resultP->mat[3][3] = d33/D;
} else {
resultP->mat[0][0] = d00; resultP->mat[0][1] = -d10; resultP->mat[0][2] = d20; resultP->mat[0][3] = -d30;
resultP->mat[1][0] = -d01; resultP->mat[1][1] = d11; resultP->mat[1][2] = -d21; resultP->mat[1][3] = d31;
resultP->mat[2][0] = d02; resultP->mat[2][1] = -d12; resultP->mat[2][2] = d22; resultP->mat[2][3] = -d32;
resultP->mat[3][0] = -d03; resultP->mat[3][1] = d13; resultP->mat[3][2] = -d23; resultP->mat[3][3] = d33;
}
return err;
}
A_Err
MultiplyMatrix4(
const A_Matrix4 *A,
const A_Matrix4 *B,
A_Matrix4 *resultP)
{
A_Err err = A_Err_NONE;
A_Matrix4 tmp;
for (register A_u_long iLu = 0; iLu < 4; iLu++){
for (register int jLu = 0; jLu < 4; jLu++) {
tmp.mat[iLu][jLu] = A->mat[iLu][0] * B->mat[0][jLu] +
A->mat[iLu][1] * B->mat[1][jLu] +
A->mat[iLu][2] * B->mat[2][jLu] +
A->mat[iLu][3] * B->mat[3][jLu];
}
}
AEFX_COPY_STRUCT(tmp, *resultP);
return err;
}
A_Err
TransformPoint4(
const PointType4D *pointP,
const A_Matrix4 *transformP,
PointType4D *resultP)
{
A_Err err = A_Err_NONE;
PointType4D tmp;
Artie_TRANSFORM_POINT4(*pointP, *transformP, tmp);
*resultP = tmp;
return err;
}
A_Err
TransformVector4(
const VectorType4D *vectorP,
const A_Matrix4 *matrixP,
VectorType4D *resultP)
{
A_Err err = A_Err_NONE;
VectorType4D tmp;
Artie_TRANSFORM_VECTOR4(*vectorP, *matrixP, tmp);
*resultP = tmp;
return err;
}
Ray CreateRay(PointType4D P0, PointType4D P1)
{
Ray R;
R.P0 = P0;
R.P1 = P1;
return R;
}
Ray
TransformRay(
const Ray *rayP,
const A_Matrix4 *xformP)
{
Ray R;
TransformPoint4(&rayP->P0, xformP, &R.P0);
TransformPoint4(&rayP->P1, xformP, &R.P1);
return R;
}
| 27.072421
| 128
| 0.635971
|
richardlalancette
|
8dcdceb83fc9d8ea0df3482ac0a2b963dda53557
| 6,152
|
hpp
|
C++
|
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | null | null | null |
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | 1
|
2020-09-10T01:17:13.000Z
|
2020-09-10T01:17:13.000Z
|
src/field/fieldI.hpp
|
NSCCWX-AMD/HSF
|
dbf5987e364ce0ca3e92e72540a66a62353f4b3a
|
[
"Apache-2.0"
] | 2
|
2019-11-29T08:00:29.000Z
|
2019-11-29T08:26:13.000Z
|
/*
The MIT License
Copyright (c) 2019 Hanfeng GU <hanfenggu@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
* @File: fieldI.hpp
* @Author: Hanfeng GU
* @Email: hanfenggu@gmail.com
* @Date: 2019-09-18 16:04:01
* @Last Modified by: Hanfeng
* @Last Modified time: 2019-11-28 14:11:47
*/
/*
* @brief: Implementation of template functions in Field class
*/
template <typename T>
Field<T>::Field()
: setType_(NULL),
ndim_(0),
locSize_(0),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
}
template <typename T>
Field<T>::Field(Word setType, label ndim, label n, T *dataPtr)
: setType_(setType),
ndim_(ndim),
locSize_(n),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
data_ = new T[n * ndim];
memcpy(data_, dataPtr, n * ndim * sizeof(T));
}
template <typename T>
Field<T>::Field(Word setType,
label ndim,
label n,
T *dataPtr,
Table<Word, Table<Word, Patch *> *> &patchTab)
: setType_(setType),
ndim_(ndim),
locSize_(n),
nbrSize_(0),
data_(NULL),
sendBufferPtr_(NULL),
sendRecvRequests_(NULL),
patchTabPtr_(NULL)
{
label sizeAll = 0;
Table<Word, Table<Word, Patch *> *>::iterator it = patchTab.find(setType);
if (it != patchTab.end())
{
patchTabPtr_ = patchTab[setType];
Table<Word, Patch *> &patches = *patchTabPtr_;
Table<Word, Patch *>::iterator it2;
for (it2 = patches.begin(); it2 != patches.end(); ++it2)
{
Patch &patchI = *(it2->second);
sizeAll += patchI.getRecvSize();
}
nbrSize_ = sizeAll;
}
else
{
par_std_out_("No such type patch in region patchTab%s\n", setType.c_str());
}
sizeAll += locSize_;
data_ = new T[sizeAll * ndim_];
memcpy(data_, dataPtr, n * ndim * sizeof(T));
forAll(i, nbrSize_)
{
forAll(j, ndim)
{
data_[(n + i) * ndim + j] = 0;
}
}
}
template <typename T>
void Field<T>::initSend()
{
//- create
if (patchTabPtr_)
{
//- create
if (!sendBufferPtr_)
{
sendBufferPtr_ = new Table<Word, T *>;
}
Table<Word, Patch *> &patches = *patchTabPtr_;
Table<Word, T *> &sendBuffer = *sendBufferPtr_;
label nPatches = patches.size();
//- create memory for MPI_Request
if (!sendRecvRequests_)
{
sendRecvRequests_ = new MPI_Request[2 * nPatches];
}
Table<Word, Patch *>::iterator it = patches.begin();
//- if nbrdata not created
if (nbrSize_ <= 0)
{
nbrSize_ = 0;
for (it = patches.begin(); it != patches.end(); ++it)
{
Patch &patchI = *(it->second);
nbrSize_ += patchI.getRecvSize();
}
T *dataOld = data_;
data_ = new T[(locSize_ + nbrSize_) * ndim_];
memcpy(data_, dataOld, locSize_ * ndim_ * sizeof(T));
DELETE_POINTER(dataOld);
}
T *recvArrayPtr = &(data_[locSize_ * ndim_]);
it = patches.begin();
for (label i = 0; i < nPatches, it != patches.end(); ++i, ++it)
{
Patch &patchI = *(it->second);
label sendSize = patchI.getSendSize();
label recvSize = patchI.getRecvSize();
Word patchName = it->first;
//- here memory created
if (!sendBuffer[patchName])
{
sendBuffer[patchName] = new T[sendSize * ndim_];
}
T *patchI_sendBuffer = sendBuffer[patchName];
T *patchI_recvBuffer = recvArrayPtr;
label *patchI_addressing = patchI.getAddressing();
for (label j = 0; j < sendSize; ++j)
{
for (label k = 0; k < ndim_; ++k)
{
patchI_sendBuffer[j * ndim_ + k] =
data_[patchI_addressing[j] * ndim_ + k];
}
}
MPI_Isend(patchI_sendBuffer,
sendSize * ndim_ * sizeof(T),
MPI_BYTE,
patchI.getNbrProcID(),
1,
MPI_COMM_WORLD,
&sendRecvRequests_[i]);
MPI_Irecv(patchI_recvBuffer,
recvSize * ndim_ * sizeof(T),
MPI_BYTE,
patchI.getNbrProcID(),
1,
MPI_COMM_WORLD,
&sendRecvRequests_[i + nPatches]);
recvArrayPtr += recvSize * ndim_;
}
}
}
template <typename T>
label Field<T>::checkSendStatus()
{
if (sendRecvRequests_)
{
Table<Word, Patch *> &patches = *patchTabPtr_;
label nPatches = patches.size();
MPI_Waitall(2 * nPatches, &sendRecvRequests_[0], MPI_STATUSES_IGNORE);
DELETE_POINTER(sendRecvRequests_);
}
return 1;
}
template <typename T>
void Field<T>::freeSendRecvBuffer()
{
//- free sendBufferPtr_
if (sendBufferPtr_)
{
Table<Word, T *> &sendBuffer = *sendBufferPtr_;
typename Table<Word, T *>::iterator it = sendBuffer.begin();
for (it = sendBuffer.begin(); it != sendBuffer.end(); ++it)
{
DELETE_POINTER(it->second);
}
DELETE_OBJECT_POINTER(sendBufferPtr_);
}
}
template <typename T>
Field<T>::~Field()
{
DELETE_POINTER(data_);
freeSendRecvBuffer();
}
| 25.957806
| 79
| 0.611996
|
NSCCWX-AMD
|
8dd36af4771b112910bf0b04fadce500a90ac765
| 1,519
|
cpp
|
C++
|
plugins/eclblas/daxpy.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 286
|
2015-01-03T12:45:17.000Z
|
2022-03-25T18:12:57.000Z
|
plugins/eclblas/daxpy.cpp
|
miguelvazq/HPCC-Platform
|
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
|
[
"Apache-2.0"
] | 9,034
|
2015-01-02T08:49:19.000Z
|
2022-03-31T20:34:44.000Z
|
plugins/eclblas/daxpy.cpp
|
cloLN/HPCC-Platform
|
42ffb763a1cdcf611d3900831973d0a68e722bbe
|
[
"Apache-2.0"
] | 208
|
2015-01-02T03:27:28.000Z
|
2022-02-11T05:54:52.000Z
|
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2016 HPCC Systems®.
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.
############################################################################## */
// Vector add, alpha X + Y
#include "eclblas.hpp"
namespace eclblas {
ECLBLAS_CALL void daxpy(bool & __isAllResult, size32_t & __lenResult,
void * & __result, uint32_t n, double alpha,
bool isAllX, size32_t lenX, const void * x, uint32_t incx,
bool isAllY, size32_t lenY, const void* y, uint32_t incy,
uint32_t x_skipped, uint32_t y_skipped) {
__isAllResult = false;
__lenResult = lenY;
const double* X = ((const double*)x) + x_skipped;
double *result = (double*) rtlMalloc(__lenResult);
memcpy(result, y,lenY);
double* Y = result + y_skipped;
cblas_daxpy(n, alpha, X, incx, Y, incy);
__result = (void*) result;
}
}
| 38.948718
| 82
| 0.597762
|
miguelvazq
|
8dd4dcd5ef4d83bb13c99645e91b6891f9c1b949
| 5,854
|
hh
|
C++
|
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:37.000Z
|
2021-05-06T04:41:37.000Z
|
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | null | null | null |
data.hh
|
cp-profiler/cp-profiler-deprecated-
|
ec163bde5c3a5bd9cc428b8fa8fd6ef713e0247a
|
[
"MIT-feh"
] | 1
|
2021-05-06T04:41:39.000Z
|
2021-05-06T04:41:39.000Z
|
/* 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 DATA_HH
#define DATA_HH
#include <vector>
#include <unordered_map>
#include <QTimer>
#include <chrono>
#include <QMutex>
#include <iostream>
#include <string>
#include <memory>
#include <QDebug>
#include <cstdint>
#include <cassert>
#include "nogood_representation.hh"
#include "cpprofiler/universal.hh"
class NameMap;
namespace cpprofiler {
class Message;
}
class DbEntry {
public:
DbEntry(NodeUID uid, NodeUID parent_uid, int _alt, int _kids,
std::string _label, int tid, int _status, int64_t _time_stamp,
int64_t _node_time) :
nodeUID(uid), parentUID(parent_uid), alt(_alt), numberOfKids(_kids), label(_label), thread_id(tid), time_stamp(_time_stamp), node_time(_node_time), status(_status)
{
/// Map message status to profiler status;
/// alternatively could make treebuilder use message status
// switch (_status) {
// case 0:
// break;
// }
// status
}
DbEntry(NodeUID uid, NodeUID parent_uid, int alt, int kids, int status)
: nodeUID(uid),
parentUID(parent_uid),
alt(alt),
numberOfKids(kids),
status(status) {}
DbEntry() = default;
friend std::ostream& operator<<(std::ostream& s, const DbEntry& e);
NodeUID nodeUID;
NodeUID parentUID;
int32_t gid {-1}; // gist id, set to -1 so we don't forget to assign the real value
int32_t alt; // which child by order
int32_t numberOfKids;
std::string label;
int32_t thread_id{-1};
int32_t depth {-1};
uint64_t time_stamp{0};
uint64_t node_time{0};
char status;
};
class NodeTimer;
class Data : public QObject {
Q_OBJECT
std::unique_ptr<NodeTimer> search_timer;
std::vector<DbEntry*> nodes_arr;
// Whether received DONE_SENDING message
bool _isDone{false};
/// How many nodes received within each NODE_RATE_STEP interval
std::vector<float> node_rate;
int last_interval_nc;
/// Map solver Id to no-good string (rid = 0 always for chuffed)
Uid2Nogood uid2nogood;
NameMap* nameMap;
/// node rate intervals
std::vector<int> nr_intervals;
std::unordered_map<NodeUID, int> uid2obj;
public:
/// Mapping from solver Id to array Id (nodes_arr)
/// can't use vector because sid is too big with threads
std::unordered_map<NodeUID, int> uid2aid;
/// Maps gist Id to dbEntry (possibly in the other Data instance);
/// i.e. needed for a merged tree to show labels etc.
/// TODO(maixm): this should probably be a vector?
std::unordered_map<int, DbEntry*> gid2entry;
std::unordered_map<NodeUID, std::shared_ptr<std::string>> uid2info;
/// synchronise access to data entries
mutable QMutex dataMutex {QMutex::Recursive};
private:
/// Populate nodes_arr with the data coming from
void pushInstance(DbEntry* entry);
public:
Data();
~Data();
void handleNodeCallback(const cpprofiler::Message& node);
/// TODO(maxim): Do I want a reference here?
/// return label by gid (Gist ID)
std::string getLabel(int gid);
/// return solver id by gid (Gist ID)
NodeUID gid2uid(int gid) const;
void connectNodeToEntry(int gid, DbEntry* const entry);
/// return total number of nodes
int size() const { return nodes_arr.size(); }
/// ********* GETTERS **********
bool isDone(void) const { return _isDone; }
const std::vector<DbEntry*>& getEntries() const { return nodes_arr; }
inline const Uid2Nogood& getNogoods(void) { return uid2nogood; }
uint64_t getTotalTime();
int32_t getGidByUID(NodeUID uid) {
return nodes_arr[uid2aid[uid]]->gid;
}
const int* getObjective(NodeUID uid) const {
auto it = uid2obj.find(uid);
if (it != uid2obj.end()) {
return &it->second;
} else {
return nullptr;
}
}
/// NOTE(maxim): this only works for a merged tree now?
DbEntry* getEntry(int gid) const;
const NameMap* getNameMap() const { return nameMap; }
void setNameMap(NameMap* names);
const std::vector<int>& node_rate_intervals() const { return nr_intervals; }
/// ****************************
/// Starts node timer
void initReceiving();
public Q_SLOTS:
void setDoneReceiving();
#ifdef MAXIM_DEBUG
void setLabel(int gid, const std::string& str);
const std::string getDebugInfo() const;
#endif
};
inline
void Data::connectNodeToEntry(int gid, DbEntry* const entry) {
gid2entry[gid] = entry;
}
inline
DbEntry* Data::getEntry(int gid) const {
auto it = gid2entry.find(gid);
if (it != gid2entry.end()) {
return it->second;
} else {
return nullptr;
}
}
#endif // DATA_HH
| 26.609091
| 171
| 0.66399
|
cp-profiler
|
8dd93358887ec518a9ba3cf295d91528162fcbea
| 7,217
|
cpp
|
C++
|
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
base/source/ESBReadWriteLock.cpp
|
duderino/everscale
|
38388289dcce869852680a167f3dcb7e090d851c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ESB_READ_WRITE_LOCK_H
#include <ESBReadWriteLock.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
namespace ESB {
ReadWriteLock::ReadWriteLock() : _magic(0) {
#ifdef HAVE_PTHREAD_RWLOCK_INIT
if (0 == pthread_rwlock_init(&_lock, 0)) {
_magic = ESB_MAGIC;
}
#elif defined HAVE_PTHREAD_MUTEX_INIT && defined HAVE_PTHREAD_COND_INIT && defined HAVE_PTHREAD_MUTEX_DESTROY && \
defined HAVE_PTHREAD_COND_DESTROY
if (0 != pthread_mutex_init(&_lock._mutex, 0)) {
return;
}
if (0 != pthread_cond_init(&_lock._readSignal, 0)) {
pthread_mutex_destroy(&_lock._mutex);
return;
}
if (0 != pthread_cond_init(&_lock._writeSignal, 0)) {
pthread_mutex_destroy(&_lock._mutex);
pthread_cond_destroy(&_lock._readSignal);
return;
}
_lock._readersActive = 0;
_lock._readersWaiting = 0;
_lock._writersActive = 0;
_lock._writersWaiting = 0;
_magic = ESB_MAGIC;
#else
#error "Platform has no rw lock initializer"
#endif
}
ReadWriteLock::~ReadWriteLock() {
if (ESB_MAGIC != _magic) {
return;
}
#ifdef HAVE_PTHREAD_RWLOCK_DESTROY
pthread_rwlock_destroy(&_lock);
#elif defined HAVE_PTHREAD_MUTEX_DESTROY && defined HAVE_PTHREAD_COND_DESTROY
pthread_mutex_destroy(&_lock._mutex);
pthread_cond_destroy(&_lock._readSignal);
pthread_cond_destroy(&_lock._writeSignal);
#else
#error "Platform has no rw lock destructor."
#endif
}
Error ReadWriteLock::writeAcquire() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_WRLOCK
return ConvertError(pthread_rwlock_wrlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_COND_WAIT && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
while (0 < _lock._writersActive || 0 < _lock._readersActive) {
++_lock._writersWaiting;
error = ConvertError(pthread_cond_wait(&_lock._writeSignal, &_lock._mutex));
--_lock._writersWaiting;
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
assert(0 == _lock._writersActive && 0 == _lock._readersActive);
_lock._writersActive = 1;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock write lock function."
#endif
}
Error ReadWriteLock::readAcquire() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_RDLOCK
return ConvertError(pthread_rwlock_rdlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_COND_WAIT && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
while (0 < _lock._writersActive || 0 < _lock._writersWaiting) {
++_lock._readersWaiting;
error = ConvertError(pthread_cond_wait(&_lock._readSignal, &_lock._mutex));
--_lock._readersWaiting;
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
++_lock._readersActive;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock read lock function."
#endif
}
Error ReadWriteLock::writeAttempt() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_TRYWRLOCK
int error = pthread_rwlock_trywrlock(&_lock);
switch (error) {
case 0:
return ESB_SUCCESS;
case EBUSY:
return ESB_AGAIN;
default:
return ConvertError(error);
}
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
if (0 < _lock._writersActive || 0 < _lock._readersActive) {
error = ConvertError(pthread_mutex_unlock(&_lock._mutex));
return ESB_SUCCESS == error ? ESB_AGAIN : error;
}
_lock._writersActive = 1;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock try write lock function."
#endif
}
Error ReadWriteLock::readAttempt() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_TRYRDLOCK
int error = pthread_rwlock_tryrdlock(&_lock);
switch (error) {
case 0:
return ESB_SUCCESS;
case EBUSY:
return ESB_AGAIN;
default:
return ConvertError(error);
}
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
if (0 < _lock._writersActive) {
error = ConvertError(pthread_mutex_unlock(&_lock._mutex));
return ESB_SUCCESS == error ? ESB_AGAIN : error;
}
++_lock._readersActive;
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock try read lock function."
#endif
}
Error ReadWriteLock::writeRelease() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_UNLOCK
return ConvertError(pthread_rwlock_unlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK && defined HAVE_PTHREAD_COND_SIGNAL && \
defined HAVE_PTHREAD_COND_BROADCAST
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
assert(1 == _lock._writersActive);
if (1 != _lock._writersActive) {
pthread_mutex_unlock(&_lock._mutex);
return ESB_INVALID_STATE;
}
_lock._writersActive = 0;
error = ESB_SUCCESS;
if (0 < _lock._writersWaiting) {
error = ConvertError(pthread_cond_signal(&_lock._writeSignal));
} else if (0 < _lock._readersWaiting) {
error = ConvertError(pthread_cond_broadcast(&_lock._readSignal));
}
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock write unlock function."
#endif
}
Error ReadWriteLock::readRelease() {
if (ESB_MAGIC != _magic) {
return ESB_NOT_INITIALIZED;
}
#ifdef HAVE_PTHREAD_RWLOCK_UNLOCK
return ConvertError(pthread_rwlock_unlock(&_lock));
#elif defined HAVE_PTHREAD_MUTEX_LOCK && defined HAVE_PTHREAD_MUTEX_UNLOCK && defined HAVE_PTHREAD_COND_SIGNAL && \
defined HAVE_PTHREAD_COND_BROADCAST
Error error = ConvertError(pthread_mutex_lock(&_lock._mutex));
if (ESB_SUCCESS != error) {
return error;
}
assert(0 == _lock._writersActive);
assert(0 < _lock._readersActive);
if (0 < _lock._writersActive || 1 > _lock._readersActive) {
pthread_mutex_unlock(&_lock._mutex);
return ESB_INVALID_STATE;
}
--_lock._readersActive;
if (0 == _lock._readersActive && 0 < _lock._writersWaiting) {
error = ConvertError(pthread_cond_signal(&_lock._writeSignal));
if (ESB_SUCCESS != error) {
pthread_mutex_unlock(&_lock._mutex);
return error;
}
}
return ConvertError(pthread_mutex_unlock(&_lock._mutex));
#else
#error "Platform has no rw lock read unlock function."
#endif
}
} // namespace ESB
| 21.803625
| 115
| 0.720382
|
duderino
|
8dd9ee89d9d3745ee949f9b6ad9642311151a589
| 1,295
|
hpp
|
C++
|
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 3
|
2021-12-16T13:57:28.000Z
|
2022-03-26T07:50:08.000Z
|
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | null | null | null |
src/servercommon/struct/global/autoparam.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 1
|
2022-03-26T07:50:11.000Z
|
2022-03-26T07:50:11.000Z
|
#pragma once
#include "common/tlvprotocol.h"
class AutoParamBase
{
public:
virtual ~AutoParamBase() = default;
virtual int Size() const = 0;
virtual void Reset() = 0;
virtual bool Serialize(TLVSerializer &serializer) = 0;
virtual bool Unserialize(TLVUnserializer &unserializer) = 0;
};
template<typename StructParam>
class AutoParamTemplate : public AutoParamBase
{
public:
int Size() const override { return sizeof(m_data); }
void Reset() override { m_data.Reset(); }
bool Serialize(TLVSerializer &serializer) override
{
TLVSerializer data;
data.Reset(static_cast<void*>(&m_data), sizeof(m_data));
data.MoveCurPos(sizeof(m_data));
return serializer.Push(data);
}
bool Unserialize(TLVUnserializer &unserializer) override
{
m_data.Reset();
if (unserializer.IsAllPoped()) return true;
TLVUnserializer data;
if (!unserializer.Pop(&data))
{
printf("UNSERIALIZE_USER_DATA %s Pop fail!\n", __FUNCTION__); return false;
}
if (sizeof(m_data) >= data.Size())
{
memcpy(&m_data, data.Ptr(), data.Size());
}
else
{
printf("UNSERIALIZE_USER_DATA %s size check fail!\n", __FUNCTION__); return false;
}
return true;
}
StructParam & Param() { return m_data; }
const StructParam & Param() const { return m_data; }
private:
StructParam m_data;
};
| 23.125
| 85
| 0.711969
|
mage-game
|
8ddc6940da14f4a282e8905395a41cad2c65b69a
| 7,484
|
cpp
|
C++
|
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
CPP_Files/Collider.cpp
|
Yaters/Knightmare
|
4440fafb910054cc70bc2d01994435011226061f
|
[
"MIT"
] | null | null | null |
#include "Collider.h"
/*Well Fudge. I've learned my lesson. Don't trust online 'optimizations' without checking.
* Square Root apparently isn't as 'costly' as some articles made it out to be. I'm not going back to change
* all my work using LSquare and radSquare instead of gl::length, but that's annoying. Real annoying
*/
//These were made for cursor cols (though PointCircle will probably never be used
GLboolean Collider::checkPointRecCol(glm::vec2 point, GameObject rect) {
GLboolean colx = (point.x >= rect.pos.x && point.x <= rect.pos.x + rect.size.x); //Check that x is between x values
GLboolean coly = (point.y >= rect.pos.y && point.y <= rect.pos.y + rect.size.y);
return colx && coly;
}
GLboolean Collider::checkPointCircleCol(glm::vec2 point, GameObject circle) {
glm::vec2 Diff = (circle.pos + 0.5f * circle.size) - point;
return glm::length(Diff) <= circle.size.y * 0.5f; //Basically is point within rad of center
}
//This isn't adjusted to factor in dir. THIS IS BROKEN DON'T USE IT UNLESS YOU'RE WILLING TO FIX IT
GLboolean Collider::checkRectRectCol(GameObject rect1, GameObject rect2) {
GLboolean colx = (rect1.pos.x + rect1.size.x >= rect2.pos.x && rect2.pos.x + rect2.size.x >= rect1.pos.x);
GLboolean coly = (rect1.pos.y + rect1.size.y >= rect2.pos.y && rect2.pos.y + rect2.size.y >= rect1.pos.y);
return colx && coly;
}
GLboolean Collider::checkCircleRectCol(GameObject circle, GameObject rect) {
//Basically ctrlc ctrlv from SpriteRender.cpp
glm::mat2 rotate = glm::mat2(rect.dir.y, rect.dir.x,
-rect.dir.x, rect.dir.y);
glm::vec2 circleCenter = circle.pos + 0.5f * circle.size;
glm::vec2 diff = circleCenter - (rect.pos + 0.5f * rect.size); //Vec2 going from rect center to circle center
diff = rotate * diff; //rotate it to follow rectangle?
circleCenter = diff; //Set circleCenter to rotate later
glm::vec2 closest = glm::clamp(diff, -0.5f * rect.size, 0.5f * rect.size); //Clamps Diff to be within rectangle- closest = closest point to circle
diff = closest - circleCenter;
return (LSquare(diff)) <= (float)(0.25 * circle.size.y * circle.size.y); //If point->circle center > r, it's colliding
}
//Ok we're assuming triangle texture on quad, with center and top corners as the points.
GLboolean Collider::checkCircleTriangleCol(GameObject circle, GameObject tri) {
//This is the inverse of normal rotation matrix, rotates clockwise instead of counterclockwise (reason is because the dir.y is now opposite dir.y wanted
glm::mat2 rotate = glm::mat2(tri.dir.y, -tri.dir.x,
tri.dir.x, tri.dir.y);
//LSquare returns length squared: -radSquare means instead of checking for <radSquare, we can check <0
//List of stuff we'll need
//I tried -y on CircCenter to adjust to normal graph, but it broke it. This works
glm::vec2 CircCenter = circle.pos + 0.5f * circle.size - (tri.pos + 0.5f * tri.size);
GLfloat radSquare = circle.size.y * circle.size.y * 0.25f;
//Points (P0 is 0,0)
glm::vec2 P1 = rotate * glm::vec2(tri.size.x / 2, tri.size.y / 2);
glm::vec2 P2 = rotate * glm::vec2(-tri.size.x / 2, tri.size.y / 2);
// Points to circle Center from vertices (C0 was replaced by CircCenter)
glm::vec2 C1 = CircCenter - P1;
glm::vec2 C2 = CircCenter - P2;
//length of previous vector squared
GLfloat C0Squared = LSquare(CircCenter) - radSquare;
GLfloat C1Squared = LSquare(C1) - radSquare;
GLfloat C2Squared = LSquare(C2) - radSquare;
//Edge vectors (e0 was = P1 and e2 was = -P2, both were replaced)
glm::vec2 e1 = P2 - P1;
/* Ok here's the deal. Right now I'm using a quad with a triangle texture to draw Triangles.
"wtf man? Opengl is like made for triangles!" i know, i know. But making a triangle draw
means making a new Draw in SpriteRender, two new shaders, and a much more annoying system for
finding vertices in here. Then I need that TWICE to get textured triangles. So sorry */
//CASE #1: CORNERS IN CIRCLE
if (C0Squared <= 0 || C1Squared <= 0 || C2Squared <= 0) return GL_TRUE;
//CASE #2: CIRCLE INSIDE TRIANGLE
//I might be able to optimize this more, but I won't for readability. Normal = (y2-y1, x1-x2)
glm::vec2 Norm0(P1.y, -P1.x);
glm::vec2 Norm1(P2.y - P1.y, P1.x - P2.x);
glm::vec2 Norm2(-P2.y, P2.x);
//If in triangle side of edge, dot is negative(I did counterclock order for norms)
if (glm::dot(Norm0, CircCenter) < 0 && glm::dot(Norm1, C1) < 0 && glm::dot(Norm2, C2) < 0) return GL_TRUE;
// CASE #3: EDGE IN CIRCLE
//k is just a temp value to store dot product. technically the length along triangle to where circle is nearest to edge
GLfloat k = glm::dot(CircCenter, P1);
//If dot product is positive(not past p1)
if (k > 0) {
GLfloat sideLenSquare = LSquare(P1);
k *= k / sideLenSquare;
//Checks if it's past P0 (bigger than edge length)
if (k < sideLenSquare) {
if (C0Squared <= k) return GL_TRUE;
}
}
k = glm::dot(C1, e1);
if (k > 0) {
GLfloat sideLenSquare = LSquare(e1);
k *= k / sideLenSquare;
if (k < sideLenSquare) {
if (C1Squared <= k) return GL_TRUE;
}
}
k = glm::dot(C2, -P2);
if (k > 0) {
GLfloat sideLenSquare = LSquare(-P2);
k *= k / sideLenSquare;
if (k < sideLenSquare) {
if (C2Squared <= k) return GL_TRUE;
}
}
return GL_FALSE;
}
//For Circles I default to using y size as radius for things like background
GLboolean Collider::checkCircleCircleCol(GameObject circle1, GameObject circle2) {
//Find vector w/ difference between centers
glm::vec2 temp = (circle1.pos + circle1.size * 0.5f) - (circle2.pos + circle2.size * 0.5f);
//If length of distance <= length of radii combined, it's a collision
return glm::length(temp) <= (circle1.size.y * 0.5f + circle2.size.y * 0.5f);
}
//Contains a given circle within the circular GameObject
void Collider::CircleContainCircle(GameObject outsideCircle, GameObject& insideCircle) {
//Vector between centers
glm::vec2 diff = (insideCircle.pos + insideCircle.size * 0.5f) - (outsideCircle.pos + outsideCircle.size * 0.5f);
GLfloat len = glm::length(diff);
//If(centers are closer than difference in radii) <- difference because one is inside
if (len > (0.5f * (outsideCircle.size.y - insideCircle.size.y))) {
//insideCircle.pos = diff * (0.5f * (outsideCircle.size.y - insideCircle.size.y)) / len; //LOL this is fun but not what I'm going for: Try it out
insideCircle.pos = diff * 0.5f * (outsideCircle.size.y - insideCircle.size.y) / len; // First move circle center to inside
insideCircle.pos -= 0.5f * insideCircle.size; // then move pos to top left of circle sprite
insideCircle.pos += outsideCircle.size * 0.5f; //then move pos to be relative to screen/big circle
}
}
//Exclued a given circle from the circular GameObject
void Collider::CircleExcludeCircle(GameObject circleStay, GameObject& circleKeepOut) {
//Vector between centers
glm::vec2 diff = (circleKeepOut.pos + circleKeepOut.size * 0.5f) - (circleStay.pos + circleStay.size * 0.5f);
GLfloat len = glm::length(diff);
if (len < (0.5f * (circleStay.size.y + circleKeepOut.size.y))) { //If distance < combined radii
diff /= len; //Normalize diff
len = 0.5f * (circleStay.size.y + circleKeepOut.size.y); //Set the distance between equal to what we want
diff *= len; //Multiply diff(gives direction) by desired length
circleKeepOut.pos = diff + (circleStay.pos + circleStay.size * 0.5f); // Set outside circle to be Circle Stay center + new diff vector
circleKeepOut.pos -= circleKeepOut.size * 0.5f; // Then adjust so pos = top left of circle
}
}
| 44.284024
| 153
| 0.700828
|
Yaters
|
8ddccfeff11d9917a006a18ae1a98158dd46e11d
| 2,336
|
inl
|
C++
|
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 1
|
2022-02-14T15:46:44.000Z
|
2022-02-14T15:46:44.000Z
|
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | null | null | null |
Kalydo/KRFReadLib/Include/kifstream.inl
|
openlastchaos/lastchaos-source-client
|
3d88594dba7347b1bb45378136605e31f73a8555
|
[
"Apache-2.0"
] | 2
|
2022-01-10T22:17:06.000Z
|
2022-01-17T09:34:08.000Z
|
#include "KRFReadLib.h"
#include "kseek.h"
inline kifstream::kifstream()
: m_File(NULL)
, m_State(std::ios_base::goodbit)
{
}
inline kifstream::kifstream(const char* filename, std::ios_base::openmode mode)
: m_File(kopen(filename, NULL))
, m_State(std::ios_base::goodbit)
{
}
inline kifstream::~kifstream()
{
close();
}
inline kifstream& kifstream::read(char* s, long long n)
{
if (!m_File)
return *this;
// n is always small enough to cast
m_Count = kread(s, 1, (size_t)n, m_File);
setState(m_Count == n);
return *this;
}
inline long long kifstream::gcount() const
{
return m_Count;
}
inline bool kifstream::is_open() const
{
return m_File != NULL;
}
inline bool kifstream::open(const char* filename, std::ios_base::openmode mode)
{
m_File = kopen(filename, NULL);
m_State = std::ios_base::goodbit;
}
inline void kifstream::close()
{
if (m_File != NULL)
{
kclose(m_File);
m_File = NULL;
}
}
inline void kifstream::seekg(long pos)
{
int res = kseek(m_File, pos, SEEK_SET);
setState(res == 0);
}
inline void kifstream::seekg(long off, std::ios_base::seekdir dir)
{
int origin;
switch(dir)
{
case std::ios_base::beg: origin = SEEK_SET; break;
case std::ios_base::cur: origin = SEEK_CUR; break;
case std::ios_base::end: origin = SEEK_END; break;
default: setState(false); return;
}
int res = kseek(m_File, off, origin);
setState(res == 0);
}
inline long long kifstream::tellg() const
{
return ktell(m_File);
}
inline void kifstream::setState(bool error)
{
if (!error)
{
m_State = std::ios_base::goodbit;
return;
}
m_State = std::ios_base::failbit;
if (keof(m_File))
m_State |= std::ios_base::eofbit;
else
m_State |= std::ios_base::badbit;
}
inline bool kifstream::good() const
{
return m_State == std::ios_base::goodbit;
}
inline bool kifstream::fail() const
{
return (m_State & (std::ios_base::failbit | std::ios_base::badbit)) != 0;
}
inline bool kifstream::bad() const
{
return (m_State & std::ios_base::badbit) != 0;
}
inline bool kifstream::eof() const
{
return (m_State & std::ios_base::eofbit) != 0;
}
inline std::ios_base::iostate kifstream::rdstate() const
{
return m_State;
}
inline void kifstream::clear(std::ios_base::iostate state)
{
m_State = state;
}
inline void kifstream::setstate(std::ios_base::iostate state)
{
clear(rdstate() | state);
}
| 17.432836
| 79
| 0.684075
|
openlastchaos
|
8de04c3d945f848d21b8c823ef034a7f5f912d49
| 919
|
cpp
|
C++
|
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | null | null | null |
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | 2
|
2019-06-13T18:53:01.000Z
|
2019-06-14T20:13:38.000Z
|
src/json/ConfigManager.cpp
|
firmware-loader/cpp-firmware-loader
|
895159a50b92526cee59f48d8f42131f5a043879
|
[
"MIT"
] | null | null | null |
//
// Created by sebastian on 03.06.19.
//
#include "ConfigManager.h"
namespace firmware::json::config {
ConfigManager::ConfigManager(const std::string &deviceName) {
ConfigFinder config{deviceName};
if (auto &content = config.getFileContents()) {
if(!content->empty()) {
mParser.emplace(*content);
} else {
mError = "config should not be empty!";
}
} else {
mError = content.error();
}
}
ConfigManager::ConfigManager(const std::filesystem::path& filePath) {
auto fileContent = utils::readFile(filePath);
if (fileContent) {
if(!fileContent->empty()) {
mParser.emplace(*fileContent);
} else {
mError = "config should not be empty!";
}
} else {
mError = fileContent.error();
}
}
}
| 29.645161
| 73
| 0.523395
|
firmware-loader
|
8de2427540199994d234727c62d0615f40bbe0fa
| 113
|
cpp
|
C++
|
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | null | null | null |
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | 1
|
2021-07-22T15:18:47.000Z
|
2021-07-26T11:12:32.000Z
|
SAI/behaviors/VDSAIDefaultBehaviors.cpp
|
VoiDjinn/vdautomata
|
2cfa263d366ec31e298a7743f63a3787f5b6ff0d
|
[
"MIT"
] | null | null | null |
#include "VDSAIDefaultBehaviors.h"
VDAsaiDBArrive::VDAsaiDBArrive() {}
void VDAsaiDBArrive::_bind_methods() {}
| 18.833333
| 39
| 0.778761
|
VoiDjinn
|
8de2c262a9224ed23cc47ebc66021bb2ef374350
| 2,947
|
hpp
|
C++
|
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/sdl/surface.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "handle/sdl.hpp"
#include "mutex.hpp"
#include "abstbuffer.hpp"
#include "lubee/src/rect.hpp"
#include "handle/sdl.hpp"
#include <SDL_surface.h>
#include <memory>
namespace rev {
struct RGB;
struct RGBA;
class Surface {
private:
SDL_Surface* _sfc;
mutable Mutex _mutex;
AB_Byte _buff;
class LockObj {
const Surface& _sfc;
void* _bits;
int _pitch;
public:
LockObj(LockObj&& lk) noexcept;
LockObj(const Surface& sfc, void* bits, int pitch) noexcept;
~LockObj();
void* getBits() noexcept;
int getPitch() const noexcept;
operator bool () const noexcept;
};
void _unlock() const noexcept;
Surface(SDL_Surface* sfc) noexcept;
Surface(SDL_Surface* sfc, ByteBuff&& buff) noexcept;
ByteBuff _extractAsContinuous(uint32_t dstFmt=0) const;
public:
struct LoadFailed : std::runtime_error {
using std::runtime_error::runtime_error;
};
static uint32_t Map(uint32_t format, RGB rgb) noexcept;
//! RGBA値をSDLのピクセルフォーマット形式にパックする
static uint32_t Map(uint32_t format, RGBA rgba);
//! SDLのピクセルフォーマットからRGB値を取り出す
static RGBA Get(uint32_t format, uint32_t pixel);
//! SDLのピクセルフォーマット名を表す文字列を取得
static const std::string& GetFormatString(uint32_t format);
//! 任意のフォーマットの画像を読み込む
static HSfc Load(HRW hRW);
//! 空のサーフェス作成
static HSfc Create(int w, int h, uint32_t format);
//! ピクセルデータを元にサーフェス作成
static HSfc Create(const ByteBuff& src, int pitch, int w, int h, uint32_t format);
static HSfc Create(ByteBuff&& src, int pitch, int w, int h, uint32_t format);
~Surface();
void saveAsBMP(HRW hDst) const;
void saveAsPNG(HRW hDst) const;
LockObj lock() const;
LockObj try_lock() const;
const SDL_PixelFormat& getFormat() const noexcept;
uint32_t getFormatEnum() const noexcept;
lubee::SizeI getSize() const noexcept;
int width() const noexcept;
int height() const noexcept;
//! 同サイズのサーフェスを作成
HSfc makeBlank() const;
HSfc duplicate() const;
HSfc flipHorizontal() const;
HSfc flipVertical() const;
//! ピクセルフォーマット変換
HSfc convert(uint32_t fmt) const;
HSfc convert(const SDL_PixelFormat& fmt) const;
//! ピクセルデータがデータ配列先頭から隙間なく詰められているか
bool isContinuous() const noexcept;
//! Continuousな状態でピクセルデータを抽出
ByteBuff extractAsContinuous(uint32_t dstFmt=0) const;
//! ビットブロック転送
void blit(const HSfc& sfc, const lubee::RectI& srcRect, int dstX, int dstY) const;
//! スケーリング有りのビットブロック転送
void blitScaled(const HSfc& sfc, const lubee::RectI& srcRect, const lubee::RectI& dstRect) const;
//! 単色での矩形塗りつぶし
void fillRect(const lubee::RectI& rect, uint32_t color);
SDL_Surface* getSurface() const noexcept;
HSfc resize(const lubee::SizeI& s) const;
void setEnableColorKey(uint32_t key);
void setDisableColorKey();
spi::Optional<uint32_t> getColorKey() const;
void setBlendMode(SDL_BlendMode mode);
SDL_BlendMode getBlendMode() const;
};
}
| 31.688172
| 100
| 0.709196
|
degarashi
|
8de6bdbe7832f99cc8adfa472432fdd5782c2df6
| 10,224
|
cc
|
C++
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 16
|
2021-09-20T12:37:01.000Z
|
2022-03-18T09:19:14.000Z
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 66
|
2021-09-17T13:49:39.000Z
|
2022-03-30T16:24:07.000Z
|
arcane/samples_build/samples/honeycomb_heat/HoneyCombHeatModule.cc
|
grospelliergilles/framework
|
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
|
[
"Apache-2.0"
] | 11
|
2021-09-27T16:48:55.000Z
|
2022-03-23T19:06:56.000Z
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* HoneycombHeatModule.cc (C) 2000-2022 */
/* */
/* Module HoneycombHeatModule of honeycomb_heat sample. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "HoneyCombHeat_axl.h"
#include <arcane/ITimeLoopMng.h>
#include <arcane/IItemFamily.h>
#include <arcane/IndexedItemConnectivityView.h>
#include <arcane/IMesh.h>
#include <arcane/UnstructuredMeshConnectivity.h>
#include <arcane/ItemPrinter.h>
#include <arcane/mesh/IncrementalItemConnectivity.h>
using namespace Arcane;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Module HoneyCombHeatModule.
*/
class HoneyCombHeatModule
: public ArcaneHoneyCombHeatObject
{
public:
explicit HoneyCombHeatModule(const ModuleBuildInfo& mbi);
public:
/*!
* \brief Méthode appelée à chaque itération.
*/
void compute() override;
/*!
* \brief Méthode appelée lors de l'initialisation.
*/
void startInit() override;
/** Retourne le numéro de version du module */
VersionInfo versionInfo() const override { return VersionInfo(1, 0, 0); }
private:
//! Connectivités standards du maillage
UnstructuredMeshConnectivityView m_mesh_connectivity_view;
//! Vue sur la connectivité Maille<->Maille par les faces
IndexedCellCellConnectivityView m_cell_cell_connectivity_view;
/*!
* \brief Index de la face (donc entre 0 et 5 (2D) ou 7 (3D)) dans la maille
* voisine pour la i-ème maille connectée.
*
* La valeur de \a i correspond au parcours via m_cell_cell_connectivity_view.
* Pour une maille interne, \a i est aussi l'index de la face dans cette propre maille
* mais ce n'est pas le cas pour une maille externe (c'est à dire une maille qui a
* au moins une face non connectée à une autre maille).
*/
VariableCellArrayInt32 m_cell_neighbour_face_index;
/*!
* \brief Index de la face (donc entre 0 et 5 (2D) ou 7 (3D)) dans notre maille
* pour la i-ème maille connectée.
*
* La valeur de \a i correspond au parcours via m_cell_cell_connectivity_view.
* Pour une maille interne, \a i est aussi l'index de la face dans cette propre maille
* mais ce n'est pas le cas pour une maille externe (c'est à dire une maille qui a
* au moins une face non connectée à une autre maille).
*/
VariableCellArrayInt32 m_cell_current_face_index;
private:
void _applyBoundaryCondition();
Int32 _getNeighbourFaceIndex(CellLocalId cell, CellLocalId neighbour_cell);
Int32 _getCurrentFaceIndex(CellLocalId cell, FaceLocalId face);
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
HoneyCombHeatModule::
HoneyCombHeatModule(const ModuleBuildInfo& mbi)
: ArcaneHoneyCombHeatObject(mbi)
, m_cell_neighbour_face_index(VariableBuildInfo(mbi.meshHandle(), "CellNeighbourFaceIndex"))
, m_cell_current_face_index(VariableBuildInfo(mbi.meshHandle(), "CellCurrentFaceIndex"))
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
compute()
{
info() << "Module HoneyCombHeatModule COMPUTE";
// Stop code after 10 iterations
if (m_global_iteration() > 500) {
subDomain()->timeLoopMng()->stopComputeLoop(true);
return;
}
// Mise a jour de la temperature aux noeuds en prenant la moyenne
// valeurs aux mailles voisines
ENUMERATE_NODE (inode, allNodes()) {
Node node = *inode;
Real sumt = 0;
for (Cell cell : node.cells())
sumt += m_cell_temperature[cell];
m_node_temperature[inode] = sumt / node.nbCell();
}
m_node_temperature.synchronize();
// Mise a jour de la temperature aux mailles en prenant la moyenne
// des valeurs aux noeuds voisins
ENUMERATE_CELL (icell, allCells()) {
Cell cell = *icell;
Real sumt = 0;
for (Node node : cell.nodes())
sumt += m_node_temperature[node];
m_cell_temperature[icell] = sumt / cell.nbNode();
}
_applyBoundaryCondition();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Retourne l'index dans la liste des faces de 'neighbour_cell' de
* la face commune entre 'cell' et 'neighbour_cell'.
*/
Int32 HoneyCombHeatModule::
_getNeighbourFaceIndex(CellLocalId cell, CellLocalId neighbour_cell)
{
auto cell_face_cv = m_mesh_connectivity_view.cellFace();
Int32 face_neighbour_index = 0;
// Recherche la face commune entre 'neighbour_cell' et 'cell'.
for (FaceLocalId neighbour_face : cell_face_cv.faces(neighbour_cell)) {
for (FaceLocalId current_face : cell_face_cv.faces(cell)) {
if (current_face == neighbour_face)
return face_neighbour_index;
}
++face_neighbour_index;
}
ARCANE_FATAL("No common face between the two cells '{0}' and '{1}'", cell, neighbour_cell);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
startInit()
{
info() << "Module HoneyCombHeatModule INIT";
m_cell_temperature.fill(0.0);
m_node_temperature.fill(0.0);
// Initialise le pas de temps à une valeur fixe
m_global_deltat = 1.0;
const bool is_verbose = false;
m_mesh_connectivity_view.setMesh(mesh());
// Créé une connectivité Maille/Maille sur les mailles voisines
IItemFamily* cell_family = mesh()->cellFamily();
CellGroup cells = cell_family->allItems();
// NOTE: l'objet est automatiquement détruit par le maillage
auto* cn = new mesh::IncrementalItemConnectivity(cell_family, cell_family, "NeighbourCellCell");
ENUMERATE_CELL (icell, cells) {
Cell cell = *icell;
Integer nb_face = cell.nbFace();
cn->notifySourceItemAdded(cell);
for (Integer i = 0; i < nb_face; ++i) {
Face face = cell.face(i);
if (face.nbCell() == 2) {
Cell opposite_cell = (face.backCell() == cell) ? face.frontCell() : face.backCell();
cn->addConnectedItem(cell, opposite_cell);
}
}
}
m_cell_cell_connectivity_view = cn->connectivityView();
const Int32 max_neighbour = (mesh()->dimension() == 3) ? 8 : 6;
m_cell_neighbour_face_index.resize(max_neighbour);
m_cell_neighbour_face_index.fill(NULL_ITEM_LOCAL_ID);
m_cell_current_face_index.resize(max_neighbour);
m_cell_current_face_index.fill(NULL_ITEM_LOCAL_ID);
// Calcul l'index de la face voisine pour chaque maille connectée
ENUMERATE_ (Cell, icell, cells) {
Cell cell = *icell;
Int32 local_cell_index = 0;
for (CellLocalId neighbour_cell : m_cell_cell_connectivity_view.cells(icell)) {
Int32 neighbour_face_index = _getNeighbourFaceIndex(cell, neighbour_cell);
Int32 current_face_index = _getNeighbourFaceIndex(neighbour_cell, cell);
if (is_verbose)
info() << "Cell=" << cell.uniqueId() << " I=" << local_cell_index
<< " neighbour_cell_local_id=" << neighbour_cell
<< " face_index_in_neighbour_cell=" << neighbour_face_index
<< " face_index_in_current_cell=" << current_face_index;
m_cell_neighbour_face_index[icell][local_cell_index] = neighbour_face_index;
m_cell_current_face_index[icell][local_cell_index] = current_face_index;
++local_cell_index;
}
}
// Vérifie que tout est OK
{
auto cell_face_cv = m_mesh_connectivity_view.cellFace();
ENUMERATE_ (Cell, icell, cells) {
Cell cell = *icell;
auto neighbour_cells_id = m_cell_cell_connectivity_view.cells(icell);
for (Int32 i = 0; i < neighbour_cells_id.size(); ++i) {
CellLocalId neighbour_cell_id = neighbour_cells_id[i];
Int32 neighbour_face_index = m_cell_neighbour_face_index[icell][i];
Int32 current_face_index = m_cell_current_face_index[icell][i];
if (is_verbose)
info() << "Check: Cell=" << cell.uniqueId() << " I=" << i
<< " neighbour_cell_local_id=" << neighbour_cell_id
<< " face_index_in_neighbour_cell=" << neighbour_face_index
<< " face_index_in_current_cell=" << current_face_index;
FaceLocalId neighbour_face_id = cell_face_cv.faces(neighbour_cell_id)[neighbour_face_index];
FaceLocalId current_face_id = cell_face_cv.faces(cell)[current_face_index];
if (neighbour_face_id != current_face_id)
ARCANE_FATAL("Bad face neighbour={0} current={1} cell={2}", neighbour_face_id, current_face_id, ItemPrinter(cell));
}
}
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void HoneyCombHeatModule::
_applyBoundaryCondition()
{
// Les 10 premières mailles ont une température fixe.
ENUMERATE_CELL (icell, allCells()) {
Cell cell = *icell;
if (cell.uniqueId() < 10)
m_cell_temperature[cell] = 10000.0;
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_REGISTER_MODULE_HONEYCOMBHEAT(HoneyCombHeatModule);
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 37.450549
| 125
| 0.586072
|
grospelliergilles
|
8de9dc71831e53c481a3b0fca8d5a92cf9f2941a
| 2,209
|
cpp
|
C++
|
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
HyoDioForm.cpp
|
hyo0913/DurgaTestSlave
|
913084be0a9ec8ffe5d2fc3f23f7fcb670007f0f
|
[
"MIT"
] | null | null | null |
#include "HyoDioForm.h"
#include "ui_HyoDioForm.h"
#include <QHBoxLayout>
#include <QPushButton>
HyoDioForm::HyoDioForm(int points, QWidget *parent) :
QWidget(parent),
ui(new Ui::HyoDioForm)
{
ui->setupUi(this);
this->setObjectName("Digital I/O");
makePoints(points);
this->adjustSize();
}
HyoDioForm::~HyoDioForm()
{
delete ui;
}
void HyoDioForm::makePoints(int points)
{
QHBoxLayout* layout = NULL;
for( int i = 0; i < points; i++ )
{
if( i% 8 == 0 ) {
layout = new QHBoxLayout();
ui->verticalLayout->addLayout(layout);
}
QPushButton* pushButton = new QPushButton();
layout->addWidget(pushButton);
m_points.append(pushButton);
pushButton->setText(QString(""));
QSize size(21, 21);
pushButton->setMaximumSize(size);
pushButton->setMinimumSize(size);
pushButton->setCheckable(true);
QIcon icon;
icon.addFile(":/Icon/IconLampOff", size, QIcon::Normal, QIcon::Off);
icon.addFile(":/Icon/IconLampOn", size, QIcon::Normal, QIcon::On);
pushButton->setIcon(icon);
if( i > 0 && i % 8 == 0 ) {
QSpacerItem* spacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed);
layout->addSpacerItem(spacer);
}
}
}
quint64 HyoDioForm::getValue() const
{
quint64 val = 0;
for( int i = m_points.count()-1; i >= 0; i-- )
{
val <<= 1;
if( this->getValue(i) ) {
val |= 1;
}
}
return val;
}
bool HyoDioForm::getValue(int idx) const
{
if( idx >= m_points.count() ) { return false; }
QPushButton* pushButton = m_points.at(idx);
if( pushButton == NULL ) { return false; }
return pushButton->isChecked();
}
void HyoDioForm::setValue(int idx, bool val)
{
if( idx >= m_points.count() ) { return; }
QPushButton* pushButton = m_points.at(idx);
if( pushButton == NULL ) { return; }
pushButton->setChecked(val);
}
void HyoDioForm::setValue(quint64 val)
{
quint64 bitVal = 1;
for( int i = 0; i < m_points.count(); i++ )
{
setValue(i, (val&bitVal));
bitVal <<= 1;
}
}
| 21.656863
| 100
| 0.57809
|
hyo0913
|
8df47a1349ede49810cac1e0af817265deb200f5
| 2,140
|
cpp
|
C++
|
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | 2
|
2020-05-27T17:45:37.000Z
|
2022-03-05T01:31:29.000Z
|
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | null | null | null |
tests/fuzz/fuzzScale.cpp
|
Lederstrumpf/substrate-c-tool
|
999bc55ffa2f354b96c347ebb122c79baad812cc
|
[
"MIT"
] | 3
|
2020-05-10T23:01:22.000Z
|
2020-07-12T07:07:53.000Z
|
#include <string>
#include <iostream>
#include <exception>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstring>
extern "C" {
#include "../../src/scale.h"
}
int print_input(uint8_t *value, size_t value_len) {
std::stringstream s;
for (unsigned int i=0; i<value_len; i++) {
s << std::setfill('0') << std::setw(2) << std::right << std::hex << +value[i];
}
std::cerr << s.str() << std::endl;
std::cerr << "Length: " << value_len << std::endl;
return 0;
}
int main(int argc, char **argv){
std::string input;
ScaleElem encoded_value;
uint8_t decoded_value[SCALE_COMPACT_MAX] = {0};
size_t decoded_value_len, consumed, encoded_value_len;
std::ifstream f;
if (argc >= 2) {
f.open(argv[1]);
}
std::istream &in = (argc >= 2) ? f : std::cin;
std::getline(in, input);
// vector to char array
size_t value_len = input.size();
uint8_t value[value_len];
copy(input.begin(), input.end(), value);
std::cerr << "Input" << std::endl;
print_input(value, value_len);
// let's start the testing
if (value_len >= SCALE_COMPACT_MAX) // this case is not interesting
return 0;
if (value_len == 0) // also not interesting
return 0;
// 1) can encode
if ( encode_scale(&encoded_value, value, value_len, type_compact) > 0)
throw std::runtime_error(std::string("Failed SCALE encoding\n"));
// 2) decodes expected value
if ( decode_scale(&encoded_value, decoded_value, &decoded_value_len) > 0)
throw std::runtime_error(std::string("Failed SCALE decoding\n"));
// 3) encoded == decoded ?
print_scale(&encoded_value);
std::cerr << "Decoded" << std::endl;
print_input(decoded_value, decoded_value_len);
if (value_len >= decoded_value_len) {
if ( std::memcmp(value, decoded_value, value_len) != 0 )
throw std::runtime_error(std::string("Failed SCALE encoded != decoded (value_len >= decoded_value_len)\n"));
} else {
if ( std::memcmp(value, decoded_value, value_len) != 0 )
throw std::runtime_error(std::string("Failed SCALE encoded != decoded (value_len < decoded_value_len)\n"));
}
return 0;
}
| 27.435897
| 114
| 0.65514
|
Lederstrumpf
|
8df64280462de89c2f71cc33cd41d98d3de72d44
| 5,613
|
cpp
|
C++
|
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 14
|
2018-03-26T13:43:58.000Z
|
2022-03-03T13:04:36.000Z
|
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | null | null | null |
camera_models/extrinsics.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 1
|
2019-08-03T23:12:08.000Z
|
2019-08-03T23:12:08.000Z
|
//Illustration of extrinsic camera parameters
// Andreas Unterweger, 2017-2022
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <opencv2/viz.hpp>
#include "common.hpp"
#include "math.hpp"
#include "conf_viz.hpp"
static constexpr auto parameter_accuracy = 0.01;
static constexpr auto cone_length = 1.0;
static constexpr char axes[] = {'x', 'y', 'z'};
static auto initializing = true; //Prevents updating incomplete values during initialization
static void AddObjects(vizutils::ConfigurableVisualization &visualization, const char * const model_filename)
{
if (model_filename)
{
const auto mesh = cv::viz::Mesh::load(model_filename);
cv::viz::WMesh original_mesh(mesh);
visualization.objects.insert(std::make_pair("Original object", original_mesh));
}
else
{
constexpr auto cone_radius = 0.5;
constexpr auto cone_resolution = 100;
cv::viz::WCone original_cone(cone_length, cone_radius, cone_resolution);
visualization.objects.insert(std::make_pair("Original object", original_cone));
}
}
static cv::Affine3d RoundCameraPose(const cv::Affine3d &old_pose)
{
cv::Vec3d rotation(old_pose.rvec());
for (size_t i = 0; i < 3; i++)
rotation[i] = floor(rotation[i] / parameter_accuracy) * parameter_accuracy;
cv::Vec3d translation(old_pose.translation());
for (size_t i = 0; i < 3; i++)
translation[i] = floor(translation[i] / parameter_accuracy) * parameter_accuracy;
const cv::Affine3d pose(rotation, translation);
return pose;
}
static std::string GetRotationTrackbarName(const char axis)
{
using namespace std::string_literals;
const auto trackbar_name = "Rotation ("s + axis + ") [°]";
return trackbar_name;
}
static std::string GetTranslationTrackbarName(const char axis)
{
using namespace std::string_literals;
const auto trackbar_name = "Translation ("s + axis + ") [px]";
return trackbar_name;
}
static void UpdateCameraPose(vizutils::ConfigurableVisualization &visualization)
{
if (initializing) //Don't update during initialization
return;
double rotation_angles[comutils::arraysize(axes)], translation_offsets[comutils::arraysize(axes)];
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetRotationTrackbarName(axis);
const auto rotation_degrees = visualization.GetTrackbarValue(trackbar_name);
rotation_angles[i] = comutils::DegreesToRadians(rotation_degrees);
}
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto translation_unscaled = visualization.GetTrackbarValue(trackbar_name);
translation_offsets[i] = translation_unscaled * parameter_accuracy;
}
const cv::Vec3d rotation(rotation_angles);
const cv::Vec3d translation(translation_offsets);
const cv::Affine3d pose(rotation, translation);
const cv::Affine3d rounded_pose = RoundCameraPose(pose);
visualization.SetViewerPose(rounded_pose);
}
static void AddControls(vizutils::ConfigurableVisualization &visualization)
{
for (const auto &axis : axes)
{
const auto trackbar_name = GetRotationTrackbarName(axis);
visualization.AddTrackbar(trackbar_name, UpdateCameraPose, 360);
}
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto limit = i == comutils::arraysize(axes) - 1 ? 500: 50;
visualization.AddTrackbar(trackbar_name, UpdateCameraPose, limit, -limit);
}
}
static void InitializeControlValues(vizutils::ConfigurableVisualization &visualization, const cv::Affine3d &pose)
{
const auto rotation = pose.rvec();
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetRotationTrackbarName(axis);
const auto rotation_radians = comutils::RadiansToDegrees(rotation[i]);
visualization.UpdateTrackbarValue(trackbar_name, rotation_radians);
}
const auto translation = pose.translation();
for (size_t i = 0; i < comutils::arraysize(axes); i++)
{
const auto &axis = axes[i];
const auto trackbar_name = GetTranslationTrackbarName(axis);
const auto translation_scaled = translation[i] / parameter_accuracy;
visualization.UpdateTrackbarValue(trackbar_name, translation_scaled);
}
initializing = false; //Done initializing
}
int main(const int argc, const char * const argv[])
{
if (argc > 2)
{
std::cout << "Illustrates the effect of the extrinsic parameters of a pinhole camera." << std::endl;
std::cout << "Usage: " << argv[0] << " [3-D model (PLY) file name]" << std::endl;
return 1;
}
const auto model_filename = (argc == 2) ? argv[1] : nullptr;
constexpr auto visualization_window_name = "Camera view";
constexpr auto control_window_name = "Extrinsic camera parameters";
vizutils::ConfigurableVisualization visualization(visualization_window_name, control_window_name);
AddObjects(visualization, model_filename);
AddControls(visualization);
visualization.ShowWindows([&visualization](const cv::Affine3d &pose)
{
const cv::Affine3d rounded_pose = RoundCameraPose(pose);
InitializeControlValues(visualization, rounded_pose);
return rounded_pose;
});
return 0;
}
| 37.42
| 113
| 0.70408
|
dustsigns
|
8dfb81bb9778d34a666d306f1b59daf6d0d56b42
| 1,091
|
cpp
|
C++
|
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | 3
|
2020-08-11T06:47:16.000Z
|
2021-07-16T09:51:28.000Z
|
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | null | null | null |
http/tests/HttpServer-Test.cpp
|
Sun-CX/reactor
|
88d90a96ae8c018c902846437ef6068da2715aa2
|
[
"Apache-2.0"
] | 2
|
2020-08-10T07:38:29.000Z
|
2021-07-16T09:48:09.000Z
|
//
// Created by suncx on 2020/9/23.
//
#include "HttpServer.h"
#include "EventLoop.h"
#include "InetAddress.h"
#include "ConsoleStream.h"
using std::string;
using std::to_string;
using reactor::net::HttpRequest;
using reactor::net::HttpResponse;
using reactor::net::http::Headers;
using reactor::net::EventLoop;
using reactor::net::InetAddress;
using reactor::net::HttpServer;
void service(const HttpRequest &request, HttpResponse &response) {
const Headers &headers = request.get_headers();
for (const auto &e: headers) {
RC_DEBUG << e.first << ':' << e.second;
}
response.set_response_status(200, "OK");
response.set_header("Content-Type", "text/plain");
string body("hello reactor!");
response.set_body(body);
response.set_header("Content-Length", to_string(body.size()));
}
int main(int argc, const char *argv[]) {
EventLoop loop;
InetAddress addr("192.168.2.2", 8080);
HttpServer httpServer(&loop, addr, "http-svr", 3, true);
httpServer.set_http_callback(service);
httpServer.start();
loop.loop();
return 0;
}
| 25.372093
| 66
| 0.683776
|
Sun-CX
|
8dfe5e6135d1354defc4941c715298dddff7d00c
| 6,771
|
hpp
|
C++
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | 1
|
2021-12-18T01:18:49.000Z
|
2021-12-18T01:18:49.000Z
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | 5
|
2021-10-05T15:12:02.000Z
|
2022-01-21T23:26:41.000Z
|
core/src/impl/Morpheus_DynamicMatrix_Impl.hpp
|
morpheus-org/morpheus
|
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
|
[
"Apache-2.0"
] | null | null | null |
/**
* Morpheus_DynamicMatrix_Impl.hpp
*
* EPCC, The University of Edinburgh
*
* (c) 2021 - 2022 The University of Edinburgh
*
* Contributing Authors:
* Christodoulos Stylianou (c.stylianou@ed.ac.uk)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MORPHEUS_DYNAMICMATRIX_IMPL_HPP
#define MORPHEUS_DYNAMICMATRIX_IMPL_HPP
#include <string>
#include <Morpheus_Exceptions.hpp>
#include <Morpheus_FormatsRegistry.hpp>
#include <impl/Morpheus_ContainerTraits.hpp>
namespace Morpheus {
namespace Impl {
template <class ValueType, class... Properties>
struct any_type_resize
: public Impl::ContainerTraits<any_type_resize, ValueType, Properties...> {
using traits =
Impl::ContainerTraits<any_type_resize, ValueType, Properties...>;
using index_type = typename traits::index_type;
using value_type = typename traits::value_type;
using result_type = void;
// Specialization for Coo resize with three arguments
template <typename... Args>
result_type operator()(
typename CooMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz) {
mat.resize(nrows, ncols, nnnz);
}
// Specialization for Csr resize with three arguments
template <typename... Args>
result_type operator()(
typename CsrMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz) {
mat.resize(nrows, ncols, nnnz);
}
// Specialization for Dia resize with five arguments
template <typename... Args>
result_type operator()(
typename DiaMatrix<ValueType, Properties...>::type &mat,
const index_type nrows, const index_type ncols, const index_type nnnz,
const index_type ndiag, const index_type alignment = 32) {
mat.resize(nrows, ncols, nnnz, ndiag, alignment);
}
// Constrains any other overloads for supporting formats
// Unsupported formats won't compile
template <typename... Args>
result_type operator()(
typename CooMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
template <typename... Args>
result_type operator()(
typename CsrMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
template <typename... Args>
result_type operator()(
typename DiaMatrix<ValueType, Properties...>::type &mat, Args &&...args) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface for current format (" +
std::to_string(mat.format_index()) + ").");
}
};
struct any_type_resize_from_mat {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst.resize(src);
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic resize interface. Src and dst tags must be "
"the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
struct any_type_allocate {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst = T2().allocate(src);
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic allocate interface. Src and std tags must "
"be the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
struct any_type_assign {
using result_type = void;
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
dst = src;
}
template <typename T1, typename T2>
result_type operator()(
const T1 &src, T2 &dst,
typename std::enable_if<
!std::is_same<typename T1::tag, typename T2::tag>::value>::type * =
nullptr) {
throw Morpheus::RuntimeException(
"Invalid use of the dynamic assign interface. Src and dst tags must be "
"the same (" +
std::to_string(src.format_index()) +
" != " + std::to_string(dst.format_index()) + ")");
}
};
template <size_t I, class ValueType, typename... Properties>
struct activate_impl {
using variant = typename MatrixFormats<ValueType, Properties...>::variant;
using type_list = typename MatrixFormats<ValueType, Properties...>::type_list;
static void activate(variant &A, size_t idx) {
if (idx == I - 1) {
A = typename type_list::template type<I - 1>{};
} else {
activate_impl<I - 1, ValueType, Properties...>::activate(A, idx);
}
}
};
// Base case, activate to the first type in the variant
template <class ValueType, typename... Properties>
struct activate_impl<0, ValueType, Properties...> {
using variant = typename MatrixFormats<ValueType, Properties...>::variant;
using type_list = typename MatrixFormats<ValueType, Properties...>::type_list;
static void activate(variant &A, size_t idx) {
idx = 0;
activate_impl<1, ValueType, Properties...>::activate(A, idx);
}
};
} // namespace Impl
} // namespace Morpheus
#endif // MORPHEUS_DYNAMICMATRIX_IMPL_HPP
| 32.868932
| 80
| 0.66962
|
morpheus-org
|
5c03373b7984c0652faf5b7d28e4efd9d412a798
| 6,137
|
cpp
|
C++
|
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | null | null | null |
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | 1
|
2019-06-19T15:55:25.000Z
|
2019-06-27T07:47:27.000Z
|
GameClient/GameStateCommunicating.cpp
|
SamirAroudj/BaseProject
|
50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d
|
[
"BSD-3-Clause"
] | 1
|
2019-07-07T04:37:56.000Z
|
2019-07-07T04:37:56.000Z
|
/*
* Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#include <cstdio>
#include "Platform/ApplicationTimer.h"
#include "Client.h"
#include "ClientTimeManager.h"
#include "FontManager.h"
#include "GameStateCommunicating.h"
#include "GameStateConnecting.h"
#include "Platform/Input/InputManager.h"
#include "MagicGameConstants.h"
#include "MagicGraphicsConstants.h"
#include "Platform/ExceptionHandling/NetworkExceptionFactory.h"
#include "Session.h"
#include "Graphics/Texture.h"
using namespace ExceptionHandling;
using namespace GamePlay;
using namespace Graphics;
using namespace GUI;
using namespace Input;
using namespace Math;
using namespace ResourceManagement;
using namespace Network;
using namespace std;
GameStateCommunicating::GameStateCommunicating(GameState *&mPreviousState) :
mCamera(FOVY, Z_NEAR, Z_FAR), mDisconnectReason(L""),
mDirectionalLight(Color(0.8f, 0.8f, 0.8f, 1.0f), Color(0.8f, 0.8f, 0.8f, 1.0f), Color(0.3f, 0.3f, 0.8f, 1.0f), Vector3(0.0f, -1.0f, 0.0f))
{
delete mPreviousState;
mPreviousState = NULL;
mTank = new LocalTank(Session::getSingleton().getOwnIdentifier());
mFloor = new StaticObject("WoodCrate.mat", "Crate");
mBlock = new StaticObject("Color.mat", "Floor");
Session::getSingleton().addListener(this);
mCamera.setAsActiveCamera();
}
GameStateCommunicating::~GameStateCommunicating()
{
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
delete mRemoteTanks[i];
delete mBlock;
delete mFloor;
delete mTank;
assert(UserResource<StaticMesh>::getNumOfResources() == 0); // test whether everything was freed
assert(UserResource<VertexLayout>::getNumOfResources() == 0);
assert(UserResource<Shader>::getNumOfResources() == 0);
assert(UserResource<Texture>::getNumOfResources() == 0);
assert(UserResource<Material>::getNumOfResources() == 0);
}
void GameStateCommunicating::notifyNewMember(const SessionMember &newMember)
{
if (newMember.getIdentifier() == Session::getSingleton().getOwnIdentifier() || newMember.getIdentifier() == 0)
return;
RemoteTank *remoteTank = new RemoteTank(newMember.getIdentifier(), Vector2(0.0f, 0.0f));
mRemoteTanks.push_back(remoteTank);
mTank->requestUpdate();
}
void GameStateCommunicating::notifyRemovedMember(uint16 identifier)
{
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
{
if (identifier == mRemoteTanks[i]->getIdentifier())
{
delete mRemoteTanks[i];
mRemoteTanks[i] = mRemoteTanks.back();
mRemoteTanks.pop_back();
return;
}
}
}
void GameStateCommunicating::postRender()
{
}
void GameStateCommunicating::render()
{
wchar_t buffer[100];
const Matrix4x4 viewProjection(mCamera.getViewMatrix() * mCamera.getProjectionMatrix());
Matrix4x4 translation;
mFloor->render(translation * viewProjection, translation);
translation.addTranslation(2.0f, 0.0f, 2.0f);
mBlock->render(translation * viewProjection, translation);
translation.addTranslation(-3.0f, 0.0f, -3.0f);
mBlock->render(translation * viewProjection, translation);
translation.addTranslation(1.0f, -0.5f, 1.0f);
mTank->render(viewProjection);
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
mRemoteTanks[i]->render(viewProjection);
swprintf(buffer, 100, L"%u", static_cast<uint32>(0.5f + 1000.0f * ClientTimeManager::getSingleton().getNetworkTime()));
FontManager::getSingleton().getFont(0).renderText(L"Connection to the chosen server was established.", 50, 50, TEXT_COLOR);
FontManager::getSingleton().getFont(0).renderText(buffer, 50, 150, TEXT_COLOR);
}
GameState::State GameStateCommunicating::update(Real deltaTime)
{
Vector4 cameraPosition;
Vector4 tankPosition;
try
{
Client::getSingleton().update();
if (ClientState::READY_TO_USE == Client::getSingleton().getState())
{
processReceivedPackets();
mTank->update(deltaTime);
tankPosition.set(mTank->getXCoordinate(), 0.0f, mTank->getZCoordinate(), 1.0f);
cameraPosition.set(tankPosition.x + 2.0f, tankPosition.y + 20.0f, tankPosition.z + 2.0f, 1.0f);
mCamera.lookAtLH(cameraPosition, tankPosition, Vector3(0.0f, 1.0f, 0.0f));
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
mRemoteTanks[i]->update(deltaTime);
if (InputManager::getSingleton().getKeyboard().isKeyPressed(KEY_ESCAPE))
{
mDisconnectReason = L"User requested disconnect.";
Client::getSingleton().disconnect();
}
else
Client::getSingleton().send();
}
}
catch(ExceptionHandling::ClosedConnectionException &exception)
{
mDisconnectReason = L"Server shut down.";
}
switch(Client::getSingleton().getState())
{
case ClientState::DISCONNECTING:
return GameState::DISCONNECTING;
case ClientState::DISCONNECTED:
return GameState::DISCONNECTED;
case ClientState::READY_TO_USE:
break;
default:
assert(false);
}
return GameState::NO_STATE_CHANGE;
}
void GameStateCommunicating::processReceivedPackets()
{
uint16 senderIdentifier = 0;
MessageType message = Client::getSingleton().getCurrentUDPMessageIdentifier(senderIdentifier);
switch(message)
{
case UDPPacket::NO_MESSAGE:
return;
case TANK_UPDATE_MESSAGE:
{
Real latency = ClientTimeManager::getSingleton().getNetworkTime() - Client::getSingleton().getUDPMessageNetworkTime();
updateRemoteTank(latency);
return;
}
default:
assert(false);
}
}
void GameStateCommunicating::updateRemoteTank(Real latency)
{
Tank remoteUpdate(0);
Client::getSingleton().getUDPMessage(&remoteUpdate, 1);
if (remoteUpdate.getIdentifier() == Session::getSingleton().getOwnIdentifier())
return;
remoteUpdate.update(latency);
uint32 numOfRemoteTanks = mRemoteTanks.size();
for(uint32 i = 0; i < numOfRemoteTanks; ++i)
{
if (remoteUpdate.getIdentifier() == mRemoteTanks[i]->getIdentifier())
{
mRemoteTanks[i]->processRemoteUpdate(remoteUpdate);
return;
}
}
assert(false);
}
| 28.812207
| 139
| 0.744338
|
SamirAroudj
|
5c05f054d1f1047c5f44822fc367f254e5b5b3f0
| 2,020
|
cpp
|
C++
|
012. Integer to Roman.cpp
|
rajeev-ranjan-au6/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | 3
|
2020-12-30T00:29:59.000Z
|
2021-01-24T22:43:04.000Z
|
012. Integer to Roman.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
012. Integer to Roman.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
// Top-voted solution (https://discuss.leetcode.com/topic/12384/simple-solution).
class Solution {
public:
string intToRoman(int num) {
string M[] = {"", "M", "MM", "MMM"};
string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
};
// While my solution is...
class Solution {
public:
string intToRoman(int num) {
//'I' = 1, 'X' = 10, 'C' = 100, 'M' = 1000, 'V' = 5, 'L' = 50, 'D' = 500;
// Subtractive Notation
// Number 4 9 40 90 400 900
// Notation IV IX XL XC CD CM
string res = "";
while(num >= 1000){
num -= 1000;
res.push_back('M');
}
if(num >= 900){
num -= 900;
res.append("CM");
}
if(num >= 500){
num -= 500;
res.push_back('D');
}
if(num >= 400){
num -= 400;
res.append("CD");
}
while(num >= 100){
num -= 100;
res.push_back('C');
}
if(num >= 90){
num -= 90;
res.append("XC");
}
if(num >= 50){
num -= 50;
res.push_back('L');
}
if(num >= 40){
num -= 40;
res.append("XL");
}
while(num >= 10){
num -= 10;
res.push_back('X');
}
if(num >= 9){
num -= 9;
res.append("IX");
}
if(num >= 5){
num -= 5;
res.push_back('V');
}
if(num >= 4){
num -= 4;
res.append("IV");
}
while(num > 0){
num -= 1;
res.push_back('I');
}
return res;
}
};
| 26.233766
| 82
| 0.357921
|
rajeev-ranjan-au6
|
5c0bcc63b1882c769eadd024b77e906337024e57
| 437
|
hpp
|
C++
|
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-grad
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | 1
|
2020-09-26T12:38:55.000Z
|
2020-09-26T12:38:55.000Z
|
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
|
crdrisko/nd-research
|
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved.
// See the LICENSE file in the project root for more information.
//
// Name: byref.hpp
// Author: crdrisko
// Date: 08/13/2020-12:12:50
// Description: Missing file from book
#ifndef BYREF_HPP
#define BYREF_HPP
template<typename T>
T const& checked(T const& a, T const& b)
{
return test() ? a : b;
}
#endif
| 23
| 121
| 0.709382
|
crdrisko
|
5c0d9b4f004dcd5e404e8024d67e964b9bfb5d83
| 8,061
|
cc
|
C++
|
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
|
billionshang/gem5
|
18cc4294f32315595f865d07d1f33434e92b06b2
|
[
"BSD-3-Clause"
] | null | null | null |
#include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_enum_TimingExprOp[] = {
120,156,197,88,239,114,211,214,18,223,35,201,78,236,56,196,
36,144,240,39,128,129,2,190,92,18,67,248,219,194,48,165,
109,218,161,211,134,123,37,58,80,181,115,85,199,58,177,21,
108,201,149,142,67,220,73,190,52,157,182,47,208,71,232,135,
62,64,223,227,190,209,237,238,202,114,36,59,164,124,184,19,
50,241,201,209,239,236,217,179,187,231,183,171,117,26,48,248,
201,225,231,195,10,64,244,167,6,224,226,175,128,54,64,71,
128,45,64,72,1,110,25,94,229,32,188,3,110,14,126,2,
176,53,144,26,236,225,68,135,111,52,240,75,188,39,15,109,
157,17,1,253,34,72,3,236,28,188,240,143,131,33,243,240,
170,8,225,119,32,132,240,5,188,116,39,192,157,132,159,80,
59,78,10,172,112,18,8,44,50,88,0,119,138,193,34,184,
37,158,76,65,191,12,178,4,246,52,137,217,199,80,237,117,
84,59,195,106,255,75,106,93,92,57,14,238,49,18,71,187,
190,38,73,131,36,249,188,25,214,130,42,116,216,60,78,227,
30,185,133,15,179,96,207,50,58,151,70,79,128,125,130,209,
147,105,116,30,236,121,70,23,210,232,41,176,79,49,122,58,
141,158,1,251,12,163,103,211,232,34,216,139,140,158,75,163,
231,193,62,207,232,133,52,90,1,187,194,232,197,52,122,9,
236,75,140,94,78,163,239,129,253,30,163,87,210,232,85,176,
175,50,122,45,141,86,193,174,50,250,143,52,122,29,236,235,
140,254,51,141,222,0,251,6,163,75,105,116,25,236,101,70,
107,105,244,38,216,55,25,189,149,70,87,192,94,97,244,118,
26,189,3,246,29,70,239,166,209,123,96,223,99,244,126,26,
125,0,246,3,70,223,79,163,31,128,253,1,163,15,193,126,
72,204,179,170,179,72,97,239,127,248,83,21,56,83,37,28,
182,100,24,121,129,239,120,254,70,224,105,180,158,167,129,8,
223,160,97,98,192,252,143,137,249,127,0,211,222,213,6,204,
223,5,16,244,12,208,214,96,151,39,187,26,244,171,176,35,
96,211,0,87,135,29,60,38,71,38,53,5,236,105,240,173,
78,2,187,56,26,200,207,243,96,168,152,246,155,204,207,88,
211,4,236,230,96,39,7,214,203,29,141,128,87,5,8,127,
135,31,22,89,233,36,43,213,96,7,71,3,246,12,216,205,
195,11,20,66,104,179,64,172,22,47,119,208,83,68,172,170,
129,214,174,165,220,37,87,92,47,244,235,29,169,40,18,142,
244,123,29,231,185,215,241,252,230,234,118,55,124,214,173,22,
19,185,32,90,238,214,85,203,228,141,58,69,164,211,85,172,
48,240,165,154,194,201,134,231,187,78,39,112,123,109,169,38,
73,155,179,225,181,165,227,240,226,211,78,55,8,213,106,24,
6,161,73,65,101,176,29,212,135,59,40,164,141,118,16,201,
42,157,198,199,152,164,94,145,244,70,151,53,146,1,108,44,
109,118,101,212,8,189,174,194,187,138,53,146,52,105,171,210,
45,241,16,213,113,168,117,124,85,107,53,55,162,154,213,170,
135,210,106,73,191,214,148,157,187,75,65,232,53,61,127,41,
82,245,245,182,92,90,185,121,235,238,210,251,75,183,107,235,
61,175,237,214,182,31,220,171,117,251,170,21,248,181,206,221,
154,231,43,137,97,106,215,198,2,180,140,66,20,186,232,181,
215,116,60,118,210,105,201,118,87,134,211,132,158,33,51,68,
89,148,68,94,232,162,42,166,113,150,195,143,46,22,181,41,
177,230,145,155,13,114,157,56,102,164,89,69,87,45,224,149,
6,225,34,113,102,19,127,5,93,50,50,199,162,53,141,215,
254,77,241,137,209,77,157,152,16,131,59,204,51,36,28,74,
62,162,171,247,129,201,146,131,205,60,196,36,66,238,197,172,
10,251,52,162,56,169,209,80,185,1,209,111,128,241,70,250,
236,192,128,90,123,58,8,191,12,170,72,5,18,209,121,60,
240,71,102,167,85,37,243,215,152,35,170,229,69,193,107,159,
111,130,230,156,79,22,70,230,95,253,103,235,155,178,161,162,
11,8,124,29,244,42,141,186,239,7,170,82,119,221,74,93,
169,208,91,239,41,25,85,84,80,185,18,85,233,114,205,227,
9,205,134,250,250,221,132,86,68,1,164,85,252,224,122,13,
133,15,115,252,192,183,16,73,133,20,105,5,110,132,56,169,
104,74,101,146,145,138,130,28,176,33,204,32,135,68,233,120,
148,59,134,207,79,18,75,152,166,213,124,66,170,72,182,55,
84,145,249,89,143,34,135,45,33,156,169,72,138,183,234,237,
158,100,237,72,38,133,6,209,52,182,225,200,201,120,138,28,
75,226,192,206,249,129,239,246,209,86,175,113,141,204,56,197,
148,44,49,41,79,34,33,39,112,204,227,223,188,152,215,26,
198,128,134,249,132,138,243,20,4,96,34,136,1,23,144,150,
123,88,140,170,26,87,19,246,143,179,245,18,205,104,179,185,
72,195,57,26,206,211,112,33,9,193,81,198,97,122,52,14,
247,233,108,141,157,103,55,233,226,244,196,77,55,147,113,167,
247,51,14,11,168,69,153,163,81,126,237,103,142,65,197,54,
124,76,35,138,114,78,234,16,61,167,210,78,25,198,202,40,
153,48,45,104,182,159,44,28,52,179,76,193,152,76,120,110,
18,121,211,12,110,166,24,108,210,125,49,125,205,211,73,221,
116,72,34,38,174,121,150,84,229,14,136,122,133,134,139,239,
34,244,251,20,108,142,81,240,33,153,81,30,80,112,154,169,
87,196,79,89,107,232,131,251,24,190,91,231,70,168,71,188,
51,14,224,221,85,154,233,227,17,120,135,148,27,248,253,105,
138,114,100,170,150,118,111,13,39,253,5,242,42,77,182,5,
108,26,94,248,11,216,7,104,220,7,220,228,62,128,123,9,
110,74,227,194,174,115,109,143,39,57,10,207,134,14,243,131,
247,123,84,192,177,27,6,219,253,74,176,81,81,236,63,213,
225,71,87,162,229,43,209,67,172,176,149,199,92,219,226,26,
27,87,209,80,118,169,10,210,214,213,237,134,228,183,42,63,
57,78,92,244,28,46,128,206,224,109,141,188,59,73,193,213,
146,168,115,249,143,84,72,85,255,200,227,94,28,198,157,220,
248,156,14,46,114,208,117,177,128,28,43,10,182,206,137,43,
63,247,112,188,138,159,143,232,34,40,2,18,232,75,139,105,
197,182,179,91,228,160,121,35,195,163,35,116,202,172,225,41,
95,37,252,201,239,243,135,62,122,146,30,191,96,107,36,136,
66,63,3,49,4,137,48,72,143,97,54,17,37,230,72,252,
63,192,121,116,64,79,193,245,201,162,62,130,37,176,108,69,
247,89,52,110,49,62,135,95,83,73,152,52,2,250,160,151,
77,55,2,198,176,182,49,181,222,234,101,111,100,139,32,93,
84,171,30,145,88,92,217,246,243,122,255,85,50,108,65,177,
178,31,37,207,38,227,35,29,178,238,219,125,150,209,171,244,
172,152,211,82,220,185,69,195,202,144,54,34,193,142,200,208,
11,240,230,30,192,137,223,44,223,144,53,6,219,63,51,193,
81,30,249,174,19,91,254,104,24,234,126,100,18,98,206,208,
160,37,149,3,235,12,182,186,170,207,253,83,124,228,16,162,
242,177,134,45,82,220,244,83,119,96,94,134,65,189,54,169,
21,49,151,97,240,86,99,182,199,245,198,151,175,185,226,240,
245,155,183,9,167,38,90,13,93,124,226,186,124,80,35,240,
49,82,190,226,178,155,89,30,217,96,245,214,15,219,128,203,
234,108,6,249,234,203,94,59,187,227,216,216,250,232,150,79,
188,173,67,183,224,250,200,22,235,111,78,177,198,79,177,254,
230,20,90,231,203,79,29,252,177,244,218,99,219,102,15,148,
81,139,25,120,245,251,94,125,196,194,153,113,129,145,243,214,
2,117,192,190,217,3,101,84,37,107,198,23,50,138,158,183,
234,126,118,239,220,193,66,234,114,22,255,44,148,117,204,137,
241,253,243,111,148,27,57,223,122,155,243,173,55,156,111,189,
229,249,105,57,117,46,179,244,212,223,194,188,201,110,46,31,
32,49,66,111,140,230,97,244,198,229,209,4,242,15,79,32,
223,85,167,51,200,179,48,43,95,26,89,85,23,179,46,122,
63,200,167,254,71,158,138,178,219,78,188,65,74,93,27,89,
104,250,171,219,74,250,238,237,149,231,193,189,59,89,37,103,
14,149,29,245,116,61,58,212,211,245,136,175,96,109,164,132,
142,95,193,168,4,127,253,107,108,213,195,119,210,27,112,229,
125,20,119,98,143,233,251,64,244,35,14,244,125,174,48,83,
16,121,141,254,189,160,99,219,51,45,12,189,84,46,24,165,
169,130,81,152,208,185,213,158,198,23,85,209,40,148,166,69,
65,251,127,127,254,2,56,224,64,222,
};
EmbeddedPython embedded_m5_internal_enum_TimingExprOp(
"m5/internal/enum_TimingExprOp.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/python/m5/internal/enum_TimingExprOp.py",
"m5.internal.enum_TimingExprOp",
data_m5_internal_enum_TimingExprOp,
1962,
5657);
} // anonymous namespace
| 57.578571
| 104
| 0.667907
|
billionshang
|
5c0e580eaed59257243f065ff4702d3e069c0041
| 246
|
cpp
|
C++
|
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
cpp/hello.cpp
|
voltrevo/project-euler
|
0db5451f72b1353b295e56f928c968801e054444
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i != 6; ++i)
cout << "Hello "[i] << ' ';
for (int i = 0; i != 6; ++i)
cout << *("World!" + i) << ' ';
cout << endl;
return 0;
}
| 15.375
| 39
| 0.390244
|
voltrevo
|
5c1015809f4e4a48c90df6c135764a90c7f180dc
| 2,593
|
cpp
|
C++
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 17
|
2017-11-07T06:44:11.000Z
|
2021-11-14T05:06:08.000Z
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 1
|
2017-09-26T04:35:31.000Z
|
2017-09-26T04:35:31.000Z
|
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
|
KetiLeeJeongHun/OpenHologram
|
c6cdddb5106fe0079d9810eea588d28aa71f0023
|
[
"BSD-2-Clause"
] | 9
|
2017-09-13T08:01:45.000Z
|
2020-04-28T10:11:14.000Z
|
#ifdef _OPENMP
#include<omp.h>
#endif
#include "WRP.h"
int OPHWRP::readxyz(string filename) //read point cloud
{
int dimen = 3;
ifstream infilee(filename);
string temp, temp2mat;
vector <string> temsplit;
if (!infilee)
{
cerr << "can not read the file";
return -1;
}
while (getline(infilee, temp))
{
istringstream LineBand(temp);
while (LineBand >> temp2mat)
{
// printf("temp2mat=%e\n", stof(temp2mat.data()));
vec_xyz.push_back(stod(temp2mat.data()));
}
}
int num = vec_xyz.size() / dimen;
obj_num = num;
cwoObjPoint *op = (cwoObjPoint*)malloc(num*sizeof(cwoObjPoint));
for (int i = 0; i < num; i++){
double x, y, z;
x = vec_xyz.at(dimen*i);
y = vec_xyz.at(dimen*i + 1);
z = vec_xyz.at(dimen*i + 2);
op[i].x = x;
op[i].y = y;
op[i].z = z;
}
obj = op;
return 0;
}
int OPHWRP::Setparameter(float m_wavelength, float m_pixelpitch, float m_resolution)
{
SetWaveLength(m_wavelength);
SetPitch(m_pixelpitch);
SetDstPitch(m_pixelpitch);
Create(m_resolution, m_resolution, 1);
return 0;
}
int OPHWRP::Fresnelpropagation(float z)
{
Diffract(z, CWO_FRESNEL_CONV);
return 0;
}
int OPHWRP::SavetoImage(char* filename)
{
SaveAsImage(filename, CWO_SAVE_AS_ARG);
return 0;
}
void OPHWRP::SingleWRP(float z) //generate WRP plane
{
float wn = GetWaveNum();
float wl = GetWaveLength();
int Nx = GetNx();
int Ny = GetNy();
float spx = GetPx(); //
float spy = GetPy();
float sox = GetOx();//point offset
float soy = GetOy();
float soz = GetOz();
float dpx = GetDstPx();//wrp pitch
float dpy = GetDstPy();
float dox = GetDstOx();//wrp offset
float doy = GetDstOy();
int Nx_h = Nx >> 1;
int Ny_h = Ny >> 1;
cwoObjPoint *pc = obj;
int num = obj_num;
#ifdef _OPENMP
omp_set_num_threads(GetThreads());
#pragma omp parallel for
#endif
for (int k = 0; k < num; k++){
float dz = z - pc[k].z;
float tw = (int)fabs(wl*dz / dpx / dpx / 2 + 0.5) * 2 - 1;
int w = (int)tw;
int tx = (int)(pc[k].x / dpx) + Nx_h;
int ty = (int)(pc[k].y / dpy) + Ny_h;
printf("num=%d, tx=%d, ty=%d, w=%d\n", k, tx, ty, w);
for (int wy = -w; wy < w; wy++){
for (int wx = -w; wx<w; wx++){//WRP coordinate
double dx = wx*dpx;
double dy = wy*dpy;
double dz = z - pc[k].z;
double sign = (dz>0.0) ? (1.0) : (-1.0);
double r = sign*sqrt(dx*dx + dy*dy + dz*dz);
cwoComplex tmp;
CWO_RE(tmp) = cosf(wn*r) / (r + 0.05);
CWO_IM(tmp) = sinf(wn*r) / (r + 0.05);
if (tx + wx >= 0 && tx + wx < Nx && ty + wy >= 0 && ty + wy < Ny)
AddPixel(wx + tx, wy + ty, tmp);
}
}
}
}
| 18.132867
| 84
| 0.59275
|
KetiLeeJeongHun
|
5c101ef567bb4dc304f721fc2f04dec87b513df2
| 5,698
|
hpp
|
C++
|
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
benchmarks/statistical/dataflow_declarations.hpp
|
vamatya/benchmarks
|
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2012 Daniel Kogler
//
// 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)
//this file simply enumerates a multitude of functions used to define the action
//used in the benchmark. Which function is used is decided based on input args
#include <hpx/hpx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/include/iostreams.hpp>
#include <hpx/include/components.hpp>
#include <hpx/util/high_resolution_timer.hpp>
#include <hpx/components/dataflow/dataflow.hpp>
#include <hpx/components/dataflow/dataflow_trigger.hpp>
#include <vector>
#include <string>
using std::vector;
using std::string;
using boost::program_options::variables_map;
using boost::program_options::options_description;
using boost::uint64_t;
using hpx::util::high_resolution_timer;
using hpx::cout;
using hpx::flush;
//global dummy variables of several different primitive types
int ivar = 1;
long lvar = 1;
float fvar = 1;
double dvar = 1;
///////////////////////////////////////////////////////////////////////////////
//forward declarations
template <typename Vector, typename Package, typename Result>
void run_empty(uint64_t number);
///////////////////////////////////////////////////////////////////////////////
//empty functions for plain_result_actions
template<typename A1>
A1 empty_thread(){
A1 dummy = 0;
return dummy;
}
template<typename A1>
A1 empty_thread(A1 arg1){;
return arg1;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2){
return arg2;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2, A1 arg3){
return arg3;
}
template<typename A1>
A1 empty_thread(A1 arg1, A1 arg2, A1 arg3, A1 arg4){
return arg4;
}
typedef hpx::actions::plain_result_action0<int, empty_thread> empty_actioni0;
HPX_REGISTER_PLAIN_ACTION(empty_actioni0);
typedef hpx::actions::plain_result_action0<long, empty_thread> empty_actionl0;
HPX_REGISTER_PLAIN_ACTION(empty_actionl0);
typedef hpx::actions::plain_result_action0<float, empty_thread> empty_actionf0;
HPX_REGISTER_PLAIN_ACTION(empty_actionf0);
typedef hpx::actions::plain_result_action0<double, empty_thread> empty_actiond0;
HPX_REGISTER_PLAIN_ACTION(empty_actiond0);
typedef hpx::actions::plain_result_action1<int, int, empty_thread>
empty_actioni1;
HPX_REGISTER_PLAIN_ACTION(empty_actioni1);
typedef hpx::actions::plain_result_action1<long, long, empty_thread>
empty_actionl1;
HPX_REGISTER_PLAIN_ACTION(empty_actionl1);
typedef hpx::actions::plain_result_action1<float, float, empty_thread>
empty_actionf1;
HPX_REGISTER_PLAIN_ACTION(empty_actionf1);
typedef hpx::actions::plain_result_action1<double, double, empty_thread>
empty_actiond1;
HPX_REGISTER_PLAIN_ACTION(empty_actiond1);
typedef hpx::actions::plain_result_action2<int, int, int, empty_thread>
empty_actioni2;
HPX_REGISTER_PLAIN_ACTION(empty_actioni2);
typedef hpx::actions::plain_result_action2<long, long, long, empty_thread>
empty_actionl2;
HPX_REGISTER_PLAIN_ACTION(empty_actionl2);
typedef hpx::actions::plain_result_action2<float, float, float, empty_thread>
empty_actionf2;
HPX_REGISTER_PLAIN_ACTION(empty_actionf2);
typedef hpx::actions::plain_result_action2<double, double, double, empty_thread>
empty_actiond2;
HPX_REGISTER_PLAIN_ACTION(empty_actiond2);
typedef hpx::actions::plain_result_action3<
int, int, int, int, empty_thread> empty_actioni3;
HPX_REGISTER_PLAIN_ACTION(empty_actioni3);
typedef hpx::actions::plain_result_action3<
long, long, long, long, empty_thread> empty_actionl3;
HPX_REGISTER_PLAIN_ACTION(empty_actionl3);
typedef hpx::actions::plain_result_action3<
float, float, float, float, empty_thread> empty_actionf3;
HPX_REGISTER_PLAIN_ACTION(empty_actionf3);
typedef hpx::actions::plain_result_action3<
double, double, double, double, empty_thread> empty_actiond3;
HPX_REGISTER_PLAIN_ACTION(empty_actiond3);
typedef hpx::actions::plain_result_action4<
int, int, int, int, int, empty_thread> empty_actioni4;
HPX_REGISTER_PLAIN_ACTION(empty_actioni4);
typedef hpx::actions::plain_result_action4<
long, long, long, long, long, empty_thread> empty_actionl4;
HPX_REGISTER_PLAIN_ACTION(empty_actionl4);
typedef hpx::actions::plain_result_action4<
float, float, float, float, float, empty_thread> empty_actionf4;
HPX_REGISTER_PLAIN_ACTION(empty_actionf4);
typedef hpx::actions::plain_result_action4<
double, double, double, double, double, empty_thread> empty_actiond4;
HPX_REGISTER_PLAIN_ACTION(empty_actiond4);
typedef hpx::lcos::dataflow<empty_actioni0> eflowi0;
typedef hpx::lcos::dataflow<empty_actionl0> eflowl0;
typedef hpx::lcos::dataflow<empty_actionf0> eflowf0;
typedef hpx::lcos::dataflow<empty_actiond0> eflowd0;
typedef hpx::lcos::dataflow<empty_actioni1> eflowi1;
typedef hpx::lcos::dataflow<empty_actionl1> eflowl1;
typedef hpx::lcos::dataflow<empty_actionf1> eflowf1;
typedef hpx::lcos::dataflow<empty_actiond1> eflowd1;
typedef hpx::lcos::dataflow<empty_actioni2> eflowi2;
typedef hpx::lcos::dataflow<empty_actionl2> eflowl2;
typedef hpx::lcos::dataflow<empty_actionf2> eflowf2;
typedef hpx::lcos::dataflow<empty_actiond2> eflowd2;
typedef hpx::lcos::dataflow<empty_actioni3> eflowi3;
typedef hpx::lcos::dataflow<empty_actionl3> eflowl3;
typedef hpx::lcos::dataflow<empty_actionf3> eflowf3;
typedef hpx::lcos::dataflow<empty_actiond3> eflowd3;
typedef hpx::lcos::dataflow<empty_actioni4> eflowi4;
typedef hpx::lcos::dataflow<empty_actionl4> eflowl4;
typedef hpx::lcos::dataflow<empty_actionf4> eflowf4;
typedef hpx::lcos::dataflow<empty_actiond4> eflowd4;
| 34.957055
| 81
| 0.777115
|
vamatya
|
5c1530cf4db20b54211ff2453e929b1abe998a88
| 564
|
cpp
|
C++
|
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
src/dummy_server/src/dummy_server_handler.cpp
|
maxerMU/db-course
|
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
|
[
"Apache-2.0"
] | null | null | null |
#include "dummy_server_handler.h"
#include <iostream>
DummyServerHandler::DummyServerHandler(
const std::shared_ptr<BaseConfig> &config) {
append_string = config->get_string_field({"AppendString"});
}
void DummyServerHandler::handle_request(const std::shared_ptr<Request> &req) {
std::cout << req->get_body() << std::endl;
std::cout << req->get_target() << std::endl;
req_body = req->get_body();
}
void DummyServerHandler::make_response(const std::shared_ptr<Response> &resp) {
std::string res = req_body + append_string;
resp->set_body(res);
}
| 29.684211
| 79
| 0.723404
|
maxerMU
|
5c1579f5da212410199c1703479b91eda172214f
| 54,852
|
cpp
|
C++
|
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
modules/juce_gui_basics/layout/juce_FlexBox.cpp
|
dikadk/JUCE
|
514c6c8de8bd34c0663d1d691a034b48922af5c8
|
[
"ISC"
] | null | null | null |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
struct FlexBoxLayoutCalculation
{
using Coord = double;
enum class Axis
{
main,
cross
};
FlexBoxLayoutCalculation(FlexBox &fb, Coord w, Coord h)
: owner(fb), parentWidth(w), parentHeight(h), numItems(owner.items.size()),
isRowDirection(fb.flexDirection == FlexBox::Direction::row || fb.flexDirection == FlexBox::Direction::rowReverse),
containerLineLength(getContainerSize(Axis::main))
{
lineItems.calloc(numItems * numItems);
lineInfo.calloc(numItems);
}
struct ItemWithState
{
ItemWithState(FlexItem &source) noexcept : item(&source) {}
FlexItem *item;
Coord lockedWidth = 0, lockedHeight = 0;
Coord lockedMarginLeft = 0, lockedMarginRight = 0, lockedMarginTop = 0, lockedMarginBottom = 0;
Coord preferredWidth = 0, preferredHeight = 0;
bool locked = false;
void resetItemLockedSize() noexcept
{
lockedWidth = preferredWidth;
lockedHeight = preferredHeight;
lockedMarginLeft = getValueOrZeroIfAuto(item->margin.left);
lockedMarginRight = getValueOrZeroIfAuto(item->margin.right);
lockedMarginTop = getValueOrZeroIfAuto(item->margin.top);
lockedMarginBottom = getValueOrZeroIfAuto(item->margin.bottom);
}
};
struct RowInfo
{
int numItems;
Coord crossSize, lineY, totalLength;
};
FlexBox &owner;
const Coord parentWidth, parentHeight;
const int numItems;
const bool isRowDirection;
const Coord containerLineLength;
int numberOfRows = 1;
Coord containerCrossLength = 0;
HeapBlock<ItemWithState *> lineItems;
HeapBlock<RowInfo> lineInfo;
Array<ItemWithState> itemStates;
ItemWithState &getItem(int x, int y) const noexcept { return *lineItems[y * numItems + x]; }
static bool isAuto(Coord value) noexcept { return value == FlexItem::autoValue; }
static bool isAssigned(Coord value) noexcept { return value != FlexItem::notAssigned; }
static Coord getValueOrZeroIfAuto(Coord value) noexcept { return isAuto(value) ? Coord() : value; }
//==============================================================================
bool isSingleLine() const { return owner.flexWrap == FlexBox::Wrap::noWrap; }
template <typename Value>
Value &pickForAxis(Axis axis, Value &x, Value &y) const
{
return (isRowDirection ? axis == Axis::main : axis == Axis::cross) ? x : y;
}
auto &getStartMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->margin.left, item.item->margin.top);
}
auto &getEndMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->margin.right, item.item->margin.bottom);
}
auto &getStartLockedMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedMarginLeft, item.lockedMarginTop);
}
auto &getEndLockedMargin(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedMarginRight, item.lockedMarginBottom);
}
auto &getLockedSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.lockedWidth, item.lockedHeight);
}
auto &getPreferredSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.preferredWidth, item.preferredHeight);
}
Coord getContainerSize(Axis axis) const
{
return pickForAxis(axis, parentWidth, parentHeight);
}
auto &getItemSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->width, item.item->height);
}
auto &getMinSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->minWidth, item.item->minHeight);
}
auto &getMaxSize(Axis axis, ItemWithState &item) const
{
return pickForAxis(axis, item.item->maxWidth, item.item->maxHeight);
}
//==============================================================================
void createStates()
{
itemStates.ensureStorageAllocated(numItems);
for (auto &item : owner.items)
itemStates.add(item);
std::stable_sort(itemStates.begin(), itemStates.end(),
[](const ItemWithState &i1, const ItemWithState &i2)
{ return i1.item->order < i2.item->order; });
for (auto &item : itemStates)
{
for (auto &axis : {Axis::main, Axis::cross})
getPreferredSize(axis, item) = computePreferredSize(axis, item);
}
}
void initialiseItems() noexcept
{
if (isSingleLine()) // for single-line, all items go in line 1
{
lineInfo[0].numItems = numItems;
int i = 0;
for (auto &item : itemStates)
{
item.resetItemLockedSize();
lineItems[i++] = &item;
}
}
else // if multi-line, group the flexbox items into multiple lines
{
auto currentLength = containerLineLength;
int column = 0, row = 0;
bool firstRow = true;
for (auto &item : itemStates)
{
item.resetItemLockedSize();
const auto flexitemLength = getItemMainSize(item);
if (flexitemLength > currentLength)
{
if (!firstRow)
row++;
if (row >= numItems)
break;
column = 0;
currentLength = containerLineLength;
numberOfRows = jmax(numberOfRows, row + 1);
}
currentLength -= flexitemLength;
lineItems[row * numItems + column] = &item;
++column;
lineInfo[row].numItems = jmax(lineInfo[row].numItems, column);
firstRow = false;
}
}
}
void resolveFlexibleLengths() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
resetRowItems(row);
for (int maxLoops = numItems; --maxLoops >= 0;)
{
resetUnlockedRowItems(row);
if (layoutRowItems(row))
break;
}
}
}
void resolveAutoMarginsOnMainAxis() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord allFlexGrow = 0;
const auto numColumns = lineInfo[row].numItems;
const auto remainingLength = containerLineLength - lineInfo[row].totalLength;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::main, item)))
++allFlexGrow;
if (isAuto(getEndMargin(Axis::main, item)))
++allFlexGrow;
}
const auto changeUnitWidth = remainingLength / allFlexGrow;
if (changeUnitWidth > 0)
{
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::main, item)))
getStartLockedMargin(Axis::main, item) = changeUnitWidth;
if (isAuto(getEndMargin(Axis::main, item)))
getEndLockedMargin(Axis::main, item) = changeUnitWidth;
}
}
}
}
void calculateCrossSizesByLine() noexcept
{
// https://www.w3.org/TR/css-flexbox-1/#algo-cross-line
// If the flex container is single-line and has a definite cross size, the cross size of the
// flex line is the flex container’s inner cross size.
if (isSingleLine())
{
lineInfo[0].crossSize = getContainerSize(Axis::cross);
}
else
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord maxSize = 0;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
maxSize = jmax(maxSize, getItemCrossSize(getItem(column, row)));
lineInfo[row].crossSize = maxSize;
}
}
}
void calculateCrossSizeOfAllItems() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAssigned(item.item->maxHeight) && item.lockedHeight > item.item->maxHeight)
item.lockedHeight = item.item->maxHeight;
if (isAssigned(item.item->maxWidth) && item.lockedWidth > item.item->maxWidth)
item.lockedWidth = item.item->maxWidth;
}
}
}
void alignLinesPerAlignContent() noexcept
{
containerCrossLength = getContainerSize(Axis::cross);
if (owner.alignContent == FlexBox::AlignContent::flexStart)
{
for (int row = 0; row < numberOfRows; ++row)
for (int row2 = row; row2 < numberOfRows; ++row2)
lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::flexEnd)
{
for (int row = 0; row < numberOfRows; ++row)
{
Coord crossHeights = 0;
for (int row2 = row; row2 < numberOfRows; ++row2)
crossHeights += lineInfo[row2].crossSize;
lineInfo[row].lineY = containerCrossLength - crossHeights;
}
}
else
{
Coord totalHeight = 0;
for (int row = 0; row < numberOfRows; ++row)
totalHeight += lineInfo[row].crossSize;
if (owner.alignContent == FlexBox::AlignContent::stretch)
{
const auto difference = jmax(Coord(), (containerCrossLength - totalHeight) / numberOfRows);
for (int row = 0; row < numberOfRows; ++row)
{
lineInfo[row].crossSize += difference;
lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
}
else if (owner.alignContent == FlexBox::AlignContent::center)
{
const auto additionalength = (containerCrossLength - totalHeight) / 2;
for (int row = 0; row < numberOfRows; ++row)
lineInfo[row].lineY = row == 0 ? additionalength : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::spaceBetween)
{
const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(numberOfRows - 1));
lineInfo[0].lineY = 0;
for (int row = 1; row < numberOfRows; ++row)
lineInfo[row].lineY += additionalength + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
else if (owner.alignContent == FlexBox::AlignContent::spaceAround)
{
const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(2 + (2 * (numberOfRows - 1))));
lineInfo[0].lineY = additionalength;
for (int row = 1; row < numberOfRows; ++row)
lineInfo[row].lineY += (2 * additionalength) + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize;
}
}
}
void resolveAutoMarginsOnCrossAxis() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
const auto crossSizeForLine = lineInfo[row].crossSize;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
getStartLockedMargin(Axis::cross, item) = [&]
{
if (isAuto(getStartMargin(Axis::cross, item)) && isAuto(getEndMargin(Axis::cross, item)))
return (crossSizeForLine - getLockedSize(Axis::cross, item)) / 2;
if (isAuto(getStartMargin(Axis::cross, item)))
return crossSizeForLine - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item);
return getStartLockedMargin(Axis::cross, item);
}();
}
}
}
// Align all flex items along the cross-axis per align-self, if neither of the item’s cross-axis margins are auto.
void alignItemsInCrossAxisInLinesPerAlignSelf() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
const auto lineSize = lineInfo[row].crossSize;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isAuto(getStartMargin(Axis::cross, item)) || isAuto(getEndMargin(Axis::cross, item)))
continue;
const auto alignment = [&]
{
switch (item.item->alignSelf)
{
case FlexItem::AlignSelf::stretch:
return FlexBox::AlignItems::stretch;
case FlexItem::AlignSelf::flexStart:
return FlexBox::AlignItems::flexStart;
case FlexItem::AlignSelf::flexEnd:
return FlexBox::AlignItems::flexEnd;
case FlexItem::AlignSelf::center:
return FlexBox::AlignItems::center;
case FlexItem::AlignSelf::autoAlign:
break;
}
return owner.alignItems;
}();
getStartLockedMargin(Axis::cross, item) = [&]
{
switch (alignment)
{
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-start
// The cross-start margin edge of the flex item is placed flush with the
// cross-start edge of the line.
case FlexBox::AlignItems::flexStart:
return (Coord)getStartMargin(Axis::cross, item);
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-end
// The cross-end margin edge of the flex item is placed flush with the cross-end
// edge of the line.
case FlexBox::AlignItems::flexEnd:
return lineSize - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item);
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-center
// The flex item’s margin box is centered in the cross axis within the line.
case FlexBox::AlignItems::center:
return getStartMargin(Axis::cross, item) + (lineSize - getLockedSize(Axis::cross, item) - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item)) / 2;
// https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-stretch
case FlexBox::AlignItems::stretch:
return (Coord)getStartMargin(Axis::cross, item);
}
jassertfalse;
return 0.0;
}();
if (alignment == FlexBox::AlignItems::stretch)
{
auto newSize = isAssigned(getItemSize(Axis::cross, item)) ? computePreferredSize(Axis::cross, item)
: lineSize - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item);
if (isAssigned(getMaxSize(Axis::cross, item)))
newSize = jmin(newSize, (Coord)getMaxSize(Axis::cross, item));
if (isAssigned(getMinSize(Axis::cross, item)))
newSize = jmax(newSize, (Coord)getMinSize(Axis::cross, item));
getLockedSize(Axis::cross, item) = newSize;
}
}
}
}
void alignItemsByJustifyContent() noexcept
{
Coord additionalMarginRight = 0, additionalMarginLeft = 0;
recalculateTotalItemLengthPerLineArray();
for (int row = 0; row < numberOfRows; ++row)
{
const auto numColumns = lineInfo[row].numItems;
Coord x = 0;
if (owner.justifyContent == FlexBox::JustifyContent::flexEnd)
{
x = containerLineLength - lineInfo[row].totalLength;
}
else if (owner.justifyContent == FlexBox::JustifyContent::center)
{
x = (containerLineLength - lineInfo[row].totalLength) / 2;
}
else if (owner.justifyContent == FlexBox::JustifyContent::spaceBetween)
{
additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, numColumns - 1));
}
else if (owner.justifyContent == FlexBox::JustifyContent::spaceAround)
{
additionalMarginLeft = additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, 2 * numColumns));
}
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
getStartLockedMargin(Axis::main, item) += additionalMarginLeft;
getEndLockedMargin(Axis::main, item) += additionalMarginRight;
item.item->currentBounds.setPosition(isRowDirection ? (float)(x + item.lockedMarginLeft)
: (float)item.lockedMarginLeft,
isRowDirection ? (float)item.lockedMarginTop
: (float)(x + item.lockedMarginTop));
x += getItemMainSize(item);
}
}
}
void layoutAllItems() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
const auto lineY = lineInfo[row].lineY;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (isRowDirection)
item.item->currentBounds.setY((float)(lineY + item.lockedMarginTop));
else
item.item->currentBounds.setX((float)(lineY + item.lockedMarginLeft));
item.item->currentBounds.setSize((float)item.lockedWidth,
(float)item.lockedHeight);
}
}
reverseLocations();
reverseWrap();
}
private:
void resetRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
resetItem(getItem(column, row));
}
void resetUnlockedRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (!item.locked)
resetItem(item);
}
}
void resetItem(ItemWithState &item) noexcept
{
item.locked = false;
for (auto &axis : {Axis::main, Axis::cross})
getLockedSize(axis, item) = computePreferredSize(axis, item);
}
bool layoutRowItems(const int row) noexcept
{
const auto numColumns = lineInfo[row].numItems;
auto flexContainerLength = containerLineLength;
Coord totalItemsLength = 0, totalFlexGrow = 0, totalFlexShrink = 0;
for (int column = 0; column < numColumns; ++column)
{
const auto &item = getItem(column, row);
if (item.locked)
{
flexContainerLength -= getItemMainSize(item);
}
else
{
totalItemsLength += getItemMainSize(item);
totalFlexGrow += item.item->flexGrow;
totalFlexShrink += item.item->flexShrink;
}
}
Coord changeUnit = 0;
const auto difference = flexContainerLength - totalItemsLength;
const bool positiveFlexibility = difference > 0;
if (positiveFlexibility)
{
if (totalFlexGrow != 0.0)
changeUnit = difference / totalFlexGrow;
}
else
{
if (totalFlexShrink != 0.0)
changeUnit = difference / totalFlexShrink;
}
bool ok = true;
for (int column = 0; column < numColumns; ++column)
{
auto &item = getItem(column, row);
if (!item.locked)
if (!addToItemLength(item, (positiveFlexibility ? item.item->flexGrow : item.item->flexShrink) * changeUnit, row))
ok = false;
}
return ok;
}
void recalculateTotalItemLengthPerLineArray() noexcept
{
for (int row = 0; row < numberOfRows; ++row)
{
lineInfo[row].totalLength = 0;
const auto numColumns = lineInfo[row].numItems;
for (int column = 0; column < numColumns; ++column)
lineInfo[row].totalLength += getItemMainSize(getItem(column, row));
}
}
void reverseLocations() noexcept
{
if (owner.flexDirection == FlexBox::Direction::rowReverse)
{
for (auto &item : owner.items)
item.currentBounds.setX((float)(containerLineLength - item.currentBounds.getRight()));
}
else if (owner.flexDirection == FlexBox::Direction::columnReverse)
{
for (auto &item : owner.items)
item.currentBounds.setY((float)(containerLineLength - item.currentBounds.getBottom()));
}
}
void reverseWrap() noexcept
{
if (owner.flexWrap == FlexBox::Wrap::wrapReverse)
{
if (isRowDirection)
{
for (auto &item : owner.items)
item.currentBounds.setY((float)(containerCrossLength - item.currentBounds.getBottom()));
}
else
{
for (auto &item : owner.items)
item.currentBounds.setX((float)(containerCrossLength - item.currentBounds.getRight()));
}
}
}
Coord getItemMainSize(const ItemWithState &item) const noexcept
{
return isRowDirection ? item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight
: item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom;
}
Coord getItemCrossSize(const ItemWithState &item) const noexcept
{
return isRowDirection ? item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom
: item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight;
}
bool addToItemLength(ItemWithState &item, const Coord length, int row) const noexcept
{
bool ok = false;
const auto prefSize = computePreferredSize(Axis::main, item);
const auto pickForMainAxis = [this](auto &a, auto &b) -> auto & { return pickForAxis(Axis::main, a, b); };
if (isAssigned(pickForMainAxis(item.item->maxWidth, item.item->maxHeight)) && pickForMainAxis(item.item->maxWidth, item.item->maxHeight) < prefSize + length)
{
pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->maxWidth, item.item->maxHeight);
item.locked = true;
}
else if (isAssigned(prefSize) && pickForMainAxis(item.item->minWidth, item.item->minHeight) > prefSize + length)
{
pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->minWidth, item.item->minHeight);
item.locked = true;
}
else
{
ok = true;
pickForMainAxis(item.lockedWidth, item.lockedHeight) = prefSize + length;
}
lineInfo[row].totalLength += pickForMainAxis(item.lockedWidth, item.lockedHeight) + pickForMainAxis(item.lockedMarginLeft, item.lockedMarginTop) + pickForMainAxis(item.lockedMarginRight, item.lockedMarginBottom);
return ok;
}
Coord computePreferredSize(Axis axis, ItemWithState &itemWithState) const noexcept
{
const auto &item = *itemWithState.item;
auto preferredSize = (item.flexBasis > 0 && axis == Axis::main) ? item.flexBasis
: (isAssigned(getItemSize(axis, itemWithState)) ? getItemSize(axis, itemWithState)
: getMinSize(axis, itemWithState));
const auto minSize = getMinSize(axis, itemWithState);
if (isAssigned(minSize) && preferredSize < minSize)
return minSize;
const auto maxSize = getMaxSize(axis, itemWithState);
if (isAssigned(maxSize) && maxSize < preferredSize)
return maxSize;
return preferredSize;
}
};
//==============================================================================
FlexBox::FlexBox() noexcept = default;
FlexBox::~FlexBox() noexcept = default;
FlexBox::FlexBox(JustifyContent jc) noexcept : justifyContent(jc) {}
FlexBox::FlexBox(Direction d, Wrap w, AlignContent ac, AlignItems ai, JustifyContent jc) noexcept
: flexDirection(d),
flexWrap(w),
alignContent(ac),
alignItems(ai),
justifyContent(jc)
{
}
void FlexBox::performLayout(Rectangle<float> targetArea)
{
if (!items.isEmpty())
{
FlexBoxLayoutCalculation layout(*this, targetArea.getWidth(), targetArea.getHeight());
layout.createStates();
layout.initialiseItems();
layout.resolveFlexibleLengths();
layout.resolveAutoMarginsOnMainAxis();
layout.calculateCrossSizesByLine();
layout.calculateCrossSizeOfAllItems();
layout.alignLinesPerAlignContent();
layout.resolveAutoMarginsOnCrossAxis();
layout.alignItemsInCrossAxisInLinesPerAlignSelf();
layout.alignItemsByJustifyContent();
layout.layoutAllItems();
for (auto &item : items)
{
item.currentBounds += targetArea.getPosition();
if (auto *comp = item.associatedComponent)
comp->setBounds(Rectangle<int>::leftTopRightBottom((int)item.currentBounds.getX(),
(int)item.currentBounds.getY(),
(int)item.currentBounds.getRight(),
(int)item.currentBounds.getBottom()));
if (auto *box = item.associatedFlexBox)
box->performLayout(item.currentBounds);
}
}
}
void FlexBox::performLayout(Rectangle<int> targetArea)
{
performLayout(targetArea.toFloat());
}
//==============================================================================
FlexItem::FlexItem() noexcept {}
FlexItem::FlexItem(float w, float h) noexcept : currentBounds(w, h), minWidth(w), minHeight(h) {}
FlexItem::FlexItem(float w, float h, Component &c) noexcept : FlexItem(w, h) { associatedComponent = &c; }
FlexItem::FlexItem(float w, float h, FlexBox &fb) noexcept : FlexItem(w, h) { associatedFlexBox = &fb; }
FlexItem::FlexItem(Component &c) noexcept : associatedComponent(&c) {}
FlexItem::FlexItem(FlexBox &fb) noexcept : associatedFlexBox(&fb) {}
FlexItem::Margin::Margin() noexcept : left(), right(), top(), bottom() {}
FlexItem::Margin::Margin(float v) noexcept : left(v), right(v), top(v), bottom(v) {}
FlexItem::Margin::Margin(float t, float r, float b, float l) noexcept : left(l), right(r), top(t), bottom(b) {}
//==============================================================================
FlexItem FlexItem::withFlex(float newFlexGrow) const noexcept
{
auto fi = *this;
fi.flexGrow = newFlexGrow;
return fi;
}
FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink) const noexcept
{
auto fi = withFlex(newFlexGrow);
fi.flexShrink = newFlexShrink;
return fi;
}
FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink, float newFlexBasis) const noexcept
{
auto fi = withFlex(newFlexGrow, newFlexShrink);
fi.flexBasis = newFlexBasis;
return fi;
}
FlexItem FlexItem::withWidth(float newWidth) const noexcept
{
auto fi = *this;
fi.width = newWidth;
return fi;
}
FlexItem FlexItem::withMinWidth(float newMinWidth) const noexcept
{
auto fi = *this;
fi.minWidth = newMinWidth;
return fi;
}
FlexItem FlexItem::withMaxWidth(float newMaxWidth) const noexcept
{
auto fi = *this;
fi.maxWidth = newMaxWidth;
return fi;
}
FlexItem FlexItem::withMinHeight(float newMinHeight) const noexcept
{
auto fi = *this;
fi.minHeight = newMinHeight;
return fi;
}
FlexItem FlexItem::withMaxHeight(float newMaxHeight) const noexcept
{
auto fi = *this;
fi.maxHeight = newMaxHeight;
return fi;
}
FlexItem FlexItem::withHeight(float newHeight) const noexcept
{
auto fi = *this;
fi.height = newHeight;
return fi;
}
FlexItem FlexItem::withMargin(Margin m) const noexcept
{
auto fi = *this;
fi.margin = m;
return fi;
}
FlexItem FlexItem::withOrder(int newOrder) const noexcept
{
auto fi = *this;
fi.order = newOrder;
return fi;
}
FlexItem FlexItem::withAlignSelf(AlignSelf a) const noexcept
{
auto fi = *this;
fi.alignSelf = a;
return fi;
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class FlexBoxTests : public UnitTest
{
public:
FlexBoxTests() : UnitTest("FlexBox", UnitTestCategories::gui) {}
void runTest() override
{
using AlignSelf = FlexItem::AlignSelf;
using Direction = FlexBox::Direction;
const Rectangle<float> rect(10.0f, 20.0f, 300.0f, 200.0f);
const auto doLayout = [&rect](Direction direction, Array<FlexItem> items)
{
juce::FlexBox flex;
flex.flexDirection = direction;
flex.items = std::move(items);
flex.performLayout(rect);
return flex;
};
beginTest("flex item with mostly auto properties");
{
const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem{}.withAlignSelf(alignment)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("flex item with specified width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h});
test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h});
}
beginTest("flex item with oversized width and height");
{
const auto w = rect.getWidth() * 2;
const auto h = rect.getHeight() * 2;
const auto test = [this, &doLayout, &w, &h](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
const Rectangle<float> baseRow(rect.getX(), rect.getY(), rect.getWidth(), h);
test(Direction::row, AlignSelf::autoAlign, baseRow);
test(Direction::row, AlignSelf::stretch, baseRow);
test(Direction::row, AlignSelf::flexStart, baseRow);
test(Direction::row, AlignSelf::flexEnd, baseRow.withBottomY(rect.getBottom()));
test(Direction::row, AlignSelf::center, baseRow.withCentre(rect.getCentre()));
const Rectangle<float> baseColumn(rect.getX(), rect.getY(), w, rect.getHeight());
test(Direction::column, AlignSelf::autoAlign, baseColumn);
test(Direction::column, AlignSelf::stretch, baseColumn);
test(Direction::column, AlignSelf::flexStart, baseColumn);
test(Direction::column, AlignSelf::flexEnd, baseColumn.withRightX(rect.getRight()));
test(Direction::column, AlignSelf::center, baseColumn.withCentre(rect.getCentre()));
}
beginTest("flex item with minimum width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMinWidth(w).withMinHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), h});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), h});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h});
test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h});
}
beginTest("flex item with maximum width and height");
{
constexpr auto w = 50.0f;
constexpr auto h = 60.0f;
const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMaxWidth(w).withMaxHeight(h)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, h});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, h});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("flex item with specified flex");
{
const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withFlex(1.0f)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), rect.getWidth(), 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()});
test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, rect.getHeight()});
}
beginTest("flex item with margin");
{
const FlexItem::Margin margin(10.0f, 20.0f, 30.0f, 40.0f);
const auto test = [this, &doLayout, &margin](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin(margin)});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
const auto remainingHeight = rect.getHeight() - margin.top - margin.bottom;
const auto remainingWidth = rect.getWidth() - margin.left - margin.right;
test(Direction::row, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight});
test(Direction::row, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight});
test(Direction::row, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::row, AlignSelf::flexEnd, {rect.getX() + margin.left, rect.getBottom() - margin.bottom, 0.0f, 0.0f});
test(Direction::row, AlignSelf::center, {rect.getX() + margin.left, rect.getY() + margin.top + remainingHeight * 0.5f, 0.0f, 0.0f});
test(Direction::column, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f});
test(Direction::column, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f});
test(Direction::column, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - margin.right, rect.getY() + margin.top, 0.0f, 0.0f});
test(Direction::column, AlignSelf::center, {rect.getX() + margin.left + remainingWidth * 0.5f, rect.getY() + margin.top, 0.0f, 0.0f});
}
const AlignSelf alignments[]{AlignSelf::autoAlign,
AlignSelf::stretch,
AlignSelf::flexStart,
AlignSelf::flexEnd,
AlignSelf::center};
beginTest("flex item with auto margin");
{
for (const auto &alignment : alignments)
{
for (const auto &direction : {Direction::row, Direction::column})
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin((float)FlexItem::autoValue)});
expect(flex.items.getFirst().currentBounds == Rectangle<float>(rect.getCentre(), rect.getCentre()));
}
}
const auto testTop = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({(float)FlexItem::autoValue, 0.0f, 0.0f, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
for (const auto &alignment : alignments)
testTop(Direction::row, alignment, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
testTop(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f});
testTop(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f});
testTop(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getBottom(), 0.0f, 0.0f});
const auto testBottom = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, (float)FlexItem::autoValue, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
for (const auto &alignment : alignments)
testBottom(Direction::row, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
testBottom(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f});
testBottom(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
testBottom(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f});
const auto testLeft = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, 0.0f, (float)FlexItem::autoValue})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
testLeft(Direction::row, AlignSelf::autoAlign, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
testLeft(Direction::row, AlignSelf::stretch, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()});
testLeft(Direction::row, AlignSelf::flexStart, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
testLeft(Direction::row, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f});
testLeft(Direction::row, AlignSelf::center, {rect.getRight(), rect.getCentreY(), 0.0f, 0.0f});
for (const auto &alignment : alignments)
testLeft(Direction::column, alignment, {rect.getRight(), rect.getY(), 0.0f, 0.0f});
const auto testRight = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds)
{
const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, (float)FlexItem::autoValue, 0.0f, 0.0f})});
expect(flex.items.getFirst().currentBounds == expectedBounds);
};
testRight(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
testRight(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()});
testRight(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f});
testRight(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f});
testRight(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f});
for (const auto &alignment : alignments)
testRight(Direction::column, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f});
}
beginTest("in a multiline layout, items too large to fit on the main axis are given a line to themselves");
{
const auto spacer = 10.0f;
for (const auto alignment : alignments)
{
juce::FlexBox flex;
flex.flexWrap = FlexBox::Wrap::wrap;
flex.items = {FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer),
FlexItem().withAlignSelf(alignment).withWidth(rect.getWidth() * 2).withHeight(rect.getHeight()),
FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer)};
flex.performLayout(rect);
expect(flex.items[0].currentBounds == Rectangle<float>(rect.getX(), rect.getY(), spacer, spacer));
expect(flex.items[1].currentBounds == Rectangle<float>(rect.getX(), rect.getY() + spacer, rect.getWidth(), rect.getHeight()));
expect(flex.items[2].currentBounds == Rectangle<float>(rect.getX(), rect.getBottom() + spacer, 10.0f, 10.0f));
}
}
}
};
static FlexBoxTests flexBoxTests;
#endif
} // namespace juce
| 46.563667
| 225
| 0.518887
|
dikadk
|
5c1d185ee8efa07f9a35db7b874ca2d7bd117211
| 483
|
cpp
|
C++
|
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
ZorkGame/ZorkGame/ZorkGame.cpp
|
PabloSanchezTrujillo/Zork
|
f861f56df8c37a126c9f90147efbc75c91a04f47
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "World.h"
using namespace std;
int main()
{
World* house = new World();
cout << "You are in the: " << house->getPlayer()->getLocation()->getName() << ". "
<< house->getPlayer()->getLocation()->getDescription() << endl;
cout << "\n";
// GameLoop
while(!house->getPlayer()->isPlayerOutside()) {
for(Entity* entity : house->getEntities()) {
entity->update();
}
}
cout << "The end." << endl;
cout << "\n";
system("pause");
return 0;
}
| 19.32
| 83
| 0.594203
|
PabloSanchezTrujillo
|
5c1dbca35795cb3a90df53cc6d6c751addffd42a
| 452
|
cpp
|
C++
|
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
misc.cpp
|
bannid/CardGame
|
c5df2adb7a96df506fa24544cd8499076bb3ebbc
|
[
"Zlib"
] | null | null | null |
#include "misc.h"
float LinearInterpolation(float first, float second, float weight){
float result = weight * second + (1.0f - weight) * first;
return result;
}
float CosineInterpolation(float first, float second, float weight){
float modifiedWeight = (1 - cos(weight * 3.14))/2.0f;
modifiedWeight = pow(modifiedWeight, 0.2f);
float result = modifiedWeight * second + (1.0f - modifiedWeight) * first;
return result;
}
| 28.25
| 78
| 0.679204
|
bannid
|
5c201c7101b0d40c9e79c696d239e37debac77e5
| 826
|
cpp
|
C++
|
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
LeetCode/338.Counting_Bits.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
class Solution {
public:
vector<int> countBits(int num) {
vector<int>ans;
int two[30];
int now;
int SIZE = 30;
two[0] = 1;
for(int i = 1; i < SIZE; i++)
two[i] = two[i - 1] * 2;
ans.push_back(0);
if(num == 0) return ans;
ans.push_back(1);
if(num == 1) return ans;
for(int i = 2; i <= num; i++) {
bool flag = false;
for(int j = 0; j < SIZE; j++) {
if(two[j] == i) {
ans.push_back(1);
flag = true;
break;
} else if(i > two[j]) {
now = two[j];
}
}
if(!flag) ans.push_back(ans[i - now] + 1);
}
return ans;
}
};
| 25.030303
| 54
| 0.349879
|
w181496
|
5c271252cbafd78ad5faa7c1951f52283703ad04
| 3,350
|
hpp
|
C++
|
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | 4
|
2016-06-03T18:41:43.000Z
|
2020-04-17T20:28:58.000Z
|
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | null | null | null |
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
|
voxie-viewer/voxie
|
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2014-2022 The Voxie Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <VoxieClient/DBusUtil.hpp>
#include <QtDBus/QDBusArgument>
#include <QtDBus/QDBusVariant>
namespace vx {
namespace DBusNumericUtilIntern {
template <typename ValueType, typename ResultType>
bool dbusTryGetNumberFromArgumentValue(const QDBusArgument& arg,
ResultType& result) {
if (dbusGetSignature<ValueType>() == dbusGetArgumentSignature(arg)) {
result =
static_cast<ResultType>(dbusGetArgumentValueUnchecked<ValueType>(arg));
return true;
} else {
return false;
}
}
template <typename ValueType, typename ResultType>
bool dbusTryGetNumber(const QVariant& var, ResultType& result) {
if (var.userType() == qMetaTypeId<QDBusArgument>()) {
QDBusArgument arg = var.value<QDBusArgument>();
return dbusTryGetNumberFromArgumentValue<ValueType>(arg, result);
} else if (var.userType() == qMetaTypeId<ValueType>()) {
result = static_cast<ResultType>(var.value<ValueType>());
return true;
} else {
return false;
}
}
} // namespace DBusNumericUtilIntern
// Helper function for extracting any-type numbers from DBus variants and
// converting them to the desired target type
template <typename T>
T dbusGetNumber(const QDBusVariant& variant) {
using namespace DBusNumericUtilIntern;
QVariant qVariant = variant.variant();
T result = T();
// Try every numeric type
bool success = dbusTryGetNumber<double>(qVariant, result) ||
dbusTryGetNumber<qint64>(qVariant, result) ||
dbusTryGetNumber<quint64>(qVariant, result) ||
dbusTryGetNumber<qint32>(qVariant, result) ||
dbusTryGetNumber<quint32>(qVariant, result) ||
dbusTryGetNumber<qint16>(qVariant, result) ||
dbusTryGetNumber<quint16>(qVariant, result) ||
dbusTryGetNumber<quint8>(qVariant, result) ||
dbusTryGetNumber<bool>(qVariant, result);
if (success) {
return result;
} else {
throw Exception(
"de.uni_stuttgart.Voxie.Error",
QString() + "Unexpected DBus variant, expected a numeric type, got " +
QMetaType::typeName(qVariant.userType()));
}
}
} // namespace vx
| 36.413043
| 80
| 0.702687
|
voxie-viewer
|
5c28e1034573a00ce52b97665327d13d08dae8f1
| 126
|
cpp
|
C++
|
chapter_4/ex_4.12.cpp
|
YasserKa/Cpp_Primer
|
198b10255fd67e31c15423a5e44b7f02abb8bdc2
|
[
"MIT"
] | null | null | null |
chapter_4/ex_4.12.cpp
|
YasserKa/Cpp_Primer
|
198b10255fd67e31c15423a5e44b7f02abb8bdc2
|
[
"MIT"
] | null | null | null |
chapter_4/ex_4.12.cpp
|
YasserKa/Cpp_Primer
|
198b10255fd67e31c15423a5e44b7f02abb8bdc2
|
[
"MIT"
] | null | null | null |
/**
* i != (j < k)
* i != (true/false)
* i != (0/1)
* It means checking if i is 1 or 0 which is resulted from j < k
*/
| 15.75
| 64
| 0.484127
|
YasserKa
|
5c388318a3c9af8911eed5f695c3eb46da682f06
| 459
|
hpp
|
C++
|
Paper/Group.hpp
|
mokafolio/Paper
|
d7e9c1450b29b1d3d8873de4f959bffa02232055
|
[
"MIT"
] | 20
|
2016-12-13T22:34:35.000Z
|
2021-09-20T12:44:56.000Z
|
Paper/Group.hpp
|
mokafolio/Paper
|
d7e9c1450b29b1d3d8873de4f959bffa02232055
|
[
"MIT"
] | null | null | null |
Paper/Group.hpp
|
mokafolio/Paper
|
d7e9c1450b29b1d3d8873de4f959bffa02232055
|
[
"MIT"
] | null | null | null |
#ifndef PAPER_GROUP_HPP
#define PAPER_GROUP_HPP
#include <Paper/Item.hpp>
#include <Paper/Constants.hpp>
namespace paper
{
class Document;
class STICK_API Group : public Item
{
friend class Item;
public:
static constexpr EntityType itemType = EntityType::Group;
Group();
void setClipped(bool _b);
bool isClipped() const;
Group clone() const;
};
}
#endif //PAPER_GROUP_HPP
| 14.806452
| 65
| 0.627451
|
mokafolio
|
5c3bc9320dc133c5b9595487d4f56053eb4b36f8
| 2,478
|
hpp
|
C++
|
src/bonefish/dealer/wamp_dealer_registration.hpp
|
aiwc/extlib-bonefish
|
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
|
[
"Apache-2.0"
] | 58
|
2015-08-24T18:43:56.000Z
|
2022-01-09T00:55:06.000Z
|
src/bonefish/dealer/wamp_dealer_registration.hpp
|
aiwc/extlib-bonefish
|
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
|
[
"Apache-2.0"
] | 47
|
2015-08-25T11:04:51.000Z
|
2018-02-28T22:38:12.000Z
|
src/bonefish/dealer/wamp_dealer_registration.hpp
|
aiwc/extlib-bonefish
|
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
|
[
"Apache-2.0"
] | 32
|
2015-08-25T15:14:45.000Z
|
2020-03-23T09:35:31.000Z
|
/**
* Copyright (C) 2015 Topology LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP
#define BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP
#include <bonefish/identifiers/wamp_registration_id.hpp>
#include <bonefish/session/wamp_session.hpp>
#include <unordered_set>
namespace bonefish {
class wamp_dealer_registration
{
public:
wamp_dealer_registration();
wamp_dealer_registration(const std::shared_ptr<wamp_session>& session,
const wamp_registration_id& registration_id);
~wamp_dealer_registration();
void set_session(const std::shared_ptr<wamp_session>& session);
void set_registration_id(const wamp_registration_id& registration_id);
const wamp_registration_id& get_registration_id() const;
const std::shared_ptr<wamp_session>& get_session() const;
private:
std::shared_ptr<wamp_session> m_session;
wamp_registration_id m_registration_id;
};
inline wamp_dealer_registration::wamp_dealer_registration()
: m_session()
, m_registration_id()
{
}
inline wamp_dealer_registration::wamp_dealer_registration(const std::shared_ptr<wamp_session>& session,
const wamp_registration_id& registration_id)
: m_session(session)
, m_registration_id(registration_id)
{
}
inline wamp_dealer_registration::~wamp_dealer_registration()
{
}
inline void wamp_dealer_registration::set_session(const std::shared_ptr<wamp_session>& session)
{
m_session = session;
}
inline void wamp_dealer_registration::set_registration_id(const wamp_registration_id& registration_id)
{
m_registration_id = registration_id;
}
inline const std::shared_ptr<wamp_session>& wamp_dealer_registration::get_session() const
{
return m_session;
}
inline const wamp_registration_id& wamp_dealer_registration::get_registration_id() const
{
return m_registration_id;
}
} // namespace bonefish
#endif // BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP
| 28.813953
| 103
| 0.778854
|
aiwc
|
5c3d62f0e2a30326c8f0458fe39c3355f406e1a8
| 983
|
cc
|
C++
|
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
|
zoranzhao/NoSDSE
|
0e3148572e7cdf3a2d012c95c81863864da236d6
|
[
"MIT"
] | 3
|
2019-01-26T20:35:47.000Z
|
2019-07-18T22:09:22.000Z
|
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
|
zoranzhao/NoSSim
|
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
|
[
"BSD-3-Clause"
] | null | null | null |
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
|
zoranzhao/NoSSim
|
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
|
[
"BSD-3-Clause"
] | 3
|
2017-09-08T22:13:28.000Z
|
2019-06-29T21:42:53.000Z
|
#include <iostream>
#include <sstream>
#include "OmnetIf_pkt.h"
OmnetIf_pkt::OmnetIf_pkt()
{
fileBuffer_arraysize = 0;
this->fileBuffer = NULL;
}
OmnetIf_pkt::~OmnetIf_pkt()
{
delete [] fileBuffer;
}
void OmnetIf_pkt::setFileBufferArraySize(unsigned int size)
{
char *fileBuffer_var2 = (size==0) ? NULL : new char[size];
unsigned int sz = fileBuffer_arraysize < size ? fileBuffer_arraysize : size;
for (unsigned int i=0; i<sz; i++)
fileBuffer_var2[i] = this->fileBuffer[i];
for (unsigned int i=sz; i<size; i++)
fileBuffer_var2[i] = 0;
fileBuffer_arraysize = size;
delete [] this->fileBuffer;
this->fileBuffer = fileBuffer_var2;
}
unsigned int OmnetIf_pkt::getFileBufferArraySize() const
{
return fileBuffer_arraysize;
}
char OmnetIf_pkt::getFileBuffer(unsigned int k) const
{
return fileBuffer[k];
}
void OmnetIf_pkt::setFileBuffer(unsigned int k, char fileBuffer)
{
this->fileBuffer[k] = fileBuffer;
}
| 20.061224
| 80
| 0.690743
|
zoranzhao
|
5c4291a9eb3539d3bbeb778695a5e4c600527e93
| 4,642
|
cpp
|
C++
|
core/src/plugin/PluginDiscovery.cpp
|
tristanseifert/lichtenstein_client
|
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
|
[
"BSD-3-Clause"
] | null | null | null |
core/src/plugin/PluginDiscovery.cpp
|
tristanseifert/lichtenstein_client
|
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
|
[
"BSD-3-Clause"
] | null | null | null |
core/src/plugin/PluginDiscovery.cpp
|
tristanseifert/lichtenstein_client
|
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
|
[
"BSD-3-Clause"
] | null | null | null |
#include "PluginDiscovery.h"
#include "LichtensteinPluginHandler.h"
#include "HardwareInfoStruct.h"
#include "../util/StringUtils.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
// includes for i2c
#ifdef __linux__
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#endif
#include <glog/logging.h>
/**
* Initializes the plugin discovery system.
*/
PluginDiscovery::PluginDiscovery(LichtensteinPluginHandler *_handler) : handler(_handler) {
this->config = this->handler->getConfig();
}
/**
* Cleans up any allocated resources.
*/
PluginDiscovery::~PluginDiscovery() {
}
/**
* Attempts to discover hardware. All EEPROMs in the specified range are read,
* and their info structs parsed.
*
* If the first I2C read times out, it's assumed no chips are at that address;
* any subsequent timeouts are considered errors.
*/
int PluginDiscovery::discover(void) {
int err = 0, numAddresses = 0;
// get a vector of all addresses
std::string addrStr = this->config->Get("discovery", "eeprom_addresses", "0x50,0x51,0x52,0x53");
std::vector<int> addr;
numAddresses = StringUtils::parseCsvList(addrStr, addr, 16);
LOG(INFO) << "Checking " << numAddresses << " addresses";
// read each memory
for(auto it = addr.begin(); it != addr.end(); it++) {
int addr = *it;
VLOG(1) << "Reading EEPROM at 0x" << std::hex << addr;
err = this->discoverAtAddress(addr);
// handle errors
if(err < 0) {
LOG(ERROR) << "Failed reading EEPROM at 0x" << std::hex << addr << std::dec
<< ": " << err << std::endl;
// errors other than a nonexistent device are fatal
if(err != kDiscoveryErrNoSuchDevice) {
return err;
}
}
}
// return error status
return err;
}
/**
* Reads the memory at the given I2C location, and attempts to match plugins to
* the input and output channels defined by the plugin.
*/
int PluginDiscovery::discoverAtAddress(int addr) {
int err;
void *romData = nullptr;
size_t romDataLen = 0;
// read the ROM
err = this->readConfigRom(addr, &romData, &romDataLen);
if(err < 0) {
LOG(ERROR) << "Couldn't read ROM: " << err;
return err;
}
// TODO: implement
return 0;
}
/**
* Reads the config ROM into memory, then provides the caller the address and
* length of the data.
*
* @note Release the buffer with free() when done.
*/
int PluginDiscovery::readConfigRom(int addr, void **data, size_t *len) {
int err = 0, fd = -1;
void *readBuf = nullptr;
// validate arguments
CHECK(data != nullptr) << "data out pointer may not be null";
CHECK(len != nullptr) << "length out pointer may not be null";
CHECK(addr > 0) << "I2C address may not be negative";
CHECK(addr < 0x80) << "I2C address may not be more than 0x7F";
// get bus number from config
int busNr = this->config->GetInteger("discovery", "eeprom_bus", 0);
CHECK(busNr >= 0) << "Address is negative, wtf (got " << busNr << ", check discovery.eeprom_bus)";
// create bus name
const size_t busPathSz = 32 + 1;
char busPath[busPathSz];
memset(&busPath, 0, busPathSz);
snprintf(busPath, (busPathSz - 1), "/dev/i2c-%d", busNr);
// open i2c device
fd = open(busPath, O_RDWR);
if(fd < 0) {
PLOG(ERROR) << "Couldn't open I2C bus at " << busPath;
return kDiscoveryErrIo;
}
// send slave address
#ifdef __linux__
err = ioctl(fd, I2C_SLAVE, addr);
if(err < 0) {
PLOG(ERROR) << "Couldn't set I2C slave address";
close(fd);
return kDiscoveryErrIoctl;
}
#endif
// allocate buffer and clear it (fixed size for now); then set its location
static const size_t readBufLen = 256;
readBuf = malloc(readBufLen);
memset(readBuf, 0, readBufLen);
*data = readBuf;
#ifdef __linux__
// write buffer for read command
static const char readCmdBuf[1] = { 0x00 };
// build i2c txn: random read starting at 0x00, 256 bytes.
static const size_t txMsgsCount = 2;
struct i2c_msg txnMsgs[txMsgsCount] = {
{
.addr = static_cast<__u16>(addr),
.flags = I2C_M_RD,
.len = sizeof(readCmdBuf),
.buf = (__u8 *) (&readCmdBuf)
},
{
.addr = static_cast<__u16>(addr),
.flags = I2C_M_RD,
.len = readBufLen,
.buf = static_cast<__u8 *>(readBuf),
}
};
struct i2c_rdwr_ioctl_data txn = {
.msgs = txnMsgs,
.nmsgs = txMsgsCount
};
err = ioctl(fd, I2C_RDWR, &txn);
if(err < 0) {
PLOG(ERROR) << "Couldn't read from EEPROM (assuming no such device)";
close(fd);
return kDiscoveryErrNoSuchDevice;
}
#endif
// success, write the output buffer location
*len = readBufLen;
return 0;
}
| 23.21
| 100
| 0.646273
|
tristanseifert
|
5c469e86a1ad9a6493481c2c4b692795a8225067
| 12,826
|
cpp
|
C++
|
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
|
Erick194/gzdoom
|
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
|
[
"RSA-MD"
] | 2
|
2020-04-19T13:37:34.000Z
|
2021-06-09T04:26:25.000Z
|
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
|
Erick194/gzdoom
|
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
|
[
"RSA-MD"
] | null | null | null |
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
|
Erick194/gzdoom
|
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
|
[
"RSA-MD"
] | null | null | null |
/*
** Provides an ALSA implementation of a MIDI output device.
**
**---------------------------------------------------------------------------
** Copyright 2008-2010 Randy Heit
** Copyright 2020 Petr Mrazek
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
**---------------------------------------------------------------------------
**
*/
#if defined __linux__ && defined HAVE_SYSTEM_MIDI
#include <thread>
#include <mutex>
#include <condition_variable>
#include "mididevice.h"
#include "zmusic/m_swap.h"
#include "zmusic/mus2midi.h"
#include "music_alsa_state.h"
#include <alsa/asoundlib.h>
namespace {
enum class EventType {
Null,
Delay,
Action
};
struct EventState {
int ticks = 0;
snd_seq_event_t data;
int size_of = 0;
void Clear() {
ticks = 0;
snd_seq_ev_clear(&data);
size_of = 0;
}
};
class AlsaMIDIDevice : public MIDIDevice
{
public:
AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char *, ...));
~AlsaMIDIDevice();
int Open() override;
void Close() override;
bool IsOpen() const override;
int GetTechnology() const override;
int SetTempo(int tempo) override;
int SetTimeDiv(int timediv) override;
int StreamOut(MidiHeader *data) override;
int StreamOutSync(MidiHeader *data) override;
int Resume() override;
void Stop() override;
bool FakeVolume() override {
// Not sure if we even can control the volume this way with Alsa, so make it fake.
return true;
};
bool Pause(bool paused) override;
void InitPlayback() override;
bool Update() override;
void PrecacheInstruments(const uint16_t *instruments, int count) override {}
bool CanHandleSysex() const override
{
// Assume we can, let Alsa sort it out. We do not truly have full control.
return true;
}
void SendStopEvents();
void SetExit(bool exit);
bool WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status);
EventType PullEvent(EventState & state);
void PumpEvents();
protected:
AlsaSequencer &sequencer;
int (*printfunc)(const char*, ...);
MidiHeader *Events = nullptr;
bool Started = false;
uint32_t Position = 0;
const static int IntendedPortId = 0;
bool Connected = false;
int PortId = -1;
int QueueId = -1;
int DestinationClientId;
int DestinationPortId;
int Technology;
int Tempo = 480000;
int TimeDiv = 480;
std::thread PlayerThread;
bool Exit = false;
std::mutex ExitLock;
std::condition_variable ExitCond;
};
}
AlsaMIDIDevice::AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char*, ...) = nullptr) : sequencer(AlsaSequencer::Get()), printfunc(printfunc_)
{
auto & internalDevices = sequencer.GetInternalDevices();
auto & device = internalDevices.at(dev_id);
DestinationClientId = device.ClientID;
DestinationPortId = device.PortNumber;
Technology = device.GetDeviceClass();
}
AlsaMIDIDevice::~AlsaMIDIDevice()
{
Close();
}
int AlsaMIDIDevice::Open()
{
if (!sequencer.IsOpen()) {
return 1;
}
if(PortId < 0)
{
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
snd_seq_port_info_set_port(pinfo, IntendedPortId);
snd_seq_port_info_set_port_specified(pinfo, 1);
snd_seq_port_info_set_name(pinfo, "GZDoom Music");
snd_seq_port_info_set_capability(pinfo, 0);
snd_seq_port_info_set_type(pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
int err = 0;
err = snd_seq_create_port(sequencer.handle, pinfo);
PortId = IntendedPortId;
}
if (QueueId < 0)
{
QueueId = snd_seq_alloc_named_queue(sequencer.handle, "GZDoom Queue");
}
if (!Connected) {
Connected = (snd_seq_connect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId) == 0);
}
return 0;
}
void AlsaMIDIDevice::Close()
{
if(Connected) {
snd_seq_disconnect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId);
Connected = false;
}
if(QueueId >= 0) {
snd_seq_free_queue(sequencer.handle, QueueId);
QueueId = -1;
}
if(PortId >= 0) {
snd_seq_delete_port(sequencer.handle, PortId);
PortId = -1;
}
}
bool AlsaMIDIDevice::IsOpen() const
{
return Connected;
}
int AlsaMIDIDevice::GetTechnology() const
{
return Technology;
}
int AlsaMIDIDevice::SetTempo(int tempo)
{
Tempo = tempo;
return 0;
}
int AlsaMIDIDevice::SetTimeDiv(int timediv)
{
TimeDiv = timediv;
return 0;
}
EventType AlsaMIDIDevice::PullEvent(EventState & state) {
state.Clear();
if(!Events) {
Callback(CallbackData);
if(!Events) {
return EventType::Null;
}
}
if (Position >= Events->dwBytesRecorded)
{
Events = Events->lpNext;
Position = 0;
if (Callback != NULL)
{
Callback(CallbackData);
}
if(!Events) {
return EventType::Null;
}
}
uint32_t *event = (uint32_t *)(Events->lpData + Position);
state.ticks = event[0];
// Advance to next event.
if (event[2] < 0x80000000)
{ // Short message
state.size_of = 12;
}
else
{ // Long message
state.size_of = 12 + ((MEVENT_EVENTPARM(event[2]) + 3) & ~3);
}
if (MEVENT_EVENTTYPE(event[2]) == MEVENT_TEMPO) {
int tempo = MEVENT_EVENTPARM(event[2]);
if(Tempo != tempo) {
Tempo = tempo;
snd_seq_change_queue_tempo(sequencer.handle, QueueId, Tempo, &state.data);
return EventType::Action;
}
}
else if (MEVENT_EVENTTYPE(event[2]) == MEVENT_LONGMSG) {
// SysEx messages...
uint8_t * data = (uint8_t *)&event[3];
int len = MEVENT_EVENTPARM(event[2]);
if (len > 1 && (data[0] == 0xF0 || data[0] == 0xF7))
{
snd_seq_ev_set_sysex(&state.data, len, (void *)data);
return EventType::Action;
}
}
else if (MEVENT_EVENTTYPE(event[2]) == 0) {
// Short MIDI event
int command = event[2] & 0xF0;
int channel = event[2] & 0x0F;
int parm1 = (event[2] >> 8) & 0x7f;
int parm2 = (event[2] >> 16) & 0x7f;
switch (command)
{
case MIDI_NOTEOFF:
snd_seq_ev_set_noteoff(&state.data, channel, parm1, parm2);
return EventType::Action;
case MIDI_NOTEON:
snd_seq_ev_set_noteon(&state.data, channel, parm1, parm2);
return EventType::Action;
case MIDI_POLYPRESS:
// FIXME: Seems to be missing in the Alsa sequencer implementation
break;
case MIDI_CTRLCHANGE:
snd_seq_ev_set_controller(&state.data, channel, parm1, parm2);
return EventType::Action;
case MIDI_PRGMCHANGE:
snd_seq_ev_set_pgmchange(&state.data, channel, parm1);
return EventType::Action;
case MIDI_CHANPRESS:
snd_seq_ev_set_chanpress(&state.data, channel, parm1);
return EventType::Action;
case MIDI_PITCHBEND: {
long bend = ((long)parm1 + (long)(parm2 << 7)) - 0x2000;
snd_seq_ev_set_pitchbend(&state.data, channel, bend);
return EventType::Action;
}
default:
break;
}
}
// We didn't really recognize the event, treat it as a delay
return EventType::Delay;
}
void AlsaMIDIDevice::SetExit(bool exit) {
std::unique_lock<std::mutex> lock(ExitLock);
if(exit != Exit) {
Exit = exit;
ExitCond.notify_all();
}
}
bool AlsaMIDIDevice::WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status) {
std::unique_lock<std::mutex> lock(ExitLock);
if(Exit) {
return true;
}
ExitCond.wait_for(lock, usec);
if(Exit) {
return true;
}
snd_seq_get_queue_status(sequencer.handle, QueueId, status);
return false;
}
/*
* Pumps events from the input to the output in a worker thread.
* It tries to keep the amount of events (time-wise) in the ALSA sequencer queue to be between 40 and 80ms by sleeping where necessary.
* This means Alsa can play them safely without running out of things to do, and we have good control over the events themselves (volume, pause, etc.).
*/
void AlsaMIDIDevice::PumpEvents() {
const std::chrono::microseconds pump_step(40000);
// TODO: fill in error handling throughout this.
snd_seq_queue_tempo_t *tempo;
snd_seq_queue_tempo_alloca(&tempo);
snd_seq_queue_tempo_set_tempo(tempo, Tempo);
snd_seq_queue_tempo_set_ppq(tempo, TimeDiv);
snd_seq_set_queue_tempo(sequencer.handle, QueueId, tempo);
snd_seq_start_queue(sequencer.handle, QueueId, NULL);
snd_seq_drain_output(sequencer.handle);
int buffer_ticks = 0;
EventState event;
snd_seq_queue_status_t *status;
snd_seq_queue_status_malloc(&status);
while (true) {
auto type = PullEvent(event);
// if we reach the end of events, await our doom at a steady rate while looking for more events
if(type == EventType::Null) {
if(WaitForExit(pump_step, status)) {
break;
}
continue;
}
// chomp delays as they come...
if(type == EventType::Delay) {
buffer_ticks += event.ticks;
Position += event.size_of;
continue;
}
// Figure out if we should sleep (the event is too far in the future for us to care), and for how long
int next_event_tick = buffer_ticks + event.ticks;
int queue_tick = snd_seq_queue_status_get_tick_time(status);
int tick_delta = next_event_tick - queue_tick;
auto usecs = std::chrono::microseconds(tick_delta * Tempo / TimeDiv);
auto schedule_time = std::max(std::chrono::microseconds(0), usecs - pump_step);
if(schedule_time >= pump_step) {
if(WaitForExit(schedule_time, status)) {
break;
}
continue;
}
if (tick_delta < 0) {
if(printfunc) {
printfunc("Alsa sequencer underrun: %d ticks!\n", tick_delta);
}
}
// We found an event worthy of sending to the sequencer
snd_seq_ev_set_source(&event.data, PortId);
snd_seq_ev_set_subs(&event.data);
snd_seq_ev_schedule_tick(&event.data, QueueId, false, buffer_ticks + event.ticks);
int result = snd_seq_event_output(sequencer.handle, &event.data);
if(result < 0) {
if(printfunc) {
printfunc("Alsa sequencer did not accept event: error %d!\n", result);
}
if(WaitForExit(pump_step, status)) {
break;
}
continue;
}
buffer_ticks += event.ticks;
Position += event.size_of;
snd_seq_drain_output(sequencer.handle);
}
snd_seq_queue_status_free(status);
snd_seq_drop_output(sequencer.handle);
// FIXME: the event source should give use these, but it doesn't.
{
for (int channel = 0; channel < 16; ++channel)
{
snd_seq_event_t ev;
snd_seq_ev_clear(&ev);
snd_seq_ev_set_source(&ev, PortId);
snd_seq_ev_set_subs(&ev);
snd_seq_ev_schedule_tick(&ev, QueueId, true, 0);
snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_ALL_NOTES_OFF, 0);
snd_seq_event_output(sequencer.handle, &ev);
snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_RESET_CONTROLLERS, 0);
snd_seq_event_output(sequencer.handle, &ev);
}
snd_seq_drain_output(sequencer.handle);
snd_seq_sync_output_queue(sequencer.handle);
}
snd_seq_sync_output_queue(sequencer.handle);
snd_seq_stop_queue(sequencer.handle, QueueId, NULL);
snd_seq_drain_output(sequencer.handle);
}
int AlsaMIDIDevice::Resume()
{
if(!Connected) {
return 1;
}
SetExit(false);
PlayerThread = std::thread(&AlsaMIDIDevice::PumpEvents, this);
return 0;
}
void AlsaMIDIDevice::InitPlayback()
{
SetExit(false);
}
void AlsaMIDIDevice::Stop()
{
SetExit(true);
PlayerThread.join();
}
bool AlsaMIDIDevice::Pause(bool paused)
{
// TODO: implement
return false;
}
int AlsaMIDIDevice::StreamOut(MidiHeader *header)
{
header->lpNext = NULL;
if (Events == NULL)
{
Events = header;
Position = 0;
}
else
{
MidiHeader **p;
for (p = &Events; *p != NULL; p = &(*p)->lpNext)
{ }
*p = header;
}
return 0;
}
int AlsaMIDIDevice::StreamOutSync(MidiHeader *header)
{
return StreamOut(header);
}
bool AlsaMIDIDevice::Update()
{
return true;
}
MIDIDevice *CreateAlsaMIDIDevice(int mididevice)
{
return new AlsaMIDIDevice(mididevice, musicCallbacks.Alsa_MessageFunc);
}
#endif
| 25.198428
| 151
| 0.710432
|
Erick194
|
5c4bd0115b98a0e53944cadf2f743dde628c407f
| 443
|
cpp
|
C++
|
heap/kSortedArray.cpp
|
sumana2001/problems450
|
90b804b7063bb3f11f90b7506576ed14d27e1776
|
[
"MIT"
] | null | null | null |
heap/kSortedArray.cpp
|
sumana2001/problems450
|
90b804b7063bb3f11f90b7506576ed14d27e1776
|
[
"MIT"
] | null | null | null |
heap/kSortedArray.cpp
|
sumana2001/problems450
|
90b804b7063bb3f11f90b7506576ed14d27e1776
|
[
"MIT"
] | 1
|
2021-08-19T12:20:06.000Z
|
2021-08-19T12:20:06.000Z
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int arr[]={6, 5, 3, 2, 8, 10, 9};
int n=sizeof(arr)/sizeof(arr[0]);
int k=3;
priority_queue<int,vector<int>,greater<int> > pq;
for(int i=0;i<n;i++){
pq.push(arr[i]);
if(pq.size()==k+1){
cout<<pq.top()<<" ";
pq.pop();
}
}
while(!pq.empty()){
cout<<pq.top()<<" ";
pq.pop();
}
return 0;
}
| 21.095238
| 53
| 0.446953
|
sumana2001
|
5c4e7d0561f155e336d64344bb8746b7ae1bbc17
| 3,927
|
cpp
|
C++
|
Source/ISnd2/LoadOgg.cpp
|
mice777/Insanity3D
|
49dc70130f786439fb0e4f91b75b6b686a134760
|
[
"Apache-2.0"
] | 2
|
2022-02-11T11:59:44.000Z
|
2022-02-16T20:33:25.000Z
|
Source/ISnd2/LoadOgg.cpp
|
mice777/Insanity3D
|
49dc70130f786439fb0e4f91b75b6b686a134760
|
[
"Apache-2.0"
] | null | null | null |
Source/ISnd2/LoadOgg.cpp
|
mice777/Insanity3D
|
49dc70130f786439fb0e4f91b75b6b686a134760
|
[
"Apache-2.0"
] | null | null | null |
#include "all.h"
#include "loader.h"
extern"C"{
#include "vorbis\vorbisfile.h"
}
#ifdef _DEBUG
#pragma comment(lib, "ogg_d.lib")
#pragma comment(lib, "vorbis_d.lib")
#else
#pragma comment(lib, "ogg.lib")
#pragma comment(lib, "vorbis.lib")
#endif
//----------------------------
const int BITDEPTH = 16; //bitdepth of data
//----------------------------
static class C_ogg_loader: public C_sound_loader{
static size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource){
PC_dta_stream dta = (PC_dta_stream)datasource;
return dta->Read(ptr, size*nmemb);
}
static int seek_func(void *datasource, __int64 offset, int whence){
PC_dta_stream dta = (PC_dta_stream)datasource;
return dta->Seek((int)offset, whence);
}
static int close_func(void *datasource){
PC_dta_stream dta = (PC_dta_stream)datasource;
dta->Release();
return 0;
//return dtaClose((int)datasource) ? 0 : -1;
}
static long tell_func(void *datasource){
PC_dta_stream dta = (PC_dta_stream)datasource;
return dta->Seek(0, DTA_SEEK_CUR);
}
public:
C_ogg_loader()
{
RegisterSoundLoader(this);
}
//----------------------------
virtual dword Open(PC_dta_stream dta, const char *file_name, void *header, dword hdr_size, S_wave_format *wf){
//if header is not RIFF, don't bother
if(hdr_size<4)
return 0;
if((*(dword*)header) != 0x5367674f)
return 0;
OggVorbis_File *vf = new OggVorbis_File;
//try to open the file
ov_callbacks ovc = { read_func, seek_func, close_func, tell_func };
int vret = ov_open_callbacks(dta, vf, (char*)header, hdr_size, ovc);
if(vret != 0){
delete vf;
return 0;
}
//init format
vorbis_info *vi = ov_info(vf, -1);
assert(vi);
wf->num_channels = vi->channels;
wf->bytes_per_sample = BITDEPTH/8 * wf->num_channels;
wf->samples_per_sec = vi->rate;
wf->size = (int)ov_pcm_total(vf, -1) * wf->bytes_per_sample;
return (dword)vf;
}
//----------------------------
virtual void Close(dword handle){
OggVorbis_File *vf = (OggVorbis_File*)handle;
assert(vf);
ov_clear(vf);
delete vf;
}
//----------------------------
virtual int Read(dword handle, void *mem, dword size){
OggVorbis_File *vf = (OggVorbis_File*)handle;
dword read = 0;
//must read in multiple chunks (design of VorbisFile?)
while(read < size){
int current_section;
dword to_read = size - read;
int rd1 = ov_read(vf,
((char*)mem) + read,
to_read,
0, //little/big endian
BITDEPTH/8, //byte-depth
BITDEPTH==8 ? 0 : 1, //unsigned=0, signed=1
¤t_section);
assert(rd1);
if(rd1<0)
return -1;
read += rd1;
}
assert(read==size);
return read;
}
//----------------------------
virtual int Seek(dword handle, dword pos){
OggVorbis_File *vf = (OggVorbis_File*)handle;
//convert position back to samples
dword sample = pos / (vf->vi->channels * 2);
ov_pcm_seek(vf, sample);
/*
assert(pos==0);
if(pos!=0)
return -1;
if(ov_pcm_tell(vf)!=0){
//re-open
int h = (int)vf->datasource;
vf->datasource = NULL;
int ok;
ok = ov_clear(vf);
assert(!ok);
dtaSeek(h, 0, DTA_SEEK_SET);
ov_callbacks ovc = { read_func, seek_func, close_func, tell_func };
ok = ov_open_callbacks((void*)h, vf, NULL, 0, ovc);
assert(!ok);
}
*/
return pos;
}
} ogg_loader;
//----------------------------
| 26.355705
| 113
| 0.531449
|
mice777
|
5c56baa2acd3c5c05d37e50e16780bdc49fe6f47
| 6,068
|
cpp
|
C++
|
QtWebApp/httpserver/staticfilecontroller.cpp
|
cbcalves/crudQtTest
|
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
|
[
"MIT"
] | null | null | null |
QtWebApp/httpserver/staticfilecontroller.cpp
|
cbcalves/crudQtTest
|
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
|
[
"MIT"
] | null | null | null |
QtWebApp/httpserver/staticfilecontroller.cpp
|
cbcalves/crudQtTest
|
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
|
[
"MIT"
] | null | null | null |
/**
@file
@author Stefan Frings
*/
#include "staticfilecontroller.h"
#include <QFileInfo>
#include <QDir>
#include <QDateTime>
using namespace stefanfrings;
StaticFileController::StaticFileController( const QSettings* settings, QObject* parent ) :
HttpRequestHandler( parent ),
m_encoding( settings->value( "encoding", "UTF-8" ).toString() ),
m_docroot( settings->value( "path", "." ).toString() ),
m_maxAge( settings->value( "maxAge", "60000" ).toInt() ),
m_cacheTimeout( settings->value( "cacheTime", "60000" ).toInt() ),
m_maxCachedFileSize( settings->value( "maxCachedFileSize", "65536" ).toInt() ) {
if ( !( m_docroot.startsWith( ":/" ) || m_docroot.startsWith( "qrc://" ) ) ) {
// Convert relative path to absolute, based on the directory of the config file.
#ifdef Q_OS_WIN32
if ( QDir::isRelativePath( docroot ) && settings->format() != QSettings::NativeFormat )
#else
if ( QDir::isRelativePath( m_docroot ) )
#endif
{
QFileInfo configFile( settings->fileName() );
m_docroot=QFileInfo( configFile.absolutePath(), m_docroot ).absoluteFilePath();
}
}
m_cache.setMaxCost( settings->value( "cacheSize", "1000000" ).toInt() );
#ifdef SUPERVERBOSE
qDebug( "StaticFileController: docroot=%s, encoding=%s, maxAge=%i", qPrintable( m_docroot ), qPrintable( m_encoding ), m_maxAge );
long int cacheMaxCost=(long int)m_cache.maxCost();
qDebug( "StaticFileController: cache timeout=%i, size=%li", m_cacheTimeout, cacheMaxCost );
#endif
}
void StaticFileController::service( HttpRequest& request, HttpResponse& response ) {
QByteArray path = request.getPath();
// Check if we have the file in cache
qint64 now = QDateTime::currentMSecsSinceEpoch();
m_mutex.lock();
CacheEntry* entry = m_cache.object( path );
if ( entry && ( m_cacheTimeout == 0 || entry->created>now - m_cacheTimeout ) ) {
QByteArray document = entry->document; //copy the cached document, because other threads may destroy the cached entry immediately after mutex unlock.
QByteArray filename = entry->filename;
m_mutex.unlock();
#ifdef SUPERVERBOSE
qDebug( "StaticFileController: Cache hit for %s", path.data() );
#endif
setContentType( filename, response );
response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) );
response.write( document, true );
return;
}
m_mutex.unlock();
// The file is not in cache.
#ifdef SUPERVERBOSE
qDebug( "StaticFileController: Cache miss for %s", path.data() );
#endif
// Forbid access to files outside the docroot directory
if ( path.contains( "/.." ) ) {
qWarning( "StaticFileController: detected forbidden characters in path %s", path.data() );
response.setStatus( 403, "forbidden" );
response.write( "403 forbidden", true );
return;
}
// If the filename is a directory, append index.html.
if ( QFileInfo( m_docroot + path ).isDir() ) {
path += "/index.html";
}
// Try to open the file
QFile file( m_docroot + path );
#ifdef SUPERVERBOSE
qDebug( "StaticFileController: Open file %s", qPrintable( file.fileName() ) );
#endif
if ( file.open( QIODevice::ReadOnly ) ) {
setContentType( path, response );
response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) );
response.setHeader( "Content-Length", QByteArray::number( file.size() ) );
if ( file.size() <= m_maxCachedFileSize ) {
// Return the file content and store it also in the cache
entry = new CacheEntry();
while ( !file.atEnd() && !file.error() ) {
QByteArray buffer = file.read( 65536 );
response.write( buffer, false );
entry->document.append( buffer, false );
}
entry->created = now;
entry->filename = path;
m_mutex.lock();
m_cache.insert( request.getPath(), entry, entry->document.size() );
m_mutex.unlock();
} else {
// Return the file content, do not store in cache
while ( !file.atEnd() && !file.error() ) {
response.write( file.read( 65536 ) );
}
}
file.close();
return;
}
if ( file.exists() ) {
qWarning( "StaticFileController: Cannot open existing file %s for reading", qPrintable( file.fileName() ) );
response.setStatus( 403, "forbidden" );
response.write( "403 forbidden", true );
return;
}
response.setStatus( 404, "not found" );
response.write( "404 not found", true );
}
void StaticFileController::setContentType( const QString& fileName, HttpResponse& response ) const {
// Todo: add all of your content types
const QMap<QString, QString> contentTypeMap = {
{ ".png", "image/png" },
{ ".jpg", "image/jpeg" },
{ ".gif", "image/gif" },
{ ".pdf", "application/pdf" },
{ ".txt", "text/plain; charset=" + m_encoding },
{ ".html", "text/html; charset=" + m_encoding },
{ ".htm", "text/html; charset=" + m_encoding },
{ ".css", "text/css" },
{ ".js", "text/javascript" },
{ ".svg", "image/svg+xml" },
{ ".woff", "font/woff" },
{ ".woff2", "font/woff2" },
{ ".ttf", "application/x-font-ttf" },
{ ".eot", "application/vnd.ms-fontobject" },
{ ".otf", "application/font-otf" },
{ ".json", "application/json" },
{ ".xml", "text/xml" },
};
for ( auto contentType = contentTypeMap.cbegin(); contentType != contentTypeMap.cend(); ++contentType ) {
if ( fileName.endsWith( contentType.key() ) ) {
response.setHeader( "Content-Type", qPrintable( contentType.value() ) );
return;
}
}
qWarning( "StaticFileController: unknown MIME type for filename '%s'", qPrintable( fileName ) );
}
| 38.897436
| 157
| 0.599044
|
cbcalves
|
5c56c79b9d72ec05c7afc418b555be8c4cd08aee
| 579
|
hpp
|
C++
|
src/common/idtypes/brushid.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 3
|
2020-03-05T06:36:51.000Z
|
2020-06-20T03:25:02.000Z
|
src/common/idtypes/brushid.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 13
|
2020-03-11T17:43:42.000Z
|
2020-12-11T03:36:05.000Z
|
src/common/idtypes/brushid.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 1
|
2020-09-28T06:53:46.000Z
|
2020-09-28T06:53:46.000Z
|
/**
* Addle source code
* @file
* @copyright Copyright 2020 Eleanor Hawk
* @copyright Modification and distribution permitted under the terms of the
* MIT License. See "LICENSE" for full details.
*/
#ifndef BRUSHID_HPP
#define BRUSHID_HPP
#include "addleid.hpp"
#include "brushengineid.hpp"
namespace Addle {
class ADDLE_COMMON_EXPORT BrushId final : public AddleId
{
ID_TYPE_BOILERPLATE(BrushId)
};
} // namespace Addle
Q_DECLARE_METATYPE(Addle::BrushId)
Q_DECLARE_TYPEINFO(Addle::BrushId, Q_PRIMITIVE_TYPE);
ID_TYPE_BOILERPLATE2(BrushId);
#endif // BRUSHID_HPP
| 20.678571
| 76
| 0.768566
|
squeevee
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.