hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count 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 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71ee75f97a2554d9a1cb1c7024b7d96104074b96 | 5,839 | cpp | C++ | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "main.h"
bool cannon_keyboard_input = true;
bool drag_pan = false, old_cki;
double drag_oldx = -1, drag_oldy = -1;
int current_view = 0;
double x_initial = -1.0;
double y_initial = -1.0;
float radius = 15.0;
float theta = 60.0 * M_PI / 180.0;
float phi = 60.0 * M_PI / 180.0;
float cur_angle_theta = 0.0;
float cur_angle_phi = 0.0;
using namespace std;
/* Executed when a regular key is pressed/released/held-down */
/* Prefered for Keyboard events */
void keyboard(GLFWwindow *window, int key, int scancode, int action, int mods) {
// Function is called first on GLFW_PRESS.
if (action == GLFW_RELEASE) {
// switch (key) {
// case GLFW_KEY_C:
// rectangle_rot_status = !rectangle_rot_status;
// break;
// case GLFW_KEY_P:
// triangle_rot_status = !triangle_rot_status;
// break;
// case GLFW_KEY_X:
//// do something ..
// break;
// default:
// break;
// }
} else if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_ESCAPE:
quit(window);
break;
default:
break;
}
}
}
/* Executed for character input (like in text boxes) */
void keyboardChar(GLFWwindow *window, unsigned int key) {
switch (key) {
case 'Q':
case 'q':
// quit(window);
break;
case 'R':
case 'r':
if(current_view == 4)
{
x_initial = -1.0;
y_initial = -1.0;
radius = 15.0;
theta = 60.0 * M_PI / 180.0;
phi = 60.0 * M_PI / 180.0;
cur_angle_theta = 0.0;
cur_angle_phi = 0.0;
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
default:
break;
}
}
/* Executed when a mouse button is pressed/released */
void mouseButton(GLFWwindow *window, int button, int action, int mods) {
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT:
if(action == GLFW_PRESS)
{
if(current_view == 4)
{
glfwGetCursorPos(window, &x_initial, &y_initial);
}
else
{
fire_missile();
}
// Do something
return;
}
else if(action == GLFW_RELEASE)
{
if(current_view == 4)
{
x_initial = -1.0;
y_initial = -1.0;
theta = fmod(theta + cur_angle_theta, 360.0);
cur_angle_theta = 0.0;
phi = fmod(phi + cur_angle_phi, 360.0);
cur_angle_phi = 0.0;
}
// Do something
}
break;
case GLFW_MOUSE_BUTTON_RIGHT:
if(action == GLFW_PRESS)
{
drop_bomb();
}
else if(action == GLFW_RELEASE)
{
// Do something
}
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
if(action == GLFW_PRESS)
{
current_view = (current_view + 1) % 5;
if(current_view == 4)
{
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
else
{
x_initial = -1.0;
y_initial = -1.0;
}
}
else if(action == GLFW_RELEASE)
{
// Do something
}
default:
break;
}
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset)
{
if(current_view == 4 && x_initial < 0.0 && y_initial < 0.0)
{
if(yoffset > 0 && radius > 7.0)
{
radius -= 1.0;
}
else if(yoffset < 0 && radius < 25.0)
{
radius += 1.0;
}
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
}
void track_cursor(GLFWwindow *window, int width, int height)
{
double x_final, y_final;
glfwGetCursorPos(window, &x_final, &y_final);
float dx = (x_final - x_initial);
float dy = (y_final - y_initial);
float angle_plane = 0.0;
float angle_vertical = 0.0;
if(x_initial >= 0.0 && y_initial >= 0.0)
{
cur_angle_theta = atan(((abs(dx) / 10.0) / (2 * M_PI * radius)) * 2 * M_PI) * dx / abs(dx);
cur_angle_phi = atan(((abs(dy) / 10.0) / (2 * M_PI * radius)) * 2 * M_PI) * dy / abs(dy) * (-1);
angle_plane = fmod(theta + cur_angle_theta, 360.0);
angle_vertical = fmod(phi + cur_angle_phi, 360.0);
view_options[4].eye.x = plane_pos.x + radius * cos(angle_plane) * sin(angle_vertical);
view_options[4].eye.y = plane_pos.y + radius * cos(angle_vertical);
view_options[4].eye.z = plane_pos.z + radius * sin(angle_plane) * sin(angle_vertical);
}
else
{
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
} | 28.34466 | 104 | 0.520466 | adhithyaarun |
71f38dc01c19713fef677cab26794d26155cccce | 2,175 | cpp | C++ | trie/trie.cpp | rusucosmin/eMag---Hai-la-Olimpiada- | 8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2 | [
"MIT"
] | null | null | null | trie/trie.cpp | rusucosmin/eMag---Hai-la-Olimpiada- | 8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2 | [
"MIT"
] | null | null | null | trie/trie.cpp | rusucosmin/eMag---Hai-la-Olimpiada- | 8adfa8e9cc6cf357e280a89e15b467c9cd77b2c2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
struct Trie {
int cnt, nrfii;
Trie *fiu[26];
Trie() {
cnt = nrfii = 0;
memset(fiu, 0, sizeof(fiu));
}
};
int getord(char x) {
if(x >= 'a' && x <= 'z')
return x - 'a';
if(x >= 'A' ** x <= 'Z')
return x - 'A';
return -1;
}
char s[30];
void _insert(Trie *node, char *s) {
if(!*s) {
node->cnt ++;
return;
}
int delta = *s - 'a';
if(node->fiu[delta] == NULL) {
node->fiu[delta] = new Trie();
node->nrfii ++;
}
_insert(node->fiu[delta], s + 1);
}
int _freq(Trie *node, char *s) {
if(!*s)
return node->cnt;
int delta = *s - 'a';
if(node->fiu[delta] == NULL)
return 0;
return _freq(node->fiu[delta], s + 1);
}
int _lcp(Trie *node, char *s) {
if(!*s)
return 0;
int delta = *s - 'a';
if(node->fiu[delta] == NULL)
return 0;
return 1 + _lcp(node->fiu[delta], s + 1);
}
Trie *root = new Trie(); /// creem nodul 'vid' (radacina)
bool _erase(Trie *node, char *s) {
if(!*s) {
node->cnt --;
if(node->cnt == 0 && node->nrfii == 0 && node != root) {
delete node;
return 1;
}
return 0;
}
int delta = *s - 'a';
if(_erase(node->fiu[delta], s + 1)) { /// daca am eliminat fiul delta, decrementez numarul de fii
node->nrfii --;
node->fiu[delta] = 0;
if(node->cnt == 0 && node->nrfii == 0 && node != root) {
delete node;
return 1;
}
}
return 0;
}
void dfs(Trie *node, string s) {
if(node->cnt)
cout << "Sirul este:\n" << s << '\n';
for(int i = 0 ; i < 26 ; ++ i)
if(node->fiu[i])
dfs(node->fiu[i], s + (char)(i + 'a'));
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
/*
0 w - adauga o aparitie a cuvantului w in lista
1 w - sterge o aparitie a cuvantului w din lista
2 w - tipareste numarul de aparitii ale cuvantului w in lista
3 w - tipareste lungimea celui mai lung prefix comun al lui w cu oricare cuvant din lista
*/
int op;
while(fin >> op >> s) {
if(op == 0) {
_insert(root, s);
}
if(op == 1) {
_erase(root, s);
}
else if(op == 2) {
fout << _freq(root, s) << '\n';
}
else if(op == 3) {
fout << _lcp(root, s) << '\n';
}
}
}
| 18.913043 | 99 | 0.53977 | rusucosmin |
71f3992f4bc823d6e39f4a146662abf9bef4a5ea | 19,458 | cpp | C++ | cpp/tests/unit-tests/StdComplexDataTypeTest.cpp | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null | cpp/tests/unit-tests/StdComplexDataTypeTest.cpp | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null | cpp/tests/unit-tests/StdComplexDataTypeTest.cpp | naeramarth7/joynr | 3c378d3447cf83678d26ef0def44a29fe1270193 | [
"Apache-2.0"
] | null | null | null | /*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <string>
#include <unordered_set>
#include <boost/math/special_functions/next.hpp>
#include <gtest/gtest.h>
#include "joynr/ByteBuffer.h"
#include "joynr/types/TestTypes/Word.h"
#include "joynr/types/TestTypes/Vowel.h"
#include "joynr/types/TestTypes/TEverythingStruct.h"
#include "joynr/types/TestTypes/TEverythingExtendedStruct.h"
#include "joynr/types/TestTypes/TEverythingExtendedExtendedStruct.h"
#include "joynr/types/TestTypes/TEnum.h"
#include "joynr/tests/StructInsideInterface.h"
#include "joynr/tests/testTypes/ComplexTestType.h"
#include "joynr/tests/StructInsideInterfaceWithoutVersion.h"
#include "joynr/types/TestTypesWithoutVersion/StructInsideTypeCollectionWithoutVersion.h"
#include "tests/PrettyPrint.h"
using namespace joynr::types;
class StdComplexDataTypeTest : public testing::Test
{
public:
StdComplexDataTypeTest()
: tInt8(-20),
tUInt8(0x42),
tInt16(-32768),
tUInt16(65535),
tInt32(-2147483648),
tUInt32(4294967295),
tInt64(6294967295),
tUInt64(-61474836480),
tDouble(0.00000000001),
tFloat(0.00001),
tString("München"),
tBoolean(true),
tByteBuffer({0x01, 0x02, 0x03, 0x04, 0x05}),
tUInt8Array({0xFF, 0xFE, 0xFD, 0xFC}),
tEnum(TestTypes::TEnum::TLITERALA),
tEnumArray({TestTypes::TEnum::TLITERALA, TestTypes::TEnum::TLITERALB}),
tStringArray({"New York", "London", "Berlin", "Tokio"}),
word(TestTypes::Word()),
wordArray({TestTypes::Word()}),
stringMap(),
typeDefForTStruct(),
tEverything1(tInt8,
tUInt8,
tInt16,
tUInt16,
tInt32,
tUInt32,
tInt64,
tUInt64,
tDouble,
tFloat,
tString,
tBoolean,
tByteBuffer,
tUInt8Array,
tEnum,
tEnumArray,
tStringArray,
word,
wordArray,
stringMap,
typeDefForTStruct),
tBooleanExtended(false),
tStringExtended("extended"),
tEverythingExtended1(tInt8,
tUInt8,
tInt16,
tUInt16,
tInt32,
tUInt32,
tInt64,
tUInt64,
tDouble,
tFloat,
tString,
tBoolean,
tByteBuffer,
tUInt8Array,
tEnum,
tEnumArray,
tStringArray,
word,
wordArray,
stringMap,
typeDefForTStruct,
tBooleanExtended,
tStringExtended)
{
}
virtual ~StdComplexDataTypeTest() = default;
protected:
std::int8_t tInt8;
std::uint8_t tUInt8;
std::int16_t tInt16;
std::uint16_t tUInt16;
std::int32_t tInt32;
std::uint32_t tUInt32;
std::int64_t tInt64;
std::uint64_t tUInt64;
double tDouble;
float tFloat;
std::string tString;
bool tBoolean;
joynr::ByteBuffer tByteBuffer;
std::vector<std::uint8_t> tUInt8Array;
TestTypes::TEnum::Enum tEnum;
std::vector<joynr::types::TestTypes::TEnum::Enum> tEnumArray;
std::vector<std::string> tStringArray;
TestTypes::Word word;
std::vector<TestTypes::Word> wordArray;
TestTypes::TStringKeyMap stringMap;
TestTypes::TypeDefForTStruct typeDefForTStruct;
TestTypes::TEverythingStruct tEverything1;
bool tBooleanExtended;
std::string tStringExtended;
TestTypes::TEverythingExtendedStruct tEverythingExtended1;
};
TEST_F(StdComplexDataTypeTest, createComplexDataType)
{
EXPECT_EQ(tEverything1.getTBoolean(), tBoolean);
EXPECT_EQ(tEverything1.getTByteBuffer(), tByteBuffer);
EXPECT_EQ(tEverything1.getTDouble(), tDouble);
EXPECT_EQ(tEverything1.getTEnum(), tEnum);
EXPECT_EQ(tEverything1.getTEnumArray(), tEnumArray);
EXPECT_EQ(tEverything1.getTEnumArray()[1], tEnumArray[1]);
EXPECT_EQ(tEverything1.getTFloat(), tFloat);
EXPECT_EQ(tEverything1.getTInt8(), tInt8);
EXPECT_EQ(tEverything1.getTInt16(), tInt16);
EXPECT_EQ(tEverything1.getTInt32(), tInt32);
EXPECT_EQ(tEverything1.getTInt64(), tInt64);
EXPECT_EQ(tEverything1.getTString(), tString);
EXPECT_EQ(tEverything1.getTStringArray(), tStringArray);
EXPECT_EQ(tEverything1.getTStringArray()[1], tStringArray[1]);
EXPECT_EQ(tEverything1.getTUInt8(), tUInt8);
EXPECT_EQ(tEverything1.getTUInt8Array(), tUInt8Array);
EXPECT_EQ(tEverything1.getTUInt8Array()[1], tUInt8Array[1]);
EXPECT_EQ(tEverything1.getTUInt16(), tUInt16);
EXPECT_EQ(tEverything1.getTUInt32(), tUInt32);
EXPECT_EQ(tEverything1.getTUInt64(), tUInt64);
}
TEST_F(StdComplexDataTypeTest, assignComplexDataType)
{
joynr::types::TestTypes::TEverythingStruct tEverything2 = tEverything1;
EXPECT_EQ(tEverything2, tEverything1);
EXPECT_EQ(tEverything2.getTBoolean(), tBoolean);
EXPECT_EQ(tEverything2.getTByteBuffer(), tByteBuffer);
EXPECT_EQ(tEverything2.getTDouble(), tDouble);
EXPECT_EQ(tEverything2.getTEnum(), tEnum);
EXPECT_EQ(tEverything2.getTEnumArray(), tEnumArray);
EXPECT_EQ(tEverything2.getTEnumArray()[1], tEnumArray[1]);
EXPECT_EQ(tEverything2.getTFloat(), tFloat);
EXPECT_EQ(tEverything2.getTInt8(), tInt8);
EXPECT_EQ(tEverything2.getTInt16(), tInt16);
EXPECT_EQ(tEverything2.getTInt32(), tInt32);
EXPECT_EQ(tEverything2.getTInt64(), tInt64);
EXPECT_EQ(tEverything2.getTString(), tString);
EXPECT_EQ(tEverything2.getTStringArray(), tStringArray);
EXPECT_EQ(tEverything2.getTStringArray()[1], tStringArray[1]);
EXPECT_EQ(tEverything2.getTUInt8(), tUInt8);
EXPECT_EQ(tEverything2.getTUInt8Array(), tUInt8Array);
EXPECT_EQ(tEverything2.getTUInt8Array()[1], tUInt8Array[1]);
EXPECT_EQ(tEverything2.getTUInt16(), tUInt16);
EXPECT_EQ(tEverything2.getTUInt32(), tUInt32);
EXPECT_EQ(tEverything2.getTUInt64(), tUInt64);
}
TEST_F(StdComplexDataTypeTest, copyConstructorComplexDataTypeCopiesValues)
{
joynr::types::TestTypes::TEverythingStruct tEverything2(tEverything1);
EXPECT_EQ(tEverything2, tEverything1);
tEverything1.setTBoolean(!tEverything1.getTBoolean());
EXPECT_NE(tEverything2, tEverything1);
joynr::types::TestTypes::TEverythingStruct tEverything3(tEverything1);
EXPECT_EQ(tEverything3, tEverything1);
tEverything1.setTStringArray({"one", "two", "three"});
EXPECT_NE(tEverything3, tEverything1);
// make sure vectors are copied and not just assigned as references:
// tEverything1 and tEverything4 should not have a reference or
// pointer to changingVector
std::vector<std::string> changingVector = {"one"};
tEverything1.setTStringArray(changingVector);
joynr::types::TestTypes::TEverythingStruct tEverything4(tEverything1);
EXPECT_EQ(tEverything4, tEverything1);
changingVector.push_back("two");
tEverything4.setTStringArray(changingVector);
EXPECT_NE(tEverything4, tEverything1);
}
TEST_F(StdComplexDataTypeTest, equalsOperator)
{
EXPECT_EQ(tEverything1, tEverything1);
joynr::types::TestTypes::TEverythingStruct tEverything2(tEverything1);
EXPECT_EQ(tEverything2, tEverything1);
EXPECT_EQ(tEverything2, tEverything1);
EXPECT_EQ(tEverything2.getTBoolean(), tBoolean);
EXPECT_EQ(tEverything2.getTByteBuffer(), tByteBuffer);
EXPECT_EQ(tEverything2.getTDouble(), tDouble);
EXPECT_EQ(tEverything2.getTEnum(), tEnum);
EXPECT_EQ(tEverything2.getTEnumArray(), tEnumArray);
EXPECT_EQ(tEverything2.getTEnumArray()[1], tEnumArray[1]);
EXPECT_EQ(tEverything2.getTFloat(), tFloat);
EXPECT_EQ(tEverything2.getTInt8(), tInt8);
EXPECT_EQ(tEverything2.getTInt16(), tInt16);
EXPECT_EQ(tEverything2.getTInt32(), tInt32);
EXPECT_EQ(tEverything2.getTInt64(), tInt64);
EXPECT_EQ(tEverything2.getTString(), tString);
EXPECT_EQ(tEverything2.getTStringArray(), tStringArray);
EXPECT_EQ(tEverything2.getTStringArray()[1], tStringArray[1]);
EXPECT_EQ(tEverything2.getTUInt8(), tUInt8);
EXPECT_EQ(tEverything2.getTUInt8Array(), tUInt8Array);
EXPECT_EQ(tEverything2.getTUInt8Array()[1], tUInt8Array[1]);
EXPECT_EQ(tEverything2.getTUInt16(), tUInt16);
EXPECT_EQ(tEverything2.getTUInt32(), tUInt32);
EXPECT_EQ(tEverything2.getTUInt64(), tUInt64);
}
TEST_F(StdComplexDataTypeTest, notEqualsOperator)
{
joynr::types::TestTypes::TEverythingStruct tEverything2;
EXPECT_NE(tEverything1, tEverything2);
tEverything2 = tEverything1;
EXPECT_EQ(tEverything1, tEverything2);
tEverything1.setTBoolean(true);
tEverything2.setTBoolean(false);
EXPECT_NE(tEverything1, tEverything2);
}
TEST_F(StdComplexDataTypeTest, createExtendedComplexDataType)
{
EXPECT_EQ(tEverythingExtended1.getTBoolean(), tBoolean);
EXPECT_EQ(tEverythingExtended1.getTByteBuffer(), tByteBuffer);
EXPECT_EQ(tEverythingExtended1.getTDouble(), tDouble);
EXPECT_EQ(tEverythingExtended1.getTEnum(), tEnum);
EXPECT_EQ(tEverythingExtended1.getTEnumArray(), tEnumArray);
EXPECT_EQ(tEverythingExtended1.getTEnumArray()[1], tEnumArray[1]);
EXPECT_EQ(tEverythingExtended1.getTFloat(), tFloat);
EXPECT_EQ(tEverythingExtended1.getTInt8(), tInt8);
EXPECT_EQ(tEverythingExtended1.getTInt16(), tInt16);
EXPECT_EQ(tEverythingExtended1.getTInt32(), tInt32);
EXPECT_EQ(tEverythingExtended1.getTInt64(), tInt64);
EXPECT_EQ(tEverythingExtended1.getTString(), tString);
EXPECT_EQ(tEverythingExtended1.getTStringArray(), tStringArray);
EXPECT_EQ(tEverythingExtended1.getTStringArray()[1], tStringArray[1]);
EXPECT_EQ(tEverythingExtended1.getTUInt8(), tUInt8);
EXPECT_EQ(tEverythingExtended1.getTUInt8Array(), tUInt8Array);
EXPECT_EQ(tEverythingExtended1.getTUInt8Array()[1], tUInt8Array[1]);
EXPECT_EQ(tEverythingExtended1.getTUInt16(), tUInt16);
EXPECT_EQ(tEverythingExtended1.getTUInt32(), tUInt32);
EXPECT_EQ(tEverythingExtended1.getTUInt64(), tUInt64);
EXPECT_EQ(tEverythingExtended1.getTUInt64(), tUInt64);
EXPECT_EQ(tEverythingExtended1.getTBooleanExtended(), tBooleanExtended);
EXPECT_EQ(tEverythingExtended1.getTStringExtended(), tStringExtended);
}
TEST_F(StdComplexDataTypeTest, equalsOperatorExtended)
{
EXPECT_EQ(tEverythingExtended1, tEverythingExtended1);
joynr::types::TestTypes::TEverythingExtendedStruct tEverythingExtended2(tEverythingExtended1);
EXPECT_EQ(tEverythingExtended2, tEverythingExtended1);
EXPECT_EQ(tEverythingExtended2.getTBoolean(), tBoolean);
EXPECT_EQ(tEverythingExtended2.getTByteBuffer(), tByteBuffer);
EXPECT_EQ(tEverythingExtended2.getTDouble(), tDouble);
EXPECT_EQ(tEverythingExtended2.getTEnum(), tEnum);
EXPECT_EQ(tEverythingExtended2.getTEnumArray(), tEnumArray);
EXPECT_EQ(tEverythingExtended2.getTEnumArray()[1], tEnumArray[1]);
EXPECT_EQ(tEverythingExtended2.getTFloat(), tFloat);
EXPECT_EQ(tEverythingExtended2.getTInt8(), tInt8);
EXPECT_EQ(tEverythingExtended2.getTInt16(), tInt16);
EXPECT_EQ(tEverythingExtended2.getTInt32(), tInt32);
EXPECT_EQ(tEverythingExtended2.getTInt64(), tInt64);
EXPECT_EQ(tEverythingExtended2.getTString(), tString);
EXPECT_EQ(tEverythingExtended2.getTStringArray(), tStringArray);
EXPECT_EQ(tEverythingExtended2.getTStringArray()[1], tStringArray[1]);
EXPECT_EQ(tEverythingExtended2.getTUInt8(), tUInt8);
EXPECT_EQ(tEverythingExtended2.getTUInt8Array(), tUInt8Array);
EXPECT_EQ(tEverythingExtended2.getTUInt8Array()[1], tUInt8Array[1]);
EXPECT_EQ(tEverythingExtended2.getTUInt16(), tUInt16);
EXPECT_EQ(tEverythingExtended2.getTUInt32(), tUInt32);
EXPECT_EQ(tEverythingExtended2.getTUInt64(), tUInt64);
EXPECT_EQ(tEverythingExtended2.getTBooleanExtended(), tBooleanExtended);
EXPECT_EQ(tEverythingExtended2.getTStringExtended(), tStringExtended);
tEverythingExtended2.setTBooleanExtended(!tEverythingExtended2.getTBooleanExtended());
EXPECT_NE(tEverythingExtended2, tEverythingExtended1);
}
TEST_F(StdComplexDataTypeTest, equalsOperatorCompareSameClass)
{
TestTypes::TEverythingExtendedStruct rhs = tEverythingExtended1;
TestTypes::TEverythingExtendedStruct lhs = rhs;
EXPECT_TRUE(lhs == rhs);
EXPECT_FALSE(lhs != rhs);
lhs.setTBoolean(!lhs.getTBoolean());
EXPECT_FALSE(lhs == rhs);
EXPECT_TRUE(lhs != rhs);
}
TEST_F(StdComplexDataTypeTest, equalsOperatorCompareWithReferenceToBase)
{
const TestTypes::TEverythingExtendedStruct& rhs = tEverythingExtended1;
const TestTypes::TEverythingStruct& lhs1 = rhs;
EXPECT_TRUE(lhs1 == rhs);
EXPECT_FALSE(lhs1 != rhs);
TestTypes::TEverythingExtendedStruct tEverythingExtended2 = tEverythingExtended1;
tEverythingExtended2.setTBoolean(!tEverythingExtended2.getTBoolean());
const TestTypes::TEverythingStruct& lhs2 = tEverythingExtended2;
EXPECT_FALSE(lhs2 == rhs);
EXPECT_TRUE(lhs2 != rhs);
}
TEST_F(StdComplexDataTypeTest, equalsOperatorBaseCompareWithDerived)
{
// intended object slicing:
// only get those parts of TEverythingExtendedStruct which stem from TEverythingStruct
TestTypes::TEverythingStruct rhs = tEverythingExtended1;
TestTypes::TEverythingExtendedStruct lhs = tEverythingExtended1;
EXPECT_FALSE(lhs == rhs);
EXPECT_TRUE(lhs != rhs);
}
TEST_F(StdComplexDataTypeTest, assignExtendedComplexDataType)
{
TestTypes::TEverythingExtendedStruct tEverythingExtended2;
tEverythingExtended2 = tEverythingExtended1;
EXPECT_EQ(tEverythingExtended1, tEverythingExtended2);
}
TEST_F(StdComplexDataTypeTest, copyExtendedComplexDataType)
{
TestTypes::TEverythingExtendedStruct tEverythingExtended2(tEverythingExtended1);
TestTypes::TEverythingExtendedStruct tEverythingExtended3 = tEverythingExtended2;
EXPECT_EQ(tEverythingExtended1, tEverythingExtended2);
EXPECT_EQ(tEverythingExtended2, tEverythingExtended3);
}
TEST_F(StdComplexDataTypeTest, equalsExtendedComplexDataTypeNotEqualBaseType)
{
std::string tStringExtendedExtended("extendedextended");
TestTypes::TEverythingExtendedExtendedStruct tEverythingExtendedExtended(
tInt8,
tUInt8,
tInt16,
tUInt16,
tInt32,
tUInt32,
tInt64,
tUInt64,
tDouble,
tFloat,
tString,
tBoolean,
tByteBuffer,
tUInt8Array,
tEnum,
tEnumArray,
tStringArray,
word,
wordArray,
stringMap,
typeDefForTStruct,
tBooleanExtended,
tStringExtended,
tStringExtendedExtended);
EXPECT_NE(tEverything1, tEverythingExtended1);
EXPECT_NE(tEverything1, tEverythingExtendedExtended);
EXPECT_NE(tEverythingExtended1, tEverythingExtendedExtended);
// currently a compile error
// EXPECT_NE(tEverythingExtendedExtended, tEverythingExtended1);
}
TEST_F(StdComplexDataTypeTest, hashCodeImplementation)
{
std::unordered_set<TestTypes::TEverythingExtendedStruct> unorderedSet;
auto returnedPair1 = unorderedSet.insert(tEverythingExtended1);
EXPECT_TRUE(returnedPair1.second);
auto returnedPair2 = unorderedSet.insert(tEverythingExtended1);
EXPECT_FALSE(returnedPair2.second);
EXPECT_EQ(unorderedSet.size(), 1);
}
TEST_F(StdComplexDataTypeTest, mapTypeListInitialization)
{
TestTypes::TStringKeyMap map = {{"lorem", "ipsum"}, {"dolor", "sit"}};
EXPECT_EQ(map.size(), 2);
EXPECT_EQ(map["lorem"], "ipsum");
}
TEST_F(StdComplexDataTypeTest, versionIsSetInStructInsideInterface)
{
std::uint32_t expectedMajorVersion = 47;
std::uint32_t expectedMinorVersion = 11;
EXPECT_EQ(expectedMajorVersion, joynr::tests::StructInsideInterface::MAJOR_VERSION);
EXPECT_EQ(expectedMinorVersion, joynr::tests::StructInsideInterface::MINOR_VERSION);
}
TEST_F(StdComplexDataTypeTest, defaultVersionIsSetInStructInsideInterfaceWithoutVersion)
{
std::uint32_t expectedMajorVersion = 0;
std::uint32_t expectedMinorVersion = 0;
EXPECT_EQ(
expectedMajorVersion, joynr::tests::StructInsideInterfaceWithoutVersion::MAJOR_VERSION);
EXPECT_EQ(
expectedMinorVersion, joynr::tests::StructInsideInterfaceWithoutVersion::MINOR_VERSION);
}
TEST_F(StdComplexDataTypeTest, versionIsSetInStructInsideTypeCollection)
{
std::uint32_t expectedMajorVersion = 48;
std::uint32_t expectedMinorVersion = 12;
EXPECT_EQ(expectedMajorVersion, joynr::tests::testTypes::ComplexTestType::MAJOR_VERSION);
EXPECT_EQ(expectedMinorVersion, joynr::tests::testTypes::ComplexTestType::MINOR_VERSION);
}
TEST_F(StdComplexDataTypeTest, defaultVersionIsSetInStructInsideTypeCollectionWithoutVersion)
{
std::uint32_t expectedMajorVersion = 0;
std::uint32_t expectedMinorVersion = 0;
EXPECT_EQ(expectedMajorVersion,
joynr::types::TestTypesWithoutVersion::StructInsideTypeCollectionWithoutVersion::
MAJOR_VERSION);
EXPECT_EQ(expectedMinorVersion,
joynr::types::TestTypesWithoutVersion::StructInsideTypeCollectionWithoutVersion::
MINOR_VERSION);
}
TEST_F(StdComplexDataTypeTest, compareFloatingPointValues)
{
using namespace boost::math;
TestTypes::TEverythingExtendedStruct struct1;
const float floatValue1 = 1.0f;
struct1.setTFloat(floatValue1);
// 3 floating point values above floatValue1
const float floatValue2 = float_next(float_next(float_next(floatValue1)));
TestTypes::TEverythingExtendedStruct struct2;
struct2.setTFloat(floatValue2);
// operator== compares 4 ULPs
EXPECT_TRUE(struct1 == struct2);
// use a custom precision
const std::size_t customMaxUlps = 2;
EXPECT_FALSE(struct1.equals(struct2, customMaxUlps));
}
| 39.710204 | 100 | 0.692312 | naeramarth7 |
71f4f5f29690ea96f7894af73f012517a50d9a85 | 618 | hpp | C++ | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | #pragma once
#include "RakPeerInterface.h"
#include "RakNetTypes.h"
#include "RakNetDefines.h"
#include "RakNetStatistics.h"
#include "BitStream.h"
#include "StringCompressor.h"
#include "GetTime.h"
#include "MessageIdentifiers.h"
#include "NetworkIDManager.h"
#include "RakSleep.h"
// std::mutex mtx;
// RakNet::RakPeerInterface *current_active_client;
void send_ping(RakNet::RakPeerInterface *client, unsigned int ms_delay);
void listen_pong(RakNet::RakPeerInterface *peer, int peer_type);
void connect_players(RakNet::RakPeerInterface *server);
void send_data(RakNet::RakPeerInterface * server);
int main(); | 23.769231 | 72 | 0.779935 | MlsDmitry |
71f57908aac86476880e84d5d9092902524641f9 | 222 | hpp | C++ | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | // Tests for Get
template <typename U>
struct St {
struct A {
int a;
static int s;
};
typedef A T;
};
#ifndef __GCCXML__
template <typename U>
int St<U>::A::s = 43;
#endif
template class St<int>;
| 11.1 | 23 | 0.594595 | paulwratt |
71f8202f267e4ebfd95289c46523925636024e83 | 976 | cc | C++ | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null |
int to_int(string s){
return std::stoi(s);
}
int to_int(float s){
return (int)s;
}
int to_int(bool s){
return (int)s;
}
int to_int(int s){
return s;
}
int to_int(char s){
return (int)s-48; // ASCII chars starts with 48
}
string to_string(int s){
string res = std::to_string(s);
return res;
}
string to_string(char s){
string res = { s };
return res;
}
string to_string(char* s){
string res = s;
return res;
}
string to_string(string s){
return s;
}
string to_string(float s){
return std::to_string(s);
}
string to_string(bool s){
if(s == true)
return "true";
return "false";
}
float to_float(int s){
return (float)s;
}
float to_float(string s){
return std::stof(s);
}
float to_float(float s){
return s;
}
float to_float(bool s){
if(s == true)
return 1.0;
return 0.0;
}
char to_char(int s){
return (char)(s+48);
}
char to_char(char c){
return c;
}
char* c_str(std::string s){
char* res = const_cast<char*>(s.c_str());
return res;
} | 12.2 | 48 | 0.643443 | hascal |
71fb19f6b6f42cb73cd54f5f176f7b060237af0f | 3,097 | cpp | C++ | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | #include "Prostopadloscian.hh"
Prostopadloscian::Prostopadloscian()
{
dl_bokow = Wektor<double,3> W;
}
Prostopadloscian::Prostopadloscian(double A,double B, double H,drawNS::Draw3DAPI *api)
{
dl_bokow[0] = A;
dl_bokow[1] = B;
dl_bokow[2] = H;
(*this).gplt = api;
}
void Prostopadloscian::ustal_wierzcholki()
{
Wektor <double,3> Ana2((*this).dl_bokow[0]/2,0,0);
Wektor <double,3> Bna2(0,(*this).dl_bokow[1]/2,0);
Wektor <double,3> Hna2(0,0,(*this).dl_bokow[2]/2);
(*this).wierzcholki[0] = (*this).srodek + (*this).orientacja * ((Ana2+Bna2+Hna2)*(-1));
(*this).wierzcholki[1] = (*this).srodek + (*this).orientacja * (Ana2-Bna2-Hna2);
(*this).wierzcholki[2] = (*this).srodek + (*this).orientacja * (Ana2+Bna2-Hna2);
(*this).wierzcholki[3] = (*this).srodek + (*this).orientacja * (Bna2-Ana2-Hna2);
(*this).wierzcholki[4] = (*this).srodek + (*this).orientacja * (Hna2-Bna2-Ana2);
(*this).wierzcholki[5] = (*this).srodek + (*this).orientacja * (Ana2-Bna2+Hna2);
(*this).wierzcholki[6] = (*this).srodek + (*this).orientacja * (Ana2+Bna2+Hna2);
(*this).wierzcholki[7] = (*this).srodek + (*this).orientacja * (Bna2-Ana2+Hna2);
}
void Prostopadloscian::rysuj()
{
(*this).ustal_wierzcholki();
(*this).id = gplt.draw_polyhedron(vector<vector<Point3D>>
{
{
{
drawNS::Point3D((*this).wierzcholki[0][0],(*this).wierzcholki[0][1],(*this).wierzcholki[0][2]),
drawNS::Point3D((*this).wierzcholki[1][0],(*this).wierzcholki[1][1],(*this).wierzcholki[1][2]),
drawNS::Point3D((*this).wierzcholki[2][0],(*this).wierzcholki[2][1],(*this).wierzcholki[2][2])
},
{
drawNS::Point3D((*this).wierzcholki[3][0],(*this).wierzcholki[3][1],(*this).wierzcholki[3][2]),
drawNS::Point3D((*this).wierzcholki[4][0],(*this).wierzcholki[4][1],(*this).wierzcholki[4][2]),
drawNS::Point3D((*this).wierzcholki[5][0],(*this).wierzcholki[5][1],(*this).wierzcholki[5][2])
},
{
drawNS::Point3D((*this).wierzcholki[6][0],(*this).wierzcholki[6][1],(*this).wierzcholki[6][2]),
drawNS::Point3D((*this).wierzcholki[7][0],(*this).wierzcholki[7][1],(*this).wierzcholki[7][2]),
drawNS::Point3D((*this).wierzcholki[8][0],(*this).wierzcholki[8][1],(*this).wierzcholki[8][2])
}
}
},"black")
}
void Prostopadloscian::wymaz()
{
(*this).gplt->erase_shape((*this).id);
}
void Prostopadloscian::jazda(double odl)
{
Wektor <double,3> jazda(0,odl,0);
(*this).gplt.erase_shape((*this).id);
(*this).srodek = (*this).srodek + (*this).orientacja * jazda;
(*this).rysuj();
}
void Prostopadloscian::obrot(double kat)
{
MacierzObr nowa_orientacja('Z',kat);
(*this).gplt.erase_shape((*this).id);
(*this).orientacja = (*this).orientacja * nowa_orientacja;
(*this).rysuj();
}
void Prostopadloscian::gora_dol(double odl)
{
(*this).gplt.erase_shape((*this).id);
(*this).srodek[2] += odl;
(*this).rysuj();
} | 38.234568 | 111 | 0.587665 | Szymon253191 |
9f98b748adce7385c99149eecc6cdfc737fa0f0e | 5,773 | cpp | C++ | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | 20 | 2017-08-20T07:32:03.000Z | 2022-02-26T16:33:36.000Z | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | null | null | null | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | 2 | 2018-07-03T06:47:39.000Z | 2020-03-12T16:52:17.000Z | //============================================================================
// Name : main.cpp
// Author : Olu Adebari
// Description : Process the captured video game frame, analyse and then send data over to Python caller program
//============================================================================
#include <iostream>
#include <vector>
#include <chrono>
#include <future>
#include <memory>
#include <string>
#include <opencv2/opencv.hpp>
#include "SeperateObjects.h"
#include "SendDataToPython.h"
#include "OCR.h"
#include "RegionOfInterest.h"
#include "BinaryImage.h"
#include "FeatureExtraction.h"
#include "RecordProcessedImage.h"
#include "ConvertToBinaryImage.h"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
boost::python::dict processImageFrame()
{
auto save_current_frame_with_bounded_boxes = true;
auto save_current_frame = true;
auto save_binary_image_of_current_frame = true;
auto save_regions_of_interest_from_current_frame_binary_image = true;
auto save_regions_of_interest_from_current_frame_binary_image_features_points = true;
static uint32_t starting_frame_number = 1;
uint32_t Number_of_frames_to_record = 1000;
auto image_processing_start_time = std::chrono::high_resolution_clock::now();
//read current video_game frame
cv::Mat img = cv::imread("../game_vision/current_game_frame/current_game_frame.jpg");
//get words in frame
OCR capture_words_in_image;
auto words_and_coordinates = std::async(std::launch::async,std::bind(&OCR::GetWordsAndLocations, capture_words_in_image,std::ref(img)));
//convert to grayscale
cv::Mat gray = cv::Mat::zeros(img.size(), img.type());
cv::cvtColor(img, gray, cv::COLOR_RGB2GRAY);
//smooth image
blur(gray, gray, cv::Size(3,3));
cv::Mat image_with_bounded_boxes_drawn_on = img.clone();
//create binary images
std::vector< std::shared_ptr<BinaryImage> > binary_images;
binary_images.emplace_back(std::make_shared<BinaryImage> (1, ConvertToBinaryImage().convertToBinary(gray,img)));
binary_images.emplace_back(std::make_shared<BinaryImage> (2, ConvertToBinaryImage().convertToBinaryInverse(gray,img)));
//extract regions of interest within an image
SeperateObjects seperate_regions_of_interest (gray,image_with_bounded_boxes_drawn_on);
auto get_binary_image_1_ROI_objects = std::async(std::launch::async,std::bind(&SeperateObjects::BoundBox, &seperate_regions_of_interest,binary_images[0] ,save_regions_of_interest_from_current_frame_binary_image));
auto get_binary_image_2_ROI_objects = std::async(std::launch::async,std::bind(&SeperateObjects::BoundBox, &seperate_regions_of_interest,binary_images[1] ,save_regions_of_interest_from_current_frame_binary_image));
get_binary_image_1_ROI_objects.wait();
get_binary_image_2_ROI_objects.wait();
//extract feature points for each region of interest
using surf_OCL = cv::xfeatures2d::SURF;
FeatureExtraction <surf_OCL> features_of_objects;
auto get_feature_points_for_binary_1_ROI_objects = std::async(std::launch::async,std::bind(&FeatureExtraction <surf_OCL>::extractFeaturePoints,
&features_of_objects,binary_images[0],save_regions_of_interest_from_current_frame_binary_image_features_points));
auto get_feature_points_for_binary_2_ROI_objects = std::async(std::launch::async,std::bind(&FeatureExtraction <surf_OCL>::extractFeaturePoints,
&features_of_objects,binary_images[1], save_regions_of_interest_from_current_frame_binary_image_features_points));
get_feature_points_for_binary_1_ROI_objects.wait();
get_feature_points_for_binary_2_ROI_objects.wait();
//Optional code: record frames with bounded boxes drawn on into their own directories.
std::string current_frame_file_name = "Image"+std::to_string(starting_frame_number)+".jpg";
RecordProcessedImage saveProcessedImages;
if (starting_frame_number >= Number_of_frames_to_record){
starting_frame_number = 1;
}
if(save_current_frame_with_bounded_boxes){
auto recordBoundBoxAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,std::ref(image_with_bounded_boxes_drawn_on),"../game_vision/cloudbank_images/Frame/bounded_boxes/",current_frame_file_name ));
}
if (save_current_frame){
auto recordCurrentFrameAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,std::ref(img),"../game_vision/cloudbank_images/Frame/Unprocessed/",current_frame_file_name));
}
if (save_binary_image_of_current_frame){
for (auto const & binary_image : binary_images){
auto recordCurrentFrameAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,binary_image->getBinaryImage(),"../game_vision/cloudbank_images/Frame/Binary/binaryImage_ID_"+std::to_string(binary_image->getID()),current_frame_file_name));
}
}
++starting_frame_number;
auto image_processing_end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(image_processing_end_time - image_processing_start_time ).count();
std::cout<< "this program took about " << duration<< " milliseconds to process the image" << std::endl;
words_and_coordinates.wait();
//send extracted image frame in python form into calling python process
SendDataToPython python_features_of_objects;
boost::python::dict send_to_python_Object_info= python_features_of_objects.SendObjectInformationToDict(binary_images, words_and_coordinates.get());
return send_to_python_Object_info;
}
int main()
{
Py_Initialize();
processImageFrame();
return 0;
}
BOOST_PYTHON_MODULE(opencv)
{
def("ProcessGameFrame", processImageFrame);
}
| 40.370629 | 286 | 0.778971 | SHEUN1 |
9f9fd055d24b87d0050cf7e7b729e23a7930dd62 | 2,455 | cc | C++ | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | null | null | null | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | 1 | 2020-11-12T15:40:37.000Z | 2020-11-12T15:40:37.000Z | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | null | null | null | #include "cellmap.h"
#include "ant.h"
#include "cell.h"
#include <cmath>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
namespace ekumen {
namespace simulation {
namespace test {
namespace {
using insect_ptr = std::shared_ptr<Insect>;
GTEST_TEST(CellMapTest, ReturnsExceptionOnConstructorWithNonPositiveCols) {
ASSERT_THROW(CellMap map(0, 1), std::invalid_argument);
ASSERT_THROW(CellMap map(-1, 1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, CellMapConstructedCorrectlyWithPositiveArguments) {
ASSERT_NO_THROW(CellMap map(1,1));
}
GTEST_TEST(CellMapTest, ReturnsExceptionOnConstructorWithNonPositiveRows) {
ASSERT_THROW(CellMap map(1, 0), std::invalid_argument);
ASSERT_THROW(CellMap map(1, -1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, ReturnedCellsAreNotNullPointer) {
CellMap map(2,2);
EXPECT_TRUE(map.GetCell(0,0));
EXPECT_TRUE(map.GetCell(0,1));
EXPECT_TRUE(map.GetCell(1,0));
EXPECT_TRUE(map.GetCell(1,1));
}
GTEST_TEST(CellMapTest, GetCellsAndVerifyThatReferenceIsCorrect) {
CellMap map(1,2);
std::shared_ptr<Cell> cell1 = map.GetCell(0,0);
std::shared_ptr<Cell> cell2 = map.GetCell(0,1);
EXPECT_TRUE(map.GetCell(0,0)->IsFree());
insect_ptr ant1(new Ant());
ant1->SetCell(cell1);
EXPECT_FALSE(map.GetCell(0,0)->IsFree());
EXPECT_TRUE(map.GetCell(0,1)->IsFree());
insect_ptr ant2(new Ant());
ant2->SetCell(cell2);
EXPECT_FALSE(map.GetCell(0,1)->IsFree());
}
GTEST_TEST(CellMapTest, GetNegativeRowsThrowsException) {
CellMap map(1,1);
ASSERT_THROW(map.GetCell(-1,0), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetNegativeColsThrowsException) {
CellMap map(1,1);
ASSERT_THROW(map.GetCell(0,-1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetExceededRowIndexThrowsException) {
CellMap map(2,2);
ASSERT_THROW(map.GetCell(2,1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetExceededColIndexThrowsException) {
CellMap map(2,2);
ASSERT_THROW(map.GetCell(1,2), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetRowsIsCorrect) {
CellMap map(7,3);
EXPECT_EQ(map.rows(), 7);
}
GTEST_TEST(CellMapTest, GetColsIsCorrect) {
CellMap map(7,3);
EXPECT_EQ(map.cols(), 3);
}
} // namespace
} // namespace test
} // namespace math
} // namespace ekumen
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.572917 | 75 | 0.716904 | LucasJSch |
9faa05bf2f62080638406437765d7fb6df63aeec | 321 | cpp | C++ | Fall-17/CSE/CPP/Assignments/Basic/LeapYear.cpp | 2Dsharp/college | 239fb4c85878f082529a3668544d1ad305b46170 | [
"MIT"
] | 1 | 2021-05-18T06:34:53.000Z | 2021-05-18T06:34:53.000Z | Fall-17/CSE/CPP/Assignments/Basic/LeapYear.cpp | 2Dsharp/college | 239fb4c85878f082529a3668544d1ad305b46170 | [
"MIT"
] | null | null | null | Fall-17/CSE/CPP/Assignments/Basic/LeapYear.cpp | 2Dsharp/college | 239fb4c85878f082529a3668544d1ad305b46170 | [
"MIT"
] | 1 | 2018-11-12T16:01:39.000Z | 2018-11-12T16:01:39.000Z | #include <iostream>
#include <string>
int main() {
int year;
std::string type;
std::cout << "Enter year: ";
std::cin >> year;
type = "Common year";
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
type= "Leap year";
}
std::cout << "It is a " << type << "\n";
return 0;
}
| 14.590909 | 67 | 0.482866 | 2Dsharp |
9fb135fb66066857d4a346cf9818ae54eb7d0231 | 5,531 | cxx | C++ | src/ai.cxx | gviegas/mad-meat-rampage | 2edd70ab4a54fda344f410c498896077f0e994e2 | [
"MIT"
] | null | null | null | src/ai.cxx | gviegas/mad-meat-rampage | 2edd70ab4a54fda344f410c498896077f0e994e2 | [
"MIT"
] | null | null | null | src/ai.cxx | gviegas/mad-meat-rampage | 2edd70ab4a54fda344f410c498896077f0e994e2 | [
"MIT"
] | null | null | null | /*
* Created by Gustavo Viegas (2016/10)
*/
#include "ai.hxx"
AI::AI() { m_lastMove = Movement::Idle; }
AI::~AI() {}
void AI::createGraph(TileMap* map) {
for(unsigned int i = 0; i < map->getGridSize().x; ++i) {
for(unsigned int j = 1; j < map->getGridSize().y; ++j) {
if(map->checkTile({i, j})) {
m_graph.insert({static_cast<int>(i), static_cast<int>(j)});
}
}
}
// create edges to adjacent tiles
int x, y, range = 3;
for(auto& iter : *m_graph.getNodes()) {
x = iter.m_x;
y = iter.m_y;
Edges edges;
Node* node = nullptr;
for(int i = 1; i <= range; ++i) {
for(int j = 1; j <= range; ++j) {
if((node = m_graph.getNode(x - i, y)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::Left));
}
if((node = m_graph.getNode(x + i, y)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::Right));
}
if((node = m_graph.getNode(x - i, y - j)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::JumpLeft));
}
if((node = m_graph.getNode(x - i, y + j)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::Left));
}
if((node = m_graph.getNode(x + i, y - j)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::JumpRight));
}
if((node = m_graph.getNode(x + i, y + j)) != nullptr) {
edges.emplace_back(Edge(node, 1, Movement::Right));
}
}
}
m_graph.addEdges(&iter, edges);
}
}
std::vector<Edge*> AI::search(const sf::Vector2u& from, const sf::Vector2u& to) {
// Node* start = m_graph.getNode(from.x / TILE_WIDTH, from.y / TILE_HEIGHT + 1);
// Node* goal = m_graph.getNode(to.x / TILE_WIDTH, to.y / TILE_HEIGHT + 1);
Node* start = m_graph.getNode(from.x, from.y + 1);
Node* goal = m_graph.getNode(to.x, to.y + 1);
if(start == nullptr) {
//std::cerr << "ERROR: no node at " << from.x / 64 <<
// " " << from.y / 64 + 1<< std::endl;
} else if(goal == nullptr) {
//std::cerr << "ERROR: no node at " << to.x / 64 <<
// " " << to.y / 64 + 1 << std::endl;
} else {
m_path.clear();
std::queue<Node*> frontier;
frontier.push(start);
m_path.emplace(start, std::make_pair(nullptr, nullptr));
while(!frontier.empty()) {
Node* current = frontier.front();
frontier.pop();
for(auto& edge : *m_graph.getEdges(current)) {
if(m_path.find(edge.m_node) == m_path.end()) {
frontier.push(edge.m_node);
m_path.emplace(edge.m_node,
std::make_pair(current, &edge));
}
}
}
std::vector<Edge*> steps;
Edge* edge = nullptr;
auto iter = m_path.find(goal);
while(iter != m_path.end() && iter->second.first) {
edge = iter->second.second;
steps.push_back(edge);
iter = m_path.find(iter->second.first);
}
return steps;
}
std::vector<Edge*> empty;
return empty;
}
void AI::act(Character* actor, Character* target, double updateInterval) {
float delta = (float)(updateInterval / 1000);
std::vector<Edge*> steps = search(
{static_cast<unsigned int>(actor->getPosition().x / actor->getBBox().width),
static_cast<unsigned int>(actor->getPosition().y / actor->getBBox().height)},
{static_cast<unsigned int>(target->getPosition().x / target->getBBox().width),
static_cast<unsigned int>(target->getPosition().y / target->getBBox().height)});
if(actor->getAction() == Action::Jump) {
if(m_lastMove == Movement::JumpLeft) {
//actor->move(Direction::Left);
actor->accelerate({-30 * delta, 0});
} else if(m_lastMove == Movement::JumpRight) {
//actor->move(Direction::Right);
actor->accelerate({30 * delta, 0});
}
}
if(steps.size()) {
Edge* nextStep = steps.back();
Movement nextMove = nextStep->m_move;
switch(nextMove) {
case Movement::Left:
if(actor->getDirection() != Direction::Left) {
actor->changeDirection();
}
actor->move(Direction::Left);
break;
case Movement::Right:
if(actor->getDirection() != Direction::Right) {
actor->changeDirection();
}
actor->move(Direction::Right);
break;
case Movement::JumpLeft:
if(actor->getDirection() != Direction::Left) {
actor->changeDirection();
}
actor->setAction(Action::Jump);
actor->jump();
break;
case Movement::JumpRight:
if(actor->getDirection() != Direction::Right) {
actor->changeDirection();
}
actor->setAction(Action::Jump);
actor->jump();
break;
case Movement::Jump:
actor->setAction(Action::Jump);
actor->jump();
break;
}
m_lastMove = nextMove;
}
}
| 37.120805 | 86 | 0.488338 | gviegas |
9fb3cd137b0eef10c67b094162cdf360e302bb59 | 734 | cpp | C++ | leetcode/491. Increasing Subsequences/s3.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/491. Increasing Subsequences/s3.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/491. Increasing Subsequences/s3.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/permutations-ii
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
private:
vector<vector<int>> ans;
void dfs(vector<int> &nums, int start, vector<int> &seq) {
if (start == nums.size()) return;
unordered_set<int> visited;
for (int i = start; i < nums.size(); ++i) {
int n = nums[i];
if (visited.count(n) || (seq.size() && seq.back() > n)) continue;
visited.insert(n);
seq.push_back(n);
if (seq.size() > 1) ans.push_back(seq);
dfs(nums, i + 1, seq);
seq.pop_back();
}
}
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<int> seq;
dfs(nums, 0, seq);
return ans;
}
}; | 27.185185 | 71 | 0.581744 | zhuohuwu0603 |
9fb3de83b9f2ec610527cc45678c9ba4d9787ecf | 706 | cpp | C++ | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | #include "stdafx.h"
#include "TVTest.h"
#include "Options.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
COptionFrame *COptions::m_pFrame=NULL;
DWORD COptions::m_GeneralUpdateFlags=0;
COptions::COptions()
: m_UpdateFlags(0)
{
}
COptions::COptions(LPCTSTR pszSection)
: CSettingsBase(pszSection)
, m_UpdateFlags(0)
{
}
COptions::~COptions()
{
}
DWORD COptions::SetUpdateFlag(DWORD Flag)
{
m_UpdateFlags|=Flag;
return m_UpdateFlags;
}
DWORD COptions::SetGeneralUpdateFlag(DWORD Flag)
{
m_GeneralUpdateFlags|=Flag;
return m_GeneralUpdateFlags;
}
void COptions::SettingError()
{
if (m_pFrame!=NULL)
m_pFrame->OnSettingError(this);
}
| 12.836364 | 48 | 0.746459 | mark10als |
9fb59be37087068fc162869dc19b2c2d61e62b97 | 15,865 | cpp | C++ | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | 1 | 2018-01-06T04:44:36.000Z | 2018-01-06T04:44:36.000Z | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | #include "Scene/COctree.h"
#include "Scene/CScene.h"
namespace VKE
{
namespace Scene
{
SOctreeNode::~SOctreeNode()
{
//m_vObjectAABBs.Destroy();
//m_vpObjectBits.Destroy();
}
//void SOctreeNode::CalcAABB( const COctree* pOctree, Math::CAABB* pOut ) const
//{
// static const Math::CVector4 aCenterVectors[ 9 ] =
// {
// Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
// Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
// Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
// Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
// Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
// Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
// Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
// Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
// Math::CVector4( 0.0f, 0.0f, 0.0f, 0.0f )
// };
// // Divide root size /2 this node level times
// const uint8_t level = m_handle.level;
// VKE_ASSERT( level > 0, "" );
// //if( level > 0 )
// {
// const OCTREE_NODE_POSITION_INDEX index = static_cast< const OCTREE_NODE_POSITION_INDEX >( m_handle.bit );
// Math::CVector4 vecExtents;
// vecExtents.x = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.x ) >> level );
// vecExtents.y = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.y ) >> level );
// vecExtents.z = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.z ) >> level );
// vecExtents.w = 0;
// Math::CVector4 vecCenter;
// // vecCenter = direction * distance + position
// Math::CVector4::Mad( aCenterVectors[ index ], vecExtents, vecParentCenter, &vecCenter );
// // vecExtentSize = vecPercentSize * vecExtentSize + vecExtentSize
// Math::CVector4::Mad( pOctree->m_vecExtraSize, vecExtents, vecExtents, &vecExtents );
// *pOut = Math::CAABB( Math::CVector3( vecCenter ), Math::CVector3( vecExtents ) );
// }
// /*else
// {
// Math::CVector4 vecExtents;
// Math::CVector4::Mad( Info.vecExtraSize, Info.vecMaxSize, Info.vecMaxSize, &vecExtents );
// *pOut = Math::CAABB( Math::CVector3( Info.vecParentCenter ), Math::CVector3( vecExtents ) );
// }*/
//}
float CalcNodeSize(float rootSize, uint8_t level)
{
float ret = (float)((uint32_t)rootSize >> level);
return ret;
}
void CalcNodeCenter( const float rootSize, const Math::CVector4& vecParentCenter,
const SOctreeNode::UNodeHandle& Handle, Math::CVector3* pOut )
{
static const Math::CVector4 aCenterVectors[9] =
{
Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 0.0f, 0.0f, 0.0f, 0.0f )
};
const OCTREE_NODE_POSITION_INDEX index = static_cast< const OCTREE_NODE_POSITION_INDEX >( Handle.bit );
Math::CVector4 vecCenter;
const float size = CalcNodeSize( rootSize, Handle.level );
Math::CVector4 vecExtents( size );
// vecCenter = direction * distance + position
Math::CVector4::Mad( aCenterVectors[ index ], vecExtents, vecParentCenter, &vecCenter );
*pOut = Math::CVector3( vecCenter );
}
void SOctreeNode::CalcAABB( const COctree* pOctree, Math::CAABB* pOut ) const
{
if( m_handle.level > 0 )
{
float size = (float)((uint32_t)(pOctree->m_vecMaxSize.x) >> m_handle.level);
size += size * pOctree->m_vecExtraSize.x;
size *= 0.5f;
*pOut = Math::CAABB( m_vecCenter, Math::CVector3( size ) );
}
else
{
*pOut = pOctree->m_RootAABB;
}
}
uint32_t SOctreeNode::AddObject( const SObjectData& Data )
{
uint32_t ret = UNDEFINED_U32;
for( uint32_t i = 0; i < m_vObjData.GetCount(); ++i )
{
if( m_vObjData[ i ].Handle.handle == 0 )
{
ret = i;
m_vObjData[ i ] = Data;
break;
}
}
if( ret == UNDEFINED_U32 )
{
ret = m_vObjData.PushBack( Data );
}
return ret;
}
COctree::COctree( CScene* pScnee ) :
m_pScene( pScnee )
{
}
COctree::~COctree()
{
}
void COctree::_Destroy()
{
}
Result COctree::_Create( const SOctreeDesc& Desc )
{
Result ret = VKE_OK;
m_Desc = Desc;
m_Desc.maxDepth = Math::Min( Desc.maxDepth, VKE_CALC_MAX_VALUE_FOR_BITS( SOctreeNode::NODE_LEVEL_BIT_COUNT ) );
m_vecExtraSize = Math::CVector4( m_Desc.extraSizePercent );
m_vecMaxSize = Math::CVector4( m_Desc.vec3MaxSize );
m_vecMinSize = Math::CVector4( m_Desc.vec3MinSize );
// Create root node
m_vNodes.Reserve( 512 ); // 8 * 8 * 8
//m_vNodeInfos.Reserve( 512 );
SOctreeNode Root;
Root.m_parentNode = 0;
Root.m_handle.handle = 0;
Root.m_vecCenter = Desc.vec3Center;
m_RootAABB = Math::CAABB( Desc.vec3Center, Desc.vec3MaxSize );
m_vNodes.PushBack( Root );
return ret;
}
void COctree::Build()
{
}
void COctree::FrustumCull( const Math::CFrustum& Frustum )
{
_FrustumCull( Frustum, m_vNodes[0], m_RootAABB );
}
void COctree::_FrustumCull( const Math::CFrustum& Frustum, const SOctreeNode& Node, const Math::CAABB& NodeAABB )
{
if( Frustum.Intersects( NodeAABB ) )
{
_FrustumCullObjects( Frustum, Node );
Math::CAABB ChildAABB;
for( uint32_t i = 0; i < Node.m_vChildNodes.GetCount(); ++i )
{
const SOctreeNode& ChildNode = m_vNodes[ Node.m_vChildNodes[ i ] ];
ChildNode.CalcAABB( this, &ChildAABB );
_FrustumCull( Frustum, ChildNode, ChildAABB );
}
}
}
void COctree::_FrustumCullObjects( const Math::CFrustum& Frustum, const SOctreeNode& Node )
{
const uint32_t count = Node.m_vObjData.GetCount();
for( uint32_t i = 0; i < count; ++i )
{
const auto& Curr = Node.m_vObjData[i];
const bool visible = Frustum.Intersects( Curr.AABB );
m_pScene->_SetObjectVisible( Curr.Handle, visible );
}
}
COctree::UObjectHandle COctree::AddObject( const Math::CAABB& AABB, const Scene::UObjectHandle& handle )
{
UObjectHandle hRet;
uint8_t level = 0;
SNodeData Data;
Data.AABB = AABB;
AABB.CalcMinMax( &Data.MinMax );
NodeHandle hNode = _CreateNode( &m_vNodes[0], m_RootAABB, Data, &level );
hRet.hNode = hNode.handle;
auto& Node = m_vNodes[ hNode.index ];
hRet.index = Node.m_vObjData.PushBack( { AABB, handle } );
return hRet;
}
COctree::UObjectHandle COctree::_AddObject( const NodeHandle& hNode, const Math::CAABB& AABB,
const Scene::UObjectHandle& handle )
{
auto& Node = m_vNodes[ hNode.index ];
UObjectHandle hRet;
hRet.hNode = hNode.handle;
hRet.index = Node.AddObject( { AABB, handle } );
return hRet;
}
COctree::UObjectHandle COctree::_UpdateObject( const handle_t& hGraph,
const Scene::UObjectHandle& hObj, const Math::CAABB& AABB )
{
UObjectHandle Handle;
Handle.handle = hGraph;
SOctreeNode::UNodeHandle hNode;
hNode.handle = Handle.hNode;
auto& CurrNode = m_vNodes[hNode.index];
// Check if new AABB fits into current node
auto hTmpNode = _CreateNodeForObject( AABB );
if( hTmpNode.handle != hNode.handle )
{
CurrNode.m_vObjData[ Handle.index ].Handle.handle = 0; // invalidate this object
Handle = _AddObject( hTmpNode, AABB, hObj );
}
return Handle;
}
bool InBounds( const Math::CVector4& V, const Math::CVector4& Bounds )
{
Math::CVector4 vec4Tmp1, vec4Tmp2, vec4NegBounds;
Math::CVector4::LessOrEquals( V, Bounds, &vec4Tmp1 );
Math::CVector4::Mul( Bounds, Math::CVector4::NEGATIVE_ONE, &vec4Tmp2 );
Math::CVector4::LessOrEquals( vec4Tmp2, V, &vec4Tmp2 );
Math::CVector4::And( vec4Tmp1, vec4Tmp2, &vec4Tmp1 );
const auto res = Math::CVector4::MoveMask( vec4Tmp1 ) & 0x7;
return ( res == 0x7 ) != 0;
}
OCTREE_NODE_POSITION_INDEX CalcChildIndex( const Math::CVector4& vecNodeCenter,
const Math::CVector4& vecObjectCenter )
{
OCTREE_NODE_POSITION_INDEX ret;
// objectAABB.center <= OctreeAABB.center
Math::CVector4 vecTmp1;
Math::CVector4::LessOrEquals( vecObjectCenter, vecNodeCenter, &vecTmp1 );
// Compare result is not a float value, make it 0-1 range
bool aResults[ 4 ];
vecTmp1.ConvertCompareToBools( aResults );
/*static const bool LEFT = 1;
static const bool RIGHT = 0;
static const bool TOP = 0;
static const bool BOTTOM = 1;
static const bool NEAR = 0;
static const bool FAR = 1;*/
static const OCTREE_NODE_POSITION_INDEX aRets[2][2][2] =
{
// RIGHT
{
{ OctreeNodePositionIndices::RIGHT_TOP_FAR, OctreeNodePositionIndices::RIGHT_TOP_NEAR }, // TOP
{ OctreeNodePositionIndices::RIGHT_BOTTOM_FAR, OctreeNodePositionIndices::RIGHT_BOTTOM_NEAR } // BOTTOM
},
// LEFT
{
{ OctreeNodePositionIndices::LEFT_TOP_FAR, OctreeNodePositionIndices::LEFT_TOP_NEAR }, // TOP
{ OctreeNodePositionIndices::LEFT_BOTTOM_FAR, OctreeNodePositionIndices::LEFT_BOTTOM_NEAR } // BOTTOM
}
};
ret = aRets[ aResults[0] ][ aResults[ 1 ] ][ aResults[ 2 ] ];
return ret;
}
COctree::NodeHandle COctree::_CreateNode( SOctreeNode* pCurrent, const Math::CAABB& CurrentAABB,
const SNodeData& Data, uint8_t* pCurrLevel )
{
NodeHandle ret = pCurrent->m_handle;
// Finish here
/*Math::CAABB CurrentAABB;
SOctreeNode::SCalcAABBInfo Info;
Info.vecExtraSize = m_vecExtraSize;
Info.vecMaxSize = m_vecMaxSize;
Info.vecParentCenter = Math::CVector4( m_vNodeInfos[ pCurrent->m_parentNode ].vecCenter );
pCurrent->CalcAABB( Info, &CurrentAABB );*/
if( *pCurrLevel < m_Desc.maxDepth &&
CurrentAABB.Extents > ( m_Desc.vec3MinSize ) )
{
// Check which child node should constains the AABB
SOctreeNode::UNodeMask NodeMask;
SOctreeNode::UPositionMask PosMask;
Math::CVector4 vecNodeCenter;
CurrentAABB.CalcCenter( &vecNodeCenter );
// Check children overlapping
const bool overlappingChildren = Data.AABB.Contains( vecNodeCenter ) != Math::IntersectResults::OUTSIDE;
if( !overlappingChildren )
{
Math::CVector4 vecObjCenter;
Data.AABB.CalcCenter( &vecObjCenter );
// Select child index
OCTREE_NODE_POSITION_INDEX childIdx = CalcChildIndex( vecNodeCenter, vecObjCenter );
// If this child doesn't exist
const bool childExists = VKE_GET_BIT( pCurrent->m_childNodeMask.mask, childIdx );
if( !childExists )
{
++( *pCurrLevel );
Math::CAABB ChildAABB;
const auto hNode = _CreateNewNode( pCurrent, CurrentAABB, childIdx, *pCurrLevel, &ChildAABB );
{
pCurrent->m_vChildNodes.PushBack( hNode.index );
pCurrent->m_childNodeMask.mask |= VKE_BIT( childIdx );
}
VKE_ASSERT( pCurrent->m_vChildNodes.GetCount() <= 8, "" );
SOctreeNode& ChildNode = m_vNodes[ hNode.index ];
ret = _CreateNode( &ChildNode, ChildAABB, Data, pCurrLevel );
}
}
}
return ret;
}
COctree::NodeHandle COctree::_CreateNodeForObject( const Math::CAABB& AABB )
{
uint8_t level = 0;
SNodeData Data;
Data.AABB = AABB;
AABB.CalcMinMax( &Data.MinMax );
return _CreateNode( &m_vNodes[ 0 ], m_RootAABB, Data, &level );
}
COctree::NodeHandle COctree::_CreateNewNode( const SOctreeNode* pParent,
const Math::CAABB& ParentAABB, OCTREE_NODE_POSITION_INDEX idx, uint8_t level, Math::CAABB* pOut )
{
static const Math::CVector4 aCenterVectors[8] =
{
Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
};
static const Math::CVector4 HALF( 0.5f );
const Math::CVector4 EXTRA_SIZE( m_Desc.extraSizePercent );
NodeHandle hRet;
{
Threads::ScopedLock l( m_NodeSyncObject );
hRet.index = m_vNodes.PushBack( {} );
VKE_ASSERT( m_vNodes.GetCount() < VKE_CALC_MAX_VALUE_FOR_BITS( SOctreeNode::BUFFER_INDEX_BIT_COUNT ), "" );
}
SOctreeNode& Node = m_vNodes[ hRet.index ];
hRet.bit = idx;
hRet.level = level;
Node.m_handle = hRet;
Node.m_parentNode = pParent->m_handle.index;
CalcNodeCenter( m_vecMaxSize.x, Math::CVector4( pParent->m_vecCenter ), hRet, &Node.m_vecCenter );
Node.CalcAABB( this, pOut );
return hRet;
}
} // Scene
} // VKE
| 40.368957 | 123 | 0.515916 | przemyslaw-szymanski |
9fb8e9c3e7e26bc435816a07831bb06ad39a7486 | 3,187 | cpp | C++ | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | 2 | 2021-05-15T03:04:17.000Z | 2021-09-16T12:21:58.000Z | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | null | null | null | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | null | null | null | #include <matching.hpp>
namespace matching {
void polygonMatching(
urquhart::Observation& ref, std::vector<size_t> refIds,
urquhart::Observation& targ, std::vector<size_t> targIds, double thresh,
std::vector<std::pair<size_t, size_t>>& polygonMatches){
std::set<size_t> matched;
for(auto rIdx : refIds){
size_t bestMatch = 0;
size_t bestDist = 100000;
urquhart::Polygon rp = ref.H->get_vertex(rIdx);
for(auto tIdx : targIds){
urquhart::Polygon tp = targ.H->get_vertex(tIdx);
// if tIdx was not matched before and the difference of number of points is not larger than 3
if(matched.find(tIdx) == matched.end() &&
std::abs(int(rp.points.size() - tp.points.size())) <= 3){
double d = euclideanDistance(rp.descriptor, tp.descriptor);
if(d < bestDist){
bestDist = d;
bestMatch = tIdx;
}
}
}
if(bestDist < thresh){
matched.insert(bestMatch);
std::pair<size_t, size_t> m = std::make_pair(rIdx, bestMatch);
polygonMatches.push_back(m);
}
}
}
void linePointMatching(const urquhart::Polygon& A, const urquhart::Polygon& B,
std::vector<std::pair<PointT, PointT>>& pointMatches){
// chi works as a permutation matrix
std::vector<size_t> chi = {0,1,2};
std::vector<size_t> bestPermutation;
double bestDist = 1000000;
do {
std::vector<double> permutation = {B.edgeLengths[chi[0]],
B.edgeLengths[chi[1]], B.edgeLengths[chi[2]]};
double d = euclideanDistance(A.edgeLengths, permutation);
if(d < bestDist){
bestDist = d;
bestPermutation = chi;
}
} while (std::next_permutation(chi.begin(), chi.end()));
for(size_t i = 0; i < 3; ++i){
PointT pA = A.points[i];
PointT pB = B.points[bestPermutation[i]];
pointMatches.push_back(std::make_pair(pA, pB));
}
}
std::vector<std::pair<PointT, PointT>> hierarchyMatching(
urquhart::Observation& ref, urquhart::Observation& targ, double thresh){
std::vector<size_t> refIds = ref.H->get_children(0);
std::vector<size_t> targIds = targ.H->get_children(0);
std::vector<std::pair<size_t, size_t>> polygonMatches;
polygonMatching(ref, refIds, targ, targIds, thresh, polygonMatches);
std::vector<std::pair<size_t,size_t>> triangleMatches;
for(auto pMatch : polygonMatches){
refIds = ref.H->get_children(pMatch.first);
targIds = targ.H->get_children(pMatch.second);
// TODO: ADD CHECK IF % OF TRIANGLES THAT MACTHED IS LARGER THAN 1/2
polygonMatching(ref, refIds, targ, targIds, thresh, triangleMatches);
}
std::vector<std::pair<PointT,PointT>> pointMatches;
for(auto tMatch : triangleMatches){
urquhart::Polygon rT = ref.H->get_vertex(tMatch.first);
urquhart::Polygon tT = targ.H->get_vertex(tMatch.second);
linePointMatching(rT, tT, pointMatches);
}
return pointMatches;
}
} // matching | 37.940476 | 106 | 0.600565 | gnardari |
9fb99605718228a2f381abae032b9fe97bb084fc | 1,681 | hpp | C++ | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | null | null | null | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | 9 | 2016-12-09T13:02:18.000Z | 2019-09-13T09:29:18.000Z | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | null | null | null | #pragma once
#include "entityx/entityx.h"
#include "fw/UniversalPhongEffect.hpp"
#include "fw/resources/Cubemap.hpp"
#include "fw/Mesh.hpp"
#include "fw/Vertices.hpp"
#include "fw/rendering/Framebuffer.hpp"
namespace ee
{
class ForwardRenderingSystem:
public entityx::System<ForwardRenderingSystem>
{
public:
ForwardRenderingSystem();
virtual ~ForwardRenderingSystem();
void setFramebuffer(std::shared_ptr<fw::IFramebuffer> framebuffer)
{
_framebuffer = framebuffer;
}
virtual void update(
entityx::EntityManager &entities,
entityx::EventManager& events,
entityx::TimeDelta
) override;
void setSkybox(std::shared_ptr<fw::Cubemap> cubemap) { _cubemap = cubemap; }
void setIrradianceMap(std::shared_ptr<fw::Cubemap> cubemap)
{
_irradianceMap = cubemap;
}
void setPrefilterMap(std::shared_ptr<fw::Cubemap> cubemap)
{
_prefilterMap = cubemap;
}
void setBrdfLut(std::shared_ptr<fw::Texture> texture)
{
_brdfLut = texture;
}
private:
std::shared_ptr<fw::Cubemap> _cubemap;
std::shared_ptr<fw::Cubemap> _irradianceMap;
std::shared_ptr<fw::Cubemap> _prefilterMap;
std::shared_ptr<fw::Texture> _brdfLut;
std::shared_ptr<fw::UniversalPhongEffect> _universalPhongEffect;
std::shared_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _box;
std::shared_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _skybox;
std::unique_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _plane;
std::shared_ptr<fw::IFramebuffer> _framebuffer;
std::shared_ptr<fw::ShaderProgram> _skyboxShader;
GLint _skyboxViewLoc, _skyboxProjLoc, _skyboxLoc;
};
}
| 25.469697 | 80 | 0.703153 | sienkiewiczkm |
9fbb6a258f4d2ca078fceb5f235c400eaf7023a6 | 3,538 | cpp | C++ | cppcms_skel/models/SqlImporter.cpp | Tatoeba/cppcms-skeleton | c4a7d3060915ce241f5eed38d0e951343ba84330 | [
"MIT"
] | 16 | 2015-03-03T13:03:59.000Z | 2021-12-27T10:19:59.000Z | cppcms_skel/models/SqlImporter.cpp | Tatoeba/cppcms-skeleton | c4a7d3060915ce241f5eed38d0e951343ba84330 | [
"MIT"
] | 1 | 2015-06-15T07:52:33.000Z | 2015-06-15T07:52:33.000Z | cppcms_skel/models/SqlImporter.cpp | Tatoeba/cppcms-skeleton | c4a7d3060915ce241f5eed38d0e951343ba84330 | [
"MIT"
] | 5 | 2015-09-14T14:01:05.000Z | 2017-08-23T11:28:01.000Z | /**
* Copyright (C) 2012-2013 Allan SIMON (Sysko) <allan.simon@supinfo.com>
* See accompanying file COPYING.TXT file for licensing details.
*
* @category Cppcms-skeleton
* @author Allan SIMON <allan.simon@supinfo.com>
* @package Models
*
*/
#include <fstream>
#include <iostream>
#include <string>
#include <booster/log.h>
#include "SqlImporter.h"
namespace cppcmsskel {
namespace models {
/**
*
*/
SqlImporter::SqlImporter(cppdb::session sqliteDbParam):
currentPosition(0),
sqliteDb(sqliteDbParam)
{
}
/**
*
*/
bool SqlImporter::from_file(
const std::string &sqlFilePath
) {
std::ifstream fileStream(sqlFilePath.c_str());
if (!fileStream.good()) {
BOOSTER_ERROR("cppcms") << "file is not readable" << std::endl;
std::cerr << "file is not readable" << std::endl;
return false;
}
std::string fileStr(
(std::istreambuf_iterator<char>(fileStream)),
std::istreambuf_iterator<char>()
);
return from_string(fileStr);
}
/**
*
*/
bool SqlImporter::from_string(
const std::string &sqlStringParam
) {
sqlString = sqlStringParam;
try {
// TODO we will ignore what's after the last ; , or everything
// if there's no ; that's a workaround because for the moment
// create_statement ... << exec will launch a "no error" exception
// if you give it an empty string
//
while (next_sql_block() != std::string::npos) {
// we split the string
sqliteDb.create_statement(currentFragment) << cppdb::exec;
}
} catch(std::exception const &e) {
std::cerr << e.what() << std::endl;
BOOSTER_ERROR("cppcms") << e.what();
return false;
}
return true;
}
/**
*
*/
size_t SqlImporter::next_sql_block() {
// we first get the position of the next ";"
size_t next = sqlString.find( ";", currentPosition );
// we split the string
currentFragment = sqlString.substr(
currentPosition,
next - currentPosition
);
if (!contains_trigger_begin(currentFragment)) {
currentPosition = next + 1;
return next;
}
next = find_trigger_end();
if (next != std::string::npos) {
currentFragment = sqlString.substr(
currentPosition,
next - currentPosition
);
currentPosition = next + 1;
}
return next;
}
/**
*
*/
bool SqlImporter::contains_trigger_begin(
const std::string &sqlFragment
) {
// we don't handle the case in which somebody has written
// cReATe
// if necessary it can be easily implemented by doing a
// "to_lower" on sqlFragment
if (sqlFragment.find("create") == std::string::npos) {
if (sqlFragment.find("CREATE") == std::string::npos) {
return false;
}
}
if (sqlFragment.find("trigger") == std::string::npos) {
if (sqlFragment.find("TRIGGER") == std::string::npos) {
return false;
}
}
return true;
}
/**
*
*/
size_t SqlImporter::find_trigger_end() {
// we first look for end/END
size_t next = sqlString.find( "end", currentPosition );
if (next == std::string::npos) {
next = sqlString.find( "END", currentPosition );
if (next == std::string::npos) {
return next;
}
}
// if we find it we look for the next ';'
return sqlString.find( ";", next);
}
} // end namespace models
} // end namespace cppcmsskel
| 20.450867 | 74 | 0.589881 | Tatoeba |
9fbbf1637bd30d8d8df212435ccbb1ad65d29c8f | 4,205 | hpp | C++ | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | /*
* @brief Template Metaprogramming 06
*
* Source: https://youtu.be/XNJlyCAr7tA
*
*/
#pragma once
// simple primality test
// this algorithm is inefficient
bool is_prime_loop(unsigned p)
{
bool ret = true;
if (p < 4)// p = 0, 1, 2, 3
{
ret = (p > 1);// p = 2 or 3, then we return true
} else {
// p = 4, 5 ,6, ...
unsigned half_p = p / 2;
// d = p/2, ..., 3, 2 (the least d is 2)
for (unsigned d = half_p; d > 1; --d) {
if (p % d == 0)// p is divisile by d
{
return false;// p is not prime
}
}
return true;// p is not divisible by 2, 3, ..., p/2
}
return ret;
}
bool _is_prime_recu(unsigned p, unsigned d)
{
bool ret = true;
if (d == 2) {// escape clause -> specialization
ret = (p % d != 0);// p is not divisible by d, then return true
} else {
/*
* Rule 1:
*
* if (true_condition)
* return true_expr;
* else
* return false_expr;
*
* return (true_condition ? true_expr : false_expr);
*
*
*/
// d is greater than 2
// if (p % d != 0)// p is not divisible by d
// {
// ret = _is_prime_recu(p, --d);
// } else {
// // p is divisible by d
// return false;
// }
// return (p%d != 0 ? _is_prime_recu(p, --d) : false);
/*
* Rule 2:
*
* if (true_condition)
* return true_expr;
* elss
* return false;
*
* return true_condition && true_expr;
*
*/
// recursive clause -> primary template
return (p % d != 0) && _is_prime_recu(p, --d);
}
return ret;
// return (d == 2 ? (p % d != 0) : (p % d != 0) && _is_prime_recu(p, --d));
}
bool is_prime_recursion(unsigned p)
{
bool ret = true;
if (p < 4)// excape clause -> specialization
// p = 0, 1, 2, 3
{
ret = (p > 1);// p = 2 or 3, then we return true
} else {
// recursive clause -> primary template
// p is 4, 5, 6, ...
return _is_prime_recu(p, p / 2);
}
return ret;
}
// primary template
// recursive clause of recursive function
template<unsigned p, unsigned d>
struct st_is_prime_recu
{
/*
* (p%d != 0) && _is_prime_recu(p, --d);
*
* p and d are template parameters.
* we cannot change template parameters
* so --d is incorerect, instead us d-1
*/
static const bool value = (p % d) && st_is_prime_recu<p, d - 1>::value;
};
// escape clause to specialization
template<unsigned p>
struct st_is_prime_recu<p, 2>
{
static const bool value = (p % 2 != 0);
};
// primary template
// when we translate recursive function
// to template class, recursive clause becomes primary template
template<unsigned p>
struct st_is_prime
{
static const bool value = st_is_prime_recu<p, p / 2>::value;
};
template<>
struct st_is_prime<3>
{
static const bool value = true;
};
template<>
struct st_is_prime<2>
{
static const bool value = true;
};
template<>
struct st_is_prime<1>
{
static const bool value = true;
};
template<>
struct st_is_prime<0>
{
static const bool value = false;
};
void test_is_prime(unsigned limit)
{
for (unsigned p = 1; p <= limit; ++p) {
std::cout << std::setw(3) << p << " is "
<< (is_prime_loop(p) ? "Yes, Prime" : "No") << std::endl;
}
}
void test_is_prime_recursion(unsigned limit)
{
for (unsigned p = 1; p <= limit; ++p) {
std::cout << std::setw(3) << p << " is "
<< (is_prime_recursion(p) ? "Yes, Prime" : "No") << std::endl;
}
}
[[maybe_unused]] constexpr unsigned magic_prime_t = 7;
void test_st_is_prime()
{
std::cout << std::setw(3) << 1 << " is "
<< (st_is_prime<1>::value ? "Yes, Prime" : "No") << std::endl;
std::cout << std::setw(3) << magic_prime_t << " is "
<< (st_is_prime<magic_prime_t>::value ? "Yes, Prime" : "No") << std::endl;
}
[[maybe_unused]] constexpr unsigned magic_prime = 25;
| 22.72973 | 88 | 0.51629 | kahido |
9fbefa6eb15cb74f1d464592a697063b1e3c6f65 | 1,599 | cpp | C++ | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 167 | 2017-04-26T00:17:34.000Z | 2019-05-06T09:50:30.000Z | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 22 | 2017-04-26T20:24:40.000Z | 2019-03-23T20:03:42.000Z | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 42 | 2017-04-27T01:51:39.000Z | 2019-04-12T21:23:17.000Z | #include "stdafx.h"
#include "IPC/detail/ChannelFactory.h"
namespace IPC
{
namespace detail
{
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
create_only_t, bool input, const char* name, const ChannelSettingsBase& settings)
{
return GetMemory(false, input, name, settings);
}
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
open_only_t, bool input, const char* name, const ChannelSettingsBase& settings)
{
return GetMemory(true, input, name, settings);
}
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
bool open, bool input, const char* name, const ChannelSettingsBase& settings)
{
const auto& config = settings.GetConfig();
const auto& channelConfig = input ? config.m_input : config.m_output;
if (config.m_shared)
{
if (auto memory = m_current.lock())
{
return memory;
}
}
auto memory = channelConfig.m_common
? channelConfig.m_common
: open
? settings.GetMemoryCache()->Open(name)
: settings.GetMemoryCache()->Create(name, channelConfig.m_size);
if (config.m_shared)
{
m_current = memory;
}
return memory;
}
} // detail
} // IPC
| 31.352941 | 94 | 0.537211 | chengwei45254 |
9fc125b0e726e5ae456466ee8cd318a8ab4fad2f | 1,763 | cpp | C++ | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
// #include <maniplator>
bool IsReversible(const std::string& str) {
std::size_t count = str.length()/2;
if (count == 0) {
return true;
}
auto begin = str.cbegin();
auto rbegin = str.crbegin();
for (std::size_t i = 0; i < count; ++i) {
char beginVal = *begin;
char rbeginVal = *rbegin;
if (beginVal != rbeginVal) {
return false;
}
++begin;
++rbegin;
}
return true;
}
bool IsKaibun(int i) {
// std::cout << i << ":\n";
std::stringstream ss;
ss << i;
auto str = ss.str();
std::cout << "\t" << str << std::endl;
bool isReversible = IsReversible(str);
if (isReversible == false) {
return false;
}
ss.clear();
ss.str("");
// 2進数のチェック
std::bitset<32> binary(i);
bool isFirst = true;
for (int i = binary.size() -1; i >= 0; --i) {
int val = binary[i];
if (binary[i] == 0) {
if (isFirst == true) {
continue;
}
} else {
isFirst = false;
}
ss << binary[i];
}
str = ss.str();
std::cout << "\t" << str << std::endl;
const bool isBinaryReversible = IsReversible(ss.str());
if (isBinaryReversible == false) {
return false;
}
ss.clear();
ss.str("");
ss << std::oct << i;
const bool isOctReversible = IsReversible(ss.str());
str = ss.str();
std::cout << "\t" << str << "\n";
return isOctReversible;
}
int main() {
// const bool nine = IsKaibun(9);
// std::cout << "nine => " << nine << std::endl;
// const bool ninty = IsKaibun(90);
// std::cout << "ninty => " << ninty << std::endl;
int i = 11;
for (; ; ++i) {
const bool isKaibun = IsKaibun(i);
if (isKaibun == true) {
break;
}
}
// int i = 121;
// const bool isKaibun = IsKaibun(i);
std::cout << "the minimum => " << i << "\n";
}
| 16.951923 | 56 | 0.559841 | taku-xhift |
9fc2753bed0ed37270c307c5ecca0c4bd43cd435 | 407 | hh | C++ | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null |
#ifndef __OCTO_STRING_HH__
#define __OCTO_STRING_HH__
#include "OctoObject.hh"
namespace types {
class OctoString : public OctoObject {
public:
virtual void assign(const char* data, size_t size) = 0;
// Compare to a null terminated string.
virtual bool equalTo(const char* data) const = 0;
virtual void toCppString(std::string& str) const = 0;
};
}
#endif
| 19.380952 | 63 | 0.665848 | KevinTheBarbarian |
9fc8f3ca97bc472b182c1f2c953479f0bb908ce0 | 16,004 | cpp | C++ | src/WMIMapper/WMIProvider/WMIBaseProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/WMIMapper/WMIProvider/WMIBaseProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/WMIMapper/WMIProvider/WMIBaseProvider.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
// Author: Barbara Packard (barbara_packard@hp.com)
//
// Modified By: Adriano Zanuz (adriano.zanuz@hp.com)
// Jair Santos, Hewlett-Packard Company (jair.santos@hp.com)
// Mateus Baur, Hewlett-Packard Company (jair.santos@hp.com)
//
//%////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider.cpp: implementation of the WMIBaseProvider class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "WMICollector.h"
#include "WMIBaseProvider.h"
#include "WMIClassProvider.h"
#include "WMIInstanceProvider.h"
#include "WMIQueryProvider.h"
#include "WMIProperty.h"
#include "WMIString.h"
#include "WMIValue.h"
#include "WMIQualifier.h"
#include "WMIQualifierSet.h"
#include "WMIType.h"
#include "WMIException.h"
PEGASUS_NAMESPACE_BEGIN
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
WMIBaseProvider::WMIBaseProvider()
{
}
WMIBaseProvider::~WMIBaseProvider()
{
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::initialize
//
// ///////////////////////////////////////////////////////////////////////////
void WMIBaseProvider::initialize(bool bLocal)
{
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::initialize()");
initCollector(bLocal);
PEG_METHOD_EXIT();
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::terminate
//
// ///////////////////////////////////////////////////////////////////////////
void WMIBaseProvider::terminate(void)
{
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::terminate()");
cleanup();
PEG_METHOD_EXIT();
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::setup
//
/////////////////////////////////////////////////////////////////////////////
void WMIBaseProvider::setup(const String & nameSpace,
const String & userName,
const String & password)
{
m_sNamespace = nameSpace;
m_sUserName = userName;
m_sPassword = password;
if (!m_bInitialized)
{
initCollector();
}
if (m_bInitialized)
{
_collector->setNamespace(m_sNamespace);
if (m_sUserName != String::EMPTY)
_collector->setUserName(m_sUserName);
if (m_sPassword != String::EMPTY)
_collector->setPassword(m_sPassword);
}
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::initCollector
//
// ///////////////////////////////////////////////////////////////////////////
void WMIBaseProvider::initCollector(bool bLocal)
{
if (!m_bInitialized)
{
_collector = new WMICollector(bLocal);
m_bInitialized = _collector->setup();
}
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::cleanup
//
// ///////////////////////////////////////////////////////////////////////////
void WMIBaseProvider::cleanup()
{
if (m_bInitialized)
{
_collector->terminate();
delete _collector;
_collector = NULL;
m_bInitialized = false;
}
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getCIMInstance - retrieves a CIMInstance object
//
// ///////////////////////////////////////////////////////////////////////////
CIMInstance WMIBaseProvider::getCIMInstance(
const String& nameSpace,
const String& userName,
const String& password,
const CIMObjectPath &instanceName,
const CIMPropertyList &propertyList)
{
CIMInstance cimInstance;
CIMStatusCode errorCode = CIM_ERR_SUCCESS;
String errorDescription;
WMIInstanceProvider provider;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::getCIMInstance()");
try
{
// This fix uses the current boolean value stored in collector
// to initialize it.
provider.initialize(_collector->isLocalConnection());
cimInstance = provider.getInstance(nameSpace,
userName,
password,
instanceName,
false,
false,
false,
propertyList);
provider.terminate();
}
catch(CIMException& exception)
{
provider.terminate();
errorCode = exception.getCode();
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(Exception& exception)
{
provider.terminate();
errorCode = CIM_ERR_FAILED;
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(...)
{
provider.terminate();
throw CIMException(CIM_ERR_FAILED);
}
PEG_METHOD_EXIT();
return cimInstance;
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getCIMClass - retrieves a CIMClass object
//
// ///////////////////////////////////////////////////////////////////////////
CIMClass WMIBaseProvider::getCIMClass(const String& nameSpace,
const String& userName,
const String& password,
const String& className,
const CIMPropertyList &propertyList)
{
CIMClass cimClass;
CIMStatusCode errorCode = CIM_ERR_SUCCESS;
String errorDescription;
WMIClassProvider provider;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::getCIMClass()");
try
{
// This fix uses the current boolean value stored in collector
// to initialize it.
provider.initialize(_collector->isLocalConnection());
cimClass = provider.getClass(nameSpace, userName, password,
className, false, true, true, propertyList);
provider.terminate();
}
catch(CIMException& exception)
{
provider.terminate();
errorCode = exception.getCode();
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(Exception& exception)
{
provider.terminate();
errorCode = CIM_ERR_FAILED;
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(...)
{
provider.terminate();
throw CIMException(CIM_ERR_FAILED);
}
PEG_METHOD_EXIT();
return cimClass;
}
/////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::execCIMQuery - retrieves a query result
//
// ///////////////////////////////////////////////////////////////////////////
Array<CIMObject> WMIBaseProvider::execCIMQuery(
const String& nameSpace,
const String& userName,
const String& password,
const String& queryLanguage,
const String& query,
const CIMPropertyList& propertyList,
Boolean includeQualifiers,
Boolean includeClassOrigin)
{
Array<CIMObject> objects;
CIMInstance cimInstance;
CIMStatusCode errorCode = CIM_ERR_SUCCESS;
String errorDescription;
WMIQueryProvider provider;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::execCIMQuery()");
try
{
// This fix uses the current boolean value stored in collector
// to initialize it.
provider.initialize(_collector->isLocalConnection());
objects = provider.execQuery(nameSpace,
userName,
password,
queryLanguage,
query,
propertyList,
includeQualifiers,
includeClassOrigin);
provider.terminate();
}
catch(CIMException& exception)
{
provider.terminate();
errorCode = exception.getCode();
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(Exception& exception)
{
provider.terminate();
errorCode = CIM_ERR_FAILED;
errorDescription = exception.getMessage();
throw PEGASUS_CIM_EXCEPTION(errorCode, errorDescription);
}
catch(...)
{
provider.terminate();
throw CIMException(CIM_ERR_FAILED);
}
PEG_METHOD_EXIT();
return objects;
}
//////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getQueryString - builds the query string from the
// input parameters for Associator and Reference commands
//
// ///////////////////////////////////////////////////////////////////////////
String WMIBaseProvider::getQueryString(const CIMObjectPath &objectName,
const String &sQueryCommand,
const String &assocClass,
const String &resultClass,
const String &role,
const String &resultRole)
{
bool hasWHERE = false;
bool isInst;
//first we need to get the object name
String sObjName = getObjectName(objectName);
// check if is an instance name
Uint32 pos = sObjName.find(qString(Q_PERIOD));
isInst = (PEG_NOT_FOUND != pos);
CMyString sQuery;
int strLength = CMyString(sQueryCommand).GetLength() +
CMyString(sObjName).GetLength() + 1;
sQuery.Format(
CMyString(sQueryCommand),
strLength, static_cast<LPCTSTR>(CMyString(sObjName)));
//set up any optional parameters
if (!((0 == assocClass.size()) && (0 == resultClass.size()) &&
(0 == role.size()) && (0 == resultRole.size())))
{
// we have optional parameters, append the appropriate ones
sQuery += qChar(Q_WHERE);
hasWHERE = true;
if (0 != assocClass.size())
{
sQuery += qChar(Q_ASSOC_CLS);
sQuery += assocClass;
}
if (0 != resultClass.size())
{
sQuery += qChar(Q_RESULT_CLASS);
sQuery += resultClass;
}
if (0 != role.size())
{
sQuery += qChar(Q_ROLE);
sQuery += role;
}
if (0 != resultRole.size())
{
sQuery += qChar(Q_RESULT_ROLE);
sQuery += resultRole;
}
}
// check if an instance
if (!isInst)
{
// have a class, add "SchemaOnly"
if (!hasWHERE)
{
sQuery += qChar(Q_WHERE);
}
sQuery += qChar(Q_SCHEMA);
}
PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL3,
"WMIBaseProvider::getQueryString() - Query is %s", (LPCTSTR)sQuery));
String s = (LPCTSTR)sQuery;
return s;
}
//////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getObjectName - extracts the String object name from
// CIMObjectPath
// removes namespace
//
// Possible input Object Path formats:
// 1. Fully-qualified path
// example: \\hostname:port\root\cimv2:ClassName.Key1="Value",Key2="Value"
//
// 2. No hostname & port (implies current host)
// example: root\cimv2:ClassName.Key1="Value",Key2="Value"
//
// 3. No namespace (implies current namespace):
// example: ClassName.Key1="Value",Key2="Value"
//
// 4. Reference instance
// example: ClassName.Key1=R"root\cimv2:RefClass.Key="RefValue""
//
// In all cases, this method needs to return only the class name and keys from
// the input object path (need to strip any hostname, port, and namespace).
// For example, the return for cases #1-3, above, should be:
// ClassName.Key1="Value",Key2="Value"
//
// Also, for "reference" keys, the reference indicator (R) needs to be
// removed. Therefore, the output from case #4, above, would be:
// ClassName.Key1="root\cimv2:RefClass.Key="RefValue""
//
// ///////////////////////////////////////////////////////////////////////////
String WMIBaseProvider::getObjectName( const CIMObjectPath& objectName)
{
String sObjName;
String sObjNameLower;
bool bHaveReference = false;
PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::getObjectName()");
sObjName = objectName.toString();
sObjNameLower = sObjName;
sObjNameLower.toLower();
PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL3,
"WMIBaseProvider::getObjectName() - ObjectName: %s",
sObjName.getCString()));
Uint32 pos;
// 1. if Object name initiates with a hostname then remove it
if ((sObjName.subString(0, 4) != "root") &&
(sObjNameLower.subString(0, 2) != "//") &&
(sObjNameLower.subString(0, 2) != "\\\\"))
{
pos = sObjNameLower.find("root");
if (sObjNameLower.find("=") > pos) {
if (PEG_NOT_FOUND != pos)
{
sObjName.remove(0, pos);
sObjNameLower.remove(0, pos);
}
}
}
//2. Remove the machine name and port if it exists
if ((sObjNameLower.subString(0, 2) == "//") ||
(sObjNameLower.subString(0, 2) == "\\\\"))
{
pos = sObjNameLower.find("root");
if (PEG_NOT_FOUND != pos)
{
sObjName.remove(0, pos);
sObjNameLower.remove(0, pos);
}
//3. After ensuring that all stuff before root was removed,
// get the class/instance name.
pos = sObjName.find(qString(Q_COLON));
if (PEG_NOT_FOUND != pos)
{
sObjName.remove(0, pos + 1);
}
}
else
{
// get the class/instance name.
if (sObjNameLower.subString(0, 4) == "root")
{
pos = sObjName.find(qString(Q_COLON));
if (PEG_NOT_FOUND != pos)
{
sObjName.remove(0, pos + 1);
}
}
}
PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL3,
"WMIBaseProvider::getObjectName() - ObjectName: %s",
sObjName.getCString()));
PEG_METHOD_EXIT();
return sObjName;
}
PEGASUS_NAMESPACE_END
| 30.310606 | 79 | 0.544989 | natronkeltner |
9fcdbaa648d982e79ee56c8467fa93f6c7b4c002 | 1,407 | cpp | C++ | c++/0198-house-robber.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | 2 | 2019-04-13T09:55:04.000Z | 2019-05-16T12:47:40.000Z | c++/0198-house-robber.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | c++/0198-house-robber.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | // 22/04/29 = Fri
// 198. House Robber [Medium]
// You are a professional robber planning to rob houses along a street. Each
// house has a certain amount of money stashed, the only constraint stopping you
// from robbing each of them is that adjacent houses have security systems
// connected and it will automatically contact the police if two adjacent houses
// were broken into on the same night.
// Given an integer array nums representing the amount of money of each house,
// return the maximum amount of money you can rob tonight without alerting the
// police.
// Example 1:
// Input: nums = [1,2,3,1]
// Output: 4
// Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
// Total amount you can rob = 1 + 3 = 4.
// Example 2:
// Input: nums = [2,7,9,3,1]
// Output: 12
// Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5
// (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
// Constraints:
// 1 <= nums.length <= 100
// 0 <= nums[i] <= 400
// Related Topics:
// [Array] [Dynamic Programming*]
class Solution {
public:
int rob(vector<int> &nums) {
int n = nums.size();
if (n == 1) {
return nums[0];
}
vector<int> dp(n);
dp[0] = nums[0];
dp[1] = std::max(nums[0], nums[1]);
for (int i = 2; i < n; ++i) {
dp[i] = std::max(dp[i - 1], nums[i] + dp[i - 2]);
}
return dp.back();
}
};
| 28.14 | 80 | 0.618337 | aafulei |
9fd1bd75eef5b961a63a43dc61fcccbb46e9fc1a | 586 | cxx | C++ | Geovis/Core/Testing/Cxx/TestGeoProjection.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | Geovis/Core/Testing/Cxx/TestGeoProjection.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | Geovis/Core/Testing/Cxx/TestGeoProjection.cxx | txwhhny/vtk | 854d9aa87b944bc9079510515996406b98b86f7c | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | #include "vtkGeoProjection.h"
int TestGeoProjection(int, char*[])
{
int np = vtkGeoProjection::GetNumberOfProjections();
cout << "Supported projections:\n";
for (int i = 0; i < np; ++i)
{
cout << "Projection: " << vtkGeoProjection::GetProjectionName(i) << "\n";
cout << "\t" << vtkGeoProjection::GetProjectionDescription(i) << "\n";
}
cout << "-------\n";
vtkGeoProjection* proj = vtkGeoProjection::New();
const char* projName = "rouss";
proj->SetName(projName);
cout << projName << " is " << proj->GetDescription() << "\n";
proj->Delete();
return 0;
}
| 29.3 | 77 | 0.617747 | txwhhny |
9fd30f542f14d939964a19a9b22a5dde0219cdf3 | 10,427 | cpp | C++ | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | 10 | 2020-03-12T12:45:50.000Z | 2020-06-28T06:10:04.000Z | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | null | null | null | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | 2 | 2021-08-24T12:37:33.000Z | 2021-09-05T14:59:58.000Z | /**
** This file is part of the "Mobile Weather" project.
** Copyright (c) 2020 Florian Meinicke <florian.meinicke@t-online.de>.
**
** 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 WeatherData.cpp
/// \author Florian Meinicke <florian.meinicke@t-online.de>
/// \date 18/02/2020
/// \brief Implementation of the CWeatherData class.
//============================================================================
//============================================================================
// INCLUDES
//============================================================================
#include "WeatherData.h"
static constexpr auto MILES_TO_KM_FACTOR = 1.609344;
//=============================================================================
CWeatherData::CWeatherData(QObject* parent) : QObject(parent)
{}
//=============================================================================
CWeatherData::CWeatherData(const CWeatherData& rhs)
: m_WeatherStateName{rhs.m_WeatherStateName},
m_WeatherStateAbbreviation{rhs.m_WeatherStateAbbreviation},
m_TheTemp{rhs.m_TheTemp},
m_MinTemp{rhs.m_MinTemp},
m_MaxTemp{rhs.m_MaxTemp}
{}
//=============================================================================
CWeatherData::CWeatherData(CWeatherData&& rhs) noexcept
: m_WeatherStateName{rhs.m_WeatherStateName},
m_WeatherStateAbbreviation{rhs.m_WeatherStateAbbreviation},
m_TheTemp{rhs.m_TheTemp},
m_MinTemp{rhs.m_MinTemp},
m_MaxTemp{rhs.m_MaxTemp}
{}
//=============================================================================
CWeatherData& CWeatherData::operator=(const CWeatherData& rhs)
{
m_WeatherStateName = rhs.m_WeatherStateName;
m_WeatherStateAbbreviation = rhs.m_WeatherStateAbbreviation;
m_TheTemp = rhs.m_TheTemp;
m_MinTemp = rhs.m_MinTemp;
m_MaxTemp = rhs.m_MaxTemp;
return *this;
}
//=============================================================================
CWeatherData& CWeatherData::operator=(CWeatherData&& rhs) noexcept
{
m_WeatherStateName = rhs.m_WeatherStateName;
m_WeatherStateAbbreviation = rhs.m_WeatherStateAbbreviation;
m_TheTemp = rhs.m_TheTemp;
m_MinTemp = rhs.m_MinTemp;
m_MaxTemp = rhs.m_MaxTemp;
return *this;
}
//=============================================================================
QDate CWeatherData::date() const
{
return m_Date;
}
//=============================================================================
void CWeatherData::setDate(const QDate& day)
{
m_Date = day;
emit dateChanged();
}
//=============================================================================
QString CWeatherData::weatherStateName() const
{
return m_WeatherStateName;
}
//=============================================================================
void CWeatherData::setWeatherStateName(const QString& weatherStateName)
{
m_WeatherStateName = weatherStateName;
emit weatherStateNameChanged();
}
//=============================================================================
QString CWeatherData::weatherStateAbbreviation() const
{
return m_WeatherStateAbbreviation;
}
//=============================================================================
void CWeatherData::setWeatherStateAbbreviation(
const QString& weatherStateAbbreviation)
{
m_WeatherStateAbbreviation = weatherStateAbbreviation;
emit weatherStateAbbreviationChanged();
}
//=============================================================================
qreal CWeatherData::theTemp() const
{
return m_TheTemp;
}
//=============================================================================
void CWeatherData::setTheTemp(const qreal& temp)
{
m_TheTemp = temp;
emit theTempChanged();
}
//=============================================================================
qreal CWeatherData::minTemp() const
{
return m_MinTemp;
}
//=============================================================================
void CWeatherData::setMinTemp(const qreal& temp)
{
m_MinTemp = temp;
emit minTempChanged();
}
//=============================================================================
qreal CWeatherData::maxTemp() const
{
return m_MaxTemp;
}
//=============================================================================
void CWeatherData::setMaxTemp(const qreal& temp)
{
m_MaxTemp = temp;
emit maxTempChanged();
}
//=============================================================================
qreal CWeatherData::windSpeed() const
{
return m_WindSpeed;
}
//=============================================================================
void CWeatherData::setWindSpeed(const qreal& speed)
{
m_WindSpeed = speed;
emit windSpeedChanged();
}
//=============================================================================
void CWeatherData::setWindSpeedInMph(const qreal& speed)
{
setWindSpeed(speed * MILES_TO_KM_FACTOR);
}
//=============================================================================
qreal CWeatherData::windDirection() const
{
return m_WindDirection;
}
//=============================================================================
void CWeatherData::setWindDirection(const qreal& dir)
{
m_WindDirection = dir;
emit windDirectionChanged();
}
//=============================================================================
QString CWeatherData::windDirCompass() const
{
return m_WindDirCompass;
}
//=============================================================================
void CWeatherData::setWindDirCompass(const QString& compass)
{
m_WindDirCompass = compass;
emit windDirCompassChanged();
}
//=============================================================================
qreal CWeatherData::airPressure() const
{
return m_AirPressure;
}
//=============================================================================
void CWeatherData::setAirPressure(const qreal& pressure)
{
m_AirPressure = pressure;
emit airPressureChanged();
}
//=============================================================================
qreal CWeatherData::humidity() const
{
return m_Humidity;
}
//=============================================================================
void CWeatherData::setHumidity(const qreal& humidity)
{
m_Humidity = humidity;
emit humidityChanged();
}
//=============================================================================
qreal CWeatherData::visibility() const
{
return m_Visibility;
}
//=============================================================================
void CWeatherData::setVisibility(const qreal& visibility)
{
m_Visibility = visibility;
emit visibilityChanged();
}
//=============================================================================
void CWeatherData::setVisibilityInMiles(const qreal& visibility)
{
setVisibility(visibility * MILES_TO_KM_FACTOR);
}
//=============================================================================
int CWeatherData::confidence() const
{
return m_Confidence;
}
//=============================================================================
void CWeatherData::setConfidence(int confidence)
{
m_Confidence = confidence;
emit confidenceChanged();
}
//=============================================================================
QDateTime CWeatherData::sunriseTime() const
{
return m_SunriseTime;
}
//=============================================================================
void CWeatherData::setSunriseTime(const QDateTime& time)
{
m_SunriseTime = time;
static auto OffsetFromUTC = QDateTime::currentDateTime().offsetFromUtc();
// Convert the time from UTC to the same time in the local timezone
// by changing the UTC offset to the current timezone's offset.
// This means, if the time 07:00 UTC-7 is given and we are currently in the
// UTC+1 timezone, the time would be displayed as 15:00 UTC+1. To prevent
// that we change the UTC offset from UTC-7 to UTC+1 (i.e. the given time
// would now be 07:00 UTC+1; the actual value of the time is not affected).
// Now the time will be displayed correctly as 07:00.
// Without this the sunrise time for e.g. Los Angeles would be displayed as
// 15:00 (if we are in the UTC+1 timezone) when it is actually 07:00 in the
// local timezone (i.e. UTC-7).
m_SunriseTime.setOffsetFromUtc(OffsetFromUTC);
emit sunriseTimeChanged();
}
//=============================================================================
QDateTime CWeatherData::sunsetTime() const
{
return m_SunsetTime;
}
//=============================================================================
void CWeatherData::setSunsetTime(const QDateTime& time)
{
m_SunsetTime = time;
static auto OffsetFromUTC = QDateTime::currentDateTime().offsetFromUtc();
// see above for an explanation
m_SunsetTime.setOffsetFromUtc(OffsetFromUTC);
emit sunsetTimeChanged();
}
| 34.299342 | 83 | 0.482018 | FMeinicke |
9fdef1ca39b0c61b56e5e893bbf52a6927962a12 | 267 | cc | C++ | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <cstring>
#include "find_first_of.h"
int main(int argc, char *argv[]){
std::string word =argv[1];
std::string character_to_find = argv[2];
std::cout << PositionOfCharacter(word, character_to_find) << std::endl;
} | 24.272727 | 73 | 0.70412 | ULL-ESIT-IB-2020-2021 |
9fe74f0633e78896deed5dd2fcaad8450039d33a | 311 | cpp | C++ | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
void moveZeroes(vector<int>& nums) {
int now = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i]){
nums[now] = nums[i];
now++;
}
}
for(int i = now; i < nums.size(); i++) nums[i] = 0;
}
};
| 22.214286 | 59 | 0.382637 | zfang399 |
9fed8a7f7f2d9a4f79551d9799b91564402649d0 | 332 | cpp | C++ | asteria/rocket/format.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | 292 | 2018-03-23T08:57:39.000Z | 2022-03-28T16:49:09.000Z | asteria/rocket/format.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | 71 | 2018-04-13T18:42:13.000Z | 2022-03-08T16:56:58.000Z | asteria/rocket/format.cpp | usama-makhzoum/asteria | ea4c893a038e0c5bef14d4d9f6723124a0cbb30f | [
"BSD-3-Clause"
] | 22 | 2018-10-20T19:14:30.000Z | 2022-03-04T08:32:30.000Z | // This file is part of Asteria.
// Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved.
#include "format.hpp"
namespace rocket {
template
tinyfmt&
vformat(tinyfmt&, const char*, size_t, const formatter*, size_t);
template
wtinyfmt&
vformat(wtinyfmt&, const wchar_t*, size_t, const wformatter*, size_t);
} // namespace rocket
| 19.529412 | 70 | 0.73494 | usama-makhzoum |
9fefee80d0f02d86c8d2a971b451ae3feb5d166f | 458 | cpp | C++ | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
unsigned long long int n;
unsigned long long int solve(unsigned long long int i)
{
if(i>=n)
{
return 0;
}
unsigned long long int x=0,y=0;
if(i+1<=n)
x = 1+solve(i+1);
if((unsigned long long int)(i*2)<=n)
y = 1+solve(i*2);
return min(x,y);
}
int main() {
int t;
cin>>t;
while(t--)
{
cin>>n;
cout<<1+solve(1)<<"\n";
}
return 0;
} | 13.470588 | 54 | 0.50655 | waytoashutosh |
9ff0d3655ea30c48c11c8c0c5958c1969d24cf18 | 6,644 | cpp | C++ | emulator/src/mame/machine/namco06.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/machine/namco06.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/machine/namco06.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************
Namco 06XX
This chip is used as an interface to up to 4 other custom chips.
It signals IRQs to the custom MCUs when writes happen, and generates
NMIs to the controlling CPU to drive reads based on a clock.
SD0-SD7 are data I/O lines connecting to the controlling CPU
SEL selects either control (1) or data (0), usually connected to
an address line of the controlling CPU
/NMI is an NMI signal line for the controlling CPU
ID0-ID7 are data I/O lines connecting to the other custom chips
/IO1-/IO4 are IRQ signal lines for each custom chip
+------+
[1]|1 28|Vcc
ID7|2 27|SD7
ID6|3 26|SD6
ID5|4 25|SD5
ID4|5 24|SD4
ID3|6 23|SD3
ID2|7 22|SD2
ID1|8 21|SD1
ID0|9 20|SD0
/IO1|10 19|/NMI
/IO2|11 18|/CS
/IO3|12 17|CLOCK
/IO4|13 16|R/W
GND|14 15|SEL
+------+
[1] on polepos, galaga, xevious, and bosco: connected to K3 of the 51xx
on bosco and xevious, connected to R8 of the 50xx
06XX interface:
---------------
Galaga 51XX ---- ---- 54XX
Bosconian (CPU board) 51XX ---- 50XX 54XX
Bosconian (Video board) 50XX 52XX ---- ----
Xevious 51XX ---- 50XX 54XX
Dig Dug 51XX 53XX ---- ----
Pole Position / PP II 51XX 53XX 52XX 54XX
Galaga writes:
control = 10(000), data = FF at startup
control = 71(011), read 3, control = 10
control = A1(101), write 4, control = 10
control = A8(101), write 12, control = 10
Xevious writes:
control = 10 at startup
control = A1(101), write 6, control = 10
control = 71(011), read 3, control = 10
control = 64(011), write 1, control = 10
control = 74(011), read 4, control = 10
control = 68(011), write 7, control = 10
Dig Dug writes:
control = 10(000), data = 10 at startup
control = A1(101), write 3, control = 10
control = 71(011), read 3, control = 10
control = D2(110), read 2, control = 10
Bosco writes:
control = 10(000), data = FF at startup
control = C8(110), write 17, control = 10
control = 61(011), write 1, control = 10
control = 71(011), read 3, control = 10
control = 94(100), read 4, control = 10
control = 64(011), write 1, control = 10
control = 84(100), write 5, control = 10
control = 34(001), write 1, control = 10
***************************************************************************/
#include "emu.h"
#include "machine/namco06.h"
#define VERBOSE 0
#include "logmacro.h"
TIMER_CALLBACK_MEMBER( namco_06xx_device::nmi_generate )
{
if (!m_nmicpu->suspended(SUSPEND_REASON_HALT | SUSPEND_REASON_RESET | SUSPEND_REASON_DISABLE))
{
LOG("NMI cpu '%s'\n",m_nmicpu->tag());
m_nmicpu->set_input_line(INPUT_LINE_NMI, PULSE_LINE);
}
else
LOG("NMI not generated because cpu '%s' is suspended\n",m_nmicpu->tag());
}
READ8_MEMBER( namco_06xx_device::data_r )
{
uint8_t result = 0xff;
LOG("%s: 06XX '%s' read offset %d\n",machine().describe_context(),tag(),offset);
if (!(m_control & 0x10))
{
logerror("%s: 06XX '%s' read in write mode %02x\n",machine().describe_context(),tag(),m_control);
return 0;
}
if (BIT(m_control, 0)) result &= m_read[0](space, 0);
if (BIT(m_control, 1)) result &= m_read[1](space, 0);
if (BIT(m_control, 2)) result &= m_read[2](space, 0);
if (BIT(m_control, 3)) result &= m_read[3](space, 0);
return result;
}
WRITE8_MEMBER( namco_06xx_device::data_w )
{
LOG("%s: 06XX '%s' write offset %d = %02x\n",machine().describe_context(),tag(),offset,data);
if (m_control & 0x10)
{
logerror("%s: 06XX '%s' write in read mode %02x\n",machine().describe_context(),tag(),m_control);
return;
}
if (BIT(m_control, 0)) m_write[0](space, 0, data);
if (BIT(m_control, 1)) m_write[1](space, 0, data);
if (BIT(m_control, 2)) m_write[2](space, 0, data);
if (BIT(m_control, 3)) m_write[3](space, 0, data);
}
READ8_MEMBER( namco_06xx_device::ctrl_r )
{
LOG("%s: 06XX '%s' ctrl_r\n",machine().describe_context(),tag());
return m_control;
}
WRITE8_MEMBER( namco_06xx_device::ctrl_w )
{
LOG("%s: 06XX '%s' control %02x\n",machine().describe_context(),tag(),data);
m_control = data;
if ((m_control & 0x0f) == 0)
{
LOG("disabling nmi generate timer\n");
m_nmi_timer->adjust(attotime::never);
}
else
{
LOG("setting nmi generate timer to 200us\n");
// this timing is critical. Due to a bug, Bosconian will stop responding to
// inputs if a transfer terminates at the wrong time.
// On the other hand, the time cannot be too short otherwise the 54XX will
// not have enough time to process the incoming controls.
m_nmi_timer->adjust(attotime::from_usec(200), 0, attotime::from_usec(200));
if (m_control & 0x10)
{
if (BIT(m_control, 0)) m_readreq[0](space, 0);
if (BIT(m_control, 1)) m_readreq[1](space, 0);
if (BIT(m_control, 2)) m_readreq[2](space, 0);
if (BIT(m_control, 3)) m_readreq[3](space, 0);
}
}
}
DEFINE_DEVICE_TYPE(NAMCO_06XX, namco_06xx_device, "namco06", "Namco 06xx")
namco_06xx_device::namco_06xx_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, NAMCO_06XX, tag, owner, clock)
, m_control(0)
, m_nmicpu(*this, finder_base::DUMMY_TAG)
, m_read{ { *this }, { *this }, { *this }, { *this } }
, m_readreq{ { *this }, { *this }, { *this }, { *this } }
, m_write{ { *this }, { *this }, { *this }, { *this } }
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void namco_06xx_device::device_start()
{
for (devcb_read8 &cb : m_read)
cb.resolve_safe(0xff);
for (devcb_write_line &cb : m_readreq)
cb.resolve_safe();
for (devcb_write8 &cb : m_write)
cb.resolve_safe();
/* allocate a timer */
m_nmi_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(namco_06xx_device::nmi_generate),this));
save_item(NAME(m_control));
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void namco_06xx_device::device_reset()
{
m_control = 0;
}
| 30.3379 | 117 | 0.579169 | rjw57 |
9ff5cfc1bc1a8e25d4d66f43c60fb532d0188333 | 1,589 | cpp | C++ | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | 4 | 2019-01-30T21:35:40.000Z | 2019-06-25T03:19:44.000Z | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | null | null | null | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | 3 | 2019-06-06T17:01:28.000Z | 2021-06-27T10:55:34.000Z | //Manuel Monforte
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "PriorityQueue.h"
/*
Coste de la solucion--> Aplicamos PriorityQueue
-->Se aplican operaciones top y pop que tiene complejidad logN
-->Se aplican K veces cada una de ella
-->Total: O(2K*logN)
*/
struct tUsuario{
int id;
int periodo;
int tiempo;
tUsuario(){};
tUsuario(int pk, int ped) : id(pk), periodo(ped),tiempo(ped){};
};
bool operator < (const tUsuario & a, const tUsuario & b){
return a.tiempo < b.tiempo || ( a.tiempo == b.tiempo && a.id < b.id) ;
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso() {
// leer los datos de la entrada
int N, K,id,periodo;
std::string registro;
std::cin >> N;
if (N== 0)
return false;
PriorityQueue<tUsuario> UCM;
for (int i = 0; i < N; i++){
std::cin >> registro >> id >> periodo;
UCM.push({ id, periodo });
}
std::cin >> K;
for (int i = 0; i < K; i++){
tUsuario aux = UCM.top();
UCM.pop();
std::cout << aux.id << "\n";
aux.tiempo += aux.periodo;
UCM.push(aux);
}
return true;
}
int main() {
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
while (resuelveCaso())
;
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | 20.113924 | 92 | 0.651353 | manumonforte |
9ff8346f48ef2d620986d0cf1fe99a9efcf36bb7 | 1,492 | cpp | C++ | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | 1 | 2022-02-27T09:01:07.000Z | 2022-02-27T09:01:07.000Z | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
bool checkPositive(int arr[], int n){
for(int i=0;i<n;i++){
if(arr[i]>0) return (true);
}
return (false);
}
vector<int> findSubarray(int a[], int n) {
// code here
if(!checkPositive(a,n)){
return (vector<int>{-1});
}
int i=0,j=0;
long long int max_sum=0;
long long int cur_sum=0;
int start=0,end=0;
while(j<n){
if(a[j]>=0){
cur_sum+=a[j];
if(cur_sum>=max_sum){
start =i;
end=j;
max_sum=cur_sum;
}
j++;
}
else{
cur_sum=0;
i=j+1;
j++;
}
}
vector<int> ans;
for(int i=start;i<=end;i++)
{
ans.push_back(a[i]);
}
if(!ans.size()) ans.push_back(-1);
return (ans);
}
};
// { Driver Code Starts.
void printAns(vector<int> &ans) {
for (auto &x : ans) {
cout << x << " ";
}
cout << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
int n, i;
cin >> n;
int a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
auto ans = ob.findSubarray(a, n);
printAns(ans);
}
return 0;
}
// } Driver Code Ends | 19.128205 | 43 | 0.419571 | champmaniac |
9ffb505d1ffe22fccd34af8f82c007adc9b46458 | 5,289 | cpp | C++ | test/src/test_writer.cpp | steinwurf/bitter | d303d9c1607ef6affd740f84464fbb23ea72a632 | [
"BSD-3-Clause"
] | 15 | 2017-02-01T19:01:01.000Z | 2021-05-04T12:00:17.000Z | test/src/test_writer.cpp | steinwurf/bitter | d303d9c1607ef6affd740f84464fbb23ea72a632 | [
"BSD-3-Clause"
] | 10 | 2016-09-05T07:28:51.000Z | 2021-11-26T13:11:48.000Z | test/src/test_writer.cpp | steinwurf/bitter | d303d9c1607ef6affd740f84464fbb23ea72a632 | [
"BSD-3-Clause"
] | 3 | 2017-12-09T20:10:35.000Z | 2019-08-23T08:42:06.000Z | // Copyright (c) Steinwurf ApS 2016.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#include <bitter/lsb0_writer.hpp>
#include <bitter/msb0_writer.hpp>
#include <cstdint>
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
TEST(test_bit_writer, write_integer)
{
{
auto writer = bitter::lsb0_writer<uint8_t, 4, 4>();
writer.field<0>(0x0U);
writer.field<1>(0xFU);
auto value = writer.data();
EXPECT_EQ(value, 0xF0U);
}
{
auto writer = bitter::lsb0_writer<uint16_t, 8, 8>();
writer.field<0>(0xF0U);
writer.field<1>(0x0FU);
auto value = writer.data();
EXPECT_EQ(value, 0x0FF0U);
}
{
auto writer = bitter::lsb0_writer<uint32_t, 16, 16>();
writer.field<0>(0xF0F0U);
writer.field<1>(0x0F0FU);
auto value = writer.data();
EXPECT_EQ(value, 0x0F0FF0F0U);
}
{
auto writer = bitter::lsb0_writer<uint64_t, 32, 32>();
writer.field<0>(0xF0F0F0F0U);
writer.field<1>(0x0F0F0F0FU);
auto value = writer.data();
EXPECT_EQ(value, 0x0F0F0F0FF0F0F0F0U);
}
}
TEST(test_bit_writer, write_bit)
{
{
auto writer = bitter::lsb0_writer<bitter::u8, 1, 7>();
writer.field<0>(true);
uint8_t input = 0b1000000;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0b10000001U);
}
{
auto writer = bitter::msb0_writer<bitter::u8, 1, 7>();
writer.field<0>(true);
uint8_t input = 0b1000000;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0b11000000U);
}
}
TEST(test_bit_writer, write_bit_1)
{
{
auto writer = bitter::lsb0_writer<bitter::u16, 16>();
uint16_t input = 2050U;
writer.field<0>(input);
auto value = writer.data();
EXPECT_EQ(value, 2050U);
}
{
auto writer = bitter::msb0_writer<bitter::u16, 16>();
uint16_t input = 2050U;
writer.field<0>(input);
auto value = writer.data();
EXPECT_EQ(value, 2050U);
}
}
TEST(test_bit_writer, write_bit_u24)
{
{
auto writer = bitter::lsb0_writer<bitter::u24, 16, 8>();
writer.field<0>(0xFF00);
auto value = writer.data();
EXPECT_EQ(value, 0xFF00U);
writer.field<1>(0xFF);
value = writer.data();
EXPECT_EQ(value, 0xFFFF00U);
}
{
auto writer = bitter::msb0_writer<bitter::u24, 16, 8>();
writer.field<0>(0xFF00);
auto value = writer.data();
EXPECT_EQ(value, 0xFF0000U);
writer.field<1>(0xFF);
value = writer.data();
EXPECT_EQ(value, 0xFF00FFU);
}
}
TEST(test_bit_writer, write_bit_2)
{
{
auto writer = bitter::lsb0_writer<bitter::u32, 32>();
uint32_t input = 323794U;
writer.field<0>(input);
auto value = writer.data();
EXPECT_EQ(value, 323794U);
}
{
auto writer = bitter::msb0_writer<bitter::u32, 32>();
uint32_t input = 323794U;
writer.field<0>(input);
auto value = writer.data();
EXPECT_EQ(value, 323794U);
}
}
TEST(test_bit_writer, write_bit_3)
{
{
auto writer = bitter::lsb0_writer<bitter::u64, 32, 32>();
uint32_t input = 0x22222222;
writer.field<0>(input);
input = 0x44444444;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x4444444422222222U);
}
{
auto writer = bitter::msb0_writer<bitter::u64, 32, 32>();
uint32_t input = 0x22222222;
writer.field<0>(input);
input = 0x44444444;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x2222222244444444U);
}
}
TEST(test_bit_writer, write_bit_4)
{
{
auto writer = bitter::lsb0_writer<bitter::u32, 16, 16>();
uint16_t input = 0x1234;
writer.field<0>(input);
input = 0x4321;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x43211234U);
}
{
auto writer = bitter::msb0_writer<bitter::u32, 16, 16>();
uint16_t input = 0x1234;
writer.field<0>(input);
input = 0x4321;
writer.field<1>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x12344321U);
}
}
TEST(test_bit_writer, write_bit_5)
{
{
auto writer = bitter::lsb0_writer<bitter::u32, 8, 8, 8, 8>();
uint8_t input = 0x11;
writer.field<0>(input);
input = 0x22;
writer.field<1>(input);
input = 0x33;
writer.field<2>(input);
input = 0x44;
writer.field<3>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x44332211U);
}
{
auto writer = bitter::msb0_writer<bitter::u32, 8, 8, 8, 8>();
uint8_t input = 0x11;
writer.field<0>(input);
input = 0x22;
writer.field<1>(input);
input = 0x33;
writer.field<2>(input);
input = 0x44;
writer.field<3>(input);
auto value = writer.data();
EXPECT_EQ(value, 0x11223344U);
}
}
| 23.717489 | 78 | 0.562488 | steinwurf |
9ffd4514974b80bf43987e06a64668aca487fc26 | 2,440 | cpp | C++ | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | // POJ 3040
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int INF = 2000000000;
const int MAXN = 20+10;
PII D[MAXN];
int N, C;
void print_d()
{
for (int i = 0; i < N; i++) printf("(%d,%d)%c", D[i].first, D[i].second,
i==N-1?'\n':' ');
}
bool cmp(const PII &a, const PII &b)
{
return a.first > b.first || (a.first==b.first && a.second > b.second);
}
int take(int amount)
{
map<int,int> m;
for (int i = 0; i < N; i++) {// descent
if (D[i].second > 0 && amount / D[i].first > 0) {
int c = (amount / D[i].first < D[i].second) ?
amount / D[i].first : D[i].second;
// printf("(%d * %d)", D[i].first, c);
m[i] += c;
D[i].second -= c;
amount -= D[i].first * c;
}
}
for (int i = N-1; i >= 0; i--) {// ascent
if (amount <= 0) break;
if (D[i].second <= 0) continue;
if (amount < D[i].first || amount / D[i].first <= D[i].second) {
int c = (amount / D[i].first > 0
&& amount <= D[i].second * D[i].first) ?
amount / D[i].first : 1;
// printf("(%d %d)", D[i].first, c);
m[i] += c;
D[i].second -= c;
amount -= D[i].first * c;
}
}
if (amount > 0) return 0;
int mi = INF;
for (map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
PII pair = *it; int index = pair.first; int cnt = pair.second;
if (cnt > 0) mi = min(mi, D[index].second / cnt);
}
for (map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
PII pair = *it; int index = pair.first; int cnt = pair.second;
D[index].second -= (mi * cnt);
}
// print_d();
return mi+1;
}
void solve()
{
sort(D, D+N, cmp);
int cnt = 0, c = 0;
while ((c = take(C)) != 0) {
cnt += c;
}
// printf("\n");
printf("%d\n", cnt);
}
int main()
{
while (scanf("%d%d", &N, &C) == 2) {
if (N == 0 && C == 0) break;
memset(D, 0, sizeof(D));
for (int i = 0; i < N; i++) {
int v, b; scanf("%d%d", &v, &b);
D[i] = PII(v, b);
}
solve();
}
}
| 25.154639 | 76 | 0.445492 | aoibird |
9ffd8f7cd96e6a971019678f43873aae23951174 | 24,131 | cpp | C++ | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/PhysicsAssetUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/PhysicsAssetUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/PhysicsAssetUtils.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UnrealEd.h"
#include "PhysicsAssetUtils.h"
#include "Developer/MeshUtilities/Public/MeshUtilities.h"
#include "Editor/UnrealEd/Private/ConvexDecompTool.h"
#include "MessageLog.h"
#include "PhysicsEngine/PhysicsAsset.h"
#include "PhysicsEngine/PhysicsConstraintTemplate.h"
#include "EngineLogs.h"
#include "PhysicsEngine/BodySetup.h"
void FPhysAssetCreateParams::Initialize()
{
MinBoneSize = 5.0f;
GeomType = EFG_Sphyl;
VertWeight = EVW_DominantWeight;
bAlignDownBone = true;
bCreateJoints = true;
bWalkPastSmall = true;
bBodyForAll = false;
AngularConstraintMode = ACM_Limited;
HullAccuracy = 0.5;
MaxHullVerts = 16;
}
namespace FPhysicsAssetUtils
{
static const float DefaultPrimSize = 15.0f;
static const float MinPrimSize = 0.5f;
/** Returns INDEX_NONE if no children in the visual asset or if more than one parent */
static int32 GetChildIndex(int32 BoneIndex, USkeletalMesh* SkelMesh, const TArray<FBoneVertInfo>& Infos)
{
int32 ChildIndex = INDEX_NONE;
for(int32 i=0; i<SkelMesh->RefSkeleton.GetNum(); i++)
{
int32 ParentIndex = SkelMesh->RefSkeleton.GetParentIndex(i);
if (ParentIndex == BoneIndex && Infos[i].Positions.Num() > 0)
{
if(ChildIndex != INDEX_NONE)
{
return INDEX_NONE; // if we already have a child, this bone has more than one so return INDEX_NONE.
}
else
{
ChildIndex = i;
}
}
}
return ChildIndex;
}
static float CalcBoneInfoLength(const FBoneVertInfo& Info)
{
FBox BoneBox(0);
for(int32 j=0; j<Info.Positions.Num(); j++)
{
BoneBox += Info.Positions[j];
}
if(BoneBox.IsValid)
{
FVector BoxExtent = BoneBox.GetExtent();
return BoxExtent.Size();
}
else
{
return 0.f;
}
}
/**
* For all bones below the give bone index, find each ones minimum box dimension, and return the maximum over those bones.
* This is used to decide if we should create physics for a bone even if its small, because there are good-sized bones below it.
*/
static float GetMaximalMinSizeBelow(int32 BoneIndex, USkeletalMesh* SkelMesh, const TArray<FBoneVertInfo>& Infos)
{
check( Infos.Num() == SkelMesh->RefSkeleton.GetNum() );
UE_LOG(LogPhysics, Log, TEXT("-------------------------------------------------"));
float MaximalMinBoxSize = 0.f;
// For all bones that are children of the supplied one...
for(int32 i=BoneIndex; i<SkelMesh->RefSkeleton.GetNum(); i++)
{
if( SkelMesh->RefSkeleton.BoneIsChildOf(i, BoneIndex) )
{
float MinBoneDim = CalcBoneInfoLength( Infos[i] );
UE_LOG(LogPhysics, Log, TEXT("Parent: %s Bone: %s Size: %f"), *SkelMesh->RefSkeleton.GetBoneName(BoneIndex).ToString(), *SkelMesh->RefSkeleton.GetBoneName(i).ToString(), MinBoneDim );
MaximalMinBoxSize = FMath::Max(MaximalMinBoxSize, MinBoneDim);
}
}
return MaximalMinBoxSize;
}
bool CreateFromSkeletalMeshInternal(UPhysicsAsset* PhysicsAsset, USkeletalMesh* SkelMesh, FPhysAssetCreateParams& Params)
{
IMeshUtilities& MeshUtilities = FModuleManager::Get().LoadModuleChecked<IMeshUtilities>("MeshUtilities");
// For each bone, get the vertices most firmly attached to it.
TArray<FBoneVertInfo> Infos;
MeshUtilities.CalcBoneVertInfos(SkelMesh, Infos, (Params.VertWeight == EVW_DominantWeight));
check(Infos.Num() == SkelMesh->RefSkeleton.GetNum());
bool bHitRoot = false;
// Iterate over each graphics bone creating body/joint.
for(int32 i=0; i<SkelMesh->RefSkeleton.GetNum(); i++)
{
FName BoneName = SkelMesh->RefSkeleton.GetBoneName(i);
int32 ParentIndex = INDEX_NONE;
FName ParentName = NAME_None;
int32 ParentBodyIndex = INDEX_NONE;
// If we have already found the 'physics root', we expect a parent.
if(bHitRoot)
{
ParentIndex = SkelMesh->RefSkeleton.GetParentIndex(i);
ParentName = SkelMesh->RefSkeleton.GetBoneName(ParentIndex);
ParentBodyIndex = PhysicsAsset->FindBodyIndex(ParentName);
// Ignore bones with no physical parent (except root)
if(ParentBodyIndex == INDEX_NONE)
{
continue;
}
}
// Determine if we should create a physics body for this bone
bool bMakeBone = false;
// If desired - make a body for EVERY bone
if(Params.bBodyForAll)
{
bMakeBone = true;
}
// If we have passed the physics 'root', and this bone has no physical parent, ignore it.
else if(!(bHitRoot && ParentBodyIndex == INDEX_NONE))
{
// If bone is big enough - create physics.
if(CalcBoneInfoLength(Infos[i]) > Params.MinBoneSize)
{
bMakeBone = true;
}
// If its too small, and we have set the option, see if it has any large children.
if(!bMakeBone && Params.bWalkPastSmall)
{
if(GetMaximalMinSizeBelow(i, SkelMesh, Infos) > Params.MinBoneSize)
{
bMakeBone = true;
}
}
}
if(bMakeBone)
{
// Go ahead and make this bone physical.
int32 NewBodyIndex = CreateNewBody(PhysicsAsset, BoneName);
UBodySetup* bs = PhysicsAsset->BodySetup[NewBodyIndex];
check(bs->BoneName == BoneName);
// Fill in collision info for this bone.
bool bSuccess = CreateCollisionFromBone(bs, SkelMesh, i, Params, Infos);
// If not root - create joint to parent body.
if(bHitRoot && Params.bCreateJoints && bSuccess)
{
int32 NewConstraintIndex = CreateNewConstraint(PhysicsAsset, BoneName);
UPhysicsConstraintTemplate* CS = PhysicsAsset->ConstraintSetup[NewConstraintIndex];
// Transform of child from parent is just child ref-pose entry.
FMatrix RelTM = SkelMesh->GetRefPoseMatrix(i);
// set angular constraint mode
CS->DefaultInstance.AngularSwing1Motion = Params.AngularConstraintMode;
CS->DefaultInstance.AngularSwing2Motion = Params.AngularConstraintMode;
CS->DefaultInstance.AngularTwistMotion = Params.AngularConstraintMode;
// Place joint at origin of child
CS->DefaultInstance.ConstraintBone1 = BoneName;
CS->DefaultInstance.Pos1 = FVector::ZeroVector;
CS->DefaultInstance.PriAxis1 = FVector(1, 0, 0);
CS->DefaultInstance.SecAxis1 = FVector(0, 1, 0);
CS->DefaultInstance.ConstraintBone2 = ParentName;
CS->DefaultInstance.Pos2 = RelTM.GetOrigin();
CS->DefaultInstance.PriAxis2 = RelTM.GetScaledAxis(EAxis::X);
CS->DefaultInstance.SecAxis2 = RelTM.GetScaledAxis(EAxis::Y);
// Disable collision between constrained bodies by default.
PhysicsAsset->DisableCollision(NewBodyIndex, ParentBodyIndex);
}
bHitRoot = true;
if (bSuccess == false)
{
DestroyBody(PhysicsAsset, NewBodyIndex);
}
}
}
return PhysicsAsset->BodySetup.Num() > 0;
}
bool CreateFromSkeletalMesh(UPhysicsAsset* PhysicsAsset, USkeletalMesh* SkelMesh, FPhysAssetCreateParams& Params, FText& OutErrorMessage)
{
PhysicsAsset->PreviewSkeletalMesh = SkelMesh;
bool bSuccess = CreateFromSkeletalMeshInternal(PhysicsAsset, SkelMesh, Params);
if (bSuccess)
{
// sets physics asset here now, so whoever creates
// new physics asset from skeletalmesh will set properly here
SkelMesh->PhysicsAsset = PhysicsAsset;
SkelMesh->MarkPackageDirty();
}
else
{
// try lower minimum bone size
Params.MinBoneSize = 1.f;
bSuccess = CreateFromSkeletalMeshInternal(PhysicsAsset, SkelMesh, Params);
if(bSuccess)
{
// sets physics asset here now, so whoever creates
// new physics asset from skeletalmesh will set properly here
SkelMesh->PhysicsAsset = PhysicsAsset;
SkelMesh->MarkPackageDirty();
}
else
{
OutErrorMessage = FText::Format(NSLOCTEXT("CreatePhysicsAsset", "CreatePhysicsAssetLinkFailed", "The bone size is too small to create Physics Asset '{0}' from Skeletal Mesh '{1}'. You will have to create physics asset manually."), FText::FromString(PhysicsAsset->GetName()), FText::FromString(SkelMesh->GetName()));
}
}
return bSuccess;
}
FMatrix ComputeCovarianceMatrix(const FBoneVertInfo& VertInfo)
{
if (VertInfo.Positions.Num() == 0)
{
return FMatrix::Identity;
}
const TArray<FVector> & Positions = VertInfo.Positions;
//get average
const float N = Positions.Num();
FVector U = FVector::ZeroVector;
for (int32 i = 0; i < N; ++i)
{
U += Positions[i];
}
U = U / N;
//compute error terms
TArray<FVector> Errors;
Errors.AddUninitialized(N);
for (int32 i = 0; i < N; ++i)
{
Errors[i] = Positions[i] - U;
}
FMatrix Covariance = FMatrix::Identity;
for (int32 j = 0; j < 3; ++j)
{
FVector Axis = FVector::ZeroVector;
float* Cj = &Axis.X;
for (int32 k = 0; k < 3; ++k)
{
float Cjk = 0.f;
for (int32 i = 0; i < N; ++i)
{
const float* error = &Errors[i].X;
Cj[k] += error[j] * error[k];
}
Cj[k] /= N;
}
Covariance.SetAxis(j, Axis);
}
return Covariance;
}
FVector ComputeEigenVector(const FMatrix& A)
{
//using the power method: this is ok because we only need the dominate eigenvector and speed is not critical: http://en.wikipedia.org/wiki/Power_iteration
FVector Bk = FVector(0, 0, 1);
for (int32 i = 0; i < 32; ++i)
{
float Length = Bk.Size();
if ( Length > 0.f )
{
Bk = A.TransformVector(Bk) / Length;
}
}
return Bk.GetSafeNormal();
}
bool CreateCollisionFromBone( UBodySetup* bs, USkeletalMesh* skelMesh, int32 BoneIndex, FPhysAssetCreateParams& Params, const TArray<FBoneVertInfo>& Infos )
{
#if WITH_EDITOR
if (Params.GeomType != EFG_MultiConvexHull) //multi convex hull can fail so wait to clear it
{
// Empty any existing collision.
bs->RemoveSimpleCollision();
}
#endif // WITH_EDITOR
// Calculate orientation of to use for collision primitive.
FMatrix ElemTM;
bool ComputeFromVerts = false;
if(Params.bAlignDownBone)
{
int32 ChildIndex = GetChildIndex(BoneIndex, skelMesh, Infos);
if(ChildIndex != INDEX_NONE)
{
// Get position of child relative to parent.
FMatrix RelTM = skelMesh->GetRefPoseMatrix(ChildIndex);
FVector ChildPos = RelTM.GetOrigin();
// Check that child is not on top of parent. If it is - we can't make an orientation
if(ChildPos.SizeSquared() > FMath::Square(KINDA_SMALL_NUMBER))
{
// ZAxis for collision geometry lies down axis to child bone.
FVector ZAxis = ChildPos.GetSafeNormal();
// Then we pick X and Y randomly.
// JTODO: Should project all the vertices onto ZAxis plane and fit a bounding box using calipers or something...
FVector XAxis, YAxis;
ZAxis.FindBestAxisVectors( YAxis, XAxis );
ElemTM = FMatrix( XAxis, YAxis, ZAxis, FVector(0) );
}
else
{
ElemTM = FMatrix::Identity;
ComputeFromVerts = true;
}
}
else
{
ElemTM = FMatrix::Identity;
ComputeFromVerts = true;
}
}
else
{
ElemTM = FMatrix::Identity;
}
if (ComputeFromVerts)
{
// Compute covariance matrix for verts of this bone
// Then use axis with largest variance for orienting bone box
const FMatrix CovarianceMatrix = ComputeCovarianceMatrix(Infos[BoneIndex]);
FVector ZAxis = ComputeEigenVector(CovarianceMatrix);
FVector XAxis, YAxis;
ZAxis.FindBestAxisVectors(YAxis, XAxis);
ElemTM = FMatrix(XAxis, YAxis, ZAxis, FVector::ZeroVector);
}
// convert to FTransform now
// Matrix inverse doesn't handle well when DET == 0, so
// convert to FTransform and use that data
FTransform ElementTransform(ElemTM);
// Get the (Unreal scale) bounding box for this bone using the rotation.
const FBoneVertInfo* BoneInfo = &Infos[BoneIndex];
FBox BoneBox(0);
for(int32 j=0; j<BoneInfo->Positions.Num(); j++)
{
BoneBox += ElementTransform.InverseTransformPosition( BoneInfo->Positions[j] );
}
FVector BoxCenter(0,0,0), BoxExtent(0,0,0);
FBox TransformedBox = BoneBox;
if( BoneBox.IsValid )
{
// make sure to apply scale to the box size
FMatrix BoneMatrix = skelMesh->GetComposedRefPoseMatrix(BoneIndex);
TransformedBox = BoneBox.TransformBy(FTransform(BoneMatrix));
BoneBox.GetCenterAndExtents(BoxCenter, BoxExtent);
}
float MinRad = TransformedBox.GetExtent().GetMin();
float MinAllowedSize = MinPrimSize;
// If the primitive is going to be too small - just use some default numbers and let the user tweak.
if( MinRad < MinAllowedSize )
{
// change min allowed size to be min, not DefaultPrimSize
BoxExtent = FVector(MinAllowedSize, MinAllowedSize, MinAllowedSize);
}
FVector BoneOrigin = ElementTransform.TransformPosition( BoxCenter );
ElementTransform.SetTranslation( BoneOrigin );
if(Params.GeomType == EFG_Box)
{
// Add a new box geometry to this body the size of the bounding box.
FKBoxElem BoxElem;
BoxElem.SetTransform(ElementTransform);
BoxElem.X = BoxExtent.X * 2.0f * 1.01f; // Side Lengths (add 1% to avoid graphics glitches)
BoxElem.Y = BoxExtent.Y * 2.0f * 1.01f;
BoxElem.Z = BoxExtent.Z * 2.0f * 1.01f;
bs->AggGeom.BoxElems.Add(BoxElem);
}
else if (Params.GeomType == EFG_Sphere)
{
FKSphereElem SphereElem;
SphereElem.Center = ElementTransform.GetTranslation();
SphereElem.Radius = BoxExtent.GetMax() * 1.01f;
bs->AggGeom.SphereElems.Add(SphereElem);
}
// Deal with creating a single convex hull
else if (Params.GeomType == EFG_SingleConvexHull)
{
if (BoneInfo->Positions.Num())
{
FKConvexElem ConvexElem;
// Add all of the vertices for this bone to the convex element
for( int32 index=0; index<BoneInfo->Positions.Num(); index++ )
{
ConvexElem.VertexData.Add(BoneInfo->Positions[index]);
}
ConvexElem.UpdateElemBox();
bs->AggGeom.ConvexElems.Add(ConvexElem);
}else
{
FMessageLog EditorErrors("EditorErrors");
EditorErrors.Warning(NSLOCTEXT("PhysicsAssetUtils", "ConvexNoPositions", "Unable to create a convex hull for the given bone as there are no vertices associated with the bone."));
EditorErrors.Open();
return false;
}
}
else if (Params.GeomType == EFG_MultiConvexHull)
{
// Just feed in all of the verts which are affected by this bone
int32 ChunkIndex;
int32 VertIndex;
bool bSoftVertex;
bool bHasExtraInfluences;
// Storage for the hull generation
TArray<uint32> Indices;
TArray<FVector> Verts;
TMap<uint32, uint32> IndexMap;
// Get the static LOD from the skeletal mesh and loop through the chunks
FStaticLODModel& LODModel = skelMesh->GetSourceModel();
TArray<uint32> indexBufferInOrder;
LODModel.MultiSizeIndexContainer.GetIndexBuffer( indexBufferInOrder );
uint32 indexBufferSize = indexBufferInOrder.Num();
uint32 currentIndex = 0;
// Add all of the verts and indices to a list I can loop over
for ( uint32 index = 0; index < indexBufferSize; index++ )
{
LODModel.GetChunkAndSkinType(indexBufferInOrder[index], ChunkIndex, VertIndex, bSoftVertex, bHasExtraInfluences);
const FSkelMeshChunk& Chunk = LODModel.Chunks[ChunkIndex];
if ( bSoftVertex )
{
// We dont want to support soft verts, only rigid
FMessageLog EditorErrors("EditorErrors");
EditorErrors.Warning(NSLOCTEXT("PhysicsAssetUtils", "MultiConvexSoft", "Unable to create physics asset with a multi convex hull due to the presence of soft vertices."));
EditorErrors.Open();
return false;
}
// Using the same code in GetSkinnedVertexPosition
const FRigidSkinVertex& RigidVert = Chunk.RigidVertices[VertIndex];
const int LocalBoneIndex = Chunk.BoneMap[RigidVert.Bone];
const FVector& VertPosition = skelMesh->RefBasesInvMatrix[LocalBoneIndex].TransformPosition(RigidVert.Position);
if ( LocalBoneIndex == BoneIndex )
{
if ( IndexMap.Contains( VertIndex ) )
{
Indices.Add( *IndexMap.Find( VertIndex ) );
}
else
{
Indices.Add( currentIndex );
IndexMap.Add( VertIndex, currentIndex++ );
Verts.Add( VertPosition );
}
}
}
if ( Params.GeomType == EFG_MultiConvexHull )
{
#if WITH_EDITOR
bs->RemoveSimpleCollision();
#endif
// Create the convex hull from the data we got from the skeletal mesh
DecomposeMeshToHulls( bs, Verts, Indices, Params.HullAccuracy, Params.MaxHullVerts );
}
else
{
//Support triangle mesh soon
return false;
}
}
else
{
FKSphylElem SphylElem;
SphylElem.SetTransform(ElementTransform);
SphylElem.Radius = FMath::Max(BoxExtent.X, BoxExtent.Y) * 1.01f;
SphylElem.Length = BoxExtent.Z * 1.01f;
bs->AggGeom.SphylElems.Add(SphylElem);
}
return true;
}
void WeldBodies(UPhysicsAsset* PhysAsset, int32 BaseBodyIndex, int32 AddBodyIndex, USkeletalMeshComponent* SkelComp)
{
if(BaseBodyIndex == INDEX_NONE || AddBodyIndex == INDEX_NONE)
return;
if (SkelComp == NULL || SkelComp->SkeletalMesh == NULL)
{
return;
}
UBodySetup* Body1 = PhysAsset->BodySetup[BaseBodyIndex];
int32 Bone1Index = SkelComp->SkeletalMesh->RefSkeleton.FindBoneIndex(Body1->BoneName);
check(Bone1Index != INDEX_NONE);
FTransform Bone1TM = SkelComp->GetBoneTransform(Bone1Index);
Bone1TM.RemoveScaling();
UBodySetup* Body2 = PhysAsset->BodySetup[AddBodyIndex];
int32 Bone2Index = SkelComp->SkeletalMesh->RefSkeleton.FindBoneIndex(Body2->BoneName);
check(Bone2Index != INDEX_NONE);
FTransform Bone2TM = SkelComp->GetBoneTransform(Bone2Index);
Bone2TM.RemoveScaling();
FTransform Bone2ToBone1TM = Bone2TM.GetRelativeTransform(Bone1TM);
// First copy all collision info over.
for(int32 i=0; i<Body2->AggGeom.SphereElems.Num(); i++)
{
int32 NewPrimIndex = Body1->AggGeom.SphereElems.Add( Body2->AggGeom.SphereElems[i] );
Body1->AggGeom.SphereElems[NewPrimIndex].Center = Bone2ToBone1TM.TransformPosition( Body2->AggGeom.SphereElems[i].Center ); // Make transform relative to body 1 instead of body 2
}
for(int32 i=0; i<Body2->AggGeom.BoxElems.Num(); i++)
{
int32 NewPrimIndex = Body1->AggGeom.BoxElems.Add( Body2->AggGeom.BoxElems[i] );
Body1->AggGeom.BoxElems[NewPrimIndex].SetTransform( Body2->AggGeom.BoxElems[i].GetTransform() * Bone2ToBone1TM );
}
for(int32 i=0; i<Body2->AggGeom.SphylElems.Num(); i++)
{
int32 NewPrimIndex = Body1->AggGeom.SphylElems.Add( Body2->AggGeom.SphylElems[i] );
Body1->AggGeom.SphylElems[NewPrimIndex].SetTransform( Body2->AggGeom.SphylElems[i].GetTransform() * Bone2ToBone1TM );
}
for(int32 i=0; i<Body2->AggGeom.ConvexElems.Num(); i++)
{
// No matrix here- we transform all the vertices into the new ref frame instead.
int32 NewPrimIndex = Body1->AggGeom.ConvexElems.Add( Body2->AggGeom.ConvexElems[i] );
FKConvexElem* cElem= &Body1->AggGeom.ConvexElems[NewPrimIndex];
for(int32 j=0; j<cElem->VertexData.Num(); j++)
{
cElem->VertexData[j] = Bone2ToBone1TM.TransformPosition( cElem->VertexData[j] );
}
// Update face data.
cElem->UpdateElemBox();
}
// We need to update the collision disable table to shift any pairs that included body2 to include body1 instead.
// We remove any pairs that include body2 & body1.
for(int32 i=0; i<PhysAsset->BodySetup.Num(); i++)
{
if(i == AddBodyIndex)
continue;
FRigidBodyIndexPair Key(i, AddBodyIndex);
if( PhysAsset->CollisionDisableTable.Find(Key) )
{
PhysAsset->CollisionDisableTable.Remove(Key);
// Only re-add pair if its not between 'base' and 'add' bodies.
if(i != BaseBodyIndex)
{
FRigidBodyIndexPair NewKey(i, BaseBodyIndex);
PhysAsset->CollisionDisableTable.Add(NewKey, 0);
}
}
}
// Make a sensible guess for the other flags
ECollisionEnabled::Type NewCollisionEnabled = FMath::Min(Body1->DefaultInstance.GetCollisionEnabled(), Body2->DefaultInstance.GetCollisionEnabled());
Body1->DefaultInstance.SetCollisionEnabled(NewCollisionEnabled);
// if different
if (Body1->PhysicsType != Body2->PhysicsType)
{
// i don't think this is necessarily good, but I think better than default
Body1->PhysicsType = FMath::Max(Body1->PhysicsType, Body2->PhysicsType);
}
// Then deal with any constraints.
TArray<int32> Body2Constraints;
PhysAsset->BodyFindConstraints(AddBodyIndex, Body2Constraints);
while( Body2Constraints.Num() > 0 )
{
int32 ConstraintIndex = Body2Constraints[0];
FConstraintInstance& Instance = PhysAsset->ConstraintSetup[ConstraintIndex]->DefaultInstance;
FName OtherBodyName;
if( Instance.ConstraintBone1 == Body2->BoneName )
OtherBodyName = Instance.ConstraintBone2;
else
OtherBodyName = Instance.ConstraintBone1;
// If this is a constraint between the two bodies we are welding, we just destroy it.
if(OtherBodyName == Body1->BoneName)
{
DestroyConstraint(PhysAsset, ConstraintIndex);
}
else // Otherwise, we reconnect it to body1 (the 'base' body) instead of body2 (the 'weldee').
{
if(Instance.ConstraintBone2 == Body2->BoneName)
{
Instance.ConstraintBone2 = Body1->BoneName;
FTransform ConFrame = Instance.GetRefFrame(EConstraintFrame::Frame2);
Instance.SetRefFrame(EConstraintFrame::Frame2, ConFrame * FTransform(Bone2ToBone1TM));
}
else
{
Instance.ConstraintBone1 = Body1->BoneName;
FTransform ConFrame = Instance.GetRefFrame(EConstraintFrame::Frame1);
Instance.SetRefFrame(EConstraintFrame::Frame1, ConFrame * FTransform(Bone2ToBone1TM));
}
}
// See if we have any more constraints to body2.
PhysAsset->BodyFindConstraints(AddBodyIndex, Body2Constraints);
}
// Finally remove the body
DestroyBody(PhysAsset, AddBodyIndex);
}
int32 CreateNewConstraint(UPhysicsAsset* PhysAsset, FName InConstraintName, UPhysicsConstraintTemplate* InConstraintSetup)
{
// constraintClass must be a subclass of UPhysicsConstraintTemplate
int32 ConstraintIndex = PhysAsset->FindConstraintIndex(InConstraintName);
if(ConstraintIndex != INDEX_NONE)
{
return ConstraintIndex;
}
UPhysicsConstraintTemplate* NewConstraintSetup = NewObject<UPhysicsConstraintTemplate>(PhysAsset, NAME_None, RF_Transactional);
if(InConstraintSetup)
{
NewConstraintSetup->DefaultInstance.CopyConstraintParamsFrom( &InConstraintSetup->DefaultInstance );
}
int32 ConstraintSetupIndex = PhysAsset->ConstraintSetup.Add( NewConstraintSetup );
NewConstraintSetup->DefaultInstance.JointName = InConstraintName;
return ConstraintSetupIndex;
}
void DestroyConstraint(UPhysicsAsset* PhysAsset, int32 ConstraintIndex)
{
check(PhysAsset);
PhysAsset->ConstraintSetup.RemoveAt(ConstraintIndex);
}
int32 CreateNewBody(UPhysicsAsset* PhysAsset, FName InBodyName)
{
check(PhysAsset);
int32 BodyIndex = PhysAsset->FindBodyIndex(InBodyName);
if(BodyIndex != INDEX_NONE)
{
return BodyIndex; // if we already have one for this name - just return that.
}
UBodySetup* NewBodySetup = NewObject<UBodySetup>(PhysAsset, NAME_None, RF_Transactional);
// make default to be use complex as simple
NewBodySetup->CollisionTraceFlag = CTF_UseSimpleAsComplex;
// newly created bodies default to simulating
NewBodySetup->PhysicsType = PhysType_Default;
int32 BodySetupIndex = PhysAsset->BodySetup.Add( NewBodySetup );
NewBodySetup->BoneName = InBodyName;
PhysAsset->UpdateBodySetupIndexMap();
PhysAsset->UpdateBoundsBodiesArray();
// Return index of new body.
return BodySetupIndex;
}
void DestroyBody(UPhysicsAsset* PhysAsset, int32 bodyIndex)
{
check(PhysAsset);
// First we must correct the CollisionDisableTable.
// All elements which refer to bodyIndex are removed.
// All elements which refer to a body with index >bodyIndex are adjusted.
TMap<FRigidBodyIndexPair,bool> NewCDT;
for(int32 i=1; i<PhysAsset->BodySetup.Num(); i++)
{
for(int32 j=0; j<i; j++)
{
FRigidBodyIndexPair Key(j,i);
// If there was an entry for this pair, and it doesn't refer to the removed body, we need to add it to the new CDT.
if( PhysAsset->CollisionDisableTable.Find(Key) )
{
if(i != bodyIndex && j != bodyIndex)
{
int32 NewI = (i > bodyIndex) ? i-1 : i;
int32 NewJ = (j > bodyIndex) ? j-1 : j;
FRigidBodyIndexPair NewKey(NewJ, NewI);
NewCDT.Add(NewKey, 0);
}
}
}
}
PhysAsset->CollisionDisableTable = NewCDT;
// Now remove any constraints that were attached to this body.
// This is a bit yuck and slow...
TArray<int32> Constraints;
PhysAsset->BodyFindConstraints(bodyIndex, Constraints);
while(Constraints.Num() > 0)
{
DestroyConstraint( PhysAsset, Constraints[0] );
PhysAsset->BodyFindConstraints(bodyIndex, Constraints);
}
// Remove pointer from array. Actual objects will be garbage collected.
PhysAsset->BodySetup.RemoveAt(bodyIndex);
PhysAsset->UpdateBodySetupIndexMap();
// Update body indices.
PhysAsset->UpdateBoundsBodiesArray();
}
}; // namespace FPhysicsAssetUtils
| 30.391688 | 318 | 0.725581 | armroyce |
b004658140899e7ae44fd85eefc013fb862fe3d9 | 1,673 | cpp | C++ | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 7 | 2018-03-25T23:45:36.000Z | 2020-02-13T13:55:41.000Z | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 1 | 2022-01-21T00:44:07.000Z | 2022-01-21T00:44:07.000Z | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 4 | 2018-03-27T19:36:00.000Z | 2022-01-10T22:24:06.000Z | #include "CipherTable.h"
#include "Functions.h"
CipherTable::CipherTable() : m_(0), n_(0), owner_(true) {}
CipherTable::CipherTable(string& ciphers, long m, ElGammal* elgammal) : m_(m), owner_(true) {
Functions::parse_ciphers(ciphers, m, C_, elgammal);
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::CipherTable(vector<vector<Cipher_elg>* >* ciphers, long m): m_(m), owner_(false) {
C_ = *ciphers;
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::CipherTable(vector<vector<Cipher_elg>* >* ciphers, long m, const bool owner):
m_(m), owner_(owner){
C_ = *ciphers;
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::~CipherTable() {
if (owner_) {
for (unsigned int i = 0; i < C_.size(); i++) {
delete C_.at(i);
}
for (unsigned int i = 0; i < elements_.size(); i++) {
delete elements_.at(i);
}
}
}
vector<vector<Cipher_elg>* >* CipherTable::getCMatrix() {
return &C_;
}
vector<vector<Mod_p>* >* CipherTable::getElementsMatrix() {
return &elements_;
}
string CipherTable::getCipher(int i, int j) {
stringstream cipher_str;
cipher_str << C_.at(i)->at(j);
return cipher_str.str();
}
Cipher_elg& CipherTable::get_elg_cipher(int i, int j) {
return C_.at(i)->at(j);
}
string CipherTable::getElement(int i, int j) {
stringstream cipher_str;
cipher_str << elements_.at(i)->at(j);
return cipher_str.str();
}
string CipherTable::encode_all_ciphers() {
return Functions::ciphers_to_str(&C_);
}
int CipherTable::rows() {
return m_;
}
int CipherTable::cols() {
return n_;
}
void CipherTable::set_dimensions(int m, int n) {
m_ = m;
n_ = n;
}
| 18.797753 | 95 | 0.632397 | fcifuentesq |
b00cb0010d1018cecccfb1d1bf690b0215f103c4 | 1,168 | cpp | C++ | DirectX11 Engine 2019/UI/Primitives/UIRectangle.cpp | FirowMD/Luna-Engine | 4011a43df48ca85f6d8f8657709471da02bd8301 | [
"MIT"
] | 2 | 2021-07-28T23:08:29.000Z | 2021-09-14T19:32:36.000Z | DirectX11 Engine 2019/UI/Primitives/UIRectangle.cpp | FirowMD/Luna-Engine | 4011a43df48ca85f6d8f8657709471da02bd8301 | [
"MIT"
] | null | null | null | DirectX11 Engine 2019/UI/Primitives/UIRectangle.cpp | FirowMD/Luna-Engine | 4011a43df48ca85f6d8f8657709471da02bd8301 | [
"MIT"
] | null | null | null | #include "pc.h"
#include "UIRectangle.h"
UIRectangle::UIRectangle(float2 TopLeft, float2 BottomRight) {
UIVertex v0{}, v1{}, v2{};
float z = (float)gLayerID;
v0.Color = gColor;
v1.Color = gColor;
v2.Color = gColor;
// Tri 1
v0.Position = float3(TopLeft.x, TopLeft.y, z);
v1.Position = float3(BottomRight.x, TopLeft.y, z);
v2.Position = float3(TopLeft.x, BottomRight.y, z);
AddTriangle(v0, v1, v2);
// Tri 2
v0.Position = float3(BottomRight.x, TopLeft.y, z);
v1.Position = float3(BottomRight.x, BottomRight.y, z);
v2.Position = float3(TopLeft.x, BottomRight.y, z);
AddTriangle(v0, v1, v2);
}
UIRectangle::UIRectangle(float x0, float y0, float x1, float y1) {
UIVertex v0{}, v1{}, v2{};
float z = (float)gLayerID;
v0.Color = gColor;
v1.Color = gColor;
v2.Color = gColor;
// Tri 1
v0.Position = float3(x0, y0, z);
v1.Position = float3(x1, y0, z);
v2.Position = float3(x0, y1, z);
AddTriangle(v0, v1, v2);
// Tri 2
v0.Position = float3(x1, y0, z);
v1.Position = float3(x1, y1, z);
v2.Position = float3(x0, y1, z);
AddTriangle(v0, v1, v2);
}
| 24.333333 | 66 | 0.605308 | FirowMD |
b016be99a66187cb8412fce6d9e6da14afaf806a | 318 | hh | C++ | source/geometry/KBGeometry.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2021-05-24T19:43:30.000Z | 2022-01-06T21:03:23.000Z | source/geometry/KBGeometry.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 4 | 2020-05-04T15:52:26.000Z | 2021-09-13T10:51:03.000Z | source/geometry/KBGeometry.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2020-06-14T10:53:58.000Z | 2022-01-06T21:03:30.000Z | #ifndef KBGEOMETRY_HH
#define KBGEOMETRY_HH
#include "KBContainer.hh"
class KBGeometry
{
protected:
Double_t fRMS = -1;
public:
KBGeometry() {}
virtual ~KBGeometry() {}
void SetRMS(Double_t val) { fRMS = val; }
Double_t GetRMS() const { return fRMS; }
ClassDef(KBGeometry, 1)
};
#endif
| 14.454545 | 45 | 0.657233 | ggfdsa10 |
b018d6335bb1a08c5c808c21859adf89cac603f5 | 7,133 | cpp | C++ | src/Flownodes/CFlowCUIOutputEntityNode.cpp | CoherentLabs/CoherentUI_CryEngine3 | 44b30e41e37a92ee16edbc6b738f996cfb3bd67e | [
"BSD-2-Clause"
] | 12 | 2015-04-04T17:21:06.000Z | 2021-05-11T16:03:36.000Z | src/Flownodes/CFlowCUIOutputEntityNode.cpp | CoherentLabs/CoherentUI_CryEngine3 | 44b30e41e37a92ee16edbc6b738f996cfb3bd67e | [
"BSD-2-Clause"
] | 1 | 2015-06-23T21:24:38.000Z | 2015-06-25T03:42:39.000Z | src/Flownodes/CFlowCUIOutputEntityNode.cpp | CoherentLabs/CoherentUI_CryEngine3 | 44b30e41e37a92ee16edbc6b738f996cfb3bd67e | [
"BSD-2-Clause"
] | 5 | 2015-02-11T22:43:43.000Z | 2017-12-03T00:38:46.000Z | #include <StdAfx.h>
#include <Nodes/G2FlowBaseNode.h>
#include <CPluginCoherentUI.h>
#include <Coherent/UI/View.h>
#include "CoherentViewListener.h"
#include "CoherentUISystem.h"
#include "ViewConfig.h"
namespace CoherentUIPlugin
{
class CFlowCUIOutputEntityNode : public CFlowBaseNode<eNCT_Instanced>
{
private:
CCoherentViewListener* m_pViewListener;
IEntity* m_pEntity;
ViewConfig* m_pViewConfig;
bool m_bViewNeedsUpdate;
enum EInputPorts
{
EIP_ACTIVATE = 0,
EIP_URL,
EIP_WIDTH,
EIP_HEIGHT,
EIP_TRANSPARENT,
EIP_CLICKABLE,
EIP_MESH,
EIP_SHARED_MEMORY,
};
enum EOutputPorts
{
EOP_VIEWID = 0
};
#define INITIALIZE_OUTPUTS(x) \
ActivateOutput<int>(x, EOP_VIEWID, -1);
public:
CFlowCUIOutputEntityNode( SActivationInfo* pActInfo )
{
m_pViewListener = NULL;
m_pEntity = NULL;
m_pViewConfig = new ViewConfig();
m_bViewNeedsUpdate = false;
}
virtual ~CFlowCUIOutputEntityNode()
{
if ( m_pViewListener )
{
gCoherentUISystem->DeleteView( m_pViewListener );
}
if ( m_pViewConfig )
{
delete m_pViewConfig;
}
}
virtual IFlowNodePtr Clone( SActivationInfo* pActInfo )
{
return new CFlowCUIOutputEntityNode( pActInfo );
}
virtual void GetMemoryUsage( ICrySizer* s ) const
{
s->Add( *this );
}
void Serialize( SActivationInfo* pActInfo, TSerialize ser )
{
}
virtual void GetConfiguration( SFlowNodeConfig& config )
{
static const SInputPortConfig inputs[] =
{
InputPortConfig_Void( "Activate", _HELP( "Activate View" ) ),
InputPortConfig<string>( "Url", "", _HELP( "Initial URL" ) ),
InputPortConfig<int>( "Width", 0, _HELP( "Width" ) ),
InputPortConfig<int>( "Height", 0, _HELP( "Height" ) ),
InputPortConfig<bool>( "Transparent", false, _HELP( "Is Transparent" ) ),
InputPortConfig<bool>( "Clickable", true, _HELP( "Is Clickable" ) ),
InputPortConfig<string>( "Mesh", "", _HELP( "Collision Mesh" ) ),
InputPortConfig<bool>( "SharedMemory", true, _HELP( "Uses Shared Memory" ) ),
InputPortConfig_AnyType( NULL ),
};
static const SOutputPortConfig outputs[] =
{
OutputPortConfig<int>( "ViewID", _HELP( "ID for Further Use" ), "nViewID" ),
OutputPortConfig_AnyType( NULL ),
};
config.pInputPorts = inputs;
config.pOutputPorts = outputs;
config.sDescription = _HELP( PLUGIN_CONSOLE_PREFIX "CoherentUI on entity" );
config.nFlags |= EFLN_TARGET_ENTITY;
config.SetCategory( EFLN_APPROVED );
}
virtual void ProcessEvent( EFlowEvent evt, SActivationInfo* pActInfo )
{
switch ( evt )
{
case eFE_Suspend:
break;
case eFE_Resume:
break;
case eFE_Initialize:
INITIALIZE_OUTPUTS( pActInfo );
break;
case eFE_SetEntityId:
m_pEntity = pActInfo->pEntity;
break;
case eFE_Activate:
if ( IsPortActive( pActInfo, EIP_ACTIVATE ) && m_pEntity )
{
// get the view definition
std::string sUrl = GetPortString( pActInfo, EIP_URL );
std::wstring sUrlW( sUrl.length(), L' ' );
sUrlW.assign( sUrl.begin(), sUrl.end() );
Coherent::UI::ViewInfo info;
info.Width = GetPortInt( pActInfo, EIP_WIDTH );
info.Height = GetPortInt( pActInfo, EIP_HEIGHT );
info.IsTransparent = GetPortBool( pActInfo, EIP_TRANSPARENT );
info.UsesSharedMemory = GetPortBool( pActInfo, EIP_SHARED_MEMORY );
info.SupportClickThrough = GetPortBool( pActInfo, EIP_CLICKABLE );
m_pViewConfig->ViewInfo = info;
m_pViewConfig->Url = sUrlW;
m_pViewConfig->Entity = m_pEntity;
m_pViewConfig->CollisionMesh = GetPortString( pActInfo, EIP_MESH );
// indicate that we have to create/update the view later
m_bViewNeedsUpdate = true;
pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, true );
}
break;
case eFE_Update:
// make sure the view is created/updated, after the system is ready
if ( m_bViewNeedsUpdate && gCoherentUISystem->IsReady() )
{
if ( m_pViewListener )
{
gCoherentUISystem->DeleteView( m_pViewListener );
}
m_pViewListener = gCoherentUISystem->CreateView( m_pViewConfig );
m_bViewNeedsUpdate = false;
}
// set the view id output after the view is available
if ( m_pViewListener )
{
Coherent::UI::View* view = m_pViewListener->GetView();
if ( view )
{
ActivateOutput<int>( pActInfo, EOP_VIEWID, view->GetId() );
// updates are not necessary until next initialization
pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, false );
}
}
break;
}
}
};
}
REGISTER_FLOW_NODE_EX( "CoherentUI_Plugin:OutputEntity", CoherentUIPlugin::CFlowCUIOutputEntityNode, CFlowCUIOutputEntityNode ); | 40.299435 | 147 | 0.451423 | CoherentLabs |
b0195ddb8638f6b42cd5717fad6555f2992e531f | 3,861 | cpp | C++ | 600-700/608.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 600-700/608.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 600-700/608.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null |
const int maxp = 2000000;
#include <pe>
const int64 mod = 1000000000+7;
const int F = 200;
const int64 N = 1000000000000;
const int64 sqrtN = sqrt(N);
int L;
int L1;
int64 invs[1000000 + 100];
int pp[F+1];
int pp2[F+1];
static_assert(sqrtN*sqrtN == N);
int64 ans;
int64 scon[1000000+10];
int64 lcon[1000000+10];
const int TC = 30;
int64 sdata[TC][1000000+10];
int64 ldata[TC][1000000+10];
void dfs0(int limit, int64 value, int64 x, int64* scon, int64* lcon, int id)
{
if (value > 1 || value == 1 && id == 0)
{
int64 t = N / value;
if (value <= t)
{
scon[value] = add_mod(scon[value], x, mod);
}
else
{
lcon[t] = add_mod(lcon[t], x, mod);
}
}
for (int i = L; i < limit; ++i)
{
if (value == 1) if (i % TC != id) continue;
const int64 p = plist[i];
int c = 1;
int64 v = p;
if (p > N / value) break;
while (v <= N / value)
{
dfs0(i, v * value, x * (c+1) % mod, scon, lcon, id);
if (v > N / value / p)
{
break;
}
v *= p;
++c;
}
}
}
void dfs1(int limit, int64 value, int64 x)
{
{
int64 other = N / value;
if (other <= sqrtN)
{
ans = add_mod(ans, scon[other] * x % mod, mod);
}
else
{
ans = add_mod(ans, lcon[N/other] * x % mod, mod);
}
}
for (int i = 0; i < limit; ++i)
{
if (value == 1) dbg(i);
const int64 p = plist[i];
int c = 1;
int64 v = p;
if (p > N / value) break;
while (v <= N / value)
{
int64 a = pp[p];
int64 b = a + c + 1;
b = b * (b + 1) / 2 % mod;
int64 bb = c;
bb = bb * (bb + 1) / 2 % mod;
b = sub_mod(b, bb, mod);
dfs1(i, v * value, x * invs[pp2[p]] % mod * b % mod);
if (v > N / value / p)
{
break;
}
v *= p;
++c;
}
}
}
int main()
{
init_primes();
init_inv(invs, 1000000, mod);
vector<int64> scnt;
vector<int64> lcnt;
tie(scnt, lcnt) = prime_pi(N);
while (plist[L] <= F) ++L;
while (plist[L1] <= sqrtN) ++L1;
{
BEGIN_PARALLEL
FROM 0 TO TC-1 EACH_BLOCK_IS 1 CACHE ""
THREADS TC
MAP
{
dfs0(L1, 1, 1, sdata[key], ldata[key], key);
}
REDUCE
{
return 0;
}
END_PARALLEL;
for (int i = 0; i < TC; ++i)
for (int j = 0; j <= sqrtN; ++j)
scon[j] = add_mod(scon[j], sdata[i][j], mod),
lcon[j] = add_mod(lcon[j], ldata[i][j], mod);
}
{
for (int i = 2; i <= sqrtN; ++i)
{
scon[i] = add_mod(scon[i], scon[i-1], mod);
}
lcon[sqrtN] = scon[sqrtN];
for (int i = sqrtN - 1; i >= 1; --i)
{
lcon[i] = add_mod(lcon[i], lcon[i+1], mod);
}
for (int64 i = 1; i < sqrtN; ++i)
for (int64 j = 1; j * sqrtN < N / i; ++j)
{
int64 cnt = lcnt[i*j];
cnt = sub_mod(cnt%mod, scnt[sqrtN]%mod, mod);
cnt = cnt * 2 % mod;
int64 t = cnt * sub_mod(scon[j], scon[j-1], mod) % mod;
lcon[i] = add_mod(lcon[i], t, mod);
}
}
int64 value = 1;
for (int i = 0; i < L; ++i)
{
int64 total = 0;
for (int64 j = plist[i]; j <= F; j *= plist[i])
{
total += F / j;
}
pp[plist[i]] = total;
pp2[plist[i]] = (total + 1 + 1) * (total + 1) / 2;
value = value * pp2[plist[i]] % mod;
}
dfs1(L, 1, value);
dbg(ans);
return 0;
}
Update:
@hk Rating removed.
Update 07/03/2017:
Instead of a hacky approach as I mentioned above, I found that it is pretty easy to obtain an approach without advanced analysis skills.
Replace d by k1 and replace k by k2, D(m,n)=∑k1|m∑nk2σ0(k1k2). Since each factor of ab can be written in the form of pbq where p|a and q|b, we have
| 21.813559 | 148 | 0.471121 | Thomaw |
b01dcb8e9ef1c33e8e21aa7cb0d155177875ee0e | 933 | cpp | C++ | WLMOJ/lcc18c3s2.cpp | starfy84/Competitive-Programming | 6e024caaf1568723e4eebab208baf366c57830e1 | [
"Unlicense"
] | null | null | null | WLMOJ/lcc18c3s2.cpp | starfy84/Competitive-Programming | 6e024caaf1568723e4eebab208baf366c57830e1 | [
"Unlicense"
] | null | null | null | WLMOJ/lcc18c3s2.cpp | starfy84/Competitive-Programming | 6e024caaf1568723e4eebab208baf366c57830e1 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
bool comp(const pii &a, const pii &b){
if(a.first == b.first)
return a.second < b.second;
else
return a.first < b.first;
}
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int i, mmax =0,mmin = INT_MAX;
vector<pii> times;
cin >> i;
for (int x=0; x < i; x++){
int a,b;
cin >> a >> b;
times.push_back({a,b});
mmax = max(mmax,b);
mmin = min(mmin,a);
}
sort (times.begin(),times.end(),comp);
int time = mmin, index=0, acc=0;
while (time < mmax && index < times.size()){
if (time < times[index].first){
acc+= times[index].first-time;
time =times[index].first;
}
if (time >= times[index].first && time < times[index].second)
time++;
index++;
}
cout << time-times[0].first-acc;
return 0;
} | 23.325 | 69 | 0.516613 | starfy84 |
b02028397eae9430a9a4bd316d0e48847620a3e9 | 708 | cpp | C++ | TOI16/Camp-3/sudden death/max rectangle.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Camp-3/sudden death/max rectangle.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Camp-3/sudden death/max rectangle.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
stack<int> stc;
int mx = 0, i = 0;
while(i < n)
{
if(stc.empty() || arr[i] >= arr[stc.top()]) stc.push(i++);
else
{
int tmp = stc.top();
stc.pop();
if(stc.empty()) mx = max(mx, i * arr[tmp]);
else mx = max(mx, (i - stc.top() - 1) * arr[tmp]);
}
}
while(!stc.empty())
{
int tmp = stc.top();
stc.pop();
if(stc.empty()) mx = max(mx, i * arr[tmp]);
else mx = max(mx, (i - stc.top() - 1) * arr[tmp]);
}
cout << mx << "\n";
}
main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--) solve();
}
| 14.44898 | 60 | 0.497175 | mrmuffinnxz |
b0239bf05d84034f3b609bd5a07f7abcf0fbef94 | 1,850 | cpp | C++ | lnetlib/lnetlib/server_session_non_ssl.cpp | cpp11nullptr/lnetlib | cf29b7a6f209e1d174e16992188d25e589c5e181 | [
"MIT"
] | 39 | 2015-10-13T22:29:29.000Z | 2021-08-14T18:40:51.000Z | lnetlib/lnetlib/server_session_non_ssl.cpp | cpp11nullptr/lnetlib | cf29b7a6f209e1d174e16992188d25e589c5e181 | [
"MIT"
] | 1 | 2015-12-29T09:23:29.000Z | 2015-12-29T09:41:20.000Z | lnetlib/lnetlib/server_session_non_ssl.cpp | cpp11nullptr/lnetlib | cf29b7a6f209e1d174e16992188d25e589c5e181 | [
"MIT"
] | 8 | 2015-10-14T09:17:09.000Z | 2022-02-21T06:47:24.000Z | /*
The MIT License (MIT)
Copyright (c) 2015 Ievgen Polyvanyi
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 "server_session_non_ssl.h"
namespace lnetlib
{
server_session_non_ssl::server_session_non_ssl(service& srv, std::shared_ptr<tcp::acceptor> acceptor)
: _socket(new tcp::socket(srv)), _acceptor(acceptor)
{
}
server_session_non_ssl::~server_session_non_ssl()
{
}
void server_session_non_ssl::start()
{
auto handler = std::bind(&server_session_non_ssl::accept_handler, this, std::placeholders::_1);
_acceptor->async_accept(*_socket.get(), handler);
}
void server_session_non_ssl::accept_handler(const error_code& err)
{
std::shared_ptr<connection> conn;
if (!err)
{
std::shared_ptr<socket> sckt = std::make_shared<socket_non_ssl>(_socket);
conn = std::make_shared<connection>(sckt);
}
connected(conn, err);
}
}
| 30.327869 | 102 | 0.770811 | cpp11nullptr |
b03041fdb7f4f82abfcfad7c5821828e8b2601cd | 885 | cpp | C++ | src/framework/graphics/opengl/vertexLayout.cpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | src/framework/graphics/opengl/vertexLayout.cpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null | src/framework/graphics/opengl/vertexLayout.cpp | oda404/oxu | 5df4755f796be976bed767cd889a2e71ed867f9b | [
"MIT"
] | null | null | null |
#include<oxu/framework/graphics/opengl/vertexLayout.hpp>
#include<oxu/framework/graphics/opengl/core.hpp>
namespace oxu::framework::graphics::opengl
{
VertexLayoutElement::VertexLayoutElement(
const unsigned int &type,
const unsigned int &count
): type(type), count(count)
{
}
template<>
void VertexLayout::pushElement<float>(unsigned int count)
{
m_elements.emplace_back(GL_FLOAT, count);
m_stride += count * sizeof(float);
}
template<>
void VertexLayout::pushElement<int>(unsigned int count)
{
m_elements.emplace_back(GL_INT, count);
m_stride += count * sizeof(int);
}
const std::vector<VertexLayoutElement> &VertexLayout::getElements() const
{
return m_elements;
}
const unsigned int &VertexLayout::getStride() const
{
return m_stride;
}
} | 23.289474 | 77 | 0.651977 | oda404 |
b033a3d9d25e486902deaff232dc156cb16599e2 | 394 | cpp | C++ | 5-Inherit/5-2-Multi-Inherit/Infantry.cpp | mtianyan/CPlusPlusCode | 61403af90c7c73faec1959d9d63238b8bfddaf87 | [
"Apache-2.0"
] | 1 | 2018-11-07T13:56:18.000Z | 2018-11-07T13:56:18.000Z | 5-Inherit/5-2-Multi-Inherit/Infantry.cpp | mtianyan/CPlusPlusCode | 61403af90c7c73faec1959d9d63238b8bfddaf87 | [
"Apache-2.0"
] | null | null | null | 5-Inherit/5-2-Multi-Inherit/Infantry.cpp | mtianyan/CPlusPlusCode | 61403af90c7c73faec1959d9d63238b8bfddaf87 | [
"Apache-2.0"
] | 1 | 2022-01-17T06:21:37.000Z | 2022-01-17T06:21:37.000Z | #include <iostream>
#include "Infantry.h"
using namespace std;
Infantry::Infantry(string name /* = "jack" */, int age /* = 30 */)
{
m_strName = name;
m_iAge = age;
cout << "Infantry()" << endl;
}
Infantry::~Infantry()
{
cout << "~Infantry()" << endl;
}
void Infantry::attack() {
cout << m_iAge << endl;
cout << m_strName << endl;
cout << "Infantry --attack" << endl;
} | 20.736842 | 67 | 0.576142 | mtianyan |
b034f81f95d0fe893fdc4b23c6902580554b177d | 334 | cpp | C++ | codes/raulcr-p3772-Accepted-s1133272.cpp | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | 1 | 2020-03-17T01:44:21.000Z | 2020-03-17T01:44:21.000Z | codes/raulcr-p3772-Accepted-s1133272.cpp | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | null | null | null | codes/raulcr-p3772-Accepted-s1133272.cpp | raulcr98/coj-solutions | b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int N;
int main()
{
cin >> N;
while(N--){
double a, sol = 0.0;
for(int i = 1 ; i <= 10 ; i++){
cin >> a;
sol += a;
}
sol = (85 * sol) / 100;
printf("%.3lf\n", sol);
}
return 0;
}
| 13.916667 | 40 | 0.350299 | raulcr98 |
b034fd1474d2f021d7be5f5b2df7804d027f879b | 1,044 | hh | C++ | App/app_serv/tx_service.hh | Nimita311/motor-driver | 7141e968798fea4a01dbc03481151cd8bfbbefeb | [
"MIT"
] | 3 | 2020-03-12T05:02:50.000Z | 2021-07-10T03:33:12.000Z | App/app_serv/tx_service.hh | Nimita311/motor-driver | 7141e968798fea4a01dbc03481151cd8bfbbefeb | [
"MIT"
] | null | null | null | App/app_serv/tx_service.hh | Nimita311/motor-driver | 7141e968798fea4a01dbc03481151cd8bfbbefeb | [
"MIT"
] | 1 | 2020-12-05T23:11:04.000Z | 2020-12-05T23:11:04.000Z | #ifndef _INC_TX_SERVICE_HH
#define _INC_TX_SERVICE_HH
#include "app_serv/service.hh"
#include "app_lib/messenger.hh"
#include "app_msg/info.pb.h"
#include "stm32h7xx_ll_usart.h"
#include "stm32h7xx_ll_dma.h"
#include "queue.h"
namespace brown {
class TXService: public Service, public Sender {
private:
const UBaseType_t txQueueSize;
QueueHandle_t txQueue;
hardware:
USART_TypeDef* const uart;
DMA_TypeDef* const dma;
const uint32_t stream;
public:
TXService(uint8_t* txBuffer, size_t txBufferSize,
void (*putblock) (char*, size_t),
UBaseType_t txQueueSize,
USART_TypeDef* uart, DMA_TypeDef* dma, uint32_t stream):
Sender(txBuffer, txBufferSize, putblock),
txQueueSize(txQueueSize),
uart(uart), dma(dma), stream(stream) {
txQueue = xQueueCreate(txQueueSize, sizeof(Info*));
}
bool init();
void run();
async:
void send(Info* pInfoContainer);
isr:
void uartISR();
};
} // namespace brown
#endif // _INC_TX_SERVICE_HH
| 21.75 | 70 | 0.681992 | Nimita311 |
b03a6852121251eaabfe59690e8bcbdbd146e768 | 283 | hpp | C++ | src/KEngine/include/KEngine/Entity/ComponentBuilders/EntityRenderableComponentBuilder.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2019-04-09T13:03:11.000Z | 2021-01-27T04:58:29.000Z | src/KEngine/include/KEngine/Entity/ComponentBuilders/EntityRenderableComponentBuilder.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 2 | 2017-02-06T03:48:45.000Z | 2020-08-31T01:30:10.000Z | src/KEngine/include/KEngine/Entity/ComponentBuilders/EntityRenderableComponentBuilder.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2020-06-28T08:19:53.000Z | 2020-06-28T16:30:19.000Z | #pragma once
#include "KEngine/Interfaces/IEntityComponentBuilder.hpp"
namespace ke
{
class EntityRenderableComponentBuilder : public ke::IEntityComponentBuilder
{
public:
virtual ke::EntityComponentSptr build(const std::any & p_jsonObject) override;
};
} | 20.214286 | 86 | 0.738516 | yxbh |
b03c7edb2e5c3c242a3dbbc141085d748e1331d2 | 7,301 | cpp | C++ | ultra96/ROOT_FS/app/fad/src/fad/OdometryCalculator/PatternMatchingVOCalculator/PatternMatchingVOCalculator.cpp | rits-drsl/ZybotR2-96-fpt19 | bed374a70fc6bad637770532244b20002f8e8a28 | [
"MIT"
] | 14 | 2019-12-25T10:17:11.000Z | 2022-01-18T09:35:05.000Z | ultra96/ROOT_FS/app/fad/src/fad/OdometryCalculator/PatternMatchingVOCalculator/PatternMatchingVOCalculator.cpp | rits-drsl/ZybotR2-96-fpt19 | bed374a70fc6bad637770532244b20002f8e8a28 | [
"MIT"
] | null | null | null | ultra96/ROOT_FS/app/fad/src/fad/OdometryCalculator/PatternMatchingVOCalculator/PatternMatchingVOCalculator.cpp | rits-drsl/ZybotR2-96-fpt19 | bed374a70fc6bad637770532244b20002f8e8a28 | [
"MIT"
] | 2 | 2020-02-02T03:12:37.000Z | 2020-09-02T00:25:21.000Z | /**
* PatternMatchingVOCalculator: 路面の俯瞰画像からVisualOdometryを導出するクラス
*
* Copyright (C) 2019 Yuya Kudo.
* Copyright (C) 2019 Atsushi Takada.
* Authors:
* Yuya Kudo <ri0049ee@ed.ritsumei.ac.jp>
* Atsushi Takada <ri0051rr@ed.ritsumei.ac.jp>
*
*/
#include "PatternMatchingVOCalculator.h"
namespace fad {
PatternMatchingVOCalculator::PatternMatchingVOCalculator() {
if(std::getenv("FAD_ROOT") == nullptr) {
throw std::logic_error("[" + std::string(__PRETTY_FUNCTION__) + "] " +
"Please set environment value : $ export FAD_ROOT=<path of project root> ");
}
const auto root_path = std::getenv("FAD_ROOT");
core::YAMLHelper::readStruct(root_path + PARAM_YAML_PATH, param_, "param");
if(param_.match_method == "AKAZE") {
pattern_matcher_ = std::make_unique<AKAZEPatternMatcher>();
}
else if(param_.match_method == "TM") {
pattern_matcher_ = std::make_unique<TMPatternMatcher>();
}
else {
throw std::logic_error("[" + std::string(__PRETTY_FUNCTION__) + "] " +
"Pattern matcher type is invalid.");
}
}
PatternMatchingVOCalculator::~PatternMatchingVOCalculator() {
}
void PatternMatchingVOCalculator::init(const core::EnvironmentMap<core::RoadType>& ref_world) {
ref_world_ = ref_world.clone();
}
core::VisualOdometry PatternMatchingVOCalculator::get(const bool reset) {
const auto ret_vo = vo_;
if(reset) vo_ = core::VisualOdometry();
return ret_vo;
}
void PatternMatchingVOCalculator::update(const core::VehicleState& current_state,
const core::EnvironmentMap<uint8_t>& bird_eye_bin_img,
const core::EnvironmentMap<uint8_t>& bird_eye_edge_img) {
if(bird_eye_bin_img.map.size() != bird_eye_edge_img.map.size()) {
throw std::invalid_argument("[" + std::string(__PRETTY_FUNCTION__) + "] " +
"Input image size is different");
}
const auto ori_size = bird_eye_bin_img.map.size();
// 二値画像とエッジ画像を合成する
// NOTE: 二値画像に対してラベリングを行い、ある一定以上の面積の領域を除去する
cv::Mat label_map;
auto label_info_map = improc::LabelingExecutor::execute(bird_eye_bin_img.map, label_map);
cv::Mat pattern_img = cv::Mat::zeros(cv::Size(ori_size.width * (1.0 - (param_.cutting_left_ratio_of_pattern_image + param_.cutting_right_ratio_of_pattern_image)),
ori_size.height * (1.0 - param_.cutting_above_ratio_of_pattern_image)), CV_8UC1);
int ori_img_x_offset = ori_size.width * param_.cutting_left_ratio_of_pattern_image;
int ori_img_y_offset = ori_size.height * param_.cutting_above_ratio_of_pattern_image;
for(int yi = 0; yi < pattern_img.rows; yi++) {
for(int xi = 0; xi < pattern_img.cols; xi++) {
const auto ori_index = ori_img_x_offset + xi + ori_size.width * (yi + ori_img_y_offset);
if(bird_eye_bin_img.map.data[ori_index] != 0 &&
label_info_map[label_map.data[ori_index]].area * std::pow(bird_eye_bin_img.ratio, 2) <= param_.line_area_thr) {
pattern_img.data[xi + pattern_img.cols * yi] = 0xFF;
}
if(bird_eye_edge_img.map.data[ori_index] != 0) {
pattern_img.data[xi + pattern_img.cols * yi] = 0x7F;
}
}
}
// 路面の俯瞰画像を正規化する
const auto target_center = cv::Point(pattern_img.cols / 2, pattern_img.rows / 2);
const auto target_angle = current_state.t + core::Theta(core::PI / 2);
const auto w_rot = (int)(std::round(pattern_img.rows * std::abs(std::sin(target_angle.get())) +
pattern_img.cols * std::abs(std::cos(target_angle.get()))));
const auto h_rot = (int)(std::round(pattern_img.rows * std::abs(std::cos(target_angle.get())) +
pattern_img.cols * std::abs(std::sin(target_angle.get()))));
const auto target_size = cv::Size(w_rot, h_rot);
auto trans_mat = cv::getRotationMatrix2D(target_center, -target_angle.getDegree(), 1.0);
trans_mat.at<double>(0, 2) += w_rot / 2 - pattern_img.cols / 2;
trans_mat.at<double>(1, 2) += h_rot / 2 - pattern_img.rows / 2;
cv::warpAffine(pattern_img, pattern_img, trans_mat, target_size, cv::INTER_CUBIC);
// 参照地図の対応する領域を切り取る
const auto offset_norm_pix = ref_world_.getCorrespondPixNum(cv::norm(bird_eye_bin_img.offset));
const auto offset_vector = cv::Point(offset_norm_pix * std::cos(current_state.t.get()), offset_norm_pix * std::sin(current_state.t.get()));
const auto ref_center = ref_world_.getPixPoint(current_state.x, current_state.y) + offset_vector;
const auto half_ref_side_length_pt = cv::Point(ref_world_.getCorrespondPixNum(param_.cutting_size_of_ref_map) / 2,
ref_world_.getCorrespondPixNum(param_.cutting_size_of_ref_map) / 2);
const auto ref_region_tl = ref_center - half_ref_side_length_pt;
const auto ref_region_br = ref_center + half_ref_side_length_pt;
const auto corrected_ref_region_tl = cv::Point(core::Util::clamp(ref_region_tl.x, 0, ref_world_.map.cols - 1),
core::Util::clamp(ref_region_tl.y, 0, ref_world_.map.rows - 1));
const auto corrected_ref_region_br = cv::Point(core::Util::clamp(ref_region_br.x, 0, ref_world_.map.cols - 1),
core::Util::clamp(ref_region_br.y, 0, ref_world_.map.rows - 1));
const auto ref_region = cv::Rect(corrected_ref_region_tl, corrected_ref_region_br);
auto ref_img = ref_world_.map(ref_region).clone();
for(int i = 0; i < ref_img.size().area(); i++) {
ref_img.data[i] =
(ref_img.data[i] == (uint8_t)core::RoadType::EDGE) ? 0x7F :
(ref_img.data[i] == (uint8_t)core::RoadType::LINE) ? 0xFF : 0x00;
}
cv::resize(pattern_img, pattern_img, cv::Size(), param_.scale_ratio, param_.scale_ratio, cv::INTER_CUBIC);
cv::resize(ref_img, ref_img, cv::Size(), param_.scale_ratio, param_.scale_ratio, cv::INTER_CUBIC);
// パターンマッチングを実行
const auto p_match_is_success = pattern_matcher_->solve(pattern_img,
ref_img,
cv::Point(ref_img.cols / 2, ref_img.rows / 2),
ref_world_.getCorrespondPixNum(param_.pattern_matcher_delta_threshord));
// パターンマッチングの結果をVOとして保持
if(p_match_is_success) {
const auto& result = pattern_matcher_->getResult();
vo_ = core::VisualOdometry(result.x * ref_world_.ratio * (1.0 / param_.scale_ratio),
result.y * ref_world_.ratio * (1.0 / param_.scale_ratio), result.t);
}
}
}
| 55.732824 | 170 | 0.594028 | rits-drsl |
b03e29a0f7ec1d4b9c6d83c5a97c1e43d4fd035c | 5,668 | cpp | C++ | src/RemotePhotoTool/UsbDriverSwitcherDlg.cpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 16 | 2015-03-26T02:32:43.000Z | 2021-10-18T16:34:31.000Z | src/RemotePhotoTool/UsbDriverSwitcherDlg.cpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 7 | 2019-02-21T06:07:09.000Z | 2022-01-01T10:00:50.000Z | src/RemotePhotoTool/UsbDriverSwitcherDlg.cpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 6 | 2019-05-07T09:21:15.000Z | 2021-09-01T06:36:24.000Z | //
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2020 Michael Fink
//
/// \file UsbDriverSwitcherDlg.cpp USB driver switcher dialog
//
#include "stdafx.h"
#include "resource.h"
#include "UsbDriverSwitcherDlg.hpp"
#include <ulib/Path.hpp>
/// timer ID for refreshing USB devices list
const UINT_PTR c_timerRefreshList = 1;
/// refresh cycle time for USB devices list
const UINT c_refreshCycleTime = 1000;
LRESULT UsbDriverSwitcherDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DlgResize_Init();
DoDataExchange(DDX_LOAD);
CenterWindow();
SetupList();
RefreshList();
SetTimer(c_timerRefreshList, c_refreshCycleTime);
return TRUE;
}
LRESULT UsbDriverSwitcherDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
KillTimer(c_timerRefreshList);
return 0;
}
LRESULT UsbDriverSwitcherDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if (wParam == c_timerRefreshList)
{
KillTimer(c_timerRefreshList);
RefreshList();
SetTimer(c_timerRefreshList, c_refreshCycleTime);
}
return 0;
}
LRESULT UsbDriverSwitcherDlg::OnButtonUsbSwitchDriver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int selectedIndex = m_listUSBDevices.GetSelectedIndex();
if (selectedIndex != -1)
{
struct wdi_device_info* selectedDeviceInfo =
(struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex);
if (selectedDeviceInfo != nullptr)
{
// stop timer or else it will mess up the wdi_device_info struct
KillTimer(c_timerRefreshList);
SwitchDriver(selectedDeviceInfo);
SetTimer(c_timerRefreshList, c_refreshCycleTime);
}
}
return 0;
}
LRESULT UsbDriverSwitcherDlg::OnButtonUsbOpenDeviceManager(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
ShellExecute(m_hWnd, _T("open"), _T("devmgmt.msc"), nullptr, nullptr, SW_SHOWNORMAL);
return 0;
}
void UsbDriverSwitcherDlg::SetupList()
{
m_listUSBDevices.AddColumn(_T("USB Device"), 0);
m_listUSBDevices.AddColumn(_T("Driver status"), 1);
m_listUSBDevices.SetColumnWidth(0, 300);
m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
m_listUSBDevices.SetExtendedListViewStyle(
LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES,
LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
}
void UsbDriverSwitcherDlg::RefreshList()
{
CString selectedDeviceId;
int selectedIndex = m_listUSBDevices.GetSelectedIndex();
if (selectedIndex != -1)
{
struct wdi_device_info* selectedDeviceInfo =
(struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex);
if (selectedDeviceInfo != nullptr)
{
selectedDeviceId = selectedDeviceInfo->device_id;
}
}
m_listUSBDevices.SetRedraw(FALSE);
m_listUSBDevices.DeleteAllItems();
struct wdi_options_create_list cl_options = { 0 };
cl_options.list_all = TRUE;
cl_options.list_hubs = FALSE;
cl_options.trim_whitespaces = TRUE;
int newSelectedIndex = -1;
struct wdi_device_info* rawDeviceInfo = nullptr;
int ret = wdi_create_list(&rawDeviceInfo, &cl_options);
if (ret == WDI_SUCCESS && rawDeviceInfo != nullptr)
{
m_deviceInfoList.reset(rawDeviceInfo, wdi_destroy_list);
for (struct wdi_device_info* deviceInfo = m_deviceInfoList.get(); deviceInfo != nullptr; deviceInfo = deviceInfo->next)
{
if (deviceInfo->desc == nullptr)
continue;
int itemIndex = m_listUSBDevices.InsertItem(
m_listUSBDevices.GetItemCount(),
CString(deviceInfo->desc),
0);
bool isWinusbDriver = CStringA(deviceInfo->driver) == "WinUSB";
m_listUSBDevices.SetItemText(itemIndex, 1, isWinusbDriver ? _T("gPhoto2 compatible") : _T("other driver"));
m_listUSBDevices.SetItemData(itemIndex, (DWORD_PTR)deviceInfo);
if (!selectedDeviceId.IsEmpty() &&
selectedDeviceId == deviceInfo->device_id)
{
newSelectedIndex = itemIndex;
}
}
}
if (newSelectedIndex != -1)
m_listUSBDevices.SelectItem(newSelectedIndex);
m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
m_listUSBDevices.SetRedraw(TRUE);
}
void UsbDriverSwitcherDlg::SwitchDriver(struct wdi_device_info* deviceInfo)
{
CString folderPath = Path::Combine(Path::TempFolder(), _T("usb_driver"));
CString infName{ _T("default.inf") };
Path::CreateDirectoryRecursive(folderPath);
wdi_options_prepare_driver prepareDriverOptions = { };
prepareDriverOptions.driver_type = WDI_WINUSB;
int ret = wdi_prepare_driver(deviceInfo, CStringA(folderPath), CStringA(infName), &prepareDriverOptions);
if (ret != WDI_SUCCESS)
{
CString text;
text.Format(_T("Error while preparing USB driver: %hs"), wdi_strerror(ret));
AtlMessageBox(m_hWnd,
text.GetString(),
IDR_MAINFRAME,
MB_OK | MB_ICONERROR);
return;
}
wdi_options_install_driver installDriverOptions = { };
installDriverOptions.hWnd = m_hWnd;
installDriverOptions.install_filter_driver = false;
ret = wdi_install_driver(deviceInfo, CStringA(folderPath), CStringA(infName), &installDriverOptions);
if (ret != WDI_SUCCESS)
{
CString text;
text.Format(_T("Error while installing USB driver: %hs"), wdi_strerror(ret));
AtlMessageBox(m_hWnd,
text.GetString(),
IDR_MAINFRAME,
MB_OK | MB_ICONERROR);
return;
}
RefreshList();
}
| 27.784314 | 132 | 0.694425 | vividos |
b03f0fb691dc7ab8491a25aa1f7762f917ca5a60 | 10,635 | cpp | C++ | test/main-test.cpp | NikolausDemmel/enum-flags | 48d25b470ee6971d0db15f020937abf6017ebf51 | [
"MIT"
] | 130 | 2015-02-24T18:22:24.000Z | 2022-03-21T18:14:22.000Z | test/main-test.cpp | NikolausDemmel/enum-flags | 48d25b470ee6971d0db15f020937abf6017ebf51 | [
"MIT"
] | 16 | 2015-05-15T01:56:47.000Z | 2020-04-12T13:03:48.000Z | test/main-test.cpp | NikolausDemmel/enum-flags | 48d25b470ee6971d0db15f020937abf6017ebf51 | [
"MIT"
] | 28 | 2015-05-18T21:15:09.000Z | 2022-03-26T10:22:20.000Z | #include "common.hpp"
#include <vector>
#include <boost/core/lightweight_test.hpp>
namespace flags {
template <class E>
auto operator<<(std::ostream& o, flags<E> fl) -> std::ostream& {
return o << "flags<" << fl.underlying_value() << '>';
}
} // namespace flags
void test_set_underlying_value() {
Enums result;
constexpr int random_number = 87;
result.set_underlying_value(random_number);
BOOST_TEST_EQ(random_number, result.underlying_value());
}
void test_empty_constructor() {
Enums null{flags::empty};
BOOST_TEST_EQ(0, null.underlying_value());
}
void test_enum_constructor_and_assignment() {
BOOST_TEST_EQ(1, static_cast<int>(Enum::One));
Enums one = Enum::One;
BOOST_TEST_EQ(1, one.underlying_value());
one = Enum::One;
BOOST_TEST_EQ(1, one.underlying_value());
BOOST_TEST_EQ(2, static_cast<int>(Enum::Two));
Enums two = Enum::Two;
BOOST_TEST_EQ(2, two.underlying_value());
two = Enum::Two;
BOOST_TEST_EQ(2, two.underlying_value());
}
void test_equality() {
const Enums one = Enum::One;
const Enums two = Enum::Two;
BOOST_TEST_EQ(one, one);
BOOST_TEST_EQ(two, two);
BOOST_TEST_NE(two, one);
BOOST_TEST_NE(one, two);
}
void test_copy_move_swap() {
const Enums one = Enum::One;
Enums copy_constructed = one;
BOOST_TEST_EQ(one, copy_constructed);
Enums copy_assigned = Enum::Two;
BOOST_TEST_NE(one, copy_assigned);
copy_assigned = one;
BOOST_TEST_EQ(one, copy_assigned);
Enums move_constructed = std::move(copy_constructed);
BOOST_TEST_EQ(one, move_constructed);
Enums move_assigned = Enum::Two;
BOOST_TEST_NE(one, move_assigned);
move_assigned = std::move(move_constructed);
BOOST_TEST_EQ(one, move_assigned);
Enums left = Enum::One, right = Enum::Two;
swap(left, right);
BOOST_TEST_EQ(2, left.underlying_value());
BOOST_TEST_EQ(1, right.underlying_value());
left.swap(right);
BOOST_TEST_EQ(1, left.underlying_value());
BOOST_TEST_EQ(2, right.underlying_value());
}
void test_initializer_list_and_variadic_constructor() {
Enums il_constructed{Enum::One, Enum::Four, Enum::Eight};
BOOST_TEST_EQ((1 | 4 | 8), il_constructed.underlying_value());
Enums il_assigned;
il_assigned = {Enum::Two, Enum::Four, Enum::Eight};
BOOST_TEST_EQ((2 | 4 | 8), il_assigned.underlying_value());
Enums var_constructed(Enum::One, Enum::Two, Enum::Eight);
BOOST_TEST_EQ((1 | 2 | 8), var_constructed.underlying_value());
}
void test_iterator_constructor() {
std::vector<Enum> vec = {Enum::Two, Enum::Four, Enum::Eight};
Enums iter_constructed{std::begin(vec), std::end(vec)};
BOOST_TEST_EQ((2 | 4 | 8), iter_constructed.underlying_value());
}
void test_bool_conversion_and_negation() {
const Enums one = Enum::One;
BOOST_TEST(one);
const Enums zero{flags::empty};
BOOST_TEST_NOT(zero);
auto not_one = ~one;
BOOST_TEST_EQ(~1, not_one.underlying_value());
}
void test_bit_and() {
const Enum zero = static_cast<Enum>(0),
one = static_cast<Enum>(1);
const Enums fzero = zero,
fone = one;
Enums result = zero & zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero & one;
BOOST_TEST_EQ(0, result.underlying_value());
result = one & zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = one & one;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero & fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero & fone;
BOOST_TEST_EQ(0, result.underlying_value());
result = one & fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = one & fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = fzero & zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero & one;
BOOST_TEST_EQ(0, result.underlying_value());
result = fone & zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fone & one;
BOOST_TEST_EQ(1, result.underlying_value());
result = fzero & fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero & fone;
BOOST_TEST_EQ(0, result.underlying_value());
result = fone & fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fone & fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero;
result &= zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result &= one;
BOOST_TEST_EQ(0, result.underlying_value());
result = one;
result &= zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = one;
result &= one;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero;
result &= fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result &= fone;
BOOST_TEST_EQ(0, result.underlying_value());
result = one;
result &= fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = one;
result &= fone;
BOOST_TEST_EQ(1, result.underlying_value());
}
void test_bit_or() {
const Enum zero = static_cast<Enum>(0);
const Enum one = static_cast<Enum>(1);
const Enums fzero = zero,
fone = one;
Enums result = zero | zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero | one;
BOOST_TEST_EQ(1, result.underlying_value());
result = one | zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one | one;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero | fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero | fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = one | fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one | fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = fzero | zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero | one;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone | zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone | one;
BOOST_TEST_EQ(1, result.underlying_value());
result = fzero | fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero | fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone | fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone | fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero;
result |= zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result |= one;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result |= zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result |= one;
BOOST_TEST_EQ(1, result.underlying_value());
result = zero;
result |= fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result |= fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result |= fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result |= fone;
BOOST_TEST_EQ(1, result.underlying_value());
}
void test_bit_xor() {
const Enum zero = static_cast<Enum>(0);
const Enum one = static_cast<Enum>(1);
const Enums fzero = zero,
fone = one;
Enums result = zero ^ zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero ^ one;
BOOST_TEST_EQ(1, result.underlying_value());
result = one ^ zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one ^ one;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero ^ fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero ^ fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = one ^ fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one ^ fone;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero ^ zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero ^ one;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone ^ zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone ^ one;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero ^ fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = fzero ^ fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone ^ fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = fone ^ fone;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result ^= zero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result ^= one;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result ^= zero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result ^= one;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result ^= fzero;
BOOST_TEST_EQ(0, result.underlying_value());
result = zero;
result ^= fone;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result ^= fzero;
BOOST_TEST_EQ(1, result.underlying_value());
result = one;
result ^= fone;
BOOST_TEST_EQ(0, result.underlying_value());
}
void test_bitset() {
auto a_bitset = (Enum::Two | Enum::Four | Enum::Eight).to_bitset();
BOOST_TEST_EQ((2 | 4 | 8), a_bitset.to_ulong());
a_bitset = (decltype(a_bitset))(Enum::One | Enum::Four | Enum::Eight);
BOOST_TEST_EQ((1 | 4 | 8), a_bitset.to_ulong());
}
void test_erase() {
Enums flags(Enum::Two, Enum::Four, Enum::Eight);
BOOST_TEST_EQ((2 | 4 | 8), flags.underlying_value());
// erase unsets flag if set:
flags.erase(Enum::Four);
BOOST_TEST_EQ((2 | 8), flags.underlying_value());
// erase is noop if not set:
flags.erase(Enum::Four);
BOOST_TEST_EQ((2 | 8), flags.underlying_value());
// erase unsets flag if set:
flags.erase(Enum::Two);
flags.erase(Enum::Eight);
BOOST_TEST_EQ(0, flags.underlying_value());
// erase is noop if not set:
flags.erase(Enum::Two);
flags.erase(Enum::Eight);
BOOST_TEST_EQ(0, flags.underlying_value());
}
void test_erase_iterator() {
Enums flags(Enum::One, Enum::Two, Enum::Four, Enum::Eight);
BOOST_TEST_EQ((1 | 2 | 4 | 8), flags.underlying_value());
// erase single value via iterator:
auto it1 = flags.erase(flags.find(Enum::Four));
BOOST_TEST_EQ((1 | 2 | 8), flags.underlying_value());
BOOST_TEST_EQ(8, static_cast<int>(*it1));
// erase range via iterator:
auto it2 = flags.erase(flags.begin(), std::next(std::next(flags.begin())));
BOOST_TEST_EQ(8, flags.underlying_value());
BOOST_TEST_EQ(8, static_cast<int>(*it2));
}
int main() {
test_set_underlying_value();
test_empty_constructor();
test_enum_constructor_and_assignment();
test_equality();
test_copy_move_swap();
test_initializer_list_and_variadic_constructor();
test_iterator_constructor();
test_bool_conversion_and_negation();
test_bit_and();
test_bit_or();
test_bit_xor();
test_bitset();
test_erase();
test_erase_iterator();
return boost::report_errors();
}
| 27.269231 | 77 | 0.693653 | NikolausDemmel |
b04246fa5d1815d3ac3f7bc4a6acd532cc68c21f | 2,816 | cpp | C++ | src/slib/social/facebook_ui.cpp | emarc99/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 146 | 2017-03-21T07:50:43.000Z | 2022-03-19T03:32:22.000Z | src/slib/social/facebook_ui.cpp | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 50 | 2017-03-22T04:08:15.000Z | 2019-10-21T16:55:48.000Z | src/slib/social/facebook_ui.cpp | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 55 | 2017-03-21T07:52:58.000Z | 2021-12-27T13:02:08.000Z | /*
* Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO>
*
* 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 "slib/social/facebook.h"
namespace slib
{
SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(FacebookResolveUserUrlParam)
FacebookResolveUserUrlParam::FacebookResolveUserUrlParam()
{
}
void Facebook::resolveUserUrl(const FacebookResolveUserUrlParam& param)
{
auto onComplete = param.onComplete;
auto dialog = param.dialog;
if (dialog.isNull()) {
dialog = OAuthWebRedirectDialog::getDefault();
}
OAuthWebRedirectDialogParam dialogParam;
dialogParam.url = "https://www.facebook.com/me";
dialogParam.options = param.dialogOptions;
auto weakDialog = dialog.toWeak();
dialogParam.onRedirect = [weakDialog, onComplete](const String& _url) {
if (_url.isEmpty()) {
onComplete(sl_null);
return;
}
if (_url.startsWith("https://www.facebook.com/") || _url.startsWith("https://m.facebook.com/")) {
Url url(_url);
String path = url.path;
sl_size n = path.getLength();
if (n >= 6) {
sl_char8* sz = path.getData();
sl_bool flagValid = sz[0] == '/';
if (flagValid) {
for (sl_size i = 1; i < n; i++) {
sl_char8 ch = sz[i];
if (!(SLIB_CHAR_IS_ALNUM(ch) || ch == '.')) {
flagValid = sl_false;
break;
}
}
}
if (flagValid) {
auto dialog = weakDialog.lock();
if (dialog.isNotNull()) {
dialog->close();
}
onComplete("https://www.facebook.com" + path);
}
}
}
};
dialog->show(dialogParam);
}
void Facebook::resolveUserUrl(const Function<void(const String& url)>& onComplete)
{
FacebookResolveUserUrlParam param;
param.onComplete = onComplete;
resolveUserUrl(param);
}
}
| 32.367816 | 100 | 0.681108 | emarc99 |
b0442b206f4edd25e44544f75b97954ea551af24 | 4,588 | hpp | C++ | include/edyn/collision/raycast.hpp | xissburg/EntityDynamics | 115da67243da53f7b5001a83260b2f3d7a0355b4 | [
"MIT"
] | null | null | null | include/edyn/collision/raycast.hpp | xissburg/EntityDynamics | 115da67243da53f7b5001a83260b2f3d7a0355b4 | [
"MIT"
] | null | null | null | include/edyn/collision/raycast.hpp | xissburg/EntityDynamics | 115da67243da53f7b5001a83260b2f3d7a0355b4 | [
"MIT"
] | null | null | null | #ifndef EDYN_COLLISION_RAYCAST_HPP
#define EDYN_COLLISION_RAYCAST_HPP
#include <variant>
#include <entt/entity/fwd.hpp>
#include <entt/entity/entity.hpp>
#include "edyn/math/vector3.hpp"
#include "edyn/shapes/cylinder_shape.hpp"
#include "edyn/shapes/capsule_shape.hpp"
namespace edyn {
struct box_shape;
struct sphere_shape;
struct polyhedron_shape;
struct compound_shape;
struct plane_shape;
struct mesh_shape;
struct paged_mesh_shape;
/**
* @brief Info provided when raycasting a box.
*/
struct box_raycast_info {
// Index of face the ray intersects.
size_t face_index;
};
/**
* @brief Info provided when raycasting a cylinder.
*/
struct cylinder_raycast_info {
// Feature the ray intersects. Either a face or side edge.
cylinder_feature feature;
// If the feature is a face, this is the index.
size_t face_index;
};
/**
* @brief Info provided when raycasting a capsule.
*/
struct capsule_raycast_info {
// Feature the ray intersects. Either a hemisphere or side.
capsule_feature feature;
// If the feature is a hemisphere, this is the index.
size_t hemisphere_index;
};
/**
* @brief Info provided when raycasting a polyhedron.
*/
struct polyhedron_raycast_info {
// Index of face the ray intersects.
size_t face_index;
};
/**
* @brief Info provided when raycasting a triangle mesh.
*/
struct mesh_raycast_info {
// Index of triangle the ray intersects.
size_t triangle_index;
};
/**
* @brief Info provided when raycasting a paged triangle mesh.
*/
struct paged_mesh_raycast_info {
// Index of submesh where the intersected triangle is located.
size_t submesh_index;
// Index of intersected triangle in the submesh.
size_t triangle_index;
};
/**
* @brief Info provided when raycasting a compound.
*/
struct compound_raycast_info {
// Index of child shape.
size_t child_index;
// Raycast info for child shape if any extra info is available.
std::variant<
std::monostate,
box_raycast_info,
cylinder_raycast_info,
capsule_raycast_info,
polyhedron_raycast_info
> child_info_var;
};
/**
* @brief Information returned from a shape-specific raycast query.
*/
struct shape_raycast_result {
// Fraction for the ray where intersection occurs. The intersection
// point is at `lerp(p0, p1, fraction)`.
scalar fraction { EDYN_SCALAR_MAX };
// Normal vector at intersection.
vector3 normal;
// Raycast details which contains a value that depends on the type of shape
// that was hit.
std::variant<
std::monostate,
box_raycast_info,
cylinder_raycast_info,
capsule_raycast_info,
polyhedron_raycast_info,
compound_raycast_info,
mesh_raycast_info,
paged_mesh_raycast_info
> info_var;
};
/**
* @brief Information returned from a general raycast query.
* It derives from `shape_raycast_result` thus bringing in the extra details of
* the raycast as well.
*/
struct raycast_result : public shape_raycast_result {
// The entity that was hit. It's set to `entt::null` if no entity is hit.
entt::entity entity { entt::null };
};
/**
* @brief Input for a shape-specific raycast query containg the spatial
* configuration.
*/
struct raycast_context {
// Position of shape.
vector3 pos;
// Orientation of shape.
quaternion orn;
// First point in the ray.
vector3 p0;
// Second point in the ray.
vector3 p1;
};
/**
* @brief Performs a raycast query on a registry.
* @param registry Data source.
* @param p0 First point in the ray.
* @param p1 Second point in the ray.
* @return Result.
*/
raycast_result raycast(entt::registry ®istry, vector3 p0, vector3 p1);
// Raycast functions for each shape.
shape_raycast_result shape_raycast(const box_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const cylinder_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const sphere_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const capsule_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const polyhedron_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const compound_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const plane_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const mesh_shape &, const raycast_context &);
shape_raycast_result shape_raycast(const paged_mesh_shape &, const raycast_context &);
}
#endif // EDYN_COLLISION_RAYCAST_HPP
| 28.147239 | 86 | 0.727768 | xissburg |
b04531e3ba791274c303ebc1421871f9188efc70 | 13,859 | cpp | C++ | src/App/glwidget.cpp | snousias/avatree | 57493c13f491ba97bfb9d7b294629c9c296e6c57 | [
"AAL"
] | 8 | 2020-04-06T14:08:15.000Z | 2022-02-15T07:48:14.000Z | src/AVATreeExtensionGUI/glwidget.cpp | snousias/avatree | 57493c13f491ba97bfb9d7b294629c9c296e6c57 | [
"AAL"
] | null | null | null | src/AVATreeExtensionGUI/glwidget.cpp | snousias/avatree | 57493c13f491ba97bfb9d7b294629c9c296e6c57 | [
"AAL"
] | 4 | 2020-08-24T13:09:37.000Z | 2021-11-08T02:26:15.000Z | #include "glwidget.h"
#include "ray.h"
#include "modellerToViewer.h"
#include <QtWidgets>
#include <QWidget>
#include <QMouseEvent>
#include <QOpenGLShaderProgram>
#include <QCoreApplication>
#include <math.h>
GLWidget::GLWidget(QWidget *parent)
: QOpenGLWidget(parent),
m_model(NULL),
m_wireframe(0),
m_bbox(false),
m_transparent(true)
{
setFocusPolicy(Qt::WheelFocus);
if (m_transparent) setAttribute(Qt::WA_TranslucentBackground);
//connect(&m_camera, SIGNAL(updated()), this, SLOT(update()));
connect(&m_camera, &Camera::updated, this, static_cast<void (GLWidget::*)()>(&GLWidget::update));
}
GLWidget::~GLWidget()
{
cleanup();
}
void GLWidget::cleanup()
{
// Make sure the context is current when deleting the buffers.
makeCurrent();
delete m_model;
m_model = NULL;
doneCurrent();
}
QSize GLWidget::minimumSizeHint() const
{
return QSize(50, 50);
}
QSize GLWidget::sizeHint() const
{
return QSize(800, 600);
}
void GLWidget::saveScreenshot()
{
qDebug() << "Save screenshot...";
// Capture
qApp->beep();
m_originalPixmap = QPixmap(); // clear image for low memory situations on embedded devices.
QScreen *screen = QGuiApplication::primaryScreen();
if (screen)
m_originalPixmap = screen->grabWindow(0);
// Save
QString format = "png";
QString initialPath = QDir::currentPath() + tr("/untitled.") + format;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(format.toUpper())
.arg(format));
if (!fileName.isEmpty())
m_originalPixmap.save(fileName, format.toLatin1().constData());
qDebug() << "Screenshot saved";
}
void GLWidget::castRay(const QPoint& pos, Ray& r)
{
int w = width();
int h = height();
// Constuct ray in camera space
// Convert selected pixel from screen space to normalized [-1, 1] cliping space
QVector3D target_clipingspace(((pos.x() + 0.5) / (0.5 * w)) - 1,
-(((pos.y() + 0.5) / (0.5 * h)) - 1),
0);
// Convert target to camera space
QVector3D target_cameraspace = m_camera.projectionMatrix().inverted() * target_clipingspace;
// Convert ray from camera to model space
QVector3D eye_modelspace = m_mvMatrix.inverted() * QVector3D(0, 0, 0);
QVector3D target_modelspace = m_mvMatrix.inverted() * target_cameraspace;
// Get the ray in model space
r.set(eye_modelspace, target_modelspace);
}
void GLWidget::initializeGL()
{
// In this example the widget's corresponding top-level window can change
// several times during the widget's lifetime. Whenever this happens, the
// QOpenGLWidget's associated context is destroyed and a new one is created.
// Therefore we have to be prepared to clean up the resources on the
// aboutToBeDestroyed() signal, instead of the destructor. The emission of
// the signal will be followed by an invocation of initializeGL() where we
// can recreate all resources.
connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::cleanup);
initializeOpenGLFunctions();
// White backround
glClearColor(0, 0, 0, m_transparent ? 0 : 1);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
glLineWidth(1);
initShaders();
QString filename = QString(":/Models/cube.obj");
std::string modelstring = filename.toStdString();
dotObj theModel;
theModel.initializeFromFile(modelstring);
lungmodel.push_back(theModel);
initModel(filename, Model::VIEW::FRONT);
tempModel = new dotObj;
// Our camera changes in this example.
m_camera.calibrate(m_model->bbox());
GLfloat dist = m_camera.distance();
// Bind the program
m_program.bind();
// Light position is fixed.
m_program.setUniformValue("lightPosition_cameraspace", QVector3D(0, 0, 0));
m_program.setUniformValue("lightColor", QVector3D(1, 1, 1));
m_program.setUniformValue("lightPower", dist * dist);
m_program.setUniformValue("isBlack", 0);
m_program.release();
// Use QBasicTimer because its faster than QTimer
//m_timer.start(12, this);
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Get the current world Matrix transformation from model
QMatrix4x4 worldMatrix = m_model->worldMatrix();
// Get the current view Matrix transformation from camera
QMatrix4x4 viewMatrix = m_camera.viewMatrix();
// Calculate modelview Matrix
m_mvMatrix = viewMatrix * worldMatrix;
m_program.bind();
m_program.setUniformValue("projMatrix", m_camera.projectionMatrix());
m_program.setUniformValue("mvMatrix", m_mvMatrix);
m_program.setUniformValue("viewMatrix", viewMatrix);
m_program.setUniformValue("modelMatrix", worldMatrix);
m_program.setUniformValue("normalMatrix", m_mvMatrix.normalMatrix());
m_model->draw(&m_program, m_wireframe, m_bbox);
m_program.release();
}
void GLWidget::resizeGL(int w, int h)
{
// Calculate aspect ratio
qreal aspect = qreal(w) / qreal(h ? h : 1);
// Set perspective projection
m_camera.setAspect(aspect);
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
std::vector<int> currentSelection;
if ((event->buttons() & Qt::RightButton) && !(event->modifiers() & Qt::ControlModifier))
{
Ray ray_modelspace;
castRay(event->pos(), ray_modelspace);
// Get a list with intersecting triangles
int closestPointID = m_lastClosestPointID;
QList<int> triainter;
m_model->intersectWithRay(ray_modelspace, closestPointID, triainter);
if (triainter.size() && closestPointID != m_lastClosestPointID)
{
m_lastClosestPointID = closestPointID;
seedPoint = closestPointID;
qDebug() << "Last clicked vertex : " << seedPoint;
if (partSelectionFunctionality)
{
std::vector<int> v = lungmodel.at(lungmodel.size() - 1).segment_property_map_per_vertex;
if (v.size() > 0){
int group = v.at(seedPoint);
lungmodel.at(lungmodel.size() - 1).selectedVertices.clear();
for (int i = 0; i < v.size(); i++){
if (v.at(i) == group){
lungmodel.at(lungmodel.size() - 1).selectedVertices.push_back(i);
}
}
}
}
if (brushSelectionFunctionality)
{
currentSelection = lungmodel.at(lungmodel.size() - 1).selectedVertices;
lungmodel.at(lungmodel.size() - 1).selectedVertices.clear();
if (_brushdistanceModeIndex==0)
{
lungmodel.at(lungmodel.size() - 1).selector(seedPoint, _brushSizeBox);
}
if (_brushdistanceModeIndex==1)
{
lungmodel.at(lungmodel.size() - 1).selectorBasedOnCenterline(seedPoint, _brushDistance);
}
lungmodel.at(lungmodel.size() - 1).selectedVertices.insert(lungmodel.at(lungmodel.size() - 1).selectedVertices.end(), currentSelection.begin(), currentSelection.end());
sort(lungmodel.at(lungmodel.size() - 1).selectedVertices.begin(), lungmodel.at(lungmodel.size() - 1).selectedVertices.end());
lungmodel.at(lungmodel.size() - 1).selectedVertices.erase(unique(lungmodel.at(lungmodel.size() - 1).selectedVertices.begin(), lungmodel.at(lungmodel.size() - 1).selectedVertices.end()), lungmodel.at(lungmodel.size() - 1).selectedVertices.end());
}
m_model->populateColorsPerVertexUniform(0.8);
if (lungmodel.at(lungmodel.size() - 1).segment_property_map.size() > 0){
m_model->populateColorsPerVertexWithSegmentProperty(lungmodel.at(lungmodel.size() - 1).segment_property_map);
}
m_model->populateColorsPerVertexList(lungmodel.at(lungmodel.size() - 1).selectedVertices);
//m_model->populateColorsPerVertex(closestPointID);
//m_model->populateColorsWithCorrelations(closestPointID);
}
else {
lungmodel.at(lungmodel.size() - 1).selectedVertices.clear();
m_model->populateColorsPerVertexUniform(0.8);
if (lungmodel.at(lungmodel.size() - 1).segment_property_map.size() > 0){
m_model->populateColorsPerVertexWithSegmentProperty(lungmodel.at(lungmodel.size() - 1).segment_property_map);
}
qDebug() << "No intersection";
}
}
m_lastPos = QVector2D(event->localPos());
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
// Mouse release position - mouse press position
QVector2D diff = QVector2D(event->localPos()) - m_lastPos;
if (event->buttons() & Qt::MiddleButton){
m_camera.translate(QVector3D(diff.x()/10, -diff.y()/10, 0));
}
if (event->buttons() & Qt::LeftButton)
{
// Rotation axis is perpendicular to the mouse position difference vector
QVector3D rotationAxis(diff.y(), diff.x(), 0.0);
// Accelerate angular speed relative to the length of the mouse sweep
qreal angle = diff.length() / 10.0;
// Update rotation
m_camera.rotate(QQuaternion::fromAxisAndAngle(rotationAxis.normalized(), angle));
}
if (event->buttons() & Qt::RightButton)
{
Ray ray_modelspace;
castRay(event->pos(), ray_modelspace);
// Get a list with intersecting triangles
int closestPointID;
QList<int> triainter;
m_model->intersectWithRay(ray_modelspace, closestPointID, triainter);
if (triainter.size())
{
if (closestPointID != m_lastClosestPointID)
{
m_lastClosestPointID = closestPointID;
seedPoint = closestPointID;
lungmodel.at(lungmodel.size() - 1).selector(seedPoint, _brushSizeBox);
m_model->populateColorsPerVertexList(lungmodel.at(lungmodel.size() - 1).selectedVertices);
}
}
else qDebug() << "No intersection";
}
m_lastPos = QVector2D(event->localPos());
}
void GLWidget::wheelEvent(QWheelEvent *event)
{
m_camera.setDistance(event->delta());
}
void GLWidget::keyPressEvent(QKeyEvent *event)
{
int modif = mkModif(event);
QString c = event->text();
unsigned char key = c.toLatin1()[0];
switch (isprint(key) ? tolower(key) : key)
{
case 'p':
saveScreenshot();
break;
case 'w':
{
m_wireframe = ++m_wireframe % 3;
emit wireframeModeChanged((Qt::CheckState) m_wireframe);
update();
}
break;
case 'b':
{
m_bbox = !m_bbox;
emit bboxModeChanged(m_bbox);
update();
}
break;
case 'c':
m_camera.calibrate(m_model->bbox());
break;
case 'l':
{
QString format = "obj";
QString initialPath = QDir::currentPath() + tr("/untitled.") + format;
QString fileName = QFileDialog::getOpenFileName(this, tr("Load Model"), initialPath,
tr("%1 Files (*.%2);;All Files (*)").arg(format.toUpper()).arg(format));
if (!fileName.isEmpty())
loadNewOBJ(fileName);
// Our camera changes in this example.
m_camera.calibrate(m_model->bbox());
}
break;
case 's':
{
QString format = "obj";
QString initialPath = QDir::currentPath() + tr("/untitled.") + format;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Model"), initialPath,
tr("%1 Files (*.%2);;All Files (*)").arg(format.toUpper()).arg(format));
if (!fileName.isEmpty())
saveOBJ(fileName);
// Our camera changes in this example.
m_camera.calibrate(m_model->bbox());
}
break;
}
switch (event->key())
{
case Qt::Key_Up:
m_camera.translate(QVector3D(0, 1, 0));
break;
case Qt::Key_Down:
m_camera.translate(QVector3D(0, -1, 0));
break;
case Qt::Key_Right:
m_camera.translate(QVector3D(1, 0, 0));
break;
case Qt::Key_Left:
m_camera.translate(QVector3D(-1, 0, 0));
break;
case Qt::Key_Escape:
qApp->quit();
break;
}
}
void GLWidget::keyReleaseEvent(QKeyEvent *event)
{}
int GLWidget::mkModif(QInputEvent *event)
{
int ctrl = event->modifiers() & Qt::ControlModifier ? 1 : 0;
int shift = event->modifiers() & Qt::ShiftModifier ? 1 : 0;
int alt = event->modifiers() & Qt::AltModifier ? 1 : 0;
int modif = (ctrl << 0) | (shift << 1) | (alt << 2);
return modif;
}
/*
void GLWidget::timerEvent(QTimerEvent *)
{
// Decrease angular speed (friction)
m_angularSpeed *= 0.99;
// Stop rotation when speed goes below threshold
if (m_angularSpeed < 0.01) {
m_angularSpeed = 0.0;
}
else {
// Update rotation
m_rotation = QQuaternion::fromAxisAndAngle(m_rotationAxis, m_angle) * m_rotation;
// Request an update
update();
}
}
//*/
void GLWidget::initShaders()
{
if (!m_program.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/vertShader.glsl"))
{
GLenum err = glGetError();
qDebug() << "OpenGL ERROR No:" << err;
close();
}
if (!m_program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/fragShader.glsl"))
{
GLenum err = glGetError();
qDebug() << "OpenGL ERROR No:" << err;
close();
}
if (!m_program.link())
{
GLenum err = glGetError();
qDebug() << "OpenGL ERROR No:" << err;
close();
}
if (!m_program.bind())
{
GLenum err = glGetError();
qDebug() << "OpenGL ERROR No:" << err;
close();
}
else m_program.release();
}
void GLWidget::initModel(QString& filename, Model::VIEW type)
{
if (m_model)
{
qDebug() << "Model already exist!! Wrong use of this API";
// Disconnect previous signals from slots
//disconnect(m_model, SIGNAL(verticesChanged()), this, SLOT(update()));
//disconnect(m_model, SIGNAL(normalsChanged()), this, SLOT(update()));
//disconnect(m_model, SIGNAL(colorsChanged()), this, SLOT(update()));
delete m_model;
m_model = NULL;
}
// Load the model
m_model = new Model(filename, &m_program, type);
// Connect new signals to slots
//connect(m_model, SIGNAL(verticesChanged()), this, SLOT(update()));
//connect(m_model, SIGNAL(normalsChanged()), this, SLOT(update()));
//connect(m_model, SIGNAL(colorsChanged()), this, SLOT(update()));
connect(m_model, &Model::verticesChanged, this, static_cast<void (GLWidget::*)()>(&GLWidget::update));
connect(m_model, &Model::normalsChanged, this, static_cast<void (GLWidget::*)()>(&GLWidget::update));
connect(m_model, &Model::colorsChanged, this, static_cast<void (GLWidget::*)()>(&GLWidget::update));
}
void GLWidget::loadNewOBJ(QString& filename)
{
// Load the model
m_model->loadNewOBJ(filename);
}
void GLWidget::loadNewOBJ(dotObj * input)
{
// Load the model
m_model->loadNewOBJ(input);
}
void GLWidget::saveOBJ(QString& filename)
{
// Load the model
m_model->saveOBJ(filename);
}
| 27.829317 | 249 | 0.702576 | snousias |
b05048428fada06c56821557b744777672c9c008 | 13,745 | cpp | C++ | src/AES.cpp | BlazingNova/APT | ba1fadb9a44588c2285646fac4a6f001ed6e065d | [
"MIT"
] | null | null | null | src/AES.cpp | BlazingNova/APT | ba1fadb9a44588c2285646fac4a6f001ed6e065d | [
"MIT"
] | 1 | 2018-04-20T20:30:58.000Z | 2018-04-20T20:30:58.000Z | src/AES.cpp | BlazingNova/APT | ba1fadb9a44588c2285646fac4a6f001ed6e065d | [
"MIT"
] | null | null | null | //============================================================================
// Name : AES.cpp
// Author : Mathew Prabakar
// Version : 2.0
// Copyright : Keep your hands off my code
// Description : AES Encryption and Decryption in C++
//============================================================================
#include <iostream>
#include <stdio.h>
#include <bitset>
#include <vector>
#include <string>
using namespace std;
class AES{
private:
uint8_t sbox [256]= {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
uint8_t sibox [256]= {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
uint8_t KEY[16];
vector<uint32_t> Text;
vector<uint32_t> W;
vector<uint32_t> Result;
int peak(uint32_t a)
{
int j = 0;
for(j=31;j>=0;j--){
if(a&(1<<j)){
//cout<<"\n"<<j<<"\n";
break;
}
}
return j;
}
uint32_t modulo(uint32_t a)
{
uint32_t q=0x11b;
uint32_t temp=a;
while(peak(temp)>=8)
{
// cout<<"Peak is "<<peak(temp)<<" "<<bitset<32>(temp)<<"\n";
// cout<<"MOD is "<<bitset<32>(q<<abs(8-peak(temp)))<<"\n ";
temp ^=(q<<abs(8-peak(temp)));
}
//cout<<"BYE\n";
return temp;
}
void SubBytes(uint32_t state[4])
{
uint8_t t[4];
for(int i=0;i<4;i++){
t[0] = sbox[ ((state[i]&0x000000f0)>>4 ) * 16 + (state[i]&0x0000000f ) ];
t[1] = sbox[ ((state[i]&0x0000f000)>>12) * 16 + ((state[i]&0x00000f00)>>8) ];
t[2] = sbox[ ((state[i]&0x00f00000)>>20) * 16 + ((state[i]&0x000f0000)>>16) ];
t[3] = sbox[ ((state[i]&0xf0000000)>>28) * 16 + ((state[i]&0x0f000000)>>24) ];
state[i] = t[3]<<24 | t[2]<<16 | t[1]<<8 | t[0];
}
}
void InvSubBytes(uint32_t state[4])
{
uint8_t t[4];
for(int i=0;i<4;i++){
t[0] = sibox[ ((state[i]&0x000000f0)>>4 ) * 16 + (state[i]&0x0000000f ) ];
t[1] = sibox[ ((state[i]&0x0000f000)>>12) * 16 + ((state[i]&0x00000f00)>>8) ];
t[2] = sibox[ ((state[i]&0x00f00000)>>20) * 16 + ((state[i]&0x000f0000)>>16) ];
t[3] = sibox[ ((state[i]&0xf0000000)>>28) * 16 + ((state[i]&0x0f000000)>>24) ];
state[i] = t[3]<<24 | t[2]<<16 | t[1]<<8 | t[0];
}
}
uint32_t ShiftBytes(uint32_t a, int b)
{
for(int i=0;i<b;i++)
{
bool t=a&(1<<31);
a<<=1;
if(t)
a|=1;
}
return a;
}
void ShiftBytes(uint32_t state[4], int b, int c)
{
uint32_t t[4];
for(int i=0;i<c;i++)
{
t[0]=state[0]&(0xff<<(24-8*b));
t[1]=state[1]&(0xff<<(24-8*b));
t[2]=state[2]&(0xff<<(24-8*b));
t[3]=state[3]&(0xff<<(24-8*b));
state[0]&=~(0xff<<(24-8*b));
state[1]&=~(0xff<<(24-8*b));
state[2]&=~(0xff<<(24-8*b));
state[3]&=~(0xff<<(24-8*b));
state[0]|=t[1];
state[1]|=t[2];
state[2]|=t[3];
state[3]|=t[0];
}
}
void InvShiftBytes(uint32_t state[4], int b, int c)
{
uint32_t t[4];
for(int i=0;i<c;i++)
{
t[0]=state[0]&(0xff<<(24-8*b));
t[1]=state[1]&(0xff<<(24-8*b));
t[2]=state[2]&(0xff<<(24-8*b));
t[3]=state[3]&(0xff<<(24-8*b));
state[0]&=~(0xff<<(24-8*b));
state[1]&=~(0xff<<(24-8*b));
state[2]&=~(0xff<<(24-8*b));
state[3]&=~(0xff<<(24-8*b));
state[0]|=t[3];
state[1]|=t[0];
state[2]|=t[1];
state[3]|=t[2];
}
}
void MixColumns(uint32_t &a)
{
uint8_t temp[4];
uint8_t r[4];
uint8_t b[4];
uint8_t h;
for(int i=3;i>=0;i--)
{
temp[i]=a&(0xff);
a>>=8;
//cout<<hex<<(int)temp[i]<<" ";
h = (temp[i]>>7) ? 0xff:0;
b[i]=temp[i]<<1;
b[i] ^= 0x1B & h;
}
r[0] = b[0] ^ temp[3] ^ temp[2] ^ b[1] ^ temp[1];
r[1] = b[1] ^ temp[0] ^ temp[3] ^ b[2] ^ temp[2];
r[2] = b[2] ^ temp[1] ^ temp[0] ^ b[3] ^ temp[3];
r[3] = b[3] ^ temp[2] ^ temp[1] ^ b[0] ^ temp[0];
a = r[0]<<24 | r[1]<<16 | r[2]<<8 | r[3];
}
void InvMixColumns(uint32_t &a)
{
uint8_t temp[4];
uint8_t r[4];
for(int i=3;i>=0;i--)
{
temp[i]=a&(0xff);
a>>=8;
//cout<<hex<<(int)temp[i]<<" ";
}
r[0] = mult(temp[0],0xe)^mult(temp[1],0xb)^mult(temp[2],0xd)^mult(temp[3],0x9);
r[1] = mult(temp[0],0x9)^mult(temp[1],0xe)^mult(temp[2],0xb)^mult(temp[3],0xd);
r[2] = mult(temp[0],0xd)^mult(temp[1],0x9)^mult(temp[2],0xe)^mult(temp[3],0xb);
r[3] = mult(temp[0],0xb)^mult(temp[1],0xd)^mult(temp[2],0x9)^mult(temp[3],0xe);
a = r[0]<<24 | r[1]<<16 | r[2]<<8 | r[3];
}
uint32_t mult (uint32_t a, uint32_t b)
{
uint32_t temp=0;
for(int i=0; i<32;i++)
{
if(b&1){
temp ^= (a<<i);
}
b=b>>1;
}
temp = modulo(temp);
return temp;
}
void AddRoundKey(uint32_t in[4], int index,bool rev)
{
//cout<<dec<<index<<" ADD\n\n";
//
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
//
//cout<<"PLUS \n";
//cout<<hex<<W[index+0]<<"\n";
//cout<<hex<<W[index+1]<<"\n";
//cout<<hex<<W[index+2]<<"\n";
//cout<<hex<<W[index+3]<<"\n\n";
if(!rev)
for(int i=0;i<4;i++)
in[i] = in[i]^W[index+i];
else
for(int i=0;i<4;i++)
in[i] = in[i]^W[index+3-i];
//cout<<"EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
}
uint8_t mulx(uint8_t ip)
{
uint16_t a=ip;
a=a<<1;
if(a &0x100)
a^=0x1b;
return a;
}
uint8_t genRC(int i)
{
if(i<=1)
return 0x01;
else
return mulx(genRC(i-1));
}
uint32_t g(uint32_t a, int i)
{
uint32_t temp;
uint32_t res;
temp = ShiftBytes(a,8);
//cout<<"After ROT \n";
//cout<<hex<<temp;
uint8_t b[4];
//cout<<"\n"<<hex<<((temp &0xf0000000)>>28)<<" "<<((temp &0x0f000000)>>24)<<"\n";
b[0] = sbox[ ((temp&0x000000f0)>>4 ) * 16 + (temp&0x0000000f ) ];
b[1] = sbox[ ((temp&0x0000f000)>>12) * 16 + ((temp&0x00000f00)>>8) ];
b[2] = sbox[ ((temp&0x00f00000)>>20) * 16 + ((temp&0x000f0000)>>16) ];
b[3] = sbox[ ((temp&0xf0000000)>>28) * 16 + ((temp &0x0f000000)>>24) ];
//cout<<"After Sbox\n";
//cout<<hex<<(int)b[3];
res =b[3]<<24 | b[2]<<16 | b[1]<<8 | b[0];
//cout<<hex<<(int)res<<"\n";
uint32_t RC=(genRC(i/4)<<24);
//cout<<hex<<(int)RC<<"\n";
return res ^ RC;
}
void SetIP(string str)
{
Text.clear();
char *myarr = new char[str.length()+1];
str.copy(myarr,str.length());
uint8_t t[4];
//cout<<char_traits<char>::length(myarr);
for(unsigned i=0;i<str.length();i+=4){
// cout<<i<<" ";
for(int j=0; j<4;j++){
if(i+j<str.length())
t[j] = (int)myarr[i+j];
else
t[j] = 0x00;
// cout<<t[j]<<" ";
}
Text.push_back(t[0]<<24 | t[1]<<16 | t[2]<<8 | t[3]);
// cout<<"\n";
}
for(unsigned i=0;i<Text.size()%4;i++)
Text.push_back(0x00000000);
delete myarr;
}
void keyexpansion()
{
uint32_t wt [4];
for(int i=0;i<4;i++)
wt[i] = (KEY[i*4]<<24)|(KEY[i*4+1]<<16)|(KEY[i*4+2]<<8)|(KEY[i*4+3]);
//cout<<hex<<(int)wt[0]<<" "<<(int)wt[1]<<" "<<(int)wt[2]<<" "<<(int)wt[3]<<"\n";
W.clear();
W.push_back(wt[0]);
W.push_back(wt[1]);
W.push_back(wt[2]);
W.push_back(wt[3]);
for(int i=3;i<43;i+=4)
{
uint32_t gt=g(wt[3],i+1);
//cout<<hex<<gt<<"\n";
wt[0] ^= gt;
wt[1] ^= wt[0];
wt[2] ^= wt[1];
wt[3] ^= wt[2];
//cout<<hex<<(int)wt[0]<<" "<<(int)wt[1]<<" "<<(int)wt[2]<<" "<<(int)wt[3]<<"\n";
W.push_back(wt[0]);
W.push_back(wt[1]);
W.push_back(wt[2]);
W.push_back(wt[3]);
}
}
void cypher(uint32_t in[4])
{
AddRoundKey(in,0,0);
for(int i=1;i<=9;i++)
{
SubBytes(in);
//cout<<"SUB BYTES EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
ShiftBytes(in,1,1);
ShiftBytes(in,2,2);
ShiftBytes(in,3,3);
//cout<<"ShiftBytes EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
MixColumns(in[0]);
MixColumns(in[1]);
MixColumns(in[2]);
MixColumns(in[3]);
//cout<<"MixColumns EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
AddRoundKey(in,i*4,0);
}
SubBytes(in);
ShiftBytes(in,1,1);
ShiftBytes(in,2,2);
ShiftBytes(in,3,3);
AddRoundKey(in,40,0);
}
void decypher(uint32_t in[4])
{
AddRoundKey(in,40,0);
for(int i=9;i>=1;i--)
{
//cout<<"SUB BYTES EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
InvShiftBytes(in,1,1);
InvShiftBytes(in,2,2);
InvShiftBytes(in,3,3);
InvSubBytes(in);
//cout<<"ShiftBytes EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
//cout<<"MixColumns EQUALS \n";
//cout<<hex<<in[0]<<"\n";
//cout<<hex<<in[1]<<"\n";
//cout<<hex<<in[2]<<"\n";
//cout<<hex<<in[3]<<"\n\n";
AddRoundKey(in,i*4,0);
InvMixColumns(in[0]);
InvMixColumns(in[1]);
InvMixColumns(in[2]);
InvMixColumns(in[3]);
}
InvShiftBytes(in,1,1);
InvShiftBytes(in,2,2);
InvShiftBytes(in,3,3);
InvSubBytes(in);
AddRoundKey(in,0,0);
}
public:
void SetKey(string str)
{
char myarr[16];
str.copy(myarr,16);
for(int i=0;i<16;i++)
KEY[i] = (int)myarr[i];
keyexpansion();
/*cout<<"\nKEY\n";
for(int i=0;i<16;i++)
cout<<hex<<(int)KEY[i]<<" ";
cout<<"\n";*/
}
vector<uint32_t> encrypt(string str)
{
SetIP(str);
Result.clear();
//cout<<"\nText\n";
/*
for(unsigned i=0;i<Text.size();i++){
cout<<hex<<Text[i]<<"\n";
if(i%4==3)
cout<<"-------------\n";
}
*/
uint32_t in[4];
// cout<<Text.size()/4<<"\n";
for(unsigned i=0;i<Text.size()/4;i++)
{
in[0]=Text[i*4+0];
in[1]=Text[i*4+1];
in[2]=Text[i*4+2];
in[3]=Text[i*4+3];
cypher(in);
/*
cout<<hex<<in[0]<<"\n";
cout<<hex<<in[1]<<"\n";
cout<<hex<<in[2]<<"\n";
cout<<hex<<in[3]<<"\n";
*/
Result.push_back(in[0]);
Result.push_back(in[1]);
Result.push_back(in[2]);
Result.push_back(in[3]);
}
return Result;
}
vector<uint32_t> decrypt(vector<uint32_t> Text)
{
Result.clear();
for(unsigned i=0;i<Text.size();i++){
cout<<hex<<Text[i]<<"\n";
if(i%4==3)
cout<<"-------------\n";
}
uint32_t in[4];
// cout<<Text.size()/4<<"\n";
for(unsigned i=0;i<Text.size()/4;i++)
{
in[0]=Text[i*4+0];
in[1]=Text[i*4+1];
in[2]=Text[i*4+2];
in[3]=Text[i*4+3];
decypher(in);
/*
cout<<hex<<in[0]<<"\n";
cout<<hex<<in[1]<<"\n";
cout<<hex<<in[2]<<"\n";
cout<<hex<<in[3]<<"\n";
*/
Result.push_back(in[0]);
Result.push_back(in[1]);
Result.push_back(in[2]);
Result.push_back(in[3]);
}
return Result;
}
const vector<uint32_t> getResult()
{
return Result;
}
const uint8_t* getKey()
{
return KEY;
}
void PrintResult()
{
cout<<"\nRESULT "<<"\n";
for(unsigned i=0;i<Result.size();i++)
cout<<hex<<Result[i]<<"\n";
}
void PrintKey()
{
cout<<"KEY\n";
for(int i=0;i<16;i++)
cout<<hex<<(int)KEY[i]<<" ";
}
};
// CLASS USAGE
/*
int main() {
vector<uint32_t> Enc;
AES obj;
// SET THE KEY
obj.SetKey("Thats my Kung Fu");
obj.PrintKey();
//ENCRYPT
Enc=obj.encrypt("Two One Nine Two");
obj.PrintResult();
//DECRYPT
obj.decrypt(Enc);
obj.PrintResult();
return 0;
}*/
| 22.870216 | 98 | 0.549218 | BlazingNova |
b0512767d9caf48c7a0ad86678a4225cdd9dd711 | 2,386 | cpp | C++ | AtCoder/Educational_DP_Contest/F.cpp | arlechann/atcoder | 1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2 | [
"CC0-1.0"
] | null | null | null | AtCoder/Educational_DP_Contest/F.cpp | arlechann/atcoder | 1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2 | [
"CC0-1.0"
] | null | null | null | AtCoder/Educational_DP_Contest/F.cpp | arlechann/atcoder | 1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2 | [
"CC0-1.0"
] | null | null | null | #include <algorithm>
#include <boost/optional.hpp>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)
#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)
#define EACH(e, a) for(auto&& e : a)
#define ALL(a) std::begin(a), std::end(a)
#define RALL(a) std::rbegin(a), std::rend(a)
#define FILL(a, n) memset((a), n, sizeof(a))
#define FILLZ(a) FILL(a, 0)
#define INT(x) (static_cast<int>(x))
using namespace std;
using ll = long long;
using VI = vector<int>;
using VI2D = vector<vector<int>>;
constexpr int INF = 2e9;
constexpr double EPS = 1e-10;
constexpr double PI = acos(-1.0);
constexpr int dx[] = {-1, 0};
constexpr int dy[] = {0, -1};
template <typename T>
constexpr int sign(T x) {
return x < 0 ? -1 : x > 0 ? 1 : 0;
}
template <>
constexpr int sign(double x) {
return x < -EPS ? -1 : x > EPS ? 1 : 0;
}
template <typename T, typename U>
constexpr bool chmax(T& m, U x) {
if(m < x) {
m = x;
return true;
}
return false;
}
template <typename T, typename U>
constexpr bool chmin(T& m, U x) {
if(m > x) {
m = x;
return true;
}
return false;
}
template <typename T>
constexpr T square(T x) {
return x * x;
}
int main() {
string s, t;
cin >> s;
cin >> t;
int n, m;
n = s.size();
m = t.size();
VI2D dp(n, VI(m, 0));
vector<vector<pair<int, int>>> prev(
n, vector<pair<int, int>>(m, make_pair(-1, -1)));
REP(i, n) {
REP(j, m) {
if(s[i] == t[j]) {
dp[i][j] = ((i > 0 && j > 0) ? dp[i - 1][j - 1] : 0) + 1;
prev[i][j] = make_pair(i - 1, j - 1);
continue;
}
REP(k, 2) {
if(i + dy[k] < 0 || j + dx[k] < 0) {
continue;
}
if(chmax(dp[i][j], dp[i + dy[k]][j + dx[k]])) {
prev[i][j] = make_pair(i + dy[k], j + dx[k]);
}
}
}
}
int i = n - 1;
int j = m - 1;
string result = "";
while(i >= 0 && j >= 0) {
auto p = prev[i][j];
if(s[i] == t[j]) {
result = s[i] + move(result);
}
i = p.first;
j = p.second;
}
cout << result << endl;
return 0;
}
| 19.398374 | 76 | 0.564543 | arlechann |
b0513d443f9110a3bfb8ae4276f086a2bfaad699 | 6,499 | cpp | C++ | Strings/AhoCorasick.cpp | NhatMinh0208/CP-Library | 4d174b01a569106d2d7ad0fa5e3594175e97de31 | [
"MIT"
] | null | null | null | Strings/AhoCorasick.cpp | NhatMinh0208/CP-Library | 4d174b01a569106d2d7ad0fa5e3594175e97de31 | [
"MIT"
] | null | null | null | Strings/AhoCorasick.cpp | NhatMinh0208/CP-Library | 4d174b01a569106d2d7ad0fa5e3594175e97de31 | [
"MIT"
] | null | null | null | #ifndef CPL_TEMPLATE
#define CPL_TEMPLATE
/*
Normie's Aho-Corasick, version 2.0.
This data structure receives a set of strings and builds 2 trees:
+) A trie of the strings
+) A suffix link tree of the strings
The implementation is kept as barebones as possible to promote flexibility.
Tested with https://codeforces.com/problemset/problem/1202/E
*/
// Standard library in one include.
#include <bits/stdc++.h>
using namespace std;
// ordered_set library.
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set(el) tree<el,null_type,less<el>,rb_tree_tag,tree_order_statistics_node_update>
// AtCoder library. (Comment out these two lines if you're not submitting in AtCoder.) (Or if you want to use it in other judges, run expander.py first.)
//#include <atcoder/all>
//using namespace atcoder;
//Pragmas (Comment out these three lines if you're submitting in szkopul or USACO.)
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,unroll-loops,tree-vectorize")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
//File I/O.
#define FILE_IN "cseq.inp"
#define FILE_OUT "cseq.out"
#define ofile freopen(FILE_IN,"r",stdin);freopen(FILE_OUT,"w",stdout)
//Fast I/O.
#define fio ios::sync_with_stdio(0);cin.tie(0)
#define nfio cin.tie(0)
#define endl "\n"
//Order checking.
#define ord(a,b,c) ((a>=b)and(b>=c))
//min/max redefines, so i dont have to resolve annoying compile errors.
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
// Fast min/max assigns to use with AVX.
// Requires g++ 9.2.0.
template<typename T>
__attribute__((always_inline)) void chkmin(T& a, const T& b) {
a=(a<b)?a:b;
}
template<typename T>
__attribute__((always_inline)) void chkmax(T& a, const T& b) {
a=(a>b)?a:b;
}
//Constants.
#define MOD (ll(998244353))
#define MAX 300001
#define mag 320
const long double PI=3.14159265358979;
//Pairs and 3-pairs.
#define p1 first
#define p2 second.first
#define p3 second.second
#define fi first
#define se second
#define pii(element_type) pair<element_type,element_type>
#define piii(element_type) pair<element_type,pii(element_type)>
//Quick power of 2.
#define pow2(x) (ll(1)<<x)
//Short for-loops.
#define ff(i,__,___) for(int i=__;i<=___;i++)
#define rr(i,__,___) for(int i=__;i>=___;i--)
//Typedefs.
#define bi BigInt
typedef long long ll;
typedef long double ld;
typedef short sh;
// Binpow and stuff
ll BOW(ll a, ll x, ll p)
{
if (!x) return 1;
ll res=BOW(a,x/2,p);
res*=res;
res%=p;
if (x%2) res*=a;
return res%p;
}
ll INV(ll a, ll p)
{
return BOW(a,p-2,p);
}
//---------END-------//
#endif
namespace CP_Library {
const int ALPHA_SZ=26;
const int SHIFT_CONST=-97;
struct Node {
unordered_map<int,int> ch_trie;
vector<int> ch2_trie;
int p_trie;
vector<int> ch_suff;
int p_suff=0;
vector<int> leaf;
int ch;
int nxt[ALPHA_SZ];
Node(int par=0, int _ch=0) {
p_trie=par;
ch=_ch;
}
};
struct Aho_Corasick {
vector<Node*> trie;
vector<int> str_store;
Aho_Corasick() {
trie.push_back(new Node);
trie.push_back(new Node);
}
void add_str(string s) { // Adds a string to the Aho_Corasick trie
int u=1;
for (auto g : s) {
if (trie[u]->ch_trie[g+SHIFT_CONST]==0) {
trie.push_back(new Node(u, g+SHIFT_CONST));
trie[u]->ch_trie[g+SHIFT_CONST]=trie.size()-1;
}
u=trie[u]->ch_trie[g+SHIFT_CONST];
}
trie[u]->leaf.push_back(str_store.size());
str_store.push_back(u);
}
void build_suff() { // Finalizes the trie and builds the suffix tree
vector<int> dq;
dq.push_back(1);
int u,v;
for (int j=0;j<dq.size();j++) {
u=dq[j];
// cout<<"suflink "<<u<<endl;
if (u==1) {
trie[u]->p_suff=u;
for (int i=0;i<ALPHA_SZ;i++) {
if (trie[u]->ch_trie[i]) trie[u]->nxt[i]=trie[u]->ch_trie[i];
else trie[u]->nxt[i]=1;
}
}
else if (trie[u]->p_trie==1) {
trie[u]->p_suff=1;
trie[1]->ch_suff.push_back(u);
for (int i=0;i<ALPHA_SZ;i++) {
if (trie[u]->ch_trie[i]) trie[u]->nxt[i]=trie[u]->ch_trie[i];
else trie[u]->nxt[i]=trie[1]->nxt[i];
}
}
else {
v=trie[trie[trie[u]->p_trie]->p_suff]->nxt[trie[u]->ch];
trie[u]->p_suff=v;
trie[v]->ch_suff.push_back(u);
for (int i=0;i<ALPHA_SZ;i++) {
if (trie[u]->ch_trie[i]) trie[u]->nxt[i]=trie[u]->ch_trie[i];
else trie[u]->nxt[i]=trie[trie[u]->p_suff]->nxt[i];
}
}
// cout<<"result: "<<u<<' '<<trie[u]->p_suff<<endl;
// for (int i=97;i<123;i++) {
// cout<<"trans "<<char(i)<<' '<<trie[u]->nxt[i]<<endl;
// }
for (auto g : trie[u]->ch_trie) {
// cout<<char(g.fi)<<' '<<g.se<<endl;
if (g.se) dq.push_back(g.se);
}
trie[u]->ch_trie.clear();
// cout<<endl;
}
}
void debug() {
for (int i=1;i<trie.size();i++) {
cout<<"Debugging node "<<i<<endl;
cout<<trie[i]->ch<<' '<<trie[i]->p_trie<<' '<<trie[i]->p_suff<<endl;
for (int j=0;j<26;j++) {
cout<<char(j-SHIFT_CONST)<<' '<<trie[i]->nxt[j]<<' ';
}
cout<<endl;
}
}
};
}
// Sample usage follows.
// Source: https://codeforces.com/contest/1202/submission/132412398
using namespace CP_Library;
Aho_Corasick ah1,ah2;
ll r1[200011];
ll r2[200011];
ll dep[200011];
string s[200011];
string tr;
ll n,m,i,j,k,t,t1,u,v,a,b;
void dfs1(int x) {
dep[x]=dep[ah1.trie[x]->p_suff]+ah1.trie[x]->leaf.size();
for (auto g : ah1.trie[x]->ch_suff) dfs1(g);
// cout<<"dfs1 "<<x<<' '<<dep[x]<<endl;
}
void dfs2(int x) {
dep[x]=dep[ah2.trie[x]->p_suff]+ah2.trie[x]->leaf.size();
for (auto g : ah2.trie[x]->ch_suff) dfs2(g);
}
int main()
{
fio;
cin>>tr;
m=tr.size();
cin>>n;
for (i=0;i<n;i++) {
cin>>s[i];
}
for (i=0;i<n;i++) {
ah1.add_str(s[i]);
}
ah1.build_suff();
dfs1(1);
u=1;
// ah1.debug();
for (i=0;i<m-1;i++) {
// cout<<u<<endl;
v=int(tr[i]+SHIFT_CONST);
// cout<<v<<endl;
u=ah1.trie[u]->nxt[v];
r1[i]=dep[u];
// cout<<u<<' '<<dep[u]<<endl;
}
for (i=0;i<n;i++) {
reverse(s[i].begin(),s[i].end());
}
reverse(tr.begin(),tr.end());
for (i=0;i<n;i++) {
ah2.add_str(s[i]);
}
ah2.build_suff();
dfs2(1);
u=1;
for (i=0;i<m-1;i++) {
// cout<<u<<endl;
v=int(tr[i]+SHIFT_CONST);
// cout<<v<<endl;
u=ah2.trie[u]->nxt[v];
r2[i]=dep[u];
// cout<<u<<' '<<dep[u]<<endl;
}
ll res=0;
for (i=0;i<m-1;i++) {
res+=r1[i]*r2[m-2-i];
// cout<<r1[i]<<' '<<r2[i]<<endl;
}
// if (res==1815024) cout<<n<<' '<<m<<' '<<ah2.trie.size()<<endl;
cout<<res;
}
| 22.333333 | 153 | 0.613325 | NhatMinh0208 |
b053f3dc61b03fc60286aed7d619458ac382da19 | 442 | hpp | C++ | includes/SpecialFood.hpp | tiboitel/Nibbler | f95341206d6750d2b85deb4ee6bb789234229201 | [
"MIT"
] | null | null | null | includes/SpecialFood.hpp | tiboitel/Nibbler | f95341206d6750d2b85deb4ee6bb789234229201 | [
"MIT"
] | null | null | null | includes/SpecialFood.hpp | tiboitel/Nibbler | f95341206d6750d2b85deb4ee6bb789234229201 | [
"MIT"
] | null | null | null | #ifndef SPECIALFOOD_HPP
# define SPECIALFOOD_HPP
# include <Food.hpp>
class SpecialFood : public Food
{
public:
SpecialFood(int x, int y, size_t score = 200, size_t lifespan = 10000);
~SpecialFood();
SpecialFood (SpecialFood const &rhs);
SpecialFood &operator=(SpecialFood const &rhs);
size_t getLifeSpan() const;
void setLifeSpan(size_t val);
private:
SpecialFood();
size_t _lifeSpan; //lifespan in ms
};
#endif
| 20.090909 | 73 | 0.71267 | tiboitel |
b057f910197a2efb139b6ef20d02a1bfb1b9afee | 4,748 | cc | C++ | src/native/VMem.cc | jappavoo/EbbRT | b0aacb6cafebd2b3e43b6636f1325e0ae10d7fba | [
"BSL-1.0"
] | 67 | 2015-02-26T17:55:43.000Z | 2022-01-06T09:30:59.000Z | src/native/VMem.cc | jmcadden/EbbRT | d213abd76f3cc065755170876cc269d97591abd3 | [
"BSL-1.0"
] | 146 | 2015-02-11T16:39:58.000Z | 2021-02-21T21:27:09.000Z | src/native/VMem.cc | jmcadden/EbbRT | d213abd76f3cc065755170876cc269d97591abd3 | [
"BSL-1.0"
] | 12 | 2015-02-04T05:49:54.000Z | 2019-08-07T10:20:09.000Z | // Copyright Boston University SESA Group 2013 - 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "VMem.h"
#include <atomic>
#include <cinttypes>
#include <cstdint>
#include <cstring>
#include "../Align.h"
#include "CpuAsm.h"
#include "Debug.h"
#include "E820.h"
#include "EarlyPageAllocator.h"
#include "PageAllocator.h"
namespace {
ebbrt::ExplicitlyConstructed<ebbrt::vmem::Pte> page_table_root;
}
void ebbrt::vmem::Init() { page_table_root.construct(); }
void ebbrt::vmem::EarlyMapMemory(uint64_t addr, uint64_t length) {
auto aligned_addr = align::Down(addr, pmem::kPageSize);
auto aligned_length =
align::Up(length + (addr - aligned_addr), pmem::kPageSize);
TraversePageTable(
GetPageTableRoot(), aligned_addr, aligned_addr + aligned_length, 0, 4,
[=](Pte& entry, uint64_t base_virt, size_t level) {
if (entry.Present()) {
kassert(entry.Addr(level > 0) == base_virt);
return;
}
entry.Set(base_virt, level > 0);
std::atomic_thread_fence(std::memory_order_release);
asm volatile("invlpg (%[addr])" : : [addr] "r"(base_virt) : "memory");
},
[=](Pte& entry) {
auto page = early_page_allocator::AllocatePage();
auto page_addr = page.ToAddr();
new (reinterpret_cast<void*>(page_addr)) Pte[512];
entry.SetNormal(page_addr);
return true;
});
}
void ebbrt::vmem::EarlyUnmapMemory(uint64_t addr, uint64_t length) {
auto aligned_addr = align::Down(addr, pmem::kPageSize);
auto aligned_length =
align::Up(length + (addr - aligned_addr), pmem::kPageSize);
TraversePageTable(
GetPageTableRoot(), aligned_addr, aligned_addr + aligned_length, 0, 4,
[=](Pte& entry, uint64_t base_virt, size_t level) {
kassert(entry.Present());
entry.SetPresent(false);
std::atomic_thread_fence(std::memory_order_release);
asm volatile("invlpg (%[addr])" : : [addr] "r"(base_virt) : "memory");
},
[=](Pte& entry) {
kprintf("Asked to unmap memory that wasn't mapped!\n");
kabort();
return false;
});
}
void ebbrt::vmem::MapMemory(Pfn vfn, Pfn pfn, uint64_t length) {
auto pte_root = Pte(ReadCr3());
auto vaddr = vfn.ToAddr();
TraversePageTable(pte_root, vaddr, vaddr + length, 0, 4,
[=](Pte& entry, uint64_t base_virt, size_t level) {
kassert(!entry.Present());
entry.Set(pfn.ToAddr() + (base_virt - vaddr), level > 0);
std::atomic_thread_fence(std::memory_order_release);
},
[](Pte& entry) {
auto page = page_allocator->Alloc();
kbugon(page == Pfn::None());
auto page_addr = page.ToAddr();
new (reinterpret_cast<void*>(page_addr)) Pte[512];
entry.SetNormal(page_addr);
return true;
});
}
// traverses per core page table and backs vaddr with physical pages
// in pfn
void ebbrt::vmem::MapMemoryLarge(uintptr_t vaddr, Pfn pfn, uint64_t length) {
auto pte_root = Pte(ReadCr3());
TraversePageTable(
pte_root, vaddr, vaddr + length, 0, 4,
[=](Pte& entry, uint64_t base_virt, size_t level) {
kassert(!entry.Present());
entry.Set(pfn.ToAddr() + (base_virt - vaddr), level > 0);
std::atomic_thread_fence(std::memory_order_release);
},
[](Pte& entry) {
auto page = page_allocator->Alloc();
kbugon(page == Pfn::None());
auto page_addr = page.ToAddr();
new (reinterpret_cast<void*>(page_addr)) Pte[512];
entry.SetNormal(page_addr);
return true;
});
}
void ebbrt::vmem::EnableRuntimePageTable() {
asm volatile("mov %[page_table], %%cr3"
:
: [page_table] "r"(GetPageTableRoot()));
}
void ebbrt::vmem::ApInit(size_t index) {
EnableRuntimePageTable();
Pte ap_pte_root;
auto nid = Cpu::GetByIndex(index)->nid();
auto& p_allocator = (*PageAllocator::allocators)[nid.val()];
auto page = p_allocator.Alloc(0, nid);
kbugon(page == Pfn::None(),
"Failed to allocate page for initial page tables\n");
auto page_addr = page.ToAddr();
std::memcpy(reinterpret_cast<void*>(page_addr),
reinterpret_cast<void*>(GetPageTableRoot().Addr(false)), 4096);
ap_pte_root.SetNormal(page_addr);
asm volatile("mov %[page_table], %%cr3" : : [page_table] "r"(ap_pte_root));
}
ebbrt::vmem::Pte& ebbrt::vmem::GetPageTableRoot() { return *page_table_root; }
| 35.432836 | 79 | 0.609941 | jappavoo |
b059fcafa945380b1b4df080e5ee6682f2127d55 | 997 | hpp | C++ | include/dracosha/validator/utils/adjust_storable_ignore.hpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 27 | 2020-09-18T13:45:33.000Z | 2022-03-16T21:14:37.000Z | include/dracosha/validator/utils/adjust_storable_ignore.hpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 7 | 2020-08-07T21:48:14.000Z | 2021-01-14T12:25:37.000Z | include/dracosha/validator/utils/adjust_storable_ignore.hpp | evgeniums/cpp-validator | e4feccdce19c249369ddb631571b60613926febd | [
"BSL-1.0"
] | 1 | 2021-03-30T09:17:58.000Z | 2021-03-30T09:17:58.000Z | /**
@copyright Evgeny Sidorov 2020
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
/****************************************************************************/
/** @file validator/utils/adjust_storable_ignore.hpp
*
* Defines adjust_storable_ignore.
*
*/
/****************************************************************************/
#ifndef DRACOSHA_VALIDATOR_ADJUST_STORABLE_IGNORE_HPP
#define DRACOSHA_VALIDATOR_ADJUST_STORABLE_IGNORE_HPP
#include <dracosha/validator/config.hpp>
DRACOSHA_VALIDATOR_NAMESPACE_BEGIN
//-------------------------------------------------------------
/**
* @brief Struct to be used as a base struct for objects that must be copied as is to adjust_storable_t wrapper.
*/
struct adjust_storable_ignore{};
//-------------------------------------------------------------
DRACOSHA_VALIDATOR_NAMESPACE_END
#endif // DRACOSHA_VALIDATOR_ADJUST_STORABLE_IGNORE_HPP
| 26.236842 | 112 | 0.57673 | evgeniums |
b05aea2b808eb84be88a18b8efded02a244b1b12 | 4,551 | cpp | C++ | kari_localization/src/mesh.cpp | karrykarry/kari_localization | e81e1fda587958e87771e149b5ca3769eae891fc | [
"MIT"
] | null | null | null | kari_localization/src/mesh.cpp | karrykarry/kari_localization | e81e1fda587958e87771e149b5ca3769eae891fc | [
"MIT"
] | null | null | null | kari_localization/src/mesh.cpp | karrykarry/kari_localization | e81e1fda587958e87771e149b5ca3769eae891fc | [
"MIT"
] | null | null | null | //meshビューア
#include <ros/ros.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/vtk_io.h>
#include <pcl/PolygonMesh.h>
#include <boost/thread/thread.hpp>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/Point.h>
#include <pcl_conversions/pcl_conversions.h>
#include <tf/transform_broadcaster.h>
#include <local_tool/filters.hpp>
#include <local_tool/mathematics.hpp>
#include <local_tool/registration.hpp>
using namespace std;
class Mesh
{
private:
ros::NodeHandle n;
ros::Rate r;
ros::Publisher input_pub;
ros::Publisher output_pub;
double MU;
double M_NEIGHBORS;//max
double G_RADIUS;
double K_SEARCH;
string file_input;
bool NORMAL_C;
pcl::PolygonMesh::Ptr triangles;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud ;
public:
Mesh(ros::NodeHandle& n);
void create_polygon(void);
void vis_polygon(void);
};
Mesh::Mesh(ros::NodeHandle &n) :
r(10)
{
n.getParam("mesh_mu",MU);
n.getParam("mesh_max_neighbors",M_NEIGHBORS);
n.getParam("mesh_radius",G_RADIUS);
n.getParam("mesh_normalconsistency",NORMAL_C);
n.getParam("normal_ksearch",K_SEARCH);
n.getParam("input/cloud",file_input);
input_pub = n.advertise<sensor_msgs::PointCloud2>("/input_cloud", 10);
output_pub = n.advertise<sensor_msgs::PointCloud2>("/output_cloud", 10);
triangles.reset (new pcl::PolygonMesh());
cloud.reset (new pcl::PointCloud<pcl::PointXYZ>);
}
void
Mesh::create_polygon(void){
pcl::PointCloud<pcl::PointXYZI>::Ptr output_cloud (new pcl::PointCloud<pcl::PointXYZI>);
// Load input file into a PointCloud<T> with an appropriate type
pcl::PCLPointCloud2 cloud_blob;
pcl::io::loadPCDFile(file_input, cloud_blob);
pcl::fromPCLPointCloud2 (cloud_blob, *cloud);
//* the data should be available in cloud
// Normal estimation*
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> nor;
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud (cloud);
nor.setInputCloud (cloud);
nor.setSearchMethod (tree);
nor.setKSearch (K_SEARCH);
nor.compute (*normals);
//* normals should not contain the point normals + surface curvatures
// Concatenate the XYZ and normal fields*
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
//* cloud_with_normals = cloud + normals
// Create search tree*
pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);
tree2->setInputCloud (cloud_with_normals);
// Initialize objects
pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
// Set the maximum distance between connected points (maximum edge length)
// gp3.setSearchRadius (0.025);
gp3.setSearchRadius (G_RADIUS);
// Set typical values for the parameters
gp3.setMu (MU);//defalut 2.5
gp3.setMaximumNearestNeighbors (M_NEIGHBORS);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(NORMAL_C);
// gp3.setNormalConsistency(true);
// Get result
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree2);
gp3.reconstruct (*triangles);
// Additional vertex information
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();
cout <<triangles->polygons.size() <<"triangles created" << endl;
//ros
// pcl::fromPCLPointCloud2 (triangles->cloud, *output_cloud);
// sensor_msgs::PointCloud2 pc, pc2;
// pcl_msgs::PolygonMesh pc3;
// pcl::toROSMsg(*cloud, pc);
// pcl::toROSMsg(*output_cloud, pc2);
// pc3.cloud = pc2;
}
void
Mesh::vis_polygon(void)
{
// 点群のビューア
pcl::visualization::PCLVisualizer viewer("Cloud Viewer");
viewer.setBackgroundColor (0.0, 0.2, 0.6);
viewer.addPolygonMesh(*triangles);
while (!viewer.wasStopped ())
{
viewer.spinOnce(10);
boost::this_thread::sleep (boost::posix_time::microseconds (100000));
}
}
int main(int argc, char** argv){
ros::init(argc, argv, "mesh");
ros::NodeHandle n;
cout<<"-------mesh ok--------"<<endl;
Mesh mesh(n);
mesh.create_polygon();
mesh.vis_polygon();
ros::spin();
return 0;
}
| 23.703125 | 99 | 0.725775 | karrykarry |
b05b855e9987739443d02d6f052641352b9d86cb | 17,149 | cpp | C++ | src/entity/RDimensionEntity.cpp | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/entity/RDimensionEntity.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/entity/RDimensionEntity.cpp | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QCAD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QCAD.
*/
#include "RDimensionEntity.h"
#include "RExporter.h"
#include "RStorage.h"
RPropertyTypeId RDimensionEntity::PropertyCustom;
RPropertyTypeId RDimensionEntity::PropertyHandle;
RPropertyTypeId RDimensionEntity::PropertyProtected;
RPropertyTypeId RDimensionEntity::PropertyType;
RPropertyTypeId RDimensionEntity::PropertyBlock;
RPropertyTypeId RDimensionEntity::PropertyLayer;
RPropertyTypeId RDimensionEntity::PropertyLinetype;
RPropertyTypeId RDimensionEntity::PropertyLinetypeScale;
RPropertyTypeId RDimensionEntity::PropertyLineweight;
RPropertyTypeId RDimensionEntity::PropertyColor;
RPropertyTypeId RDimensionEntity::PropertyDisplayedColor;
RPropertyTypeId RDimensionEntity::PropertyDrawOrder;
RPropertyTypeId RDimensionEntity::PropertyDefinitionPointX;
RPropertyTypeId RDimensionEntity::PropertyDefinitionPointY;
RPropertyTypeId RDimensionEntity::PropertyDefinitionPointZ;
RPropertyTypeId RDimensionEntity::PropertyMiddleOfTextX;
RPropertyTypeId RDimensionEntity::PropertyMiddleOfTextY;
RPropertyTypeId RDimensionEntity::PropertyMiddleOfTextZ;
RPropertyTypeId RDimensionEntity::PropertyText;
RPropertyTypeId RDimensionEntity::PropertyUpperTolerance;
RPropertyTypeId RDimensionEntity::PropertyLowerTolerance;
RPropertyTypeId RDimensionEntity::PropertyLinearFactor;
RPropertyTypeId RDimensionEntity::PropertyDimScale;
RPropertyTypeId RDimensionEntity::PropertyDimBlockName;
RPropertyTypeId RDimensionEntity::PropertyAutoTextPos;
RPropertyTypeId RDimensionEntity::PropertyFontName;
//RPropertyTypeId RDimensionEntity::PropertyHeight;
//RPropertyTypeId RDimensionEntity::PropertyAngle;
//RPropertyTypeId RDimensionEntity::PropertyLineSpacingFactor;
//RPropertyTypeId RDimensionEntity::PropertyHAlign;
//RPropertyTypeId RDimensionEntity::PropertyVAlign;
RPropertyTypeId RDimensionEntity::PropertyAutoLabel;
RPropertyTypeId RDimensionEntity::PropertyMeasuredValue;
RDimensionEntity::RDimensionEntity(RDocument* document) :
REntity(document) {
}
RDimensionEntity::~RDimensionEntity() {
}
void RDimensionEntity::init() {
RDimensionEntity::PropertyCustom.generateId(typeid(RDimensionEntity), RObject::PropertyCustom);
RDimensionEntity::PropertyHandle.generateId(typeid(RDimensionEntity), RObject::PropertyHandle);
RDimensionEntity::PropertyProtected.generateId(typeid(RDimensionEntity), RObject::PropertyProtected);
RDimensionEntity::PropertyType.generateId(typeid(RDimensionEntity), REntity::PropertyType);
RDimensionEntity::PropertyBlock.generateId(typeid(RDimensionEntity), REntity::PropertyBlock);
RDimensionEntity::PropertyLayer.generateId(typeid(RDimensionEntity), REntity::PropertyLayer);
RDimensionEntity::PropertyLinetype.generateId(typeid(RDimensionEntity), REntity::PropertyLinetype);
RDimensionEntity::PropertyLinetypeScale.generateId(typeid(RDimensionEntity), REntity::PropertyLinetypeScale);
RDimensionEntity::PropertyLineweight.generateId(typeid(RDimensionEntity), REntity::PropertyLineweight);
RDimensionEntity::PropertyColor.generateId(typeid(RDimensionEntity), REntity::PropertyColor);
RDimensionEntity::PropertyDisplayedColor.generateId(typeid(RDimensionEntity), REntity::PropertyDisplayedColor);
RDimensionEntity::PropertyDrawOrder.generateId(typeid(RDimensionEntity), REntity::PropertyDrawOrder);
RDimensionEntity::PropertyText.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Label"));
RDimensionEntity::PropertyUpperTolerance.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Tolerance"), QT_TRANSLATE_NOOP("REntity", "Upper Limit"));
RDimensionEntity::PropertyLowerTolerance.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Tolerance"), QT_TRANSLATE_NOOP("REntity", "Lower Limit"));
RDimensionEntity::PropertyDefinitionPointX.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Definition Point"), QT_TRANSLATE_NOOP("REntity", "X"));
RDimensionEntity::PropertyDefinitionPointY.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Definition Point"), QT_TRANSLATE_NOOP("REntity", "Y"));
RDimensionEntity::PropertyDefinitionPointZ.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Definition Point"), QT_TRANSLATE_NOOP("REntity", "Z"));
RDimensionEntity::PropertyMiddleOfTextX.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Text Position"), QT_TRANSLATE_NOOP("REntity", "X"));
RDimensionEntity::PropertyMiddleOfTextY.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Text Position"), QT_TRANSLATE_NOOP("REntity", "Y"));
RDimensionEntity::PropertyMiddleOfTextZ.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Text Position"), QT_TRANSLATE_NOOP("REntity", "Z"));
// RDimensionEntity::PropertyFontName.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Font"));
// RDimensionEntity::PropertyHeight.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Height"));
// RDimensionEntity::PropertyAngle.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Angle"));
// RDimensionEntity::PropertyLineSpacingFactor.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Line Spacing"));
// RDimensionEntity::PropertyHAlign.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Alignment"), QT_TRANSLATE_NOOP("REntity", "Horizontal"));
// RDimensionEntity::PropertyVAlign.generateId(typeid(RDimensionEntity), QT_TRANSLATE_NOOP("REntity", "Alignment"), QT_TRANSLATE_NOOP("REntity", "Vertical"));
RDimensionEntity::PropertyAutoLabel.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Auto Label"));
RDimensionEntity::PropertyMeasuredValue.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Measured Value"));
RDimensionEntity::PropertyLinearFactor.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Linear Factor"));
RDimensionEntity::PropertyDimScale.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Scale"));
RDimensionEntity::PropertyDimBlockName.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Block Name"));
RDimensionEntity::PropertyAutoTextPos.generateId(typeid(RDimensionEntity), "", QT_TRANSLATE_NOOP("REntity", "Auto Label Position"));
}
bool RDimensionEntity::setProperty(RPropertyTypeId propertyTypeId,
const QVariant& value, RTransaction* transaction) {
bool ret = REntity::setProperty(propertyTypeId, value, transaction);
ret = ret || RObject::setMember(getData().definitionPoint.x, value, PropertyDefinitionPointX == propertyTypeId);
ret = ret || RObject::setMember(getData().definitionPoint.y, value, PropertyDefinitionPointY == propertyTypeId);
ret = ret || RObject::setMember(getData().definitionPoint.z, value, PropertyDefinitionPointZ == propertyTypeId);
if (RObject::setMember(getData().textPositionCenter.x, value, PropertyMiddleOfTextX == propertyTypeId)) {
ret = true;
getData().autoTextPos = false;
getData().textPositionSide = RVector::invalid;
//getData().updateFromTextPosition();
}
if (RObject::setMember(getData().textPositionCenter.y, value, PropertyMiddleOfTextY == propertyTypeId)) {
ret = true;
getData().autoTextPos = false;
getData().textPositionSide = RVector::invalid;
//getData().updateFromTextPosition();
}
if (RObject::setMember(getData().textPositionCenter.z, value, PropertyMiddleOfTextZ == propertyTypeId)) {
ret = true;
getData().autoTextPos = false;
getData().textPositionSide = RVector::invalid;
//getData().updateFromTextPosition();
}
ret = ret || RObject::setMember(getData().text, value, PropertyText == propertyTypeId);
ret = ret || RObject::setMember(getData().upperTolerance, value, PropertyUpperTolerance == propertyTypeId);
ret = ret || RObject::setMember(getData().lowerTolerance, value, PropertyLowerTolerance == propertyTypeId);
ret = ret || RObject::setMember(getData().linearFactor, value, PropertyLinearFactor == propertyTypeId);
ret = ret || RObject::setMember(getData().dimScale, value, PropertyDimScale == propertyTypeId);
ret = ret || RObject::setMember(getData().dimBlockName, value, PropertyDimBlockName == propertyTypeId);
ret = ret || RObject::setMember(getData().autoTextPos, value, PropertyAutoTextPos == propertyTypeId);
// if (RPluginLoader::hasPlugin("DWG")) {
// ret = ret || RObject::setMember(getData().fontName, value, PropertyFontName == propertyTypeId);
// }
// ret = ret || RObject::setMember(getData().textHeight, value, PropertyHeight == propertyTypeId);
// ret = ret || RObject::setMember(getData().angle, value, PropertyAngle == propertyTypeId);
// ret = ret || RObject::setMember(getData().lineSpacingFactor, value, PropertyLineSpacingFactor == propertyTypeId);
// ret = ret || RObject::setMember((int&)getData().horizontalAlignment, value.value<int>(), PropertyHAlign == propertyTypeId);
// ret = ret || RObject::setMember((int&)getData().verticalAlignment, value.value<int>(), PropertyVAlign == propertyTypeId);
if (ret) {
getData().update();
}
return ret;
}
QPair<QVariant, RPropertyAttributes> RDimensionEntity::getProperty(
RPropertyTypeId& propertyTypeId, bool humanReadable, bool noAttributes) {
if (propertyTypeId == PropertyDefinitionPointX) {
return qMakePair(QVariant(getData().definitionPoint.x), RPropertyAttributes());
} else if (propertyTypeId == PropertyDefinitionPointY) {
return qMakePair(QVariant(getData().definitionPoint.y), RPropertyAttributes());
} else if (propertyTypeId == PropertyDefinitionPointZ) {
return qMakePair(QVariant(getData().definitionPoint.z), RPropertyAttributes());
} else if (propertyTypeId == PropertyMiddleOfTextX) {
if (getData().textPositionSide.isValid()) {
return qMakePair(QVariant(getData().textPositionSide.x), RPropertyAttributes());
}
else {
return qMakePair(QVariant(getData().textPositionCenter.x), RPropertyAttributes());
}
} else if (propertyTypeId == PropertyMiddleOfTextY) {
if (getData().textPositionSide.isValid()) {
return qMakePair(QVariant(getData().textPositionSide.y), RPropertyAttributes());
}
else {
return qMakePair(QVariant(getData().textPositionCenter.y), RPropertyAttributes());
}
} else if (propertyTypeId == PropertyMiddleOfTextZ) {
if (getData().textPositionSide.isValid()) {
return qMakePair(QVariant(getData().textPositionSide.z), RPropertyAttributes());
}
else {
return qMakePair(QVariant(getData().textPositionCenter.z), RPropertyAttributes());
}
} else if (propertyTypeId == PropertyText) {
return qMakePair(QVariant(getData().text),
RPropertyAttributes(RPropertyAttributes::DimensionLabel));
} else if (propertyTypeId == PropertyUpperTolerance) {
return qMakePair(QVariant(getData().upperTolerance),
RPropertyAttributes(RPropertyAttributes::Label));
} else if (propertyTypeId == PropertyLowerTolerance) {
return qMakePair(QVariant(getData().lowerTolerance),
RPropertyAttributes(RPropertyAttributes::Label));
} else if (propertyTypeId == PropertyAutoLabel) {
if (getType()==RS::EntityDimAngular) {
return qMakePair(QVariant(getData().getAutoLabel()),
RPropertyAttributes(RPropertyAttributes::ReadOnly | RPropertyAttributes::Angle));
}
else {
return qMakePair(QVariant(getData().getAutoLabel()),
RPropertyAttributes(RPropertyAttributes::ReadOnly));
}
} else if (propertyTypeId == PropertyMeasuredValue) {
if (getType()==RS::EntityDimAngular) {
return qMakePair(QVariant(getData().getMeasuredValue()),
RPropertyAttributes(RPropertyAttributes::ReadOnly | RPropertyAttributes::Angle));
}
else {
return qMakePair(QVariant(getData().getMeasuredValue()),
RPropertyAttributes(RPropertyAttributes::ReadOnly));
}
} else if (propertyTypeId == PropertyLinearFactor) {
return qMakePair(QVariant(getData().linearFactor), RPropertyAttributes());
} else if (propertyTypeId == PropertyDimScale) {
return qMakePair(QVariant(getData().dimScale), RPropertyAttributes());
} else if (propertyTypeId == PropertyDimBlockName) {
return qMakePair(QVariant(getData().dimBlockName), RPropertyAttributes(RPropertyAttributes::ReadOnly));
} else if (propertyTypeId == PropertyAutoTextPos) {
return qMakePair(QVariant(getData().autoTextPos), RPropertyAttributes(RPropertyAttributes::Invisible));
}
// else if (propertyTypeId == PropertyFontName) {
// return qMakePair(QVariant(getData().fontName),
// RPropertyAttributes(RPropertyAttributes::Style));
// }
/*else if (propertyTypeId == PropertyHeight) {
return qMakePair(QVariant(getData().textHeight), RPropertyAttributes());
} else if (propertyTypeId == PropertyAngle) {
return qMakePair(QVariant(getData().angle), RPropertyAttributes(
RPropertyAttributes::Angle));
} else if (propertyTypeId == PropertyLineSpacingFactor) {
return qMakePair(QVariant(getData().lineSpacingFactor), RPropertyAttributes());
} else if (propertyTypeId == PropertyHAlign) {
return qMakePair(QVariant(getData().horizontalAlignment), RPropertyAttributes());
} else if (propertyTypeId == PropertyVAlign) {
return qMakePair(QVariant(getData().verticalAlignment), RPropertyAttributes());
}*/
return REntity::getProperty(propertyTypeId, humanReadable, noAttributes);
}
void RDimensionEntity::exportEntity(RExporter& e, bool preview, bool forceSelected) const {
Q_UNUSED(preview);
// make sure text data is removed:
//e.unexportEntity(e.getBlockRefOrEntity()->getId());
const RDimensionData& data = getData();
// if a block is assiciated with this dimension, look up and export block:
QSharedPointer<RBlockReferenceEntity> dimBlockReference = data.getDimensionBlockReference();
if (!dimBlockReference.isNull()) {
getDocument()->getStorage().setObjectId(*dimBlockReference, getId());
e.exportEntity(*dimBlockReference, preview, false, isSelected());
return;
}
data.dirty = true;
// export shapes:
QList<QSharedPointer<RShape> > shapes = getShapes();
//e.setBrush(Qt::NoBrush);
//e.exportShapes(shapes);
QBrush brush = e.getBrush();
for (int i=0; i<shapes.size(); i++) {
QSharedPointer<RShape> s = shapes.at(i);
if (s.isNull()) {
continue;
}
// triangles (arrows) are filled:
if (!s.dynamicCast<RTriangle>().isNull()) {
e.setBrush(brush);
}
// lines are not filled:
else {
e.setBrush(Qt::NoBrush);
}
e.exportShape(s);
}
// export text label:
RTextData& textData = data.getTextData();
//qDebug() << "export dim: angle: " << textData.getAngle();
if (RSettings::isTextRenderedAsText()) {
QList<RPainterPath> paths = e.exportText(textData, forceSelected);
e.exportPainterPaths(paths);
}
else {
e.setBrush(brush);
e.exportPainterPathSource(textData);
}
e.setBrush(Qt::NoBrush);
data.dirty = false;
}
void RDimensionEntity::print(QDebug dbg) const {
dbg.nospace() << "RDimensionEntity(";
REntity::print(dbg);
dbg.nospace() << ", definitionPoint: " << getData().definitionPoint
<< ", autoTextPos: " << getData().autoTextPos
<< ", middleOfText: " << getData().getTextPosition()
<< ", text: " << getData().text
<< ", upper tolerance: " << getData().upperTolerance
<< ", lower tolerance: " << getData().lowerTolerance
<< ", measurement (label): " << getData().getMeasurement(true)
<< ", measurement (stored): " << getData().getMeasurement(false)
<< ", dimscale: " << getData().getDimScale()
<< ")";
}
| 54.61465 | 170 | 0.72115 | ouxianghui |
b05fc83f6dc3bcb9390f9d004b6a905d84165c44 | 5,826 | cc | C++ | doc/user-guide/core-functionalities/functionspace/NodeColumns.cc | egparedes/atlas | fff4b692334b1dcb5abd14a36a09df9c9204b08b | [
"Apache-2.0"
] | 1 | 2019-12-02T20:41:33.000Z | 2019-12-02T20:41:33.000Z | doc/user-guide/core-functionalities/functionspace/NodeColumns.cc | egparedes/atlas | fff4b692334b1dcb5abd14a36a09df9c9204b08b | [
"Apache-2.0"
] | null | null | null | doc/user-guide/core-functionalities/functionspace/NodeColumns.cc | egparedes/atlas | fff4b692334b1dcb5abd14a36a09df9c9204b08b | [
"Apache-2.0"
] | null | null | null | #include "atlas/functionspace/NodeColumns.h"
#include "atlas/array/ArrayView.h"
#include "atlas/field.h"
#include "atlas/grid.h"
#include "atlas/library/Library.h"
#include "atlas/mesh.h"
#include "atlas/meshgenerator.h"
#include "atlas/output/Gmsh.h"
#include "atlas/runtime/Log.h"
using namespace atlas;
using atlas::StructuredMeshGenerator;
using atlas::array::make_shape;
using atlas::array::make_view;
using atlas::functionspace::NodeColumns;
using atlas::gidx_t;
using atlas::idx_t;
using atlas::StructuredGrid;
using atlas::output::Gmsh;
int main( int argc, char* argv[] ) {
atlas::Library::instance().initialise( argc, argv );
// Generate global classic reduced Gaussian grid
StructuredGrid grid( "N32" );
// Generate mesh associated to structured grid
StructuredMeshGenerator meshgenerator;
Mesh mesh = meshgenerator.generate( grid );
// Number of nodes in the mesh
// (different from number of points on a grid!)
size_t nb_nodes = mesh.nodes().size();
// Number of vertical levels required
size_t nb_levels = 10;
// Generate functionspace associated to mesh
NodeColumns fs_nodes( mesh, option::levels( nb_levels ) | option::halo( 1 ) );
// Note on field generation
Field field_scalar1 = fs_nodes.createField<double>( option::name( "scalar1" ) | option::levels( false ) );
Field field_scalar2 = fs_nodes.createField<double>( option::name( "scalar2" ) );
Field field_vector1 =
fs_nodes.createField<double>( option::name( "vector1" ) | option::levels( false ) | option::variables( 2 ) );
Field field_vector2 = fs_nodes.createField<double>( option::name( "vector2" ) | option::variables( 2 ) );
Field field_tensor1 = fs_nodes.createField<double>( option::name( "tensor1" ) | option::levels( false ) |
option::variables( 2 * 2 ) );
Field field_tensor2 = fs_nodes.createField<double>( option::name( "tensor2" ) | option::variables( 2 * 2 ) );
/* .... */
// Variables for scalar1 field definition
const double rpi = 2.0 * asin( 1.0 );
const double deg2rad = rpi / 180.;
const double zlatc = 0.0 * rpi;
const double zlonc = 1.0 * rpi;
const double zrad = 2.0 * rpi / 9.0;
double zdist, zlon, zlat;
// Retrieve lonlat field to calculate scalar1 function
auto scalar1 = make_view<double, 1>( field_scalar1 );
auto lonlat = make_view<double, 2>( mesh.nodes().lonlat() );
for ( size_t jnode = 0; jnode < nb_nodes; ++jnode ) {
zlon = lonlat( jnode, 0 ) * deg2rad;
zlat = lonlat( jnode, 1 ) * deg2rad;
zdist =
2.0 * sqrt( ( cos( zlat ) * sin( ( zlon - zlonc ) / 2 ) ) * ( cos( zlat ) * sin( ( zlon - zlonc ) / 2 ) ) +
sin( ( zlat - zlatc ) / 2 ) * sin( ( zlat - zlatc ) / 2 ) );
scalar1( jnode ) = 0.0;
if ( zdist < zrad ) { scalar1( jnode ) = 0.5 * ( 1. + cos( rpi * zdist / zrad ) ); }
}
// Write mesh and field in gmsh format for visualization
Gmsh gmsh( "scalar1.msh" );
gmsh.write( mesh );
gmsh.write( field_scalar1 );
/* .... */
// Halo exchange
fs_nodes.haloExchange( field_scalar1 );
std::string checksum = fs_nodes.checksum( field_scalar1 );
Log::info() << checksum << std::endl;
// Create a global field
Field field_global = fs_nodes.createField( field_scalar1, option::name( "global" ) | option::global() );
// Gather operation
fs_nodes.gather( field_scalar1, field_global );
Log::info() << "local nodes = " << fs_nodes.nb_nodes() << std::endl;
Log::info() << "grid points = " << grid.size() << std::endl;
Log::info() << "field_global.shape(0) = " << field_global.shape( 0 ) << std::endl;
// Scatter operation
fs_nodes.scatter( field_global, field_scalar1 );
// Halo exchange and checksum
fs_nodes.haloExchange( field_scalar1 );
checksum = fs_nodes.checksum( field_scalar1 );
Log::info() << field_scalar1.name() << " checksum : " << checksum << std::endl;
// FieldSet checksum
FieldSet fields;
fields.add( field_scalar1 );
fields.add( field_vector1 );
checksum = fs_nodes.checksum( fields );
Log::info() << "FieldSet checksum : " << checksum << std::endl;
/* .... */
// Operations
idx_t N;
gidx_t gidx_min, gidx_max;
double min, max, sum, mean, stddev;
// Minimum and maximum
fs_nodes.minimum( field_scalar1, min );
fs_nodes.maximum( field_scalar1, max );
Log::info() << "min: " << min << std::endl;
Log::info() << "max: " << max << std::endl;
// Minimum and maximum + location
fs_nodes.minimumAndLocation( field_scalar1, min, gidx_min );
fs_nodes.maximumAndLocation( field_scalar1, max, gidx_max );
Log::info() << "min: " << min << ", "
<< "global_id = " << gidx_min << std::endl;
Log::info() << "max: " << max << ", "
<< "global_id = " << gidx_max << std::endl;
// Summation
fs_nodes.sum( field_scalar1, sum, N );
Log::info() << "sum: " << sum << ", nb_nodes = " << N << std::endl;
// Order independent (from partitioning) summation
fs_nodes.orderIndependentSum( field_scalar1, sum, N );
Log::info() << "oi_sum: " << sum << ", nb_nodes = " << N << std::endl;
// Average over number of nodes
fs_nodes.mean( field_scalar1, mean, N );
Log::info() << "mean: " << mean << ", nb_nodes = " << N << std::endl;
// Average and standard deviation over number of nodes
fs_nodes.meanAndStandardDeviation( field_scalar1, mean, stddev, N );
Log::info() << "mean = " << mean << ", "
<< "std_deviation: " << stddev << ", "
<< "nb_nodes: " << N << std::endl;
atlas::Library::instance().finalise();
return 0;
}
| 38.328947 | 119 | 0.60539 | egparedes |
b0601f9cf3454394bcedea54ce2f50e5069a8e59 | 397 | cpp | C++ | Level_4/1_ExamGrade/ExamGrade.cpp | LeeHeungrok/BaekjoonAlgorithm | fca6ce5729938df64099074e9276325ca5e11c8a | [
"MIT"
] | null | null | null | Level_4/1_ExamGrade/ExamGrade.cpp | LeeHeungrok/BaekjoonAlgorithm | fca6ce5729938df64099074e9276325ca5e11c8a | [
"MIT"
] | null | null | null | Level_4/1_ExamGrade/ExamGrade.cpp | LeeHeungrok/BaekjoonAlgorithm | fca6ce5729938df64099074e9276325ca5e11c8a | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void){
int examGrade;
cin>>examGrade;
if(examGrade >= 90){
cout<<"A"<<endl;
}
else if(examGrade >= 80){
cout<<"B"<<endl;
}
else if(examGrade >= 70){
cout<<"C"<<endl;
}
else if(examGrade >= 60){
cout<<"D"<<endl;
}
else {
cout<<"F"<<endl;
}
return 0;
} | 14.703704 | 29 | 0.471033 | LeeHeungrok |
b061614cac6d8d343308adb38f0ef5047c6ea317 | 1,346 | cpp | C++ | TSS/src/locotrain.cpp | valdiz777/TSS | 49c915a2da83eab202a2c5ea992c95f8e0d3d06b | [
"MIT"
] | null | null | null | TSS/src/locotrain.cpp | valdiz777/TSS | 49c915a2da83eab202a2c5ea992c95f8e0d3d06b | [
"MIT"
] | null | null | null | TSS/src/locotrain.cpp | valdiz777/TSS | 49c915a2da83eab202a2c5ea992c95f8e0d3d06b | [
"MIT"
] | null | null | null | #include "locotrain.h"
bool LocoTrain::debug = false;
LocoTrain::LocoTrain()
{
name = "";
slot = LocoByte("00");
adr = LocoByte("00");
speed = LocoByte("00");
reverse = 1;
}
LocoTrain::~LocoTrain()
{
}
QString LocoTrain::timeStamp()
{
return(QTime::currentTime().toString("[HH:mm:ss:zzz] "));
}
bool LocoTrain::operator ==(LocoTrain _arg)
{
return((this->get_adr() == _arg.get_adr()) && (this->get_slot() == _arg.get_slot()));
}
void LocoTrain::set_name(QString _name)
{
name = _name;
}
void LocoTrain::set_adr(LocoByte _adr)
{
adr = _adr;
}
void LocoTrain::set_slot(LocoByte _slot)
{
slot = _slot;
}
void LocoTrain::set_reverse(bool _forward)
{
reverse = _forward;
}
void LocoTrain::set_speed(LocoByte _speed)
{
speed = _speed;
}
void LocoTrain::set_state(QString _state)
{
state = _state;
}
QString LocoTrain::get_state()
{
return(state);
}
LocoByte LocoTrain::get_adr()
{
return (adr);
}
LocoByte LocoTrain::get_slot()
{
return(slot);
}
LocoByte LocoTrain::get_speed()
{
return(speed);
}
bool LocoTrain::get_direction()
{
return(reverse);
}
QString LocoTrain::get_descrtiption()
{
QString _desc = "Train[" + adr.get_hex() + "]";
_desc.append(" Slot[" + slot.get_hex() + "]");
_desc.append(" Speed[" + speed.get_hex() + "]");
_desc.append(" Reverse[" + QString::number(reverse) + "]");
return(_desc);
}
| 14.630435 | 86 | 0.661218 | valdiz777 |
b062af68b9cd6c89c1e6074d4f0f713cffbcbe6d | 2,413 | cpp | C++ | test/SelectedEntryTest.cpp | DronMDF/zond | c882400aff5f41569e6deee609ddbe7b2b1bc378 | [
"MIT"
] | 5 | 2018-11-14T19:46:49.000Z | 2022-01-08T09:00:45.000Z | test/SelectedEntryTest.cpp | DronMDF/zond | c882400aff5f41569e6deee609ddbe7b2b1bc378 | [
"MIT"
] | 223 | 2018-11-14T19:20:27.000Z | 2019-02-13T11:53:23.000Z | test/SelectedEntryTest.cpp | DronMDF/zond | c882400aff5f41569e6deee609ddbe7b2b1bc378 | [
"MIT"
] | null | null | null | // Copyright (c) 2018-2019 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include "SelectedEntryTest.h"
#include "../http/EqualCriterion.h"
#include "../http/HttpHeader.h"
#include "../http/HttpRequest.h"
#include "../http/Response.h"
#include "../http/MethodCriterion.h"
#include "../http/SelectedEntry.h"
#include "EntryRepr.h"
#include "FakeEntry.h"
using namespace std;
using namespace oout;
SelectedEntryTest::SelectedEntryTest()
: TestSuite(
make_shared<TestNamed>(
"SelectedEntry select entry by matched uri",
make_shared<TestContainText>(
make_shared<EntryRepr>(
make_shared<SelectedEntry>(
make_shared<EqualCriterion>("/version"),
make_shared<FakeEntry>("Wooho")
),
make_shared<HttpRequest>(
"GET /version HTTP/1.1\r\n"
"\r\n"
)
),
"Wooho"
)
),
make_shared<TestNamed>(
"SelectedEntry select last entry as fallback",
make_shared<TestContainText>(
make_shared<EntryRepr>(
make_shared<SelectedEntry>(
make_shared<EqualCriterion>("/version"),
make_shared<FakeEntry>("Wow"),
make_shared<FakeEntry>("Failure")
),
make_shared<HttpRequest>(
"GET /something HTTP/1.1\r\n"
"\r\n"
)
),
"Failure"
)
),
make_shared<TestNamed>(
"SelectedEntry chain entries",
make_shared<TestContainText>(
make_shared<EntryRepr>(
make_shared<SelectedEntry>(
make_shared<EqualCriterion>("/first"),
make_shared<FakeEntry>("First"),
make_shared<EqualCriterion>("/second"),
make_shared<FakeEntry>("Second"),
make_shared<FakeEntry>("Last")
),
make_shared<HttpRequest>(
"GET /second HTTP/1.1\r\n"
"\r\n"
)
),
"Second"
)
),
make_shared<TestNamed>(
"SelectedEntry check by method too",
make_shared<TestContainText>(
make_shared<EntryRepr>(
make_shared<SelectedEntry>(
make_shared<MethodCriterion>(
"GET",
make_shared<EqualCriterion>("/uri")
),
make_shared<FakeEntry>("Get"),
make_shared<MethodCriterion>(
"POST",
make_shared<EqualCriterion>("/uri")
),
make_shared<FakeEntry>("Post")
),
make_shared<HttpRequest>(
"POST /uri HTTP/1.1\r\n"
"\r\n"
)
),
"Post"
)
)
)
{
}
| 24.13 | 66 | 0.636966 | DronMDF |
b0648b54dbf40086ac386e7e90446ccf2e32c4ae | 3,913 | cpp | C++ | stl/src/wlocale.cpp | elay00/STL | 7f04137880e1c3df5125c1baf808f16f399dee2e | [
"Apache-2.0"
] | null | null | null | stl/src/wlocale.cpp | elay00/STL | 7f04137880e1c3df5125c1baf808f16f399dee2e | [
"Apache-2.0"
] | null | null | null | stl/src/wlocale.cpp | elay00/STL | 7f04137880e1c3df5125c1baf808f16f399dee2e | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// class locale wide member functions
#include <istream>
#include <locale>
_STD_BEGIN
#pragma warning(disable : 4074)
#pragma init_seg(compiler)
// facets associated with C categories
#define ADDFAC(Facet, cat, ptrimp, ptrloc) \
if ((_CATMASK(Facet::_Getcat()) & cat) == 0) { \
; \
} else if (ptrloc == nullptr) { \
ptrimp->_Addfac(new Facet(lobj), Facet::id); \
} else { \
ptrimp->_Addfac( \
const_cast<locale::facet*>(static_cast<const locale::facet*>(&_STD use_facet<Facet>(*ptrloc))), \
Facet::id); \
}
// moved from locale to ease subsetting
using _Tw1 = ctype<wchar_t>;
using _Tw2 = num_get<wchar_t>;
using _Tw3 = num_put<wchar_t>;
using _Tw4 = numpunct<wchar_t>;
using _Tw5 = collate<wchar_t>;
using _Tw6 = messages<wchar_t>;
using _Tw7 = money_get<wchar_t>;
using _Tw8 = money_put<wchar_t>;
using _Tw9 = moneypunct<wchar_t, false>;
using _Tw10 = moneypunct<wchar_t, true>;
using _Tw11 = time_get<wchar_t>;
using _Tw12 = time_put<wchar_t>;
using _Tw13 = codecvt<wchar_t, char, _Mbstatet>;
__PURE_APPDOMAIN_GLOBAL locale::id time_put<wchar_t>::id(0);
void __CLRCALL_OR_CDECL locale::_Locimp::_Makewloc(const _Locinfo& lobj, locale::category cat, _Locimp* ptrimp,
const locale* ptrloc) { // setup wide part of a new locale
ADDFAC(_Tw1, cat, ptrimp, ptrloc);
ADDFAC(_Tw2, cat, ptrimp, ptrloc);
ADDFAC(_Tw3, cat, ptrimp, ptrloc);
ADDFAC(_Tw4, cat, ptrimp, ptrloc);
ADDFAC(_Tw5, cat, ptrimp, ptrloc);
ADDFAC(_Tw6, cat, ptrimp, ptrloc);
ADDFAC(_Tw7, cat, ptrimp, ptrloc);
ADDFAC(_Tw8, cat, ptrimp, ptrloc);
ADDFAC(_Tw9, cat, ptrimp, ptrloc);
ADDFAC(_Tw10, cat, ptrimp, ptrloc);
ADDFAC(_Tw11, cat, ptrimp, ptrloc);
ADDFAC(_Tw12, cat, ptrimp, ptrloc);
ADDFAC(_Tw13, cat, ptrimp, ptrloc);
}
// moved from locale to ease subsetting
using _Tu1 = ctype<unsigned short>;
using _Tu2 = num_get<unsigned short>;
using _Tu3 = num_put<unsigned short>;
using _Tu4 = numpunct<unsigned short>;
using _Tu5 = collate<unsigned short>;
using _Tu6 = messages<unsigned short>;
using _Tu7 = money_get<unsigned short>;
using _Tu8 = money_put<unsigned short>;
using _Tu9 = moneypunct<unsigned short, false>;
using _Tu10 = moneypunct<unsigned short, true>;
using _Tu11 = time_get<unsigned short>;
using _Tu12 = time_put<unsigned short>;
using _Tu13 = codecvt<unsigned short, char, _Mbstatet>;
void __CLRCALL_OR_CDECL locale::_Locimp::_Makeushloc(const _Locinfo& lobj, locale::category cat, _Locimp* ptrimp,
const locale* ptrloc) { // setup wide part of a new locale
ADDFAC(_Tu1, cat, ptrimp, ptrloc);
ADDFAC(_Tu2, cat, ptrimp, ptrloc);
ADDFAC(_Tu3, cat, ptrimp, ptrloc);
ADDFAC(_Tu4, cat, ptrimp, ptrloc);
ADDFAC(_Tu5, cat, ptrimp, ptrloc);
ADDFAC(_Tu6, cat, ptrimp, ptrloc);
ADDFAC(_Tu7, cat, ptrimp, ptrloc);
ADDFAC(_Tu8, cat, ptrimp, ptrloc);
ADDFAC(_Tu9, cat, ptrimp, ptrloc);
ADDFAC(_Tu10, cat, ptrimp, ptrloc);
ADDFAC(_Tu11, cat, ptrimp, ptrloc);
ADDFAC(_Tu12, cat, ptrimp, ptrloc);
ADDFAC(_Tu13, cat, ptrimp, ptrloc);
}
_STD_END
| 43 | 114 | 0.567851 | elay00 |
b065bddc05ce7632d3e5cdc60ef43a602ce47995 | 6,820 | cpp | C++ | Code/src/OE/Misc/RectsPacker.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 21 | 2018-06-26T16:37:36.000Z | 2022-01-11T01:19:42.000Z | Code/src/OE/Misc/RectsPacker.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | null | null | null | Code/src/OE/Misc/RectsPacker.cpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 3 | 2019-10-01T14:10:50.000Z | 2021-11-19T20:30:18.000Z | #include "OE/Misc/RectsPacker.hpp"
/*
This is a modified version of this algorithm:
http://blackpawn.com/texts/lightmaps/default.html
*/
#include "OE/Math/Math.hpp"
namespace OrbitEngine { namespace Misc {
bool area(Packeable2D* a, Packeable2D* b) {
return a->area() > b->area();
}
bool perimeter(Packeable2D* a, Packeable2D* b) {
return a->perimeter() > b->perimeter();
}
bool max_side(Packeable2D* a, Packeable2D* b) {
return std::max(a->w, a->h) > std::max(b->w, b->h);
}
bool max_width(Packeable2D* a, Packeable2D* b) {
return a->w > b->w;
}
bool max_height(Packeable2D* a, Packeable2D* b) {
return a->h > b->h;
}
bool(*cmpf[])(Packeable2D*, Packeable2D*) = {
area,
perimeter,
max_side,
max_width,
max_height
};
struct Packeable2DNode {
struct pnode {
Packeable2DNode* pn;
bool fill;
pnode() : fill(false), pn(0) {}
void set(int l, int t, int r, int b) {
if (!pn) pn = new Packeable2DNode(Packeable2DRectLTRB(l, t, r, b));
else {
(*pn).rc = Packeable2DRectLTRB(l, t, r, b);
(*pn).id = false;
}
fill = true;
}
};
pnode c[2];
Packeable2DRectLTRB rc;
bool id;
Packeable2DNode(Packeable2DRectLTRB rc = Packeable2DRectLTRB()) : id(false), rc(rc) {}
void reset(const Packeable2DRectWH& r) {
id = false;
rc = Packeable2DRectLTRB(0, 0, r.w, r.h);
delcheck();
}
Packeable2DNode* insert(Packeable2D& img) {
if (c[0].pn && c[0].fill) {
Packeable2DNode* newn;
if (newn = c[0].pn->insert(img)) return newn;
return c[1].pn->insert(img);
}
if (id) return 0;
int f = img.fits(Packeable2DRectXYWH(rc));
switch (f) {
case 0: return 0;
case 1: img.flipped = false; break;
case 2: img.flipped = true; break;
case 3: id = true; img.flipped = false; return this;
case 4: id = true; img.flipped = true; return this;
}
int iw = (img.flipped ? img.h : img.w), ih = (img.flipped ? img.w : img.h);
if (rc.w() - iw > rc.h() - ih) {
c[0].set(rc.l, rc.t, rc.l + iw, rc.b);
c[1].set(rc.l + iw, rc.t, rc.r, rc.b);
}
else {
c[0].set(rc.l, rc.t, rc.r, rc.t + ih);
c[1].set(rc.l, rc.t + ih, rc.r, rc.b);
}
return c[0].pn->insert(img);
}
void delcheck() {
if (c[0].pn) { c[0].fill = false; c[0].pn->delcheck(); }
if (c[1].pn) { c[1].fill = false; c[1].pn->delcheck(); }
}
~Packeable2DNode() {
if (c[0].pn) delete c[0].pn;
if (c[1].pn) delete c[1].pn;
}
};
bool Packer2D::Pack(std::vector<Packeable2D*>& rects, int max_side, unsigned int& out_width, unsigned int& out_height, int discard_step) {
Packeable2DRectWH size(max_side, max_side);
for (Packeable2D* p : rects)
if (!p->fits(size)) return false;
Packeable2DNode root;
const int funcs = (sizeof(cmpf) / sizeof(bool(*)(Packeable2D*, Packeable2D*)));
std::vector<Packeable2D*> order[funcs];
for (int f = 0; f < funcs; ++f) {
order[f] = std::vector<Packeable2D*>(rects);
std::sort(order[f].begin(), order[f].end(), cmpf[f]);
}
int min_func = -1, best_func = 0, best_area = 0, _area = 0, step, fit;
size_t i;
bool fail = false;
for (int f = 0; f < funcs; ++f) {
rects = order[f];
step = size.w / 2;
root.reset(size);
while (true) {
if (root.rc.w() > size.w) {
if (min_func > -1) break;
_area = 0;
root.reset(size);
for (i = 0; i < rects.size(); ++i)
if (root.insert(*rects[i]))
_area += rects[i]->area();
fail = true;
break;
}
fit = -1;
for (i = 0; i < rects.size(); ++i)
if (!root.insert(*rects[i])) {
fit = 1;
break;
}
if (fit == -1 && step <= discard_step)
break;
root.reset(Packeable2DRectWH(root.rc.w() + fit*step, root.rc.h() + fit*step));
step /= 2;
if (!step)
step = 1;
}
if (!fail && (size.area() >= root.rc.area())) {
size = Packeable2DRectWH(root.rc);
min_func = f;
}
else if (fail && (_area > best_area)) {
best_area = _area;
best_func = f;
}
fail = false;
}
rects = order[min_func == -1 ? best_func : min_func];
int clip_x = 0, clip_y = 0;
Packeable2DNode* ret;
root.reset(size);
for (i = 0; i < rects.size(); ++i) {
if (ret = root.insert(*rects[i])) {
rects[i]->x = ret->rc.l;
rects[i]->y = ret->rc.t;
if (rects[i]->flipped) {
rects[i]->flipped = false;
rects[i]->flip();
}
clip_x = std::max(clip_x, ret->rc.r);
clip_y = std::max(clip_y, ret->rc.b);
}
else
return false;
}
for (int f = 0; f < funcs; ++f) {
order[f].clear();
order[f].shrink_to_fit();
}
out_width = clip_x;
out_height = clip_y;
return true;
}
Packeable2DRectWH::Packeable2DRectWH(const Packeable2DRectLTRB& rr) : w(rr.w()), h(rr.h()) {}
Packeable2DRectWH::Packeable2DRectWH(const Packeable2DRectXYWH& rr) : w(rr.w), h(rr.h) {}
Packeable2DRectWH::Packeable2DRectWH(int w, int h) : w(w), h(h) {}
int Packeable2DRectWH::fits(const Packeable2DRectWH& r) const {
if (w == r.w && h == r.h) return 3;
if (h == r.w && w == r.h) return 4;
if (w <= r.w && h <= r.h) return 1;
if (h <= r.w && w <= r.h) return 2;
return 0;
}
Packeable2DRectLTRB::Packeable2DRectLTRB() : l(0), t(0), r(0), b(0) {}
Packeable2DRectLTRB::Packeable2DRectLTRB(int l, int t, int r, int b) : l(l), t(t), r(r), b(b) {}
int Packeable2DRectLTRB::w() const {
return r - l;
}
int Packeable2DRectLTRB::h() const {
return b - t;
}
int Packeable2DRectLTRB::area() const {
return w()*h();
}
int Packeable2DRectLTRB::perimeter() const {
return 2 * w() + 2 * h();
}
void Packeable2DRectLTRB::w(int ww) {
r = l + ww;
}
void Packeable2DRectLTRB::h(int hh) {
b = t + hh;
}
Packeable2DRectXYWH::Packeable2DRectXYWH() : x(0), y(0) {}
Packeable2DRectXYWH::Packeable2DRectXYWH(const Packeable2DRectLTRB& rc) : x(rc.l), y(rc.t) { b(rc.b); r(rc.r); }
Packeable2DRectXYWH::Packeable2DRectXYWH(int x, int y, int w, int h) : x(x), y(y), Packeable2DRectWH(w, h) {}
Packeable2DRectXYWH::operator Packeable2DRectLTRB() {
Packeable2DRectLTRB rr(x, y, 0, 0);
rr.w(w); rr.h(h);
return rr;
}
int Packeable2DRectXYWH::r() const {
return x + w;
};
int Packeable2DRectXYWH::b() const {
return y + h;
}
void Packeable2DRectXYWH::r(int right) {
w = right - x;
}
void Packeable2DRectXYWH::b(int bottom) {
h = bottom - y;
}
int Packeable2DRectWH::area() {
return w * h;
}
int Packeable2DRectWH::perimeter() {
return 2 * w + 2 * h;
}
Packeable2D::Packeable2D(const Packeable2DRectLTRB& rr) : Packeable2DRectXYWH(rr), flipped(false) {}
Packeable2D::Packeable2D(int x, int y, int width, int height) : Packeable2DRectXYWH(x, y, width, height), flipped(false) {}
Packeable2D::Packeable2D() : flipped(false) {}
void Packeable2D::flip() {
flipped = !flipped;
std::swap(w, h);
}
} } | 23.197279 | 139 | 0.589589 | mlomb |
b068406ae9586c61520c5083560ef173049838cf | 6,682 | cc | C++ | lib/ghmm.cc | wwood/exportpred | 55238e5f06d7837b27899cd51bc3f3763d2233c8 | [
"MIT"
] | 1 | 2018-06-23T06:05:56.000Z | 2018-06-23T06:05:56.000Z | lib/ghmm.cc | wwood/exportpred | 55238e5f06d7837b27899cd51bc3f3763d2233c8 | [
"MIT"
] | null | null | null | lib/ghmm.cc | wwood/exportpred | 55238e5f06d7837b27899cd51bc3f3763d2233c8 | [
"MIT"
] | null | null | null | // Copyright (c) 2005 The Walter and Eliza Hall Institute
//
// 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 <GHMM/ghmm.hh>
const static int C_BEGIN = -1;
const static int C_END = -2;
using namespace GHMM;
const std::string Model::BEGIN = "__BEGIN__";
const std::string Model::END = "__END__";
Model::Model(const std::vector<std::pair<std::string, StateBase::Ptr> > &in_states,
const std::map<std::pair<int, int>, double> &in_state_trans_map) :
RefObj(), state_names(), state_name_map(), pred_states(), succ_states(), states(), state_trans(NULL), state_count(0) {
std::vector<bool> reachable(in_states.size(), false);
{
int l = in_states.size() + 2;
int *a = new int[l * l];
std::fill(a, a + l * l, 0);
for (std::map<std::pair<int, int>, double>::const_iterator i = in_state_trans_map.begin(), e = in_state_trans_map.end(); i != e; ++i) {
int s = (*i).first.first;
int t = (*i).first.second;
if (s < 0) s += l;
if (t < 0) t += l;
a[s * l + t] = 1;
}
for (int k = 0; k < l; k++) {
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
a[i * l + j] = a[i * l + j] | (a[i * l + k] & a[k * l + j]);
}
}
}
for (int i = 0; i < (int)in_states.size(); i++) {
if (a[(l + C_BEGIN) * l + i] && a[(i * l) + (l + C_END)]) {
reachable[i] = true;
}
}
delete [] a;
}
std::map<int, int> state_num_remap;
states.push_back(StateBase::Ptr());
state_names.push_back(BEGIN);
state_num_remap[C_BEGIN] = 0;
for (unsigned i = 0; i < in_states.size(); i++) {
if (reachable[i] && in_states[i].second != NULL) {
// std::cerr << "REMAP " << i << " : " << in_states[i].first << " -> " << states.size() << std::endl;
state_num_remap[i] = states.size();
state_name_map[in_states[i].first] = states.size();
state_names.push_back(in_states[i].first);
states.push_back(in_states[i].second);
} else {
state_num_remap[i] = -1;
}
}
state_num_remap[C_END] = states.size();
states.push_back(StateBase::Ptr());
state_names.push_back(END);
state_count = states.size();
pred_states.resize(state_count);
succ_states.resize(state_count);
state_trans = new double[state_count * state_count];
state_log_trans = new double[state_count * state_count];
std::fill(state_trans, state_trans + state_count * state_count, 0.0);
for (std::map<std::pair<int, int>, double>::const_iterator i = in_state_trans_map.begin(), e = in_state_trans_map.end(); i != e; ++i) {
int s = state_num_remap[(*i).first.first];
int t = state_num_remap[(*i).first.second];
double p = (*i).second;
// std::cerr << "s=" << s << " -> t=" << t << " : " << p << std::endl;
state_trans[s * state_count + t] = p;
}
for (int s = 0; s < state_count - 1; s++) {
int idx = s * state_count;
double sum = std::accumulate(state_trans + idx, state_trans + idx + state_count, 0.0);
// std::cerr << "s=" << s << " sum=" << sum << std::endl;
assert(sum > 0.0);
for (int t = 0; t < state_count; t++) {
state_trans[idx + t] /= sum;
}
if (LENGTH::Geometric *gp = dynamic_cast<LENGTH::Geometric *>(&*states[s])) {
double p_self = gp->pLength(1);
double not_p_self = 1.0 - p_self;
for (int t = 0; t < s; t++) {
state_trans[s * state_count + t] *= not_p_self;
}
state_trans[s * state_count + s] = p_self;
for (int t = s + 1; t < state_count; t++) {
state_trans[s * state_count + t] *= not_p_self;
}
}
for (int t = 0; t < state_count; t++) {
if (state_trans[idx + t] != 0.0) {
pred_states[t].push_back(s);
succ_states[s].push_back(t);
}
}
}
for (int i = 0; i < state_count * state_count; i++) {
state_log_trans[i] = MATH::logClip(state_trans[i]);
}
// for (int i = 0; i < state_count; i++) {
// for (int j = 0; j < state_count; j++) {
// fprintf(stderr, "%9.7f ", state_trans[i * state_count + j]);
// }
// fprintf(stderr, "\n");
// }
}
Model::~Model() {
if (state_trans) delete [] state_trans;
if (state_log_trans) delete [] state_log_trans;
}
ModelBuilder::ModelBuilder() :
RefObj(), states(), state_name_map(), state_trans_map() {
state_name_map[Model::BEGIN] = C_BEGIN;
state_name_map[Model::END] = C_END;
}
ModelBuilder::~ModelBuilder() {
}
void ModelBuilder::addState(const std::string &state_name, const StateBase::Ptr &state) {
int i = stateNum(state_name);
if (i < 0) return;
states[i] = std::make_pair(state_name, state);
}
void ModelBuilder::removeState(const std::string &state_name) {
int s = stateNum(state_name);
if (s < 0) return;
// remove state.
states[s].second = NULL;
// remove transitions.
std::map<std::pair<int, int>, double>::iterator i = state_trans_map.begin(), j, e = state_trans_map.end();
while (i != e) {
if ((*i).first.first == s or (*i).first.second == s) {
j = i;
++j;
state_trans_map.erase(i);
} else {
++i;
}
}
}
int ModelBuilder::stateNum(const std::string &s) {
std::map<std::string, int>::iterator i = state_name_map.find(s);
if (i != state_name_map.end()) return i->second;
state_name_map[s] = states.size();
states.push_back(std::make_pair(s, StateBase::Ptr()));
return states.size() - 1;
}
void ModelBuilder::addStateTransition(const std::string &src_state, const std::string &tgt_state, double freq) {
state_trans_map[std::make_pair(stateNum(src_state), stateNum(tgt_state))] = freq;
}
Model::Ptr ModelBuilder::make() {
return new Model(states, state_trans_map);
}
| 33.243781 | 139 | 0.614636 | wwood |
b06e28e4bb831c4c3f30ed1a9882b86f941e0ee7 | 594 | cxx | C++ | panda/src/downloader/p3downloader_composite2.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/downloader/p3downloader_composite2.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/downloader/p3downloader_composite2.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | #include "httpAuthorization.cxx"
#include "httpBasicAuthorization.cxx"
#include "httpChannel.cxx"
#include "httpClient.cxx"
#include "httpCookie.cxx"
#include "httpDate.cxx"
#include "httpDigestAuthorization.cxx"
#include "httpEntityTag.cxx"
#include "httpEnum.cxx"
#include "identityStream.cxx"
#include "identityStreamBuf.cxx"
#include "multiplexStream.cxx"
#include "multiplexStreamBuf.cxx"
#include "patcher.cxx"
#include "socketStream.cxx"
#include "stringStreamBuf.cxx"
#include "stringStream.cxx"
#include "urlSpec.cxx"
#include "virtualFileHTTP.cxx"
#include "virtualFileMountHTTP.cxx"
| 28.285714 | 38 | 0.79798 | cmarshall108 |
b06e2b3129c556cc581ea35d8dc3a568e688b64b | 8,756 | cpp | C++ | src/Generation/BuildQueueBuilder.cpp | PoetaKodu/cpp-pkg | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | 9 | 2021-05-07T21:18:26.000Z | 2022-02-01T20:44:13.000Z | src/Generation/BuildQueueBuilder.cpp | PoetaKodu/pacc | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | null | null | null | src/Generation/BuildQueueBuilder.cpp | PoetaKodu/pacc | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | null | null | null | #include PACC_PCH
#include <Pacc/Generation/BuildQueueBuilder.hpp>
#include <Pacc/Generation/OutputFormatter.hpp>
#include <Pacc/System/Filesystem.hpp>
#include <Pacc/System/Environment.hpp>
///////////////////////////////////////////////////////////////
// Private functions (forward declaration)
///////////////////////////////////////////////////////////////
bool wasDependencyQueued(Dependency const& dep, BuildQueueBuilder::DepQueue const& readyQueue_);
bool projectHasPendingDependencies(Project const& project, BuildQueueBuilder::DepQueue const& readyQueue_);
bool packageHasPendingDependencies(PackageDependency & dep, BuildQueueBuilder::DepQueue const& readyQueue_);
bool selfPackageHasPendingDependencies(SelfDependency & dep, BuildQueueBuilder::DepQueue const& readyQueue_);
///////////////////////////////////////////////////////////////
// Public functions:
///////////////////////////////////////////////////////////////
void BuildQueueBuilder::performConfigurationMerging()
{
auto const& q = this->getQueue();
// fmt::print("Configuration steps: {}\n", q.size());
// size_t stepCounter = 0;
for(auto & step : q)
{
// fmt::print("Step {}: [ ", stepCounter++);
// size_t depCounter = 0;
for(auto & depInfo : step)
{
// if (depCounter++ != 0)
// fmt::print(", ");
// fmt::print("\"{}\"", dep.project->name);
Project& mergeTarget = *(depInfo.project);
AccessType mergeMode = depInfo.dep->accessType;
if (depInfo.dep->isSelf())
{
auto &selfDependency = depInfo.dep->self();
Project const& depProj = selfDependency.package->requireProject(selfDependency.depProjName);
mergeTarget.inheritConfigurationFrom(*selfDependency.package, depProj, mergeMode );
}
else if (depInfo.dep->isPackage())
{
auto& packageDependency = depInfo.dep->package();
// Should be loaded by now
auto& depReferencedPkg = *packageDependency.package;
for (auto const & depProjName : packageDependency.projects)
{
Project const& depProj = depReferencedPkg.requireProject(depProjName);
mergeTarget.inheritConfigurationFrom(depReferencedPkg, depProj, mergeMode );
}
}
}
// fmt::print(" ]\n", stepCounter++);
}
}
/////////////////////////////////////////////////
void BuildQueueBuilder::recursiveLoad(Package & pkg_)
{
const std::array<AccessType, 3> methodsLoop = {
AccessType::Private,
AccessType::Public,
AccessType::Interface
};
size_t methodIdx = 0;
for(auto & p : pkg_.projects)
{
std::vector<Configuration*> configs;
configs.reserve(1 + p.premakeFilters.size());
configs.push_back(&p);
for(auto& [key, value] : p.premakeFilters)
{
configs.push_back(&value);
}
for(Configuration* cfg : configs)
{
methodIdx = 0;
for(auto* access : getAccesses(cfg->dependencies.self))
{
for(auto& dep : *access)
{
dep.accessType = methodsLoop[methodIdx];
switch(dep.type())
{
case Dependency::Raw:
{
auto& rawDep = dep.raw();
// fmt::print("Added raw dependency \"{}\"\n", rawDep);
auto& target = targetByAccessType(cfg->linkedLibraries.computed, dep.accessType);
// TODO: improve this:
target.push_back( rawDep );
break;
}
case Dependency::Self:
{
pendingDeps.push_back( { &p, &dep } );
break;
}
case Dependency::Package:
{
pendingDeps.push_back( { &p, &dep } );
auto& pkgDep = dep.package();
PackagePtr pkgPtr;
// Load dependency (and bind it to shared pointer)
{
UPtr<Package> pkg;
try {
pkg = Package::loadByName(pkgDep.packageName, pkgDep.version, &pkg);
}
catch(PaccException &)
{
// This means that the package was loaded, but does not meet version requirements.
if (pkg && !pkg->name.empty())
{
throw PaccException("Could not load package \"{}\". Version \"{}\" is incompatible with requirement \"{}\"",
pkgDep.packageName, pkg->version.toString(), pkgDep.version.toString()
)
.withHelp(
"Consider installing version of the package that meets requirements.\n"
"You can list available package versions with \"pacc lsver [package_name]\"\n"
"To install package at a specific version, use \"pacc install [package_name]@[version]\""
);
}
else
throw; // Rethrow exception
}
if (this->isPackageLoaded(pkg->root))
continue; // ignore package, was loaded yet
// if (pkgDep.version.empty())
// fmt::print("Loaded dependency \"{}\"\n", pkgDep.packageName);
// else
// fmt::print("Loaded dependency \"{}\"@\"{}\"\n", pkgDep.packageName, pkgDep.version);
pkgPtr = std::move(pkg);
}
// Assign loaded package:
pkgDep.package = pkgPtr;
// Insert in sorted order:
{
auto it = rg::upper_bound(
loadedPackages, pkgPtr->root, {},
[](auto& elem) -> fs::path const&
{
return elem->root;
}
);
loadedPackages.insert(it, pkgPtr);
}
this->recursiveLoad(*pkgPtr);
break;
}
}
}
methodIdx++;
}
}
}
}
/////////////////////////////////////////////////
BuildQueueBuilder::DepQueue const& BuildQueueBuilder::setup()
{
std::size_t totalDeps = pendingDeps.size();
std::size_t totalCollected = 0;
while(totalCollected < totalDeps)
{
DepQueueStep step = this->collectReadyDependencies(queue, pendingDeps);
// Could not collect any?
if (step.empty())
throw PaccException("cyclic dependency detected");
totalCollected += step.size();
queue.push_back( std::move(step) );
}
return queue;
}
/////////////////////////////////////////////////
BuildQueueBuilder::DepQueueStep BuildQueueBuilder::collectReadyDependencies(DepQueue const& ready_, PendingDeps & pending_)
{
PendingDeps newPending;
newPending.reserve(pending_.size());
DepQueueStep nextStep;
for(auto& dep : pending_)
{
bool ready = false;
if (dep.dep->isPackage())
{
ready = !packageHasPendingDependencies(dep.dep->package(), ready_);
}
else if (dep.dep->isSelf())
{
ready = !selfPackageHasPendingDependencies(dep.dep->self(), ready_);
}
if (!ready)
newPending.push_back(dep);
else
nextStep.push_back(dep);
}
pending_ = std::move(newPending);
return nextStep;
}
/////////////////////////////////////////////////
PackagePtr BuildQueueBuilder::findPackageByRoot(fs::path root_) const
{
auto it = rg::lower_bound(
loadedPackages, root_, {},
[](auto& elem) { return elem->root; }
);
if (it != loadedPackages.end() && (*it)->root == root_)
return *it;
return nullptr;
}
/////////////////////////////////////////////////
bool BuildQueueBuilder::isPackageLoaded(fs::path root_) const
{
return rg::binary_search(
loadedPackages, root_, {},
[](auto& elem) { return elem->root; }
);
}
///////////////////////////////////////////////////////////////
// Private functions:
///////////////////////////////////////////////////////////////
/////////////////////////////////////////////////
bool wasDependencyQueued(Dependency const& dep, BuildQueueBuilder::DepQueue const& readyQueue_)
{
for (auto const& step : readyQueue_)
{
// TODO: Can be done better (binary search on sorted range)
auto it = rg::find(step, &dep, &BuildQueueBuilder::ProjectDep::dep);
if (it != step.end())
{
return true;
}
}
return false;
}
/////////////////////////////////////////////////
bool projectHasPendingDependencies(Project const& project, BuildQueueBuilder::DepQueue const& readyQueue_)
{
auto selfDepsAcc = getAccesses(project.dependencies.self);
for (auto access : selfDepsAcc)
{
for(auto& selfDep : *access)
{
if (!selfDep.isPackage() && !selfDep.isSelf())
continue;
if (!wasDependencyQueued(selfDep, readyQueue_))
return true;
}
}
return false;
}
/////////////////////////////////////////////////
bool packageHasPendingDependencies(PackageDependency & dep, BuildQueueBuilder::DepQueue const& readyQueue_)
{
auto& packagePtr = dep.package;
for (auto const& projectName : dep.projects)
{
// Find pointer to project:
auto& project = packagePtr->requireProject(projectName);
if (projectHasPendingDependencies(project, readyQueue_))
return true;
}
return false;
}
/////////////////////////////////////////////////
bool selfPackageHasPendingDependencies(SelfDependency & dep, BuildQueueBuilder::DepQueue const& readyQueue_)
{
auto& packagePtr = dep.package;
// Find pointer to project:
auto& project = packagePtr->requireProject(dep.depProjName);
if (projectHasPendingDependencies(project, readyQueue_))
return true;
return false;
}
| 26.137313 | 123 | 0.596962 | PoetaKodu |
b070791a72d7c010876e8671ba5721a4179d900f | 4,388 | cpp | C++ | src/dicebot/data/manual_dice_control.cpp | DrakeOu/coolq-dicebot | a38a500bbecbb44ee82adbbd191d9a5b73324606 | [
"MIT"
] | 2 | 2019-06-01T13:52:28.000Z | 2019-06-03T08:17:56.000Z | src/dicebot/data/manual_dice_control.cpp | DrakeOu/coolq-dicebot | a38a500bbecbb44ee82adbbd191d9a5b73324606 | [
"MIT"
] | null | null | null | src/dicebot/data/manual_dice_control.cpp | DrakeOu/coolq-dicebot | a38a500bbecbb44ee82adbbd191d9a5b73324606 | [
"MIT"
] | null | null | null | #include "./manual_dice_control.h"
#include <iostream>
#include <sstream>
#include "../entity/manual_dice.h"
#include "./database_manager.h"
using namespace dicebot;
using namespace dicebot::manual;
using namespace dicebot::database;
using db_manager = dicebot::database::database_manager;
#define MANUALDICE_TABLE_NAME "manualdice"
#define MANUALDICE_TABLE_DEFINE \
"create table " MANUALDICE_TABLE_NAME \
"(qqid int NOT NULL," \
"groupid int NOT NULL," \
"source text NOT NULL," \
"primary key (QQID,GROUPID));"
static bool insert_database(const utils::pair_t &manual_dice_key, const manual_dice &manual_dice_target) {
std::ostringstream ostrs_sql_command;
ostrs_sql_command << "insert into " MANUALDICE_TABLE_NAME " (qqid, groupid, source) "
<< "values ( " << manual_dice_key.first << ", " << manual_dice_key.second << ", '"
<< manual_dice_target.encode() << "'"
<< ");";
return db_manager::get_instance()->exec_noquery(ostrs_sql_command.str().c_str());
}
static bool update_database(const utils::pair_t &manual_dice_key, const manual_dice &manual_dice_target) {
std::ostringstream ostrs_sql_command;
ostrs_sql_command << "update " MANUALDICE_TABLE_NAME " set "
<< " source='" << manual_dice_target.encode() << "'"
<< " where qqid=" << manual_dice_key.first << " and groupid=" << manual_dice_key.second;
return db_manager::get_instance()->exec_noquery(ostrs_sql_command.str().c_str());
}
static bool read_database(const utils::pair_t &manual_dice_key, manual_dice &manual_dice_target) {
std::ostringstream ostrs_sql_command;
ostrs_sql_command << "SELECT source FROM " MANUALDICE_TABLE_NAME " where qqid=" << manual_dice_key.first
<< " and groupid=" << manual_dice_key.second;
std::string str_manualdice_read;
return db_manager::get_instance()->exec(
ostrs_sql_command.str().c_str(), &manual_dice_target, [](void *data, int argc, char **argv, char **azColName) -> int {
if (argc == 1) {
manual_dice *pstr_ret = reinterpret_cast<manual_dice *>(data);
pstr_ret->decode(argv[0]);
return SQLITE_OK;
}
return SQLITE_ABORT;
});
}
static bool exist_database(const utils::pair_t &manual_dice_key) {
bool ret = false;
std::ostringstream ostrs_sql_command;
ostrs_sql_command << "SELECT count(*) FROM " MANUALDICE_TABLE_NAME " where qqid=" << manual_dice_key.first
<< " and groupid=" << manual_dice_key.second;
database::database_manager::get_instance()->exec(
ostrs_sql_command.str().c_str(), &ret, [](void *data, int argc, char **argv, char **azColName) -> int {
*(reinterpret_cast<bool *>(data)) = std::stoi(argv[0]) > 0;
return SQLITE_OK;
});
return ret;
}
std::unique_ptr<manual_dice_control> manual_dice_control::instance = nullptr;
manual_dice_control *manual_dice_control::create_instance() {
db_manager::get_instance()->register_table(MANUALDICE_TABLE_NAME, MANUALDICE_TABLE_DEFINE);
manual_dice_control::instance = std::make_unique<manual_dice_control>();
return manual_dice_control::instance.get();
}
manual_dice_control *manual_dice_control::get_instance() { return instance.get(); }
void manual_dice_control::destroy_instance() { instance = nullptr; }
manual_dice_control::md_map_t::iterator manual_dice_control::find_manual_dice(const event_info &event) {
auto iter = this->manual_dice_map.find(event.pair());
if (iter != this->manual_dice_map.end()) return iter;
auto insert_result = this->manual_dice_map.insert({event.pair(), manual_dice()});
if (!insert_result.second) return this->manual_dice_map.end();
if (exist_database(insert_result.first->first)) {
read_database(insert_result.first->first, insert_result.first->second);
return insert_result.first;
} else {
insert_database(insert_result.first->first, insert_result.first->second);
return insert_result.first;
}
}
void manual_dice_control::sync_database(const md_map_t::iterator iter) const {
if (iter != this->manual_dice_map.end()) {
update_database(iter->first, iter->second);
}
} | 43.019608 | 126 | 0.670465 | DrakeOu |
b073a809fe1bb93b32ddb4a15bd5a02483c8bd71 | 10,770 | cc | C++ | modules/kernel/src/hardware/mb1.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 12 | 2018-12-03T15:16:52.000Z | 2022-03-16T21:07:13.000Z | modules/kernel/src/hardware/mb1.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | null | null | null | modules/kernel/src/hardware/mb1.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 2 | 2018-11-13T01:30:41.000Z | 2021-08-12T18:22:26.000Z | //===================================================================================================================
//
// mb1.c -- This is the parser for the Multiboot 1 information structure
//
// Copyright (c) 2017-2020 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2017-Jun-05 Initial 0.1.0 ADCL Initial version
//
//===================================================================================================================
#include "types.h"
#include "serial.h"
#include "mmu.h"
#include "printf.h"
#include "hw-disc.h"
//
// -- This is the loaded modules block (which will repeat)
// ----------------------------------------------------
typedef struct Mb1Mods_t {
uint32_t modStart;
uint32_t modEnd;
char *modIdent;
uint32_t modReserved;
} __attribute__((packed)) Mb1Mods_t;
//
// -- Memory Map entries, which will repeat (pointer points to mmapAddr)
// ------------------------------------------------------------------
typedef struct Mb1MmapEntry_t {
uint32_t mmapSize;
uint64_t mmapAddr;
uint64_t mmapLength;
uint32_t mmapType;
} __attribute__((packed)) Mb1MmapEntry_t;
//
// -- This is the Multiboot 1 information structure as defined by the spec
// --------------------------------------------------------------------
typedef struct MB1 {
//
// -- These flags indicate which data elements have valid data
// --------------------------------------------------------
const uint32_t flags;
//
// -- The basic memory limits are valid when flag 0 is set; these values are in kilobytes
// -----------------------------------------------------------------------------------
const uint32_t availLowerMem;
const uint32_t availUpperMem;
//
// -- The boot device when flag 1 is set
// ----------------------------------
const uint32_t bootDev;
//
// -- The command line for this kernel when flag 2 is set
// ---------------------------------------------------
const uint32_t cmdLine;
//
// -- The loaded module list when flag 3 is set
// -----------------------------------------
const uint32_t modCount;
const uint32_t modAddr;
//
// -- The ELF symbol information (a.out-type symbols are not supported) when flag 5 is set
// ------------------------------------------------------------------------------------
const uint32_t shdrNum; // may still be 0 if not available
const uint32_t shdrSize;
const uint32_t shdrAddr;
const uint32_t shdrShndx;
//
// -- The Memory Map information when flag 6 is set
// ---------------------------------------------
const uint32_t mmapLen;
const uint32_t mmapAddr;
//
// -- The Drives information when flag 7 is set
// -----------------------------------------
const uint32_t drivesLen;
const uint32_t drivesAddr;
//
// -- The Config table when flag 8 is set
// -----------------------------------
const uint32_t configTable;
//
// -- The boot loader name when flag 9 is set
// ---------------------------------------
const uint32_t bootLoaderName;
//
// -- The APM table location when bit 10 is set
// -----------------------------------------
const uint32_t apmTable;
//
// -- The VBE interface information when bit 11 is set
// ------------------------------------------------
const uint32_t vbeControlInfo;
const uint32_t vbeModeInfo;
const uint16_t vbeMode;
const uint16_t vbeInterfaceSeg;
const uint16_t vbeInterfaceOff;
const uint16_t vbeInterfaceLen;
//
// -- The FrameBuffer information when bit 12 is set
// ----------------------------------------------
const uint64_t framebufferAddr;
const uint32_t framebufferPitch;
const uint32_t framebufferWidth;
const uint32_t framebufferHeight;
const uint8_t framebufferBpp;
const uint8_t framebufferType;
union {
struct {
const uint8_t framebufferRedFieldPos;
const uint8_t framebufferRedMaskSize;
const uint8_t framebufferGreenFieldPos;
const uint8_t framebufferGreenMaskSize;
const uint8_t framebufferBlueFieldPos;
const uint8_t framebufferBlueMaskSize;
};
struct {
const uint32_t framebufferPalletAddr;
const uint16_t framebufferPalletNumColors;
};
};
} __attribute__((packed)) MB1;
//
// -- This is the address of the MB1 Multiboot information structure
// --------------------------------------------------------------
EXTERN EXPORT LOADER_BSS MB1 *mb1Data;
//
// -- A quick MACRO to help determine if a flag is set
// ------------------------------------------------
#define CHECK_FLAG(f) (mb1Data->flags & (1<<f))
//
// -- Parse the Multiboot 1 header
// ----------------------------
EXTERN_C EXPORT LOADER
void Mb1Parse(void)
{
if (!mb1Data) return;
kprintf("Found the mbi structure at %p\n", mb1Data);
//
// -- the mb1Data structure needs to be identity mapped
// -------------------------------------------------
archsize_t mb1Page = (archsize_t)mb1Data;
MmuMapToFrame(mb1Page, mb1Page >> 12, PG_KRN);
MmuMapToFrame(mb1Page + PAGE_SIZE, (mb1Page + PAGE_SIZE) >> 12, PG_KRN);
kprintf(" The flags are: %p\n", mb1Data->flags);
//
// -- Check for basic memory information
// ----------------------------------
if (CHECK_FLAG(0)) {
kprintf("Setting basic memory information\n");
SetAvailLowerMem(mb1Data->availLowerMem);
SetAvailUpperMem(mb1Data->availUpperMem);
}
//
// -- Check for boot device information
// ---------------------------------
if (CHECK_FLAG(1)) {
// TODO: Implement this feature
}
//
// -- Check for the command line -- we might have parameters to the loader
// --------------------------------------------------------------------
if (CHECK_FLAG(2)) {
kprintf("Identifying command line information: %s\n", mb1Data->cmdLine);
}
//
// -- Check for the module information -- we will need this for the additional loaded modules (i.e. the kernel)
// ---------------------------------------------------------------------------------------------------------
if (CHECK_FLAG(3)) {
uint32_t i;
Mb1Mods_t *m;
kprintf("Module information present\n");
for (m = (Mb1Mods_t *)mb1Data->modAddr, i = 0; i < mb1Data->modCount; i ++) {
kprintf(" Found Module: %s\n", m[i].modIdent);
kprintf(" .. Name is at : %p\n", m[i].modIdent);
kprintf(" .. Start: %p\n", m[i].modStart);
kprintf(" .. End: %p\n", m[i].modEnd);
AddModule(m[i].modStart, m[i].modEnd, m[i].modIdent);
}
}
//
// -- We skip flag 4 since we will never be an a.out-type executable. Check for ELF symbols with flag 5
// --------------------------------------------------------------------------------------------------
if (CHECK_FLAG(5)) {
// TODO: Implement this feature
}
//
// -- Check for Memory Map data, which we will require
// ------------------------------------------------
if (CHECK_FLAG(6)) {
kprintf("Setting memory map data\n");
uint32_t size = mb1Data->mmapLen;
Mb1MmapEntry_t *entry = (Mb1MmapEntry_t *)(((uint32_t)mb1Data->mmapAddr));
while (size) {
if (entry->mmapType == 1) {
kprintf(" iterating in mmap\n");
kprintf(" entry address is: %p\n", entry);
kprintf(" entry type is: %x\n", entry->mmapType);
kprintf(" entry base is: %p : %p\n", (uint32_t)(entry->mmapAddr>>32),
(uint32_t)entry->mmapAddr&0xffffffff);
kprintf(" entry length is: %p : %p\n", (uint32_t)(entry->mmapLength>>32),
(uint32_t)entry->mmapLength&0xffffffff);
kprintf(" entry size is: %p\n", entry->mmapSize);
}
if (entry->mmapType == 1) AddAvailMem(entry->mmapAddr, entry->mmapLength);
uint64_t newLimit = entry->mmapAddr + entry->mmapLength;
if (newLimit > GetUpperMemLimit()) SetUpperMemLimit(newLimit);
size -= (entry->mmapSize + 4);
entry = (Mb1MmapEntry_t *)(((uint32_t)entry) + entry->mmapSize + 4);
}
kprintf("Memory Map is complete\n");
}
//
// -- Check for the drives information
// --------------------------------
if (CHECK_FLAG(7)) {
// TODO: Implement this feature
}
//
// -- Check for the config data information
// -------------------------------------
if (CHECK_FLAG(8)) {
// TODO: Implmement this feature
}
//
// -- Check for the boot loader name
// ------------------------------
if (CHECK_FLAG(9)) {
kprintf("Identifying bootloader: %s\n", mb1Data->bootLoaderName);
}
//
// -- Check for the APM table
// -----------------------
if (CHECK_FLAG(10)) {
// TODO: Implmement this feature
}
//
// -- Check for the VBE table
// -----------------------
if (CHECK_FLAG(11)) {
// TODO: Implmement this feature
}
//
// -- Check for the framebuffer information (GRUB specific; see
// https://www.gnu.org/software/grub/manual/multiboot/multiboot.html)
// ------------------------------------------------------------------
if (CHECK_FLAG(12)) {
kprintf("Capturing framebuffer information\n");
SetFrameBufferAddr((uint16_t *)mb1Data->framebufferAddr);
SetFrameBufferPitch(mb1Data->framebufferPitch);
SetFrameBufferWidth(mb1Data->framebufferWidth);
SetFrameBufferHeight(mb1Data->framebufferHeight);
SetFrameBufferBpp(mb1Data->framebufferBpp);
SetFrameBufferType((FrameBufferType)mb1Data->framebufferType);
kprintf("Frame Buffer is at: %p; The pitch is: %p; The height is: %p\n",
mb1Data->framebufferAddr, mb1Data->framebufferPitch, mb1Data->framebufferHeight);
}
kprintf("Done parsing MB1 information\n");
MmuUnmapPage(mb1Page);
MmuUnmapPage(mb1Page + PAGE_SIZE);
}
| 33.138462 | 117 | 0.480316 | eryjus |
b073ffe0a2281614d0f089894080910fc40ff001 | 860 | cpp | C++ | apps/concepts/api-cpp/assfire/concepts/Speed.cpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | apps/concepts/api-cpp/assfire/concepts/Speed.cpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | apps/concepts/api-cpp/assfire/concepts/Speed.cpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | #include "Speed.hpp"
using namespace assfire;
assfire::Speed::Speed(double meters_per_second)
: meters_per_second(meters_per_second)
{}
double assfire::Speed::toMetersPerSecond() const
{
return meters_per_second;
}
double assfire::Speed::toMetersPerSecondWithPrecision(double precision) const
{
return round(meters_per_second / precision) * precision;
}
double assfire::Speed::toKilometersPerHour() const
{
return meters_per_second / 1000.0 * 3600;
}
assfire::TimeInterval assfire::Speed::getSecondsToTravel(const assfire::Distance &distance)
{
return TimeInterval::fromSeconds(distance.toMeters() / meters_per_second);
}
assfire::Speed assfire::Speed::fromMetersPerSecond(double value)
{
return Speed(value);
}
assfire::Speed assfire::Speed::fromKilometersPerHour(double value)
{
return Speed(value / 3600.0 * 1000);
}
| 22.631579 | 91 | 0.756977 | Eaglegor |
b076a108878a3ecc3e24a423777b6e2bf14034ce | 263 | hpp | C++ | Modules/TinyOBJ/Public/Toon/TinyOBJ/TinyOBJConfig.hpp | benjinx/Toon | f21032b2f9ad5fbc9a3618a7719c33159257d954 | [
"MIT"
] | 2 | 2021-01-28T03:08:08.000Z | 2021-01-28T03:08:21.000Z | Modules/TinyOBJ/Public/Toon/TinyOBJ/TinyOBJConfig.hpp | benjinx/Toon | f21032b2f9ad5fbc9a3618a7719c33159257d954 | [
"MIT"
] | null | null | null | Modules/TinyOBJ/Public/Toon/TinyOBJ/TinyOBJConfig.hpp | benjinx/Toon | f21032b2f9ad5fbc9a3618a7719c33159257d954 | [
"MIT"
] | null | null | null | #ifndef TOON_TINYOBJ_CONFIG_HPP
#define TOON_TINYOBJ_CONFIG_HPP
#include <Toon/Config.hpp>
#if defined(TOON_TINYOBJ_EXPORT)
#define TOON_TINYOBJ_API TOON_API_EXPORT
#else
#define TOON_TINYOBJ_API TOON_API_IMPORT
#endif
#endif // TOON_TINYOBJ_CONFIG_HPP | 21.916667 | 44 | 0.825095 | benjinx |
b0794a6bbc80df3023456cefb0d31b2a2161a6cd | 2,512 | cpp | C++ | engine/core/object/Light.cpp | supernovaengine/supernova | 54dfdc1032a0e7cf2de10a2dd72ae6654e75c8b8 | [
"MIT"
] | 10 | 2020-05-17T15:19:11.000Z | 2022-03-31T13:46:19.000Z | engine/core/object/Light.cpp | supernovaengine/supernova | 54dfdc1032a0e7cf2de10a2dd72ae6654e75c8b8 | [
"MIT"
] | null | null | null | engine/core/object/Light.cpp | supernovaengine/supernova | 54dfdc1032a0e7cf2de10a2dd72ae6654e75c8b8 | [
"MIT"
] | 2 | 2020-06-17T21:43:02.000Z | 2022-03-31T13:46:21.000Z | //
// (c) 2021 Eduardo Doria.
//
#include "Light.h"
#include "math/Angle.h"
#include "math/Color.h"
#include <math.h>
using namespace Supernova;
Light::Light(Scene* scene): Object(scene){
addComponent<LightComponent>({});
}
Light::~Light(){
}
void Light::setType(LightType type){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.type = type;
}
void Light::setDirection(Vector3 direction){
LightComponent& lightcomp = getComponent<LightComponent>();
Transform& transform = getComponent<Transform>();
lightcomp.direction = direction;
transform.needUpdate = true; //Does not affect children
}
void Light::setDirection(const float x, const float y, const float z){
setDirection(Vector3(x,y,z));
}
void Light::setColor(Vector3 color){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.color = Color::sRGBToLinear(color);
}
void Light::setColor(const float r, const float g, const float b){
setColor(Vector3(r,g,b));
}
void Light::setRange(float range){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.range = range;
}
void Light::setIntensity(float intensity){
LightComponent& lightcomp = getComponent<LightComponent>();
Transform& transform = getComponent<Transform>();
if (intensity > 0 && lightcomp.intensity == 0)
transform.needUpdate = true; //Does not affect children
lightcomp.intensity = intensity;
}
void Light::setConeAngle(float inner, float outer){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.innerConeCos = cos(Angle::defaultToRad(inner / 2));
lightcomp.outerConeCos = cos(Angle::defaultToRad(outer / 2));
}
void Light::setShadows(bool shadows){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.shadows = shadows;
}
void Light::setBias(float bias){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.shadowBias = bias;
}
void Light::setShadowMapSize(unsigned int size){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.mapResolution = size;
}
void Light::setShadowCameraNearFar(float near, float far){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.shadowCameraNearFar = Vector2(near, far);
}
void Light::setNumCascades(unsigned int numCascades){
LightComponent& lightcomp = getComponent<LightComponent>();
lightcomp.numShadowCascades = numCascades;
} | 24.871287 | 70 | 0.717755 | supernovaengine |
b081d930c276620854c86d7e2c142be8bbb6ae0c | 3,615 | cpp | C++ | Dependencies/Build/mac/share/faust/minimal-bench.cpp | SKyzZz/test | 9b03adce666adb85e5ae2d8af5262e0acb4b91e1 | [
"Zlib"
] | 2 | 2020-10-25T09:03:03.000Z | 2021-06-24T13:20:01.000Z | Dependencies/Build/mac/share/faust/minimal-bench.cpp | SKyzZz/test | 9b03adce666adb85e5ae2d8af5262e0acb4b91e1 | [
"Zlib"
] | null | null | null | Dependencies/Build/mac/share/faust/minimal-bench.cpp | SKyzZz/test | 9b03adce666adb85e5ae2d8af5262e0acb4b91e1 | [
"Zlib"
] | null | null | null | /************************************************************************
IMPORTANT NOTE : this file contains two clearly delimited sections :
the ARCHITECTURE section (in two parts) and the USER section. Each section
is governed by its own copyright and license. Please check individually
each section for license and copyright information.
*************************************************************************/
/*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************
************************************************************************/
#include <iostream>
#include <string>
#include "faust/gui/PrintUI.h"
#include "faust/gui/meta.h"
#include "faust/audio/dummy-audio.h"
#include "faust/dsp/dsp-bench.h"
// faust -a minimal-bench.cpp noise.dsp -o noise.cpp && c++ -std=c++11 noise.cpp -o noise && ./noise
/******************************************************************************
*******************************************************************************
VECTOR INTRINSICS
*******************************************************************************
*******************************************************************************/
<<includeIntrinsic>>
/********************END ARCHITECTURE SECTION (part 1/2)****************/
/**************************BEGIN USER SECTION **************************/
<<includeclass>>
/***************************END USER SECTION ***************************/
/*******************BEGIN ARCHITECTURE SECTION (part 2/2)***************/
static void bench(dsp* dsp, int dsp_size, const std::string& name, int run)
{
// Buffer_size and duration in sec of measure
measure_dsp mes(dsp, 512, 5., true);
for (int i = 0; i < run; i++) {
mes.measure();
std::cout << name << " : " << mes.getStats() << " " << "(DSP CPU % : " << (mes.getCPULoad() * 100) << "), DSP size : " << dsp_size << std::endl;
}
}
int main(int argc, char* argv[])
{
mydsp DSP;
// Bench the dsp
bench(DSP.clone(), sizeof(DSP), "mydsp", 3);
// Activate the UI, here that only print the control paths
PrintUI ui;
DSP.buildUserInterface(&ui);
// Allocate the audio driver to render 5 buffers of 512 frames
dummyaudio audio(1);
audio.init("Test", &DSP);
// Render buffers...
audio.start();
audio.stop();
}
/********************END ARCHITECTURE SECTION (part 2/2)****************/
| 37.268041 | 152 | 0.503181 | SKyzZz |
b0837617a00055bac00c5c0e00752c31637a81b0 | 844 | cpp | C++ | 999_Practice/Day_25/0116_transpose_matrix.cpp | Gandham-Srinithya/Data-Structure-and-Algorithms | 177d03105188c83a157947ca9870bf8037e92528 | [
"MIT"
] | 126 | 2019-12-22T17:49:08.000Z | 2021-12-14T18:45:51.000Z | 999_Practice/Day_25/0116_transpose_matrix.cpp | Gandham-Srinithya/Data-Structure-and-Algorithms | 177d03105188c83a157947ca9870bf8037e92528 | [
"MIT"
] | 7 | 2019-12-25T18:03:41.000Z | 2021-02-20T06:25:27.000Z | 999_Practice/Day_25/0116_transpose_matrix.cpp | Gandham-Srinithya/Data-Structure-and-Algorithms | 177d03105188c83a157947ca9870bf8037e92528 | [
"MIT"
] | 54 | 2019-12-26T06:28:39.000Z | 2022-02-01T05:04:43.000Z | // Given a square matrix A and its number of rows (or columns) N,
// return the transpose of A.
//
// The transpose of a matrix is the matrix flipped over it's main
// diagonal, switching the row and column indices of the matrix.
//
// CONSTRAINS
// 1 <= N <= 1000
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n][n];
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin>>arr[i][j];
}
}
for(int i=0; i<n; i++)
{
for(int j=i; i+j<n; j++)
{
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
return 0;
} | 17.583333 | 65 | 0.438389 | Gandham-Srinithya |
b083b2a51dfe8cd8b3f5ea853d7b4357f0338f79 | 36,425 | cpp | C++ | drlvm/vm/jitrino/src/dynopt/EdgeProfiler.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 8 | 2015-11-04T06:06:35.000Z | 2021-07-04T13:47:36.000Z | drlvm/vm/jitrino/src/dynopt/EdgeProfiler.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 1 | 2021-10-17T13:07:28.000Z | 2021-10-17T13:07:28.000Z | drlvm/vm/jitrino/src/dynopt/EdgeProfiler.cpp | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 13 | 2015-11-27T03:14:50.000Z | 2022-02-26T15:12:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* COPYRIGHT_NOTICE */
/**
* @author Jack Liu, Mikhail Y. Fursov, Chen-Dong Yuan
*/
#include "EMInterface.h"
#include "Jitrino.h"
#include "Inst.h"
#include "Stl.h"
#include "StaticProfiler.h"
#include "Dominator.h"
#include "Loop.h"
#include "FlowGraph.h"
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <sstream>
namespace Jitrino {
#define MAX(a, b) ((a)>(b)?a:b)
static bool isMethodTrivial( ControlFlowGraph& cfg );
static void checkBCMapping( ControlFlowGraph& cfg );
static U_32 computeCheckSum( MemoryManager& mm, IRManager& irm, const StlSet<Node*>& nodesToIgnore, bool bcLevel);
static bool calculateProbsFromProfile(MemoryManager& mm, ControlFlowGraph& fg, const Edges& edges, DominatorTree* dt, LoopTree* lt, EdgeMethodProfile* profile, bool bcLevelProfiling, const StlSet<Node*>& nodesToIgnore);
static Node* selectNodeToInstrument(IRManager& irm, Edge* edge);
static void selectEdgesToInstrument(MemoryManager& mm, IRManager& irm, Edges& result, const StlSet<Node*>& nodesToIgnore, bool bcLevel);
static U_32 genKey( U_32 n, Edge* edge, bool bcLevel, bool debug);
static bool hasCatch( Node* node );
static void selectNodesToIgnore(IRManager& irm, LoopTree* lt, StlSet<Node*>& result, bool bcLevel);
class EdgeProfileFlags {
public:
bool bcLevelProfiling;
EdgeProfileFlags() : bcLevelProfiling(false) {}
};
class EdgeProfilerAction : public Action {
public:
void init() {
flags.bcLevelProfiling = getBoolArg("bcLevel", false);
}
const EdgeProfileFlags& getFlags() {return flags;}
protected:
EdgeProfileFlags flags;
};
DEFINE_SESSION_ACTION_WITH_ACTION(EdgeProfilerInstrumentationPass, EdgeProfilerAction, edge_instrument, "Perform edge instrumentation pass")
void EdgeProfilerInstrumentationPass::_run(IRManager& irm)
{
ControlFlowGraph& flowGraph = irm.getFlowGraph();
MemoryManager mm("Edge InstrumentationPass");
MethodDesc& md = irm.getMethodDesc();
InstFactory& instFactory = irm.getInstFactory();
EdgeProfilerAction* action = (EdgeProfilerAction*)getAction();
const EdgeProfileFlags& flags = action->getFlags();
bool debug = Log::isEnabled();
if (debug) {
Log::out()<<"EdgeProfilerInstrumentationPass. BcLevel="<<flags.bcLevelProfiling<<std::endl;
}
if (flags.bcLevelProfiling) {
checkBCMapping(flowGraph);
}
OptPass::computeDominatorsAndLoops(irm);
LogStream& irdump = log(LogStream::IRDUMP);
if (irdump.isEnabled()) {
printHIR(irm, "IR before instrumentation");
}
LoopTree* lt = irm.getLoopTree();
//set of nodes with out-edges are not taken into account during instrumentation
//and checksum calculation
//such nodes are optional in CFG. E.g. nodes with class initializers insts
StlSet<Node*> nodesToIgnore(mm);
selectNodesToIgnore(irm, lt, nodesToIgnore, flags.bcLevelProfiling);
//compute checksum first
U_32 _checkSum = computeCheckSum(mm, irm, nodesToIgnore, flags.bcLevelProfiling);
StlVector<U_32> counterKeys(mm);
// Instrument method entry first.
Node* entryNode = flowGraph.getEntryNode();
entryNode->prependInst(instFactory.makeIncCounter(0));
bool methodIsTrivial = isMethodTrivial(flowGraph);
if (!methodIsTrivial) {
// Scan the CFG node in topological order and record the blocks and
// edges where we need to add instrumentation code.
// The actual instrumentation will be done in a separate phase so that
// we won't disturb the CFG as we are traversing it.
Edges edgesToInstrument(mm);
selectEdgesToInstrument(mm, irm, edgesToInstrument, nodesToIgnore, flags.bcLevelProfiling);
//compute edge-ids before CFG modification: edge-ids are part of CFG consistency check.
for (Edges::const_iterator it = edgesToInstrument.begin(), end = edgesToInstrument.end(); it!=end; ++it) {
Edge* edge = *it;
U_32 key = genKey((U_32)counterKeys.size() + 1, edge, flags.bcLevelProfiling, debug);
assert( key != 0 );
counterKeys.push_back(key);
}
// Now revisit all of the edges that need to be instrumented
// and generate instrumentation code.
U_32 i = 0;
for (Edges::const_iterator it = edgesToInstrument.begin(), end = edgesToInstrument.end(); it!=end; ++it, ++i) {
Edge* edge = *it;
Node* nodeToInstrument = selectNodeToInstrument(irm, edge);
assert(nodeToInstrument!=NULL && nodeToInstrument->isBlockNode());
U_32 key = counterKeys[i];
Inst* incInst = instFactory.makeIncCounter( key );
assert(((Inst*)nodeToInstrument->getFirstInst())->getOpcode() != Op_IncCounter );
nodeToInstrument->prependInst(incInst);
}
if (flags.bcLevelProfiling) { //remove duplicates from keys
std::sort(counterKeys.begin(), counterKeys.end());
counterKeys.resize(std::unique(counterKeys.begin(), counterKeys.end()) - counterKeys.begin());
}
}
irm.getCompilationInterface().lockMethodData();
ProfilingInterface* pi = irm.getProfilingInterface();
if (!pi->hasMethodProfile(ProfileType_Edge, md, JITProfilingRole_GEN)) {
pi->createEdgeMethodProfile(mm , md, (U_32)counterKeys.size(), counterKeys.empty()?NULL:(U_32*)&counterKeys.front(), _checkSum);
}
irm.getCompilationInterface().unlockMethodData();
if (debug) {
Log::out() << std::endl << "EdgePC:: instrumented, nCounters="<<counterKeys.size() <<" checksum="<<_checkSum << std::endl;
}
}
DEFINE_SESSION_ACTION_WITH_ACTION(EdgeProfilerAnnotationPass, EdgeProfilerAction, edge_annotate, "Perform edge annotation pass")
void EdgeProfilerAnnotationPass::_run(IRManager& irm) {
ControlFlowGraph& flowGraph = irm.getFlowGraph();
MethodDesc& md = irm.getMethodDesc();
MemoryManager mm("Edge AnnotationPass");
bool debug = Log::isEnabled();
EdgeProfilerAction* action = (EdgeProfilerAction*)getAction();
const EdgeProfileFlags& flags = action->getFlags();
if (debug) {
Log::out()<<"EdgeProfilerAnnotationPass. BcLevel="<<flags.bcLevelProfiling<<std::endl;
}
// Create the edge profile structure for the compiled method in 'irm'.
ProfilingInterface* pi = irm.getProfilingInterface();
bool edgeProfilerMode = pi->isProfilingEnabled(ProfileType_Edge, JITProfilingRole_USE);
bool entryBackedgeProfilerMode = !edgeProfilerMode && pi->isProfilingEnabled(ProfileType_EntryBackedge, JITProfilingRole_USE);
U_32 entryCount = (edgeProfilerMode || entryBackedgeProfilerMode) ? pi->getProfileMethodCount(md) : 0;
if (isMethodTrivial(flowGraph) || !edgeProfilerMode || entryCount == 0) {
// Annotate the CFG using static profiler heuristics.
if (debug) {
Log::out()<<"Using static profiler to estimate trivial graph"<<std::endl;
}
StaticProfiler::estimateGraph(irm, entryCount);
return;
}
OptPass::computeDominatorsAndLoops(irm);
DominatorTree* dt = irm.getDominatorTree();
LoopTree* lt = irm.getLoopTree();
LogStream& irdump = log(LogStream::IRDUMP);
if (irdump.isEnabled()) {
printHIR(irm, "IR before instrumentation");
}
// sync checksum
StlSet<Node*> nodesToIgnore(mm); //see instrumentation pass for comments
selectNodesToIgnore(irm, lt, nodesToIgnore, flags.bcLevelProfiling);
U_32 cfgCheckSum = computeCheckSum(mm, irm, nodesToIgnore, flags.bcLevelProfiling);
EdgeMethodProfile* edgeProfile = pi->getEdgeMethodProfile(mm, md);
U_32 profileCheckSum = edgeProfile->getCheckSum();
//assert(profileCheckSum == cfgCheckSum);
if (cfgCheckSum == profileCheckSum) {
// Start propagating the CFG from instrumented edges.
Edges edges(mm);
selectEdgesToInstrument(mm, irm, edges, nodesToIgnore, flags.bcLevelProfiling);
//assert if num counters is not equal -> must be guaranteed after checksum check
//for BC-level profiling checksum calculation is simplified -> no assertion
assert(edges.size() == edgeProfile->getNumCounters() || flags.bcLevelProfiling);
bool res = calculateProbsFromProfile(mm, flowGraph, edges, dt, lt, edgeProfile, flags.bcLevelProfiling, nodesToIgnore);
if (res) {
flowGraph.setEdgeProfile(true);
}
}
if (!flowGraph.hasEdgeProfile()) {
if (debug) {
Log::out()<<"DynProf failed: using static profiler to estimate graph!"<<std::endl;
}
StaticProfiler::estimateGraph(irm, 10000, true);
}
if (irm.getParent() == NULL) {
// fix profile: estimate cold paths that was never executed and recalculate frequencies
StaticProfiler::fixEdgeProbs(irm);
flowGraph.smoothEdgeProfile();
}
}
static inline void setEdgeFreq(StlVector<double>& edgeFreqs, Edge* edge, double freq, bool debug) {
if (debug) {
Log::out()<<"\t settings edge(id="<<edge->getId()<<") freq ("; FlowGraph::printLabel(Log::out(), edge->getSourceNode());
Log::out() << "->"; FlowGraph::printLabel(Log::out(), edge->getTargetNode()); Log::out()<<") to "<<freq << std::endl;
}
assert(freq>=0);
edgeFreqs[edge->getId()] = freq;
}
static void updateDispatchPathsToCatch(Node* node, StlVector<double>& edgeFreqs, bool debug) {
double freq = node->getExecCount();
const Edges& inEdges = node->getInEdges();
for (Edges::const_iterator it = inEdges.begin(), end = inEdges.end(); it!=end; ++it) {
Edge* edge = *it;
Node* srcNode = edge->getSourceNode();
if (srcNode->isDispatchNode() && freq > edgeFreqs[edge->getId()]) {
setEdgeFreq(edgeFreqs, edge, freq, debug);
srcNode->setExecCount(std::max(0.0, srcNode->getExecCount()) + freq);
updateDispatchPathsToCatch(srcNode, edgeFreqs, debug);
}
}
}
static bool calculateProbsFromProfile(MemoryManager& mm, ControlFlowGraph& fg, const Edges& pEdges,
DominatorTree* dt, LoopTree* lt, EdgeMethodProfile* profile,
bool bcLevelProfiling, const StlSet<Node*>& nodesToIgnore)
{
//calculate edge freqs and use them to calculate edge probs.
bool debug = Log::isEnabled();
if (debug) {
Log::out()<<"Starting probs calculation" <<std::endl;
}
U_32 entryCount = *profile->getEntryCounter();
//1. assign default value to nodes and edges, this value is used for consistency checks latter
StlVector<Node*> nodes(mm);
fg.getNodesPostOrder(nodes);
for (StlVector<Node*>::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
node->setExecCount(-1);
const Edges& edges = node->getOutEdges();
for (Edges::const_iterator it2 = edges.begin(), end2 = edges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
edge->setEdgeProb(-1);
}
}
//2. calculate edge-freq for every edge.
//2.1 get freqs from profile
StlVector<double> edgeFreqs(mm, fg.getMaxEdgeId(), -1);
U_32 n = 1;
for (Edges::const_iterator it = pEdges.begin(), end = pEdges.end(); it!=end; ++it, ++n) {
Edge* edge = *it;
U_32 key = genKey(n, edge, bcLevelProfiling, debug);
U_32* counterAddr = profile->getCounter(key);
//assert(bcLevelProfiling || counterAddr!=NULL); -> TODO: hits in lazy resolution mode
U_32 freq = 0;
if (counterAddr == NULL) {
if (!bcLevelProfiling) { //avoid crash, use static profiler for a method
return false;
}
} else {
freq = *counterAddr;
}
setEdgeFreq(edgeFreqs, edge, freq, debug);
}
//2.2 propagate edge frequencies on linear paths
// this operation is needed because we do not instrument artificial edges (edges that connect nodes with the same bc-mapping)
if (bcLevelProfiling) {
for (StlVector<Node*>::reverse_iterator it = nodes.rbegin(), end = nodes.rend(); it!=end; ++it) {
Node* node = *it;
const Edges& outEdges = node->getOutEdges();
for (Edges::const_iterator it2 = outEdges.begin(), end2 = outEdges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
double freq = edgeFreqs[edge->getId()];
if (freq==-1) { //this edge has no profile -> can't use it for propagation
continue;
}
Node* targetNode = edge->getTargetNode();
//check pattern for artificial nodes: 1 unconditional + no changes in bcmapping
if (targetNode->isBlockNode() && targetNode->getOutDegree() <= 2 && targetNode->getUnconditionalEdge()!=NULL) {
Edge* unconditionalEdge = targetNode->getUnconditionalEdge();
if (targetNode->getFirstInst()->getBCOffset() == unconditionalEdge->getTargetNode()->getFirstInst()->getBCOffset()) {
double ufreq = edgeFreqs[unconditionalEdge->getId()];
double newUFreq= freq + MAX(ufreq, 0);
if (debug) {
Log::out()<<"Restoring profile for artificial edge : edge-id="<<unconditionalEdge->getId()<<std::endl;
}
setEdgeFreq(edgeFreqs, unconditionalEdge, newUFreq, debug);
}
}
}
}
}
//2.3 fix catch freqs, so we will have estimated D->C edges
if (debug) {
Log::out()<<"\tFixing catch freqs"<<std::endl;
}
for (StlVector<Node*>::reverse_iterator it = nodes.rbegin(), end = nodes.rend(); it!=end; ++it) {
Node* node = *it;
bool ignored = nodesToIgnore.find(node)!=nodesToIgnore.end();
if (!node->isCatchBlock() || ignored) {
continue;
}
//set up catch block prob -> will be used for dispatch nodes.
double nodeFreq = 0;
const Edges& outEdges = node->getOutEdges();
for (Edges::const_iterator it2 = outEdges.begin(), end2 = outEdges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
double edgeFreq = edgeFreqs[edge->getId()];
edgeFreq = MAX(0, edgeFreq); //if Cn->Ln edge is marked as artificial it's not instrumented
nodeFreq+=edgeFreq;
}
node->setExecCount(nodeFreq);
if (debug) {
Log::out()<<"\t\t fixing catch node ";FlowGraph::printLabel(Log::out(), node);Log::out()<<" freq="<<nodeFreq<<std::endl;
}
updateDispatchPathsToCatch(node, edgeFreqs, debug);
}
//2.4 calculate freqs for every edge in topological order
// set up nodes exec count for every node.
if (debug) {
Log::out()<<"\tPropagating edge freqs"<<std::endl;
}
for (StlVector<Node*>::reverse_iterator it = nodes.rbegin(), end = nodes.rend(); it!=end; ++it) {
Node* node = *it;
bool ignored = nodesToIgnore.find(node)!=nodesToIgnore.end();
double nodeFreq = 0;
const Edges& outEdges = node->getOutEdges();
const Edges& inEdges = node->getInEdges();
if (debug) {
Log::out()<<"\t\tNode="; FlowGraph::printLabel(Log::out(), node);Log::out()<<" in-edges="<<inEdges.size() << " was ignored="<<ignored<<std::endl;
}
if (node->getInDegree() == 0) {
assert(node == fg.getEntryNode());
nodeFreq = entryCount;
} else if (node->isCatchBlock()) { //set up catch block prob -> will be used for dispatch nodes.
if (ignored) {
// ignored catch edge (successor of ignored node or catch-loop)
// max we can do here is to try to get catch freq from in-edge
double _freq = 0;
Edge* inEdge = *node->getInEdges().begin();
if (node->getInDegree() == 1 && edgeFreqs[inEdge->getId()]>=0) {
_freq = edgeFreqs[inEdge->getId()];
}
Edge* outEdge = *node->getOutEdges().begin();
nodeFreq = edgeFreqs[outEdge->getId()] = _freq;
} else {//all out-edges were instrumented -> easy to calculate freq
nodeFreq = node->getExecCount(); //already assigned
assert(nodeFreq>=0);
}
} else {
for (Edges::const_iterator it2 = inEdges.begin(), end2 = inEdges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
Node* srcNode = edge->getSourceNode();
//assign edge-freq when available
//or 0-freq when source is dispatch (catches handled separately)
//or freq of src node when src node was removed from instrumentation(equal freq for all out-edges)
double edgeFreq = 0;
if (nodesToIgnore.find(srcNode)!=nodesToIgnore.end()) {
assert(srcNode->getExecCount()!= -1 || (srcNode->isCatchBlock() && dt->dominates(node, srcNode)) || (hasCatch(node) && srcNode->isEmpty()));
edgeFreq = srcNode->getExecCount();
} else if (srcNode->isBlockNode()) {
edgeFreq = edgeFreqs[edge->getId()];
}
if (debug) {
Log::out()<<"\t\t\tedge id="<<edge->getId()<<" from="; FlowGraph::printLabel(Log::out(), srcNode);
Log::out()<<" freq="<<edgeFreq<<std::endl;
}
if (edgeFreq == -1) {
//the only way to get not estimated edge here is to have catch loops (monexit pattern)
#ifdef _DEBUG
Node* head = lt->getLoopHeader(node, false); //catch loops are not instrumented
assert(head != NULL && (head->isCatchBlock() || head->isDispatchNode() || hasCatch(head)));
#endif
edgeFreq = 0;
setEdgeFreq(edgeFreqs, edge, edgeFreq, debug);
}
nodeFreq +=edgeFreq;
}
}
if (debug) {
Log::out()<<"\t\t\tnode freq="<<nodeFreq<<std::endl;
}
assert(nodeFreq!=-1);
node->setExecCount(nodeFreq);
if (node->isExitNode()) {
continue;
}
//now we able to calculate all outgoing edge freqs for current node
//if node is bb -> only 1 edge is allowed to be without freq here and we will fix it
//if node is dispatch -> use catch node freqs
//if node was ignored -> equal freq for every bb edge, 0 to dispatch edge
double freqLeft = nodeFreq;
if (ignored) {
if ( outEdges.size()==1 ) {
Edge* edge = *outEdges.begin();
setEdgeFreq(edgeFreqs, edge, nodeFreq, debug);
} else {
double freqPerBB = nodeFreq / (outEdges.size() - (node->getExceptionEdge() == NULL ? 0 : 1));
for (Edges::const_iterator it = outEdges.begin(), end = outEdges.end(); it!=end; ++it) {
Edge* edge = *it;
setEdgeFreq(edgeFreqs, edge, edge->getTargetNode()->isBlockNode() ? freqPerBB : 0, debug);
}
}
} else if (node->isBlockNode()) {
Edge* notEstimatedEdge = NULL;
for (Edges::const_iterator it2 = outEdges.begin(), end2 = outEdges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
double edgeFreq = edgeFreqs[edge->getId()];
if (edgeFreq != -1) {
freqLeft-=edgeFreq;
} else {
// here we can have 2 not-estimated edges only of this block was connected to 'ignored' node during annotation.
if (notEstimatedEdge == NULL) {
notEstimatedEdge = edge;
} else if (notEstimatedEdge->getTargetNode()->isDispatchNode()) {
setEdgeFreq(edgeFreqs, notEstimatedEdge, 0, debug);
notEstimatedEdge = edge;
} else {
setEdgeFreq(edgeFreqs, edge, 0, debug);
}
}
}
if (notEstimatedEdge!=NULL) {
freqLeft = freqLeft < 0 ? 0 : freqLeft;
setEdgeFreq(edgeFreqs, notEstimatedEdge, freqLeft, debug);
}
} else if (node->isDispatchNode()) {
//for all not estimated on step 2.2 D->X edges set edge prob to min (0).
for (Edges::const_iterator it = outEdges.begin(), end = outEdges.end(); it!=end; ++it) {
Edge* edge = *it;
double _freq = edgeFreqs[edge->getId()];
if (_freq==-1) {
setEdgeFreq(edgeFreqs, edge, 0, false);
}
}
}
}
//3. calculate edge probs using edge freqs.
if (debug) {
Log::out()<<"Calculating edge probs using freqs.."<<std::endl;
}
for (StlVector<Node*>::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it, n++) {
Node* node = *it;
double nodeFreq = node->getExecCount();
assert(nodeFreq!=-1);
const Edges& edges = node->getOutEdges();
for (Edges::const_iterator it2 = edges.begin(), end2 = edges.end(); it2!=end2; ++it2) {
Edge* edge = *it2;
double edgeFreq =edgeFreqs[edge->getId()];
assert(edgeFreq!=-1);
double edgeProb = nodeFreq == 0 ? 0 : edgeFreq / nodeFreq ;
// assert(edgeProb >= 0 && edgeProb <= 1);
edge->setEdgeProb(edgeProb);
}
}
if (debug) {
Log::out()<<"Finished probs calculation";
}
return true;
}
//
// Compute the checksum contribution of the given Edge
//
static U_32 _computeCheckSum(Node* node, const StlSet<Node*>& nodesToIgnore, StlVector<bool>& flags, U_32 depth, bool debug) {
assert(flags[node->getId()] == false);
flags[node->getId()] = true;
//node is removed from checksum calculation if
// 1) it's in ignore list
// 2) it's dispatch or catch -> due to the fact that ignore-list nodes can add more dispatches & catches(finally-blocks)
bool ignored = nodesToIgnore.find(node)!=nodesToIgnore.end();
bool skipped = ignored || node->getOutDegree()==1
|| (node->isCatchBlock() && node->isEmpty()) || node->isDispatchNode() || node->isExitNode();
U_32 dSum = skipped ? 0 : depth;
U_32 childDepth = skipped ? depth : depth + 1;
const Edges& outEdges = node->getOutEdges();
U_32 childsSum = 0;
for (Edges::const_iterator it = outEdges.begin(), end = outEdges.end(); it!=end; ++it) {
Edge* edge = *it;
Node* childNode = edge->getTargetNode();
//visit only those not visited child nodes that are not dispatch edges of ignored nodes
if (flags[childNode->getId()] == false && !(ignored && childNode->isDispatchNode())) {
childsSum+=_computeCheckSum(childNode, nodesToIgnore, flags, childDepth, debug);
}
}
if (debug){
Log::out()<< "\t<checksum calculation: node:"; FlowGraph::printLabel(Log::out(), node);
Log::out() << "=+"<<dSum<<" depth="<<depth<< " child sum="<<childsSum<<std::endl;
}
return dSum+childsSum;
}
static U_32 computeCheckSum( MemoryManager& mm, IRManager& irm, const StlSet<Node*>& nodesToIgnore, bool bcLevel) {
bool debug = Log::isEnabled();
if (debug) {
Log::out()<< "calculating checksum.." << std::endl;
}
U_32 checkSum = 0;
if (!bcLevel) {
ControlFlowGraph& cfg = irm.getFlowGraph();
StlVector<bool> flags(mm, cfg.getMaxNodeId(), false);
checkSum = _computeCheckSum(cfg.getEntryNode(), nodesToIgnore, flags, 1, debug);
} else {
checkSum = irm.getMethodDesc().getByteCodeSize();
}
if( debug){
Log::out()<< "checkSum= "<<checkSum<<std::endl;
}
return checkSum;
}
static Node* selectNodeToInstrument(IRManager& irm, Edge* edge) {
ControlFlowGraph& fg = irm.getFlowGraph();
Node* srcNode = edge->getSourceNode();
Node* dstNode = edge->getTargetNode();
Node* result = NULL;
assert(srcNode->isBlockNode() && dstNode->isBlockNode());
if (srcNode->isCatchBlock()) {
// catch blocks handled separately. We must add counter only after catch inst
assert(srcNode->hasOnlyOneSuccEdge() || hasCatch(srcNode));
if (srcNode->hasOnlyOneSuccEdge() && hasCatch(srcNode)) { //filter-out catches with ret -> instrument srcNode
result = srcNode;
} else {
result = dstNode;
}
} else {
result = srcNode->hasOnlyOneSuccEdge() ? srcNode : dstNode;
}
if( result->hasTwoOrMorePredEdges() ){
// Splice a new block on edge from srcNode to dstNode and put
// instrumentation code there.
result = fg.spliceBlockOnEdge(edge, irm.getInstFactory().makeLabel());
}
return result;
}
static bool hasCatch( Node* node ) {
Inst* inst = (Inst*)node->getFirstInst();
assert(inst->isLabel());
// Op_Catch is allowed to be not in the second position only (after label inst)
// but in arbitrary position if Op_Phi insts present.
do {
inst = inst->getNextInst();
} while (inst!=NULL && inst->getOpcode() == Op_Phi);
return inst != NULL && inst->getOpcode() == Op_Catch;
}
/*static bool hasCounter( Node* node ) {
for (Inst* inst = node->getFirstInst()->next(); inst!=node->getFirstInst(); inst = inst->next()) {
if (inst->getOpcode() == Op_IncCounter) {
return true;
}
}
return false;
}*/
static void selectNodesToIgnore(IRManager& irm, LoopTree* lt, StlSet<Node*>& result, bool bcLevel) {
ControlFlowGraph& fg = irm.getFlowGraph();
bool debug = Log::isEnabled();
if (debug) {
Log::out() << "Selecting nodes to ignore:"<<std::endl;
}
const Nodes& nodes = fg.getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
//first pattern to ignore: class initializers in non-bc-level mode
Node* loopHead = lt->getLoopHeader(node, false);
bool inCatchLoop = loopHead!=NULL && (loopHead->isCatchBlock() || loopHead->isDispatchNode() || hasCatch(loopHead));
if (!bcLevel && node->isBlockNode()
&& node->getOutDegree() == 2 && node->getExceptionEdge()!=NULL
&& ((Inst*)node->getLastInst())->getOpcode() == Op_InitType)
{
result.insert(node);
if (debug) {
Log::out() << "\tIgnoring Op_InitType node:";FlowGraph::printLabel(Log::out(), node);Log::out() << std::endl;
}
} else if (inCatchLoop && node->isEmpty()) {
//common block for multiple catches in catch loop -> add to ignore
result.insert(node);
if (debug) {
Log::out() << "\tIgnoring catch-loop preheader node:";FlowGraph::printLabel(Log::out(), node);Log::out() << std::endl;
}
} else if (node->isCatchBlock()) {
Node* blockWithCatchInst = NULL;
if (hasCatch(node)) {
// blockWithCatchInst = node; //TODO: recheck
} else {
assert(node->hasOnlyOneSuccEdge());
Edge* e = *node->getOutEdges().begin();
blockWithCatchInst = e->getTargetNode();
}
if (blockWithCatchInst!=NULL && blockWithCatchInst->hasTwoOrMorePredEdges()) { //avoid mon-exit loops (catch loops) instrumentation
result.insert(node);
if (debug) {
Log::out() << "\tIgnoring '1-catch-inst*N-catches' node:";FlowGraph::printLabel(Log::out(), node);Log::out() << std::endl;
}
}
}
}
if (debug) {
Log::out() << "DONE. ignored nodes: " << result.size() << std::endl;
}
}
static void _selectEdgesToInstrument(Node* srcNode, IRManager& irm, Edges& result,
const StlSet<Node*>& nodesToIgnore, StlVector<bool>& flags, bool bcLevel)
{
bool profileDispatchEdges = true; //TODO: cmd-line param
assert(flags[srcNode->getId()] == false);
flags[srcNode->getId()] = true;
Node* returnNode = irm.getFlowGraph().getReturnNode();
LoopTree* loopTree = irm.getLoopTree();
const Edges& oEdges = srcNode->getOutEdges();
bool ignored = nodesToIgnore.find(srcNode)!=nodesToIgnore.end();
if (!ignored && srcNode->isBlockNode()) {
Edge* skipEdge = NULL; //instrument all edges except one
if (srcNode->isCatchBlock()) {
// for a catch block we can have only 1 successor edge if catch inst is in next block
// if catch inst is in catch block -> instrument every outgoing edge to be able to restore catch
// node frequency.
assert(hasCatch(srcNode) || srcNode->hasOnlyOneSuccEdge());
} else if (!bcLevel) { //instrument all edges if bcLevel profiling. Artificial edges will be filtered later
for(Edges::const_iterator it = oEdges.begin(); it!= oEdges.end(); ++it ){
Edge* edge = *it;
Node* targetNode = edge->getTargetNode();
bool isBackEdge = loopTree->isBackEdge(edge);
//we must instrument backedges to be able to restore loop iteration count
if( isBackEdge || (!targetNode->isBlockNode() && profileDispatchEdges) ){
// We run into a dispatch node, so we have to instrument all the other edges.
skipEdge = NULL;
break;
}
// It is profitable to instrument along the loop exit edge.
if (skipEdge == NULL || loopTree->isLoopExit(skipEdge)) {
skipEdge = edge;
}
}
}
bool debug = Log::isEnabled();
for(Edges::const_iterator it = oEdges.begin(); it!= oEdges.end(); ++it ){
Edge* edge = *it;
Node* targetNode = edge->getTargetNode();
if( targetNode->isBlockNode() && edge!=skipEdge){
bool skip = false;
if (bcLevel && targetNode->getNodeStartBCOffset() == edge->getSourceNode()->getNodeEndBCOffset()) {
skip = true;//skip this edge, it's artificial code
}
if (bcLevel && targetNode == returnNode) {
skip = true;
}
if (!skip) {
result.push_back(edge);
}
if (debug) {
Log::out()<<"\tedge id="<<edge->getId()<<" ("; FlowGraph::printLabel(Log::out(), edge->getSourceNode());
Log::out()<<"->"; FlowGraph::printLabel(Log::out(), edge->getTargetNode());Log::out()<<")";
if (skip) Log::out()<<" SKIPPED as artificial ";
Log::out()<<std::endl;
}
}
}
}
// process all child nodes. for ignored nodes we do not process dispatches
// because new catch block can be created that must also be ignored
for(Edges::const_iterator it = oEdges.begin(); it!= oEdges.end(); ++it ){
Edge* edge = *it;
Node* targetNode = edge->getTargetNode();
if (flags[targetNode->getId()] == false && !(ignored && targetNode->isDispatchNode())) {
_selectEdgesToInstrument(targetNode, irm, result, nodesToIgnore, flags, bcLevel);
}
}
}
static void selectEdgesToInstrument(MemoryManager& mm, IRManager& irm, Edges& result,
const StlSet<Node*>& nodesToIgnore, bool bcLevel)
{
ControlFlowGraph& fg = irm.getFlowGraph();
StlVector<bool> flags(mm, fg.getMaxNodeId(), false);
bool debug = Log::isEnabled();
if (debug) {
Log::out() << "List of edges to instrument: "<<std::endl;
}
_selectEdgesToInstrument(fg.getEntryNode(), irm, result, nodesToIgnore, flags, bcLevel);
if (debug) {
Log::out() << "End of list.."<<std::endl;
}
}
//
// Return true if the method represented by <cfg> is trivial.
// A method is trivial if it is a leaf method, and it has no if-then-else
// statement.
//
static bool isMethodTrivial( ControlFlowGraph& cfg ) {
const Nodes& nodes = cfg.getNodes();
Nodes::const_iterator niter;
for( niter = nodes.begin(); niter != nodes.end(); niter++ ){
Node* node = *niter;
if( !node->isBlockNode() || node->isEmpty() ){
continue;
}
Inst* last = (Inst*)node->getLastInst();
// This method is not a leaf method.
if( last->getOpcode() >= Op_DirectCall && last->getOpcode() <= Op_VMHelperCall ){
return false;
}
Edges::const_iterator eiter;
const Edges& oEdges = node->getOutEdges();
int succ = 0;
for(eiter = oEdges.begin(); eiter != oEdges.end(); ++eiter) {
Edge* edge = *eiter;
if( edge->getTargetNode()->isBlockNode() ){
succ++;
}
}
// This method has if-then-else statement(s).
if( succ > 1 ){
return false;
}
}
return true;
}
static U_32 genKey( U_32 pos, Edge* edge, bool bcLevel, bool debug) {
U_32 key = 0;
if (debug) {
Log::out()<<"\t\t key for edge with id="<<edge->getId()<<" ("; FlowGraph::printLabel(Log::out(), edge->getSourceNode());
Log::out() << "->"; FlowGraph::printLabel(Log::out(), edge->getTargetNode()); Log::out()<<") is ";Log::out().flush();
}
if (bcLevel) {
uint16 bcBefore = edge->getSourceNode()->getNodeEndBCOffset();
uint16 bcAfter = edge->getTargetNode()->getNodeStartBCOffset();
assert(bcBefore!=ILLEGAL_BC_MAPPING_VALUE && bcAfter!=ILLEGAL_BC_MAPPING_VALUE);
key = (((U_32)bcBefore)<<16) + bcAfter;
} else {
//TODO: this algorithm is not 100% effective: we can't rely on edges order in CFG
U_32 edgePos = 0;
const Edges& edges = edge->getSourceNode()->getOutEdges();
for (Edges::const_iterator it = edges.begin(), end = edges.end(); it!=end; ++it) {
Edge* outEdge = *it;
if (outEdge == edge) {
break;
}
if (outEdge->isDispatchEdge()) { //dispatch edge order is the reason of the most of the edge ordering errors
continue;
}
edgePos++;
}
key = pos + (edgePos << 16);
}
if (debug) {
Log::out() << key << std::endl;
}
return key;
}
static void checkBCMapping( ControlFlowGraph& cfg ) {
#ifdef _DEBUG
const Nodes& nodes = cfg.getNodes();
for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) {
Node* node = *it;
if (node->isBlockNode() && node!=cfg.getReturnNode()) {
CFGInst* inst = node->getFirstInst();
assert(inst!=NULL && inst->isLabel());
if (inst->getBCOffset()==ILLEGAL_BC_MAPPING_VALUE) {
if (Log::isEnabled()) {
Log::out()<<"Illegal BC-Map for node:";FlowGraph::printLabel(Log::out(), node);
}
assert(inst->getBCOffset()!=ILLEGAL_BC_MAPPING_VALUE);
}
}
}
#endif
}
} //namespace
| 44.04474 | 219 | 0.591517 | sirinath |
b08714ac2529a53c41ba7485e95325d5f0d876c4 | 25,842 | cpp | C++ | lib/smack/SmackInstGenerator.cpp | jjgarzella/smack | 1458fa20de42af69b40b09de00256c799574ca52 | [
"MIT"
] | null | null | null | lib/smack/SmackInstGenerator.cpp | jjgarzella/smack | 1458fa20de42af69b40b09de00256c799574ca52 | [
"MIT"
] | null | null | null | lib/smack/SmackInstGenerator.cpp | jjgarzella/smack | 1458fa20de42af69b40b09de00256c799574ca52 | [
"MIT"
] | null | null | null | //
// This file is distributed under the MIT License. See LICENSE for details.
//
#define DEBUG_TYPE "smack-inst-gen"
#include "smack/SmackInstGenerator.h"
#include "smack/BoogieAst.h"
#include "smack/SmackRep.h"
#include "smack/SmackOptions.h"
#include "smack/Naming.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/DebugInfo.h"
#include "smack/Debug.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Analysis/LoopInfo.h"
#include <sstream>
#include <iostream>
#include "llvm/Support/raw_ostream.h"
#include "dsa/DSNode.h"
namespace smack {
using llvm::errs;
using namespace llvm;
const bool CODE_WARN = true;
const bool SHOW_ORIG = false;
#define WARN(str) \
if (CODE_WARN) emit(Stmt::comment(std::string("WARNING: ") + str))
#define ORIG(ins) \
if (SHOW_ORIG) emit(Stmt::comment(i2s(ins)))
Regex VAR_DECL("^[[:space:]]*var[[:space:]]+([[:alpha:]_.$#'`~^\\?][[:alnum:]_.$#'`~^\\?]*):.*;");
// Procedures whose return value should not be marked as external
Regex EXTERNAL_PROC_IGNORE("^(malloc|__VERIFIER_nondet)$");
std::string i2s(const llvm::Instruction& i) {
std::string s;
llvm::raw_string_ostream ss(s);
ss << i;
s = s.substr(2);
return s;
}
void SmackInstGenerator::emit(const Stmt* s) {
// stringstream str;
// s->print(str);
// DEBUG(llvm::errs() << "emit: " << str.str() << "\n");
currBlock->addStmt(s);
}
const Stmt* SmackInstGenerator::recordProcedureCall(
llvm::Value* V, std::list<const Attr*> attrs) {
return Stmt::call("boogie_si_record_" + rep->type(V), {rep->expr(V)}, {}, attrs);
}
Block* SmackInstGenerator::createBlock() {
Block* b = Block::block(naming->freshBlockName());
proc->getBlocks().push_back(b);
return b;
}
Block* SmackInstGenerator::getBlock(llvm::BasicBlock* bb) {
if (blockMap.count(bb) == 0)
blockMap[bb] = createBlock();
return blockMap[bb];
}
void SmackInstGenerator::nameInstruction(llvm::Instruction& inst) {
if (inst.getType()->isVoidTy())
return;
proc->getDeclarations().push_back(
Decl::variable(naming->get(inst), rep->type(&inst))
);
}
void SmackInstGenerator::annotate(llvm::Instruction& I, Block* B) {
// do not generate sourceloc from calls to llvm.debug since
// those point to variable declaration lines and such
if (llvm::CallInst* ci = llvm::dyn_cast<llvm::CallInst>(&I)) {
llvm::Function* f = ci->getCalledFunction();
std::string name = f && f->hasName() ? f->getName().str() : "";
if (name.find("llvm.dbg.") != std::string::npos) {
return;
}
}
if (SmackOptions::SourceLocSymbols && I.getMetadata("dbg")) {
const DebugLoc DL = I.getDebugLoc();
auto *scope = cast<DIScope>(DL.getScope());
B->addStmt(Stmt::annot(Attr::attr("sourceloc", scope->getFilename().str(),
DL.getLine(), DL.getCol())));
}
//https://stackoverflow.com/questions/22138947/reading-metadata-from-instruction
SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
I.getAllMetadata(MDForInst);
SmallVector<StringRef, 8> Names;
I.getModule()->getMDKindNames(Names);
// for(auto II = MDForInst.begin(), EE = MDForInst.end(); II !=EE; ++II) {
for (auto II : MDForInst){
std::string name = Names[II.first];
if(name.find("smack.") == 0 || name.find("verifier.") == 0) {
std::list<const Expr*> attrs;
for(auto AI = II.second->op_begin(), AE = II.second->op_end(); AI != AE; ++AI){
if (auto *CI = mdconst::dyn_extract<ConstantInt>(*AI)){
auto value = CI->getZExtValue();
attrs.push_back(Expr::lit((long) value));
} else if (auto *CI = dyn_cast<MDString>(*AI)){
auto value = CI->getString();
attrs.push_back(Expr::lit(value));
} else {
llvm_unreachable("unexpected attribute type in smack metadata");
}
}
B->addStmt(Stmt::annot(Attr::attr(name, attrs)));
}
}
}
void SmackInstGenerator::processInstruction(llvm::Instruction& inst) {
DEBUG(errs() << "Inst: " << inst << "\n");
annotate(inst, currBlock);
ORIG(inst);
nameInstruction(inst);
nextInst++;
}
void SmackInstGenerator::visitBasicBlock(llvm::BasicBlock& bb) {
nextInst = bb.begin();
currBlock = getBlock(&bb);
auto* F = bb.getParent();
if (SmackOptions::isEntryPoint(naming->get(*F)) && &bb == &F->getEntryBlock()) {
for (auto& I : bb.getInstList()) {
if (llvm::isa<llvm::DbgInfoIntrinsic>(I))
continue;
if (I.getDebugLoc()) {
annotate(I, currBlock);
break;
}
}
emit(recordProcedureCall(F, {Attr::attr("cexpr", "smack:entry:" + naming->get(*F))}));
for (auto& A : F->getArgumentList()) {
emit(recordProcedureCall(&A, {Attr::attr("cexpr", "smack:arg:" + naming->get(*F) + ":" + naming->get(A))}));
}
}
}
void SmackInstGenerator::visitInstruction(llvm::Instruction& inst) {
DEBUG(errs() << "Instruction not handled: " << inst << "\n");
llvm_unreachable("Instruction not handled.");
}
void SmackInstGenerator::generatePhiAssigns(llvm::TerminatorInst& ti) {
llvm::BasicBlock* block = ti.getParent();
std::list<const Expr*> lhs;
std::list<const Expr*> rhs;
for (unsigned i = 0; i < ti.getNumSuccessors(); i++) {
// write to the phi-node variable of the successor
for (llvm::BasicBlock::iterator
s = ti.getSuccessor(i)->begin(), e = ti.getSuccessor(i)->end();
s != e && llvm::isa<llvm::PHINode>(s); ++s) {
llvm::PHINode* phi = llvm::cast<llvm::PHINode>(s);
if (llvm::Value* v = phi->getIncomingValueForBlock(block)) {
v = v->stripPointerCasts();
lhs.push_back(rep->expr(phi));
rhs.push_back(rep->expr(v));
}
}
}
if (!lhs.empty()) {
emit(Stmt::assign(lhs, rhs));
}
}
void SmackInstGenerator::generateGotoStmts(
llvm::Instruction& inst,
std::vector<std::pair<const Expr*, llvm::BasicBlock*> > targets) {
assert(targets.size() > 0);
if (targets.size() > 1) {
std::list<std::string> dispatch;
for (unsigned i = 0; i < targets.size(); i++) {
const Expr* condition = targets[i].first;
llvm::BasicBlock* target = targets[i].second;
if (target->getUniquePredecessor() == inst.getParent()) {
Block* b = getBlock(target);
b->insert(Stmt::assume(condition));
dispatch.push_back(b->getName());
} else {
Block* b = createBlock();
annotate(inst, b);
b->addStmt(Stmt::assume(condition));
b->addStmt(Stmt::goto_({getBlock(target)->getName()}));
dispatch.push_back(b->getName());
}
}
emit(Stmt::goto_(dispatch));
} else
emit(Stmt::goto_({getBlock(targets[0].second)->getName()}));
}
/******************************************************************************/
/* TERMINATOR INSTRUCTIONS */
/******************************************************************************/
void SmackInstGenerator::visitReturnInst(llvm::ReturnInst& ri) {
processInstruction(ri);
llvm::Value* v = ri.getReturnValue();
if (v)
emit(Stmt::assign(Expr::id(Naming::RET_VAR), rep->expr(v)));
emit(Stmt::assign(Expr::id(Naming::EXN_VAR), Expr::lit(false)));
emit(Stmt::return_());
}
void SmackInstGenerator::visitBranchInst(llvm::BranchInst& bi) {
processInstruction(bi);
// Collect the list of tarets
std::vector<std::pair<const Expr*, llvm::BasicBlock*> > targets;
if (bi.getNumSuccessors() == 1) {
// Unconditional branch
targets.push_back({Expr::lit(true),bi.getSuccessor(0)});
} else {
// Conditional branch
assert(bi.getNumSuccessors() == 2);
const Expr* e = Expr::eq(rep->expr(bi.getCondition()), rep->integerLit(1UL,1));
targets.push_back({e,bi.getSuccessor(0)});
targets.push_back({Expr::not_(e),bi.getSuccessor(1)});
}
generatePhiAssigns(bi);
if (bi.getNumSuccessors() > 1)
emit(Stmt::annot(Attr::attr(Naming::BRANCH_CONDITION_ANNOTATION,
{rep->expr(bi.getCondition())})));
generateGotoStmts(bi, targets);
}
void SmackInstGenerator::visitSwitchInst(llvm::SwitchInst& si) {
processInstruction(si);
// Collect the list of tarets
std::vector<std::pair<const Expr*, llvm::BasicBlock*> > targets;
const Expr* e = rep->expr(si.getCondition());
const Expr* n = Expr::lit(true);
for (llvm::SwitchInst::CaseIt
i = si.case_begin(); i != si.case_begin(); ++i) {
const Expr* v = rep->expr(i.getCaseValue());
targets.push_back({Expr::eq(e,v),i.getCaseSuccessor()});
// Add the negation of this case to the default case
n = Expr::and_(n, Expr::neq(e, v));
}
// The default case
targets.push_back({n,si.getDefaultDest()});
generatePhiAssigns(si);
emit(Stmt::annot(Attr::attr(Naming::BRANCH_CONDITION_ANNOTATION,
{rep->expr(si.getCondition())})));
generateGotoStmts(si, targets);
}
void SmackInstGenerator::visitInvokeInst(llvm::InvokeInst& ii) {
processInstruction(ii);
llvm::Function* f = ii.getCalledFunction();
if (f) {
emit(rep->call(f, ii));
} else {
// llvm_unreachable("Unexpected invoke instruction.");
WARN("unsoundly ignoring invoke instruction... ");
}
std::vector<std::pair<const Expr*, llvm::BasicBlock*> > targets;
targets.push_back({
Expr::not_(Expr::id(Naming::EXN_VAR)),
ii.getNormalDest()});
targets.push_back({
Expr::id(Naming::EXN_VAR),
ii.getUnwindDest()});
emit(Stmt::annot(Attr::attr(Naming::BRANCH_CONDITION_ANNOTATION,
{Expr::id(Naming::EXN_VAR)})));
generateGotoStmts(ii, targets);
}
void SmackInstGenerator::visitResumeInst(llvm::ResumeInst& ri) {
processInstruction(ri);
emit(Stmt::assign(Expr::id(Naming::EXN_VAR), Expr::lit(true)));
emit(Stmt::assign(Expr::id(Naming::EXN_VAL_VAR), rep->expr(ri.getValue())));
emit(Stmt::return_());
}
void SmackInstGenerator::visitUnreachableInst(llvm::UnreachableInst& ii) {
processInstruction(ii);
emit(Stmt::assume(Expr::lit(false)));
}
/******************************************************************************/
/* BINARY OPERATIONS */
/******************************************************************************/
void SmackInstGenerator::visitBinaryOperator(llvm::BinaryOperator& I) {
processInstruction(I);
emit(Stmt::assign(rep->expr(&I),rep->bop(&I)));
}
/******************************************************************************/
/* VECTOR OPERATIONS */
/******************************************************************************/
// TODO implement std::vector operations
/******************************************************************************/
/* AGGREGATE OPERATIONS */
/******************************************************************************/
void SmackInstGenerator::visitExtractValueInst(llvm::ExtractValueInst& evi) {
processInstruction(evi);
if (!SmackOptions::BitPrecise) {
const Expr* e = rep->expr(evi.getAggregateOperand());
for (unsigned i = 0; i < evi.getNumIndices(); i++)
e = Expr::fn(Naming::EXTRACT_VALUE, e, Expr::lit((unsigned long) evi.getIndices()[i]));
emit(Stmt::assign(rep->expr(&evi),e));
} else {
WARN("Ignoring extract instruction under bit vector mode.");
}
}
void SmackInstGenerator::visitInsertValueInst(llvm::InsertValueInst& ivi) {
processInstruction(ivi);
const Expr* old = rep->expr(ivi.getAggregateOperand());
const Expr* res = rep->expr(&ivi);
const llvm::Type* t = ivi.getType();
for (unsigned i = 0; i < ivi.getNumIndices(); i++) {
unsigned idx = ivi.getIndices()[i];
unsigned num_elements;
if (const llvm::StructType* st = llvm::dyn_cast<const llvm::StructType>(t)) {
num_elements = st->getNumElements();
t = st->getElementType(idx);
} else if (const llvm::ArrayType* at = llvm::dyn_cast<const llvm::ArrayType>(t)) {
num_elements = at->getNumElements();
t = at->getElementType();
} else {
llvm_unreachable("Unexpected aggregate type.");
}
for (unsigned j = 0; j < num_elements; j++) {
if (j != idx) {
emit(Stmt::assume(Expr::eq(
Expr::fn(Naming::EXTRACT_VALUE, res, Expr::lit(j)),
Expr::fn(Naming::EXTRACT_VALUE, old, Expr::lit(j))
)));
}
}
res = Expr::fn(Naming::EXTRACT_VALUE, res, Expr::lit(idx));
old = Expr::fn(Naming::EXTRACT_VALUE, old, Expr::lit(idx));
}
emit(Stmt::assume(Expr::eq(res,rep->expr(ivi.getInsertedValueOperand()))));
}
/******************************************************************************/
/* MEMORY ACCESS AND ADDRESSING OPERATIONS */
/******************************************************************************/
void SmackInstGenerator::visitAllocaInst(llvm::AllocaInst& ai) {
processInstruction(ai);
emit(rep->alloca(ai));
}
void SmackInstGenerator::visitLoadInst(llvm::LoadInst& li) {
processInstruction(li);
// TODO what happens with aggregate types?
// assert (!li.getType()->isAggregateType() && "Unexpected load value.");
emit(Stmt::assign(rep->expr(&li), rep->load(li.getPointerOperand())));
if (SmackOptions::MemoryModelDebug) {
emit(Stmt::call(Naming::REC_MEM_OP, {Expr::id(Naming::MEM_OP_VAL)}));
emit(Stmt::call("boogie_si_record_int", {Expr::lit(0L)}));
emit(Stmt::call("boogie_si_record_int", {rep->expr(li.getPointerOperand())}));
emit(Stmt::call("boogie_si_record_int", {rep->expr(&li)}));
}
}
void SmackInstGenerator::visitStoreInst(llvm::StoreInst& si) {
processInstruction(si);
const llvm::Value* P = si.getPointerOperand();
const llvm::Value* V = si.getOperand(0)->stripPointerCasts();
assert (!V->getType()->isAggregateType() && "Unexpected store value.");
emit(rep->store(P,V));
if (SmackOptions::SourceLocSymbols) {
if (const llvm::GlobalVariable* G = llvm::dyn_cast<const llvm::GlobalVariable>(P)) {
if (const llvm::PointerType* t = llvm::dyn_cast<const llvm::PointerType>(G->getType())) {
if (!t->getElementType()->isPointerTy()) {
assert(G->hasName() && "Expected named global variable.");
emit(Stmt::call("boogie_si_record_" + rep->type(V), {rep->expr(V)}, {}, {Attr::attr("cexpr", G->getName().str())}));
}
}
}
}
if (SmackOptions::MemoryModelDebug) {
emit(Stmt::call(Naming::REC_MEM_OP, {Expr::id(Naming::MEM_OP_VAL)}));
emit(Stmt::call("boogie_si_record_int", {Expr::lit(1L)}));
emit(Stmt::call("boogie_si_record_int", {rep->expr(P)}));
emit(Stmt::call("boogie_si_record_int", {rep->expr(V)}));
}
}
void SmackInstGenerator::visitAtomicCmpXchgInst(llvm::AtomicCmpXchgInst& i) {
processInstruction(i);
const Expr* res = rep->expr(&i);
const Expr* mem = rep->load(i.getOperand(0));
const Expr* cmp = rep->expr(i.getOperand(1));
const Expr* swp = rep->expr(i.getOperand(2));
emit(Stmt::assign(res,mem));
emit(rep->store(i.getOperand(0), Expr::cond(Expr::eq(mem, cmp), swp, mem)));
}
void SmackInstGenerator::visitAtomicRMWInst(llvm::AtomicRMWInst& i) {
using llvm::AtomicRMWInst;
processInstruction(i);
const Expr* res = rep->expr(&i);
const Expr* mem = rep->load(i.getPointerOperand());
const Expr* val = rep->expr(i.getValOperand());
emit(Stmt::assign(res,mem));
emit(rep->store(i.getPointerOperand(),
i.getOperation() == AtomicRMWInst::Xchg
? val
: Expr::fn(Naming::ATOMICRMWINST_TABLE.at(i.getOperation()),mem,val) ));
}
void SmackInstGenerator::visitGetElementPtrInst(llvm::GetElementPtrInst& I) {
processInstruction(I);
emit(Stmt::assign(rep->expr(&I), rep->ptrArith(&I)));
}
/******************************************************************************/
/* CONVERSION OPERATIONS */
/******************************************************************************/
void SmackInstGenerator::visitCastInst(llvm::CastInst& I) {
processInstruction(I);
emit(Stmt::assign(rep->expr(&I),rep->cast(&I)));
}
/******************************************************************************/
/* OTHER OPERATIONS */
/******************************************************************************/
void SmackInstGenerator::visitCmpInst(llvm::CmpInst& I) {
processInstruction(I);
emit(Stmt::assign(rep->expr(&I),rep->cmp(&I)));
}
void SmackInstGenerator::visitPHINode(llvm::PHINode& phi) {
// NOTE: this is really a No-Op, since assignments to the phi nodes
// are handled in the translation of branch/switch instructions.
processInstruction(phi);
}
void SmackInstGenerator::visitSelectInst(llvm::SelectInst& i) {
processInstruction(i);
std::string x = naming->get(i);
const Expr
*c = rep->expr(i.getOperand(0)),
*v1 = rep->expr(i.getOperand(1)),
*v2 = rep->expr(i.getOperand(2));
emit(Stmt::havoc(x));
emit(Stmt::assume(Expr::and_(
Expr::impl(Expr::eq(c,rep->integerLit(1L,1)), Expr::eq(Expr::id(x), v1)),
Expr::impl(Expr::neq(c,rep->integerLit(1L,1)), Expr::eq(Expr::id(x), v2))
)));
}
void SmackInstGenerator::visitCallInst(llvm::CallInst& ci) {
processInstruction(ci);
Function* f = ci.getCalledFunction();
if (!f) {
assert(ci.getCalledValue() && "Called value is null");
f = cast<Function>(ci.getCalledValue()->stripPointerCasts());
}
std::string name = f->hasName() ? f->getName() : "";
if (ci.isInlineAsm()) {
WARN("unsoundly ignoring inline asm call: " + i2s(ci));
emit(Stmt::skip());
} else if (name.find("llvm.dbg.") != std::string::npos) {
WARN("ignoring llvm.debug call.");
emit(Stmt::skip());
} else if (name.find(Naming::VALUE_PROC) != std::string::npos) {
emit(rep->valueAnnotation(ci));
} else if (name.find(Naming::RETURN_VALUE_PROC) != std::string::npos) {
emit(rep->returnValueAnnotation(ci));
} else if (name.find(Naming::MOD_PROC) != std::string::npos) {
proc->getModifies().push_back(rep->code(ci));
} else if (name.find(Naming::CODE_PROC) != std::string::npos) {
emit(Stmt::code(rep->code(ci)));
} else if (name.find(Naming::DECL_PROC) != std::string::npos) {
std::string code = rep->code(ci);
proc->getDeclarations().push_back(Decl::code(code, code));
} else if (name.find(Naming::TOP_DECL_PROC) != std::string::npos) {
std::string decl = rep->code(ci);
rep->getProgram()->getDeclarations().push_back(Decl::code(decl, decl));
if (VAR_DECL.match(decl)) {
std::string var = VAR_DECL.sub("\\1",decl);
rep->addBplGlobal(var);
}
} else if (name.find(Naming::CONTRACT_EXPR) != std::string::npos) {
// NOTE do not generate code for contract expressions
} else if (name == "__CONTRACT_int_variable") {
// TODO assume that all variables are within an expression scope (?)
// emit(Stmt::assign(rep->expr(&ci), Expr::id(rep->getString(ci.getArgOperand(0)))));
} else if (name == Naming::CONTRACT_FORALL) {
assert(ci.getNumArgOperands() == 2
&& "Expected contract expression argument to contract function.");
CallInst* cj = dyn_cast<CallInst>(ci.getArgOperand(1));
assert(cj && "Expected contract expression argument to contract function.");
Function* F = cj->getCalledFunction();
assert(F && F->getName().find(Naming::CONTRACT_EXPR) != std::string::npos
&& "Expected contract expression argument to contract function.");
auto binding = rep->getString(ci.getArgOperand(0));
std::list<const Expr*> args;
auto AX = F->getAttributes();
for (unsigned i = 0; i < cj->getNumArgOperands(); i++) {
std::string var = "";
if (AX.hasAttribute(i+1, "contract-var"))
var = AX.getAttribute(i+1, "contract-var").getValueAsString();
args.push_back(
var == binding ? Expr::id(binding) : rep->expr(cj->getArgOperand(i)));
}
for (auto m : rep->memoryMaps())
args.push_back(Expr::id(m.first));
auto E = Expr::fn(F->getName(), args);
emit(Stmt::assign(rep->expr(&ci),
Expr::cond(Expr::forall(binding, "int", E),
rep->integerLit(1U,1), rep->integerLit(0U,1))));
} else if (name == Naming::CONTRACT_REQUIRES ||
name == Naming::CONTRACT_ENSURES ||
name == Naming::CONTRACT_INVARIANT) {
assert(ci.getNumArgOperands() == 1
&& "Expected contract expression argument to contract function.");
CallInst* cj = dyn_cast<CallInst>(ci.getArgOperand(0));
assert(cj && "Expected contract expression argument to contract function.");
Function* F = cj->getCalledFunction();
assert(F && F->getName().find(Naming::CONTRACT_EXPR) != std::string::npos
&& "Expected contract expression argument to contract function.");
std::list<const Expr*> args;
for (auto& V : cj->arg_operands())
args.push_back(rep->expr(V));
for (auto m : rep->memoryMaps())
args.push_back(Expr::id(m.first));
auto E = Expr::fn(F->getName(), args);
if (name == Naming::CONTRACT_REQUIRES)
proc->getRequires().push_back(E);
else if (name == Naming::CONTRACT_ENSURES)
proc->getEnsures().push_back(E);
else {
auto L = loops[ci.getParent()];
assert(L);
auto H = L->getHeader();
assert(H && blockMap.count(H));
blockMap[H]->getStatements().push_front(
Stmt::assert_(E, {Attr::attr(Naming::LOOP_INVARIANT_ANNOTATION)}));
}
// } else if (name == "result") {
// assert(ci.getNumArgOperands() == 0 && "Unexpected operands to result.");
// emit(Stmt::assign(rep->expr(&ci),Expr::id(Naming::RET_VAR)));
//
// } else if (name == "qvar") {
// assert(ci.getNumArgOperands() == 1 && "Unexpected operands to qvar.");
// emit(Stmt::assign(rep->expr(&ci),Expr::id(rep->getString(ci.getArgOperand(0)))));
//
// } else if (name == "old") {
// assert(ci.getNumArgOperands() == 1 && "Unexpected operands to old.");
// llvm::LoadInst* LI = llvm::dyn_cast<llvm::LoadInst>(ci.getArgOperand(0));
// assert(LI && "Expected value from Load.");
// emit(Stmt::assign(rep->expr(&ci),
// Expr::fn("old",rep->load(LI->getPointerOperand())) ));
// } else if (name == "forall") {
// assert(ci.getNumArgOperands() == 2 && "Unexpected operands to forall.");
// Value* var = ci.getArgOperand(0);
// Value* arg = ci.getArgOperand(1);
// Slice* S = getSlice(arg);
// emit(Stmt::assign(rep->expr(&ci),
// Expr::forall(rep->getString(var), "int", S->getBoogieExpression(naming,rep))));
//
// } else if (name == "exists") {
// assert(ci.getNumArgOperands() == 2 && "Unexpected operands to forall.");
// Value* var = ci.getArgOperand(0);
// Value* arg = ci.getArgOperand(1);
// Slice* S = getSlice(arg);
// emit(Stmt::assign(rep->expr(&ci),
// Expr::exists(rep->getString(var), "int", S->getBoogieExpression(naming,rep))));
//
// } else if (name == "invariant") {
// assert(ci.getNumArgOperands() == 1 && "Unexpected operands to invariant.");
// Slice* S = getSlice(ci.getArgOperand(0));
// emit(Stmt::assert_(S->getBoogieExpression(naming,rep)));
} else {
emit(rep->call(f, ci));
}
if (f->isDeclaration() && rep->isExternal(&ci)) {
std::string name = naming->get(*f);
if (!EXTERNAL_PROC_IGNORE.match(name))
emit(Stmt::assume(Expr::fn(Naming::EXTERNAL_ADDR,rep->expr(&ci))));
}
if ((naming->get(*f).find("__SMACK") == 0 || naming->get(*f).find("__VERIFIER") == 0)
&& !f->getReturnType()->isVoidTy()) {
emit(recordProcedureCall(&ci, {Attr::attr("cexpr", "smack:ext:" + naming->get(*f))}));
}
}
bool isSourceLoc(const Stmt* stmt) {
return (stmt->getKind() == Stmt::ASSUME
&& (llvm::cast<const AssumeStmt>(stmt))->hasAttr("sourceloc"))
|| (stmt->getKind() == Stmt::CALL);
}
void SmackInstGenerator::visitDbgValueInst(llvm::DbgValueInst& dvi) {
processInstruction(dvi);
if (SmackOptions::SourceLocSymbols) {
const Value* V = dvi.getValue();
const llvm::DILocalVariable *var = dvi.getVariable();
//if (V && !V->getType()->isPointerTy() && !llvm::isa<ConstantInt>(V)) {
if (V && !V->getType()->isPointerTy()) {
//if (currBlock->begin() != currBlock->end()
//&& currBlock->getStatements().back()->getKind() == Stmt::ASSUME) {
// && isSourceLoc(currBlock->getStatements().back())) {
//assert(&*currInst == &dvi && "Current Instruction mismatch!");
auto currInst = std::prev(nextInst);
if (currInst != dvi.getParent()->begin()) {
const Instruction& pi = *std::prev(currInst);
V = V->stripPointerCasts();
WARN(i2s(pi));
if (!llvm::isa<const PHINode>(&pi) && V == llvm::dyn_cast<const Value>(&pi)) {
std::stringstream recordProc;
recordProc << "boogie_si_record_" << rep->type(V);
emit(Stmt::call(recordProc.str(), {rep->expr(V)}, {}, {Attr::attr("cexpr", var->getName().str())}));
}
}
}
}
}
void SmackInstGenerator::visitLandingPadInst(llvm::LandingPadInst& lpi) {
processInstruction(lpi);
// TODO what exactly!?
emit(Stmt::assign(rep->expr(&lpi),Expr::id(Naming::EXN_VAL_VAR)));
if (lpi.isCleanup())
emit(Stmt::assign(Expr::id(Naming::EXN_VAR), Expr::lit(false)));
WARN("unsoundly ignoring landingpad clauses...");
}
/******************************************************************************/
/* INTRINSIC FUNCTIONS */
/******************************************************************************/
void SmackInstGenerator::visitMemCpyInst(llvm::MemCpyInst& mci) {
processInstruction(mci);
assert (mci.getNumOperands() == 6);
emit(rep->memcpy(mci));
}
void SmackInstGenerator::visitMemSetInst(llvm::MemSetInst& msi) {
processInstruction(msi);
assert (msi.getNumOperands() == 6);
emit(rep->memset(msi));
}
} // namespace smack
| 35.69337 | 126 | 0.598174 | jjgarzella |
b087c2613764b330c046071cf30e3e05f2e50536 | 211 | cpp | C++ | Baekjoon/14490.cpp | r4k0nb4k0n/Programming-Challenges | 3d734902a7503f9dc49c97fe6e69e7541cd73e56 | [
"MIT"
] | 2 | 2019-05-24T08:58:26.000Z | 2022-01-09T00:46:42.000Z | Baekjoon/14490.cpp | r4k0nb4k0n/Programming-Challenges | 3d734902a7503f9dc49c97fe6e69e7541cd73e56 | [
"MIT"
] | null | null | null | Baekjoon/14490.cpp | r4k0nb4k0n/Programming-Challenges | 3d734902a7503f9dc49c97fe6e69e7541cd73e56 | [
"MIT"
] | null | null | null | #include <cstdio>
int gcd(int a, int b){
if(a%b==0) return b;
return gcd(b, a%b);
}
int main(){
int n, m;
scanf("%d:%d",&n,&m);
int x = (n>m)?(gcd(n, m)):(gcd(m, n));
printf("%d:%d",n/x,m/x);
return 0;
}
| 16.230769 | 39 | 0.507109 | r4k0nb4k0n |
b087ef516e123f5e6a886e665388daaace3cad99 | 1,056 | cpp | C++ | Linked Lists/Add Two Numbers as Lists.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | Linked Lists/Add Two Numbers as Lists.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | Linked Lists/Add Two Numbers as Lists.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
ListNode *currA = A;
ListNode *currB = B;
int sum = 0, carry = 0;
if (!A)
return B;
if (!B)
return A;
while (currA->next && currB->next)
{
sum = currA->val + currB->val + carry;
carry = sum / 10;
currA->val = sum % 10;
currA = currA->next;
currB = currB->next;
}
sum = currA->val + currB->val + carry;
carry = sum / 10;
currA->val = sum % 10;
if (!(currA->next))
currA->next = currB->next;
while (currA->next)
{
currA = currA->next;
sum = currA->val + carry;
carry = sum / 10;
currA->val = sum % 10;
}
if (carry > 0)
{
ListNode *l = new ListNode(carry);
currA->next = l;
l->next = NULL;
}
return A;
}
| 23.466667 | 62 | 0.466856 | torquecoder |
b08b0e1cabd5291ee1dc735c7ac91f9df52a38b4 | 4,215 | cpp | C++ | sample/main.cpp | xerdink/enetpp | 57b6f030eed7bc42347eec6df2b27d37e6c14925 | [
"MIT"
] | 77 | 2015-10-03T01:02:20.000Z | 2022-01-17T14:39:43.000Z | third_party/enetpp/sample/main.cpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 45 | 2017-05-03T16:47:29.000Z | 2019-12-02T14:49:50.000Z | third_party/enetpp/sample/main.cpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 16 | 2015-10-03T04:00:19.000Z | 2021-10-01T03:18:11.000Z | #include <iostream>
#include <string>
#include <random>
#include <conio.h>
#include "enetpp/client.h"
#include "enetpp/server.h"
static const int CLIENT_COUNT = 10;
static const int PORT = 123;
static bool s_exit = false;
static std::mutex s_cout_mutex;
class server_client {
public:
unsigned int _uid;
public:
server_client()
: _uid(0) {
}
unsigned int get_uid() const {
return _uid;
}
};
void run_server() {
auto trace_handler = [&](const std::string& msg) {
std::lock_guard<std::mutex> lock(s_cout_mutex);
std::cout << "server: " << msg << std::endl;
};
enetpp::server<server_client> server;
server.set_trace_handler(trace_handler);
unsigned int next_uid = 0;
auto init_client_func = [&](server_client& client, const char* ip) {
client._uid = next_uid;
next_uid++;
};
server.start_listening(enetpp::server_listen_params<server_client>()
.set_max_client_count(CLIENT_COUNT)
.set_channel_count(1)
.set_listen_port(PORT)
.set_initialize_client_function(init_client_func));
while (server.is_listening()) {
auto on_client_connected = [&](server_client& client) { trace_handler("on_client_connected"); };
auto on_client_disconnected = [&](unsigned int client_uid) { trace_handler("on_client_disconnected"); };
auto on_client_data_received = [&](server_client& client, const enet_uint8* data, size_t data_size) {
trace_handler("received packet from client : '" + std::string(reinterpret_cast<const char*>(data), data_size) + "'");
trace_handler("forwarding packet to all other clients...");
server.send_packet_to_all_if(0, data, data_size, ENET_PACKET_FLAG_RELIABLE, [&](const server_client& destination) {
return destination.get_uid() != client.get_uid();
});
};
server.consume_events(
on_client_connected,
on_client_disconnected,
on_client_data_received);
if (s_exit) {
server.stop_listening();
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void run_client(int client_index) {
auto trace_handler = [&](const std::string& msg) {
std::lock_guard<std::mutex> lock(s_cout_mutex);
std::cout << "client(" << client_index << "): " << msg << std::endl;
};
enetpp::client client;
client.set_trace_handler(trace_handler);
client.connect(enetpp::client_connect_params()
.set_channel_count(1)
.set_server_host_name_and_port("localhost", PORT));
std::mt19937 rand;
rand.seed(static_cast<unsigned long>(client_index));
std::uniform_int_distribution<> rand_distribution(5000, 20000);
auto last_send_time = std::chrono::system_clock::now();
unsigned int next_send_time_delta = rand_distribution(rand);
while (client.is_connecting_or_connected()) {
if (std::chrono::system_clock::now() - last_send_time > std::chrono::milliseconds(next_send_time_delta)) {
last_send_time = std::chrono::system_clock::now();
next_send_time_delta = rand_distribution(rand);
trace_handler("sending packet to server");
std::string packet = "hello from client:" + std::to_string(client_index);
assert(sizeof(char) == sizeof(enet_uint8));
client.send_packet(0, reinterpret_cast<const enet_uint8*>(packet.data()), packet.length(), ENET_PACKET_FLAG_RELIABLE);
}
auto on_connected = [&](){ trace_handler("on_connected"); };
auto on_disconnected = [&]() { trace_handler("on_disconnected"); };
auto on_data_received = [&](const enet_uint8* data, size_t data_size) {
trace_handler("received packet from server : '" + std::string(reinterpret_cast<const char*>(data), data_size) + "'");
};
client.consume_events(
on_connected,
on_disconnected,
on_data_received);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main(int argc, char** argv) {
enetpp::global_state::get().initialize();
auto server_thread = std::make_unique<std::thread>(&run_server);
std::vector<std::unique_ptr<std::thread>> client_threads;
for (int i = 0; i < CLIENT_COUNT; ++i) {
client_threads.push_back(std::make_unique<std::thread>(&run_client, i));
}
std::cout << "press any key to exit..." << std::endl;
_getch();
s_exit = true;
server_thread->join();
for (auto& ct : client_threads) {
ct->join();
}
enetpp::global_state::get().deinitialize();
return 0;
}
| 29.475524 | 121 | 0.714116 | xerdink |
b08b55ecfe251456b1271ff39c5938171f494de9 | 75 | cpp | C++ | tests/test_serialization/main_test_serialization.cpp | Xoanis/s2smtp | 2262d39cbe8c1c0cfd4e7dfb7761f6bd15e7caeb | [
"MIT"
] | null | null | null | tests/test_serialization/main_test_serialization.cpp | Xoanis/s2smtp | 2262d39cbe8c1c0cfd4e7dfb7761f6bd15e7caeb | [
"MIT"
] | null | null | null | tests/test_serialization/main_test_serialization.cpp | Xoanis/s2smtp | 2262d39cbe8c1c0cfd4e7dfb7761f6bd15e7caeb | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE serialization
#include <boost/test/unit_test.hpp> | 37.5 | 39 | 0.853333 | Xoanis |
b0906fe8bfa5157f850e330e16d18d614c771f72 | 1,007 | cpp | C++ | test/zoneserver.test/MockPlayerPartyController.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | test/zoneserver.test/MockPlayerPartyController.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | test/zoneserver.test/MockPlayerPartyController.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | #include "ZoneServerTestPCH.h"
#include "MockPlayerPartyController.h"
using namespace gideon::zoneserver;
MockPlayerPartyController::MockPlayerPartyController(zoneserver::go::Entity* owner) :
PlayerPartyController(owner),
lastErrorCode_(ecWhatDidYouTest)
{
}
// = rpc::PartyRpc overriding
DEFINE_SRPC_METHOD_6(MockPlayerPartyController, onPartyMemberSubInfo,
ObjectId, objectId, CharacterClass, characterClass,
CreatureLevel, level, HitPoints, hitPoints,
ManaPoints, manaPoints, Position, position)
{
addCallCount("onPartyMemberSubInfo");
objectId, characterClass, level, hitPoints, manaPoints, position;
}
DEFINE_SRPC_METHOD_2(MockPlayerPartyController, evPartyMemberLevelup,
ObjectId, objectId, CreatureLevel, level)
{
addCallCount("evPartyMemberLevelup");
objectId, level;
}
DEFINE_SRPC_METHOD_2(MockPlayerPartyController, evPartyMemberMoved,
ObjectId, objectId, Position, position)
{
addCallCount("evPartyMemberMoved");
objectId, position;
}
| 26.5 | 85 | 0.784508 | mark-online |
b091c971338652de7f1d45a3da43fe9badcaf11a | 4,676 | cpp | C++ | aws-cpp-sdk-kendra/source/model/WorkDocsConfiguration.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-kendra/source/model/WorkDocsConfiguration.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-kendra/source/model/WorkDocsConfiguration.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/kendra/model/WorkDocsConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace kendra
{
namespace Model
{
WorkDocsConfiguration::WorkDocsConfiguration() :
m_organizationIdHasBeenSet(false),
m_crawlComments(false),
m_crawlCommentsHasBeenSet(false),
m_useChangeLog(false),
m_useChangeLogHasBeenSet(false),
m_inclusionPatternsHasBeenSet(false),
m_exclusionPatternsHasBeenSet(false),
m_fieldMappingsHasBeenSet(false)
{
}
WorkDocsConfiguration::WorkDocsConfiguration(JsonView jsonValue) :
m_organizationIdHasBeenSet(false),
m_crawlComments(false),
m_crawlCommentsHasBeenSet(false),
m_useChangeLog(false),
m_useChangeLogHasBeenSet(false),
m_inclusionPatternsHasBeenSet(false),
m_exclusionPatternsHasBeenSet(false),
m_fieldMappingsHasBeenSet(false)
{
*this = jsonValue;
}
WorkDocsConfiguration& WorkDocsConfiguration::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("OrganizationId"))
{
m_organizationId = jsonValue.GetString("OrganizationId");
m_organizationIdHasBeenSet = true;
}
if(jsonValue.ValueExists("CrawlComments"))
{
m_crawlComments = jsonValue.GetBool("CrawlComments");
m_crawlCommentsHasBeenSet = true;
}
if(jsonValue.ValueExists("UseChangeLog"))
{
m_useChangeLog = jsonValue.GetBool("UseChangeLog");
m_useChangeLogHasBeenSet = true;
}
if(jsonValue.ValueExists("InclusionPatterns"))
{
Array<JsonView> inclusionPatternsJsonList = jsonValue.GetArray("InclusionPatterns");
for(unsigned inclusionPatternsIndex = 0; inclusionPatternsIndex < inclusionPatternsJsonList.GetLength(); ++inclusionPatternsIndex)
{
m_inclusionPatterns.push_back(inclusionPatternsJsonList[inclusionPatternsIndex].AsString());
}
m_inclusionPatternsHasBeenSet = true;
}
if(jsonValue.ValueExists("ExclusionPatterns"))
{
Array<JsonView> exclusionPatternsJsonList = jsonValue.GetArray("ExclusionPatterns");
for(unsigned exclusionPatternsIndex = 0; exclusionPatternsIndex < exclusionPatternsJsonList.GetLength(); ++exclusionPatternsIndex)
{
m_exclusionPatterns.push_back(exclusionPatternsJsonList[exclusionPatternsIndex].AsString());
}
m_exclusionPatternsHasBeenSet = true;
}
if(jsonValue.ValueExists("FieldMappings"))
{
Array<JsonView> fieldMappingsJsonList = jsonValue.GetArray("FieldMappings");
for(unsigned fieldMappingsIndex = 0; fieldMappingsIndex < fieldMappingsJsonList.GetLength(); ++fieldMappingsIndex)
{
m_fieldMappings.push_back(fieldMappingsJsonList[fieldMappingsIndex].AsObject());
}
m_fieldMappingsHasBeenSet = true;
}
return *this;
}
JsonValue WorkDocsConfiguration::Jsonize() const
{
JsonValue payload;
if(m_organizationIdHasBeenSet)
{
payload.WithString("OrganizationId", m_organizationId);
}
if(m_crawlCommentsHasBeenSet)
{
payload.WithBool("CrawlComments", m_crawlComments);
}
if(m_useChangeLogHasBeenSet)
{
payload.WithBool("UseChangeLog", m_useChangeLog);
}
if(m_inclusionPatternsHasBeenSet)
{
Array<JsonValue> inclusionPatternsJsonList(m_inclusionPatterns.size());
for(unsigned inclusionPatternsIndex = 0; inclusionPatternsIndex < inclusionPatternsJsonList.GetLength(); ++inclusionPatternsIndex)
{
inclusionPatternsJsonList[inclusionPatternsIndex].AsString(m_inclusionPatterns[inclusionPatternsIndex]);
}
payload.WithArray("InclusionPatterns", std::move(inclusionPatternsJsonList));
}
if(m_exclusionPatternsHasBeenSet)
{
Array<JsonValue> exclusionPatternsJsonList(m_exclusionPatterns.size());
for(unsigned exclusionPatternsIndex = 0; exclusionPatternsIndex < exclusionPatternsJsonList.GetLength(); ++exclusionPatternsIndex)
{
exclusionPatternsJsonList[exclusionPatternsIndex].AsString(m_exclusionPatterns[exclusionPatternsIndex]);
}
payload.WithArray("ExclusionPatterns", std::move(exclusionPatternsJsonList));
}
if(m_fieldMappingsHasBeenSet)
{
Array<JsonValue> fieldMappingsJsonList(m_fieldMappings.size());
for(unsigned fieldMappingsIndex = 0; fieldMappingsIndex < fieldMappingsJsonList.GetLength(); ++fieldMappingsIndex)
{
fieldMappingsJsonList[fieldMappingsIndex].AsObject(m_fieldMappings[fieldMappingsIndex].Jsonize());
}
payload.WithArray("FieldMappings", std::move(fieldMappingsJsonList));
}
return payload;
}
} // namespace Model
} // namespace kendra
} // namespace Aws
| 28.687117 | 134 | 0.767109 | perfectrecall |
b093a41a060dc900cfc4dd72b779a8e8ade57c40 | 652 | hpp | C++ | Include/Oak/Platform/AtomicDataTypes.hpp | n-suudai/OakPlanet | fd13328ad97b87151bf3fafb00fc01440832393a | [
"MIT"
] | null | null | null | Include/Oak/Platform/AtomicDataTypes.hpp | n-suudai/OakPlanet | fd13328ad97b87151bf3fafb00fc01440832393a | [
"MIT"
] | null | null | null | Include/Oak/Platform/AtomicDataTypes.hpp | n-suudai/OakPlanet | fd13328ad97b87151bf3fafb00fc01440832393a | [
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <cstddef>
namespace Oak
{
typedef std::int8_t Int8;
typedef std::int16_t Int16;
typedef std::int32_t Int32;
typedef std::int64_t Int64;
typedef std::uint8_t UInt8;
typedef std::uint16_t UInt16;
typedef std::uint32_t UInt32;
typedef std::uint64_t UInt64;
typedef float Float;
typedef double Double;
typedef char Char;
typedef char16_t Char16;
typedef char32_t Char32;
typedef wchar_t WChar;
#if defined(UNICODE)
typedef WChar TChar;
#else
typedef Char TChar;
#endif
typedef bool Bool;
typedef void Void;
typedef size_t SizeT;
typedef time_t TimeT;
typedef std::ptrdiff_t PtrDiff;
} // namespace Oak
| 15.162791 | 31 | 0.773006 | n-suudai |
b097e42d11d1f08a92f9032f0802f8df03490101 | 2,131 | cpp | C++ | examples/WolfEggs/Egg.cpp | geegrow/Geegrow_ILI9341 | f2b5f3d70f4f5e36c7a8817b54b10eee5350cbad | [
"BSD-3-Clause"
] | null | null | null | examples/WolfEggs/Egg.cpp | geegrow/Geegrow_ILI9341 | f2b5f3d70f4f5e36c7a8817b54b10eee5350cbad | [
"BSD-3-Clause"
] | null | null | null | examples/WolfEggs/Egg.cpp | geegrow/Geegrow_ILI9341 | f2b5f3d70f4f5e36c7a8817b54b10eee5350cbad | [
"BSD-3-Clause"
] | null | null | null | #include "Egg.h"
uint8_t Egg::id_counter = 0;
Egg::Egg(){
this->_obj = Drawer::instance().createCircleObj();
this->_obj->setColorBG(WHITE);
this->id = Egg::id_counter;
Egg::id_counter++;
this->callbackID = Tweak::attachMsMemberCallback(this, 1000);
Tweak::setCallbackActive(this->callbackID, false);
}
void Egg::tweakHandler(){
this->step();
}
void Egg::born(uint8_t new_slide){
if (!this->isAlive){
this->currentSlide = new_slide;
this->currentState = EGG_STATE_1;
this->isAlive = true;
this->step();
Tweak::setCallbackActive(this->callbackID, true);
}
}
void Egg::step(){
CommonInfo::safeDelayAfterUpdateCounter = TICKS_SAFE_DELAY_AFTER_UPDATE;
this->beep();
if (this->currentState == EGG_STATE_LAST){
this->lastStep();
return;
}
this->_obj->moveTo(
slides[this->currentSlide][this->currentState][0],
slides[this->currentSlide][this->currentState][1],
this->radius,
this->color
);
this->currentState++;
}
void Egg::lastStep(){
if (this->currentSlide == Wolf::basket_position){
this->catched();
} else {
this->broken();
}
this->die();
}
void Egg::die(){
this->_obj->disappear();
this->isAlive = false;
Tweak::setCallbackActive(this->callbackID, false);
}
void Egg::catched(){
CommonInfo::updateScore(CommonInfo::score + 1);
if (CommonInfo::score%20 == 0)
CommonInfo::difficulty += 1;
if (CommonInfo::score%100 == 0){
CommonInfo::difficulty -= 3;
CommonInfo::updateScoreBroken(0);
}
}
void Egg::broken(){
CommonInfo::updateScoreBroken(CommonInfo::score_broken + 1);
if (this->currentSlide == LEFT_DOWN || this->currentSlide == LEFT_UP){
CommonInfo::showLeftBroken();
}
if (this->currentSlide == RIGHT_DOWN || this->currentSlide == RIGHT_UP){
CommonInfo::showRightBroken();
}
if (CommonInfo::score_broken == 3){
CommonInfo::isGameover = true;
}
}
void Egg::beep(){
tone(BUZZER_PWM, 10000 + (this->currentSlide*2000), 100);
}
| 23.677778 | 76 | 0.614735 | geegrow |
b0992c467b5ba4b533ab958e1d45b4a89dab736d | 1,589 | cpp | C++ | test-example.cpp | bhargavthriler/OpenGL-env-setup | a40e2fbb98b76a818ffcaaa1a8a65bc638751b69 | [
"MIT"
] | null | null | null | test-example.cpp | bhargavthriler/OpenGL-env-setup | a40e2fbb98b76a818ffcaaa1a8a65bc638751b69 | [
"MIT"
] | null | null | null | test-example.cpp | bhargavthriler/OpenGL-env-setup | a40e2fbb98b76a818ffcaaa1a8a65bc638751b69 | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
//test flow
//default height and width
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main(){
//initialising OpenGL with version OpenGL3.3 and Core profile
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//Creating window object
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Hello OpenGL", NULL, NULL);
if(window == NULL){
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
//call window object
glfwMakeContextCurrent(window);
//initialise GLAD
if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//the openGL rendering window
glViewport(0, 0, 800, 600);
//call framebuffer_size_callback whenver screen is resized
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
//till stopped by the user
while(!glfwWindowShouldClose(window)){
glfwSwapBuffers(window);
glfwPollEvents();
}
//clean GLFW resources
glfwTerminate();
return 0;
}
//framebuffer size callback function defination
void framebuffer_size_callback(GLFWwindow* window, int width, int height){
glViewport(0, 0, width, height);
}
| 27.396552 | 93 | 0.701699 | bhargavthriler |
b09d7c777a68c7968fa2ac5b2234b885b2ba23d5 | 350 | cpp | C++ | Linked Lists/Reverse Linked List/soln(iterative).cpp | shrustimy/LeetCode_Solutions-C_Cpp | b6f7da9dbfa83f6fc13573e22c4ee4086921e148 | [
"MIT"
] | null | null | null | Linked Lists/Reverse Linked List/soln(iterative).cpp | shrustimy/LeetCode_Solutions-C_Cpp | b6f7da9dbfa83f6fc13573e22c4ee4086921e148 | [
"MIT"
] | null | null | null | Linked Lists/Reverse Linked List/soln(iterative).cpp | shrustimy/LeetCode_Solutions-C_Cpp | b6f7da9dbfa83f6fc13573e22c4ee4086921e148 | [
"MIT"
] | null | null | null | class Solution {
//Iterative
public:
ListNode* reverseList(ListNode* head) {
ListNode* curr=head;
ListNode* prev=NULL;
ListNode* next=NULL;
while(curr!=NULL)
{
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
}
};
| 19.444444 | 43 | 0.485714 | shrustimy |
b09f3fbb569dbf65749bc6c715062b058c59d570 | 835 | cpp | C++ | Framework/AI/Src/FleeBehavior.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | Framework/AI/Src/FleeBehavior.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | Framework/AI/Src/FleeBehavior.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "FleeBehavior.h"
using namespace JimmyGod::AI;
JimmyGod::Math::Vector2 FleeBehavior::Calculate(Agent & agent)
{
if (IsActive())
{
const float PanicDistanceSq = panicDistance * panicDistance;
if (JimmyGod::Math::DistanceSqr(agent.Position, agent.Destination) > PanicDistanceSq)
return JimmyGod::Math::Vector2{ 0,0 };
if (IsDebugUIActive())
{
JimmyGod::Graphics::SimpleDraw::AddScreenLine(agent.Destination, agent.Position, JimmyGod::Graphics::Colors::Aqua);
JimmyGod::Graphics::SimpleDraw::AddScreenCircle(JimmyGod::Math::Circle{ agent.Destination,10.0f },JimmyGod::Graphics::Colors::Aqua);
}
return ((JimmyGod::Math::Normalize(agent.Position - agent.Destination) *agent.MaxSpeed) - agent.Velocity);
}
else
{
return JimmyGod::Math::Vector2();
}
}
| 33.4 | 136 | 0.71497 | TheJimmyGod |
b09fd305fd8d805ed9b6d2f16c20c98f30836fe7 | 469 | cpp | C++ | acmicpc.net/source/3040.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 7 | 2019-06-26T07:03:32.000Z | 2020-11-21T16:12:51.000Z | acmicpc.net/source/3040.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | null | null | null | acmicpc.net/source/3040.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 9 | 2019-02-28T03:34:54.000Z | 2020-12-18T03:02:40.000Z | // 3040. 백설 공주와 일곱 난쟁이
// 2019.05.21
// 구현
#include<iostream>
using namespace std;
int main()
{
int a[9];
int sum = 0;
for (int i = 0; i < 9; i++)
{
cin >> a[i];
sum += a[i];
}
// 두개를 뺏을때 100이 되도록 모든 경우에 대해 계산
for (int i = 0; i < 8; i++)
{
for (int j = i + 1; j < 9; j++)
{
if (sum - a[i] - a[j] == 100)
{
for (int k = 0; k < 9; k++)
{
if (k != i && k != j)
{
cout << a[k] << endl;
}
}
}
}
}
return 0;
}
| 12.675676 | 33 | 0.398721 | tdm1223 |
b0a2be33f92e8c476ad3d32a0334756134f8f966 | 2,841 | cpp | C++ | source/FileControl.cpp | mystesPF/Raw-Format-Convert-to-BMP | 8e0640b488a0cc441e7a9d8db2a2e79976e89eb2 | [
"BSD-3-Clause"
] | 1 | 2021-01-25T03:19:13.000Z | 2021-01-25T03:19:13.000Z | source/FileControl.cpp | mystesPF/Raw-Format-Convert-to-BMP | 8e0640b488a0cc441e7a9d8db2a2e79976e89eb2 | [
"BSD-3-Clause"
] | null | null | null | source/FileControl.cpp | mystesPF/Raw-Format-Convert-to-BMP | 8e0640b488a0cc441e7a9d8db2a2e79976e89eb2 | [
"BSD-3-Clause"
] | 1 | 2019-05-28T09:55:42.000Z | 2019-05-28T09:55:42.000Z | #include "StdAfx.h"
#include "FileControl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CFileControl::CFileControl(void){}
CFileControl::~CFileControl(void){}
BOOL CFileControl::DoConvertRawFile(CFiles* pFile)
{
// Create File Data
if( !OpenRawFile(pFile))
{
AfxMessageBox(_T("Cannot Create File"));
return FALSE;
}
// Do interpolation
if(!Interpolation.DoInterpolation(pFile))
{
return FALSE;
}
else
{
delete[] pFile->getRawFileData();
}
// Create Full Image ( Headers + Data )
if(pFile->getFileExt() == "BMP")
{
if( !MakeBmpImage(pFile, pFile->getInterpolatedData()) )
{
return FALSE;
}
delete[] pFile->getInterpolatedData();
}
else // JPG, PNG, etc
{
AfxMessageBox(_T("Cannot Support yet"));
exit(0);
}
return TRUE;
}
BOOL CFileControl::OpenRawFile(CFiles* pFile)
{
FILE* fp;
CT2A ascii(pFile->getFileName(), CP_UTF8); // CString to const char*
if((fopen_s(&fp, ascii.m_psz, "rb")) != 0)
{
AfxMessageBox(_T("fopen_s() Error"));
return FALSE ;
}
switch(pFile->getBitDepth()) // File Bit Depth Check
{
case 8:
fread(pFile->getRawFileData(), 1, pFile->getImageSize(), fp);
break;
case 10:
BYTE* szTemp = new BYTE[(pFile->getImageSize()) * 2];
fread(szTemp, 2, pFile->getImageSize(), fp);
// Convert 10bit to 8bit
for(int i = 0; i < pFile->getImageSize(); i++)
{
// and Normalization 0~1023 to 0~255
pFile->getRawFileData()[i] = (szTemp[2 * i] + (szTemp[(2 * i) + 1] * 256)) >> 2; // 16^0 and 16^1 -> 16^2 and 16^3 Because Little Endian
}
delete[] szTemp;
break;
}
fclose(fp);
return TRUE;
}
BOOL CFileControl::MakeBmpImage(CFiles* pFile, BYTE* szInputData)
{
FILE* fp2;
CBmpClass BmpFile(pFile);
BmpFile.CreateBmpImage(pFile->getResultFileData(), szInputData);
CT2A ascii(MakeFileName(pFile->getFileName(), pFile->getFileExt()), CP_UTF8); // CString to const char*
if( (fopen_s(&fp2, ascii.m_psz, "wb")) != NULL)
{
AfxMessageBox(_T("Cannot Save File"));
return FALSE;
}
// Write Bitmap Headers
fwrite(&BmpFile.bfh, sizeof(BITMAPFILEHEADER), 1, fp2);
fwrite(&BmpFile.bih, sizeof(BITMAPINFOHEADER), 1, fp2);
if(pFile->getColorType() == GRAY_SCALE)
{
fwrite(&BmpFile.rgb, sizeof(RGBQUAD), 256, fp2);
}
fwrite(pFile->getResultFileData(), 1, pFile->getResultImageSize(), fp2);
fclose(fp2);
return TRUE;
}
CString CFileControl::MakeFileName(CString fName, CString ext)
{
int nPos;
CString originFileName = fName;
CString strNewPath;
nPos = originFileName.ReverseFind('.');
if(nPos == -1)
{
strNewPath = originFileName + _T(".") + ext;
}
else
{
strNewPath = originFileName.Left(nPos) + _T(".") + ext;
}
return strNewPath;
} | 22.023256 | 140 | 0.637804 | mystesPF |
b0aad6c22b4c85330c066ca5ff4b0a640c10e449 | 7,092 | hpp | C++ | SharedPtr.hpp | avinarsale/Smart-Pointers | a5cae680012710a99008eef2fda2b9b4b1db02af | [
"Apache-2.0"
] | null | null | null | SharedPtr.hpp | avinarsale/Smart-Pointers | a5cae680012710a99008eef2fda2b9b4b1db02af | [
"Apache-2.0"
] | null | null | null | SharedPtr.hpp | avinarsale/Smart-Pointers | a5cae680012710a99008eef2fda2b9b4b1db02af | [
"Apache-2.0"
] | null | null | null | #ifndef SHARED_PTR
#define SHARED_PTR
#include<iostream>
#include <mutex>
namespace cs540 {
std::mutex myMutex;
class ReferenceCount{
public:
int refCount;
ReferenceCount() : refCount(0) {}
virtual ~ReferenceCount() {}
};
template <typename T>
class CriticalSection : public ReferenceCount
{
public:
T *obj;
CriticalSection(T* tempObj) : obj(tempObj){}
~CriticalSection(){
delete obj;
obj=nullptr;
}
};
template <typename T>
class SharedPtr{
public:
T* myPtr;
ReferenceCount* objShared;
SharedPtr() : objShared(nullptr),myPtr(nullptr) {}
template <typename U>
explicit SharedPtr(U *obj) : myPtr(obj),objShared(new CriticalSection<U>(obj)) {
if(objShared!=nullptr){
myMutex.lock();
objShared->refCount=1;
myMutex.unlock();
}
}
SharedPtr(const SharedPtr &p) : objShared(p.objShared),myPtr(p.myPtr) {
if(objShared!=nullptr){
myMutex.lock();
objShared->refCount++;
myMutex.unlock();
}
}
template <typename U>
SharedPtr(const SharedPtr<U>& p) : objShared(p.objShared), myPtr(p.myPtr) {
if(objShared!=nullptr){
myMutex.lock();
objShared->refCount++;
myMutex.unlock();
}
}
SharedPtr(SharedPtr &&p) : objShared(p.objShared), myPtr(p.myPtr) {
if(p!=nullptr) {
//delete p.objShared;
p.objShared=nullptr;
p.myPtr=nullptr;
}
}
template <typename U>
SharedPtr(SharedPtr<U> &&p) : objShared(p.objShared), myPtr(p.myPtr) {
if(p!=nullptr) {
//delete p.objShared;
p.objShared=nullptr;
p.myPtr=nullptr;
}
}
SharedPtr &operator=(const SharedPtr &p) {
if(p!=nullptr) {
if (objShared == p.objShared) {
return *this;
}else{
if(objShared!=nullptr){
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if( tempCount == 0) {
if(objShared!=nullptr)
delete objShared;
}
}
objShared = p.objShared;
myMutex.lock();
objShared->refCount++;
myMutex.unlock();
}
}
return *this;
}
template <typename U>
SharedPtr<T> &operator=(const SharedPtr<U> &p) {
if(p!=nullptr) {
if (objShared == p.objShared) {
return *this;
}else{
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if( tempCount == 0) {
if(objShared!=nullptr)
delete objShared;
}
}
objShared = p.objShared;
myMutex.lock();
objShared->refCount++;
myMutex.unlock();
}
}
return *this;
}
SharedPtr &operator=(SharedPtr &&p) {
if(p!=nullptr) {
if (objShared == p.objShared) {
return *this;
}else{
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if( tempCount == 0) {
if(objShared!=nullptr)
delete objShared;
}
}
objShared = p.objShared;
}
p.objShared=nullptr;
p.myPtr=nullptr;
}
return *this;
}
template <typename U>
SharedPtr &operator=(SharedPtr<U> &&p) {
if(p!=nullptr) {
if (objShared == p.objShared) {
return *this;
}else{
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if( tempCount == 0) {
if(objShared!=nullptr)
delete objShared;
}
}
objShared = p.objShared;
}
p.objShared=nullptr;
p.myPtr=nullptr;
}
return *this;
}
~SharedPtr() {
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if( tempCount == 0) {
delete objShared;
objShared=nullptr;
myPtr=nullptr;
}
}
}
void reset() {
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if(tempCount == 0) {
delete objShared;
}
objShared=nullptr;
myPtr=nullptr;
}
}
template <typename U>
void reset(U *p) {
if(objShared!=nullptr) {
myMutex.lock();
int tempCount=--objShared->refCount;
myMutex.unlock();
if(tempCount==0) {
delete objShared;
}
objShared=nullptr;
}
myPtr=p;
objShared= new CriticalSection<U>(p);
myMutex.lock();
objShared->refCount++;
myMutex.unlock();
}
T *get() const {
return myPtr;
}
T &operator*() const {
return *myPtr;
}
T *operator->() const {
return myPtr;
}
explicit operator bool() const {
if(myPtr!=nullptr) {
return true;
}
return false;
}
template <typename T1, typename T2>
friend bool operator==(const SharedPtr<T1> &, const SharedPtr<T2> &);
template <typename T1>
friend bool operator==(const SharedPtr<T1> &, std::nullptr_t);
template <typename T1>
friend bool operator==(std::nullptr_t, const SharedPtr<T1> &);
template <typename T1, typename T2>
friend bool operator!=(const SharedPtr<T1>&, const SharedPtr<T2> &);
template <typename T1>
friend bool operator!=(const SharedPtr<T1> &, std::nullptr_t);
template <typename T1>
friend bool operator!=(std::nullptr_t, const SharedPtr<T1> &);
template <typename T1, typename U1>
friend SharedPtr<T1> static_pointer_cast(const SharedPtr<U1> &sp);
template <typename T1, typename U1>
friend SharedPtr<T1> dynamic_pointer_cast(const SharedPtr<U1> &sp);
};
template <typename T1, typename T2>
bool operator==(const SharedPtr<T1>& p1, const SharedPtr<T2>& p2){
if(p1.myPtr==p2.myPtr){
return true;
}
if(p1==nullptr && p2==nullptr){
return true;
}
return false;
}
template <typename T1>
bool operator==(const SharedPtr<T1>& p1, std::nullptr_t p2){
if(p1.objShared == p2){
return true;
}
return false;
}
template <typename T1>
bool operator==(std::nullptr_t p1, const SharedPtr<T1>& p2){
if(p1 == p2){
return true;
}
return false;
}
template <typename T1, typename T2>
bool operator!=(const SharedPtr<T1>& p1, const SharedPtr<T2>& p2){
if (p1 == p2) {
return false;
}
return true;
}
template <typename T1>
bool operator!=(const SharedPtr<T1>& p1, std::nullptr_t p2){
if (p1 == p2) {
return false;
}
return true;
}
template <typename T1>
bool operator!=(std::nullptr_t p1, const SharedPtr<T1>& p2){
if (p1 == p2) {
return false;
}
return true;
}
template <typename T1, typename U1>
SharedPtr<T1> static_pointer_cast(const SharedPtr<U1>& sp){
SharedPtr<T1> castPtr;
castPtr.objShared=sp.objShared;
myMutex.lock();
++castPtr.objShared->refCount;
myMutex.unlock();
castPtr.myPtr=static_cast<T1 *>(sp.myPtr);
return castPtr;
}
template <typename T1, typename U1>
SharedPtr<T1> dynamic_pointer_cast(const SharedPtr<U1> &sp){
SharedPtr<T1> castPtr;
castPtr.objShared=sp.objShared;
myMutex.lock();
++castPtr.objShared->refCount;
myMutex.unlock();
castPtr.myPtr=dynamic_cast<T1 *>(sp.myPtr);
return castPtr;
}
}//namespace
#endif | 21.956656 | 82 | 0.609278 | avinarsale |
b0ad5831b8e4ecfb9ccb44e5b5855e0ac5f9b01c | 1,911 | cpp | C++ | NAS2D/Renderer/Color.cpp | cugone/nas2d-core | 632983fa6e9d334d79fdf2dfc54719eee5b5d3ca | [
"Zlib"
] | 13 | 2017-03-23T06:11:30.000Z | 2021-09-15T16:22:56.000Z | NAS2D/Renderer/Color.cpp | cugone/nas2d-core | 632983fa6e9d334d79fdf2dfc54719eee5b5d3ca | [
"Zlib"
] | 467 | 2016-06-28T22:47:06.000Z | 2022-02-08T18:08:12.000Z | NAS2D/Renderer/Color.cpp | cugone/nas2d-core | 632983fa6e9d334d79fdf2dfc54719eee5b5d3ca | [
"Zlib"
] | 8 | 2015-10-12T21:36:10.000Z | 2021-06-24T07:46:31.000Z | // ==================================================================================
// = NAS2D
// = Copyright © 2008 - 2020 New Age Software
// ==================================================================================
// = NAS2D is distributed under the terms of the zlib license. You are free to copy,
// = modify and distribute the software under the terms of the zlib license.
// =
// = Acknowledgment of your use of NAS2D is appreciated but is not required.
// ==================================================================================
#include "Color.h"
using namespace NAS2D;
const Color Color::Black{0, 0, 0};
const Color Color::Blue{0, 0, 255};
const Color Color::Green{0, 255, 0};
const Color Color::Cyan{0, 255, 255};
const Color Color::DarkGreen{0, 128, 0};
const Color Color::DarkGray{64, 64, 64};
const Color Color::Gray{128, 128, 128};
const Color Color::LightGray{192, 192, 192};
const Color Color::CoolGray{128, 128, 143};
const Color Color::CoolLightGray{192, 192, 207};
const Color Color::CoolDarkGray{64, 64, 79};
const Color Color::WarmGray{143, 143, 128};
const Color Color::WarmLightGray{207, 207, 192};
const Color Color::WarmDarkGray{79, 79, 64};
const Color Color::Magenta{255, 0, 255};
const Color Color::Navy{35, 60, 85};
const Color Color::Orange{255, 128, 0};
const Color Color::Red{255, 0, 0};
const Color Color::Silver{192, 192, 192};
const Color Color::White{255, 255, 255};
const Color Color::Yellow{255, 255, 0};
const Color Color::Normal{255, 255, 255};
const Color Color::NormalZ{128, 128, 255};
const Color Color::NoAlpha{0, 0, 0, 0};
bool Color::operator==(Color other) const
{
return (red == other.red) && (green == other.green) && (blue == other.blue) && (alpha == other.alpha);
}
bool Color::operator!=(Color other) const
{
return !(*this == other);
}
Color Color::alphaFade(uint8_t newAlpha) const
{
return {red, green, blue, newAlpha};
}
| 34.125 | 103 | 0.603349 | cugone |
b0b090a596b98fbbe44d008d616dc42b567a5992 | 76,642 | cpp | C++ | FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D10/AdvancedParticles/AdvancedParticles.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D10/AdvancedParticles/AdvancedParticles.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D10/AdvancedParticles/AdvancedParticles.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------------------
// File: ParticlesGS.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "DXUTgui.h"
#include "DXUTsettingsdlg.h"
#include "DXUTcamera.h"
#include "SDKmisc.h"
#include "SDKmesh.h"
#include "resource.h"
#include "Commdlg.h"
#define MAX_BONE_MATRICES 255
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
CModelViewerCamera g_Camera; // A model viewing camera
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // manages the 3D UI
CDXUTDialog g_SampleUI; // dialog for sample specific controls
bool g_bFirst = true;
ID3DX10Font* g_pFont10 = NULL;
ID3DX10Sprite* g_pSprite10 = NULL;
CDXUTTextHelper* g_pTxtHelper = NULL;
ID3D10Effect* g_pParticleEffect10 = NULL;
ID3D10Effect* g_pMeshEffect10 = NULL;
ID3D10Effect* g_pVolEffect10 = NULL;
ID3D10Effect* g_pPaintEffect10 = NULL;
ID3D10InputLayout* g_pParticleVertexLayout = NULL;
ID3D10InputLayout* g_pMeshVertexLayout = NULL;
ID3D10InputLayout* g_pQuadVertexLayout = NULL;
ID3D10InputLayout* g_pAnimVertexLayout = NULL;
ID3D10InputLayout* g_pPaintAnimVertexLayout = NULL;
struct QUAD_VERTEX
{
D3DXVECTOR3 Pos;
D3DXVECTOR2 Tex;
};
ID3D10Buffer* g_pQuadVB = NULL;
// particle necessities
D3DXVECTOR4 g_vGravity( 0,-0.5f,0,0 );
D3DXVECTOR3 g_vParticleColor( 1,0,0 );
float g_fParticleOpacity = 1.0f;
ID3D10Buffer* g_pParticleStart = NULL;
ID3D10Buffer* g_pParticleStreamTo = NULL;
ID3D10Buffer* g_pParticleDrawFrom = NULL;
ID3D10ShaderResourceView* g_pParticleStreamToRV = NULL;
ID3D10ShaderResourceView* g_pParticleDrawFromRV = NULL;
ID3D10ShaderResourceView* g_pParticleTexRV = NULL;
ID3D10Texture1D* g_pRandomTexture = NULL;
ID3D10ShaderResourceView* g_pRandomTexRV = NULL;
// render to volume necessities
D3DXVECTOR3 g_vEmitterPos( 0,1.5f,0 );
UINT g_VolumeWidth = 32;
UINT g_VolumeHeight = 32;
UINT g_VolumeDepth = 32;
float g_VolumeSize = 2.0f;
float g_fEmitterSize = 0.3f;
ID3D10Texture3D* g_pVolumeTexture = NULL;
ID3D10ShaderResourceView* g_pVolumeTexRV = NULL;
ID3D10RenderTargetView** g_pVolumeTexRTVs = NULL;
ID3D10RenderTargetView* g_pVolumeTexTotalRTV = NULL;
ID3D10Texture3D* g_pVelocityTexture = NULL;
ID3D10ShaderResourceView* g_pVelocityTexRV = NULL;
ID3D10RenderTargetView** g_pVelocityTexRTVs = NULL;
ID3D10RenderTargetView* g_pVelocityTexTotalRTV = NULL;
// paint necessities
int g_iControlMesh = 1;
bool g_bPaint = false;
bool g_bRandomizeColor = false;
UINT g_PositionWidth = 256;
UINT g_PositionHeight = 256;
UINT g_iParticleStart = 0;
UINT g_iParticleStep = 0;
float g_fParticlePaintRadSq = 0.0005f;
struct MESH
{
CDXUTSDKMesh Mesh;
ID3D10Texture2D* pMeshPositionTexture;
ID3D10ShaderResourceView* pMeshPositionRV;
ID3D10RenderTargetView* pMeshPositionRTV;
UINT MeshTextureWidth;
UINT MeshTextureHeight;
ID3D10Texture2D* pMeshTexture;
ID3D10ShaderResourceView* pMeshRV;
ID3D10RenderTargetView* pMeshRTV;
D3DXMATRIX mWorld;
D3DXMATRIX mWorldPrev;
D3DXVECTOR3 vPosition;
D3DXVECTOR3 vRotation;
};
#define NUM_MESHES 2
MESH g_WorldMesh[NUM_MESHES];
// particle fx
ID3D10EffectTechnique* g_pRenderParticles_Particle;
ID3D10EffectTechnique* g_pAdvanceParticles_Particle;
ID3D10EffectMatrixVariable* g_pmWorldViewProj_Particle;
ID3D10EffectMatrixVariable* g_pmInvView_Particle;
ID3D10EffectScalarVariable* g_pfGlobalTime_Particle;
ID3D10EffectScalarVariable* g_pfElapsedTime_Particle;
ID3D10EffectScalarVariable* g_pfVolumeSize_Particle;
ID3D10EffectScalarVariable* g_pfEmitterSize_Particle;
ID3D10EffectVectorVariable* g_pvVolumeOffsets_Particle;
ID3D10EffectVectorVariable* g_pvFrameGravity_Particle;
ID3D10EffectVectorVariable* g_pvParticleColor_Particle;
ID3D10EffectVectorVariable* g_pvEmitterPos_Particle;
ID3D10EffectShaderResourceVariable* g_ptxDiffuse_Particle;
ID3D10EffectShaderResourceVariable* g_ptxRandom_Particle;
ID3D10EffectShaderResourceVariable* g_ptxVolume_Particle;
ID3D10EffectShaderResourceVariable* g_ptxVelocity_Particle;
// mesh fx
ID3D10EffectTechnique* g_pRenderScene_Mesh;
ID3D10EffectTechnique* g_pRenderAnimScene_Mesh;
ID3D10EffectMatrixVariable* g_pmWorldViewProj_Mesh;
ID3D10EffectMatrixVariable* g_pmViewProj_Mesh;
ID3D10EffectMatrixVariable* g_pmWorld_Mesh;
ID3D10EffectMatrixVariable* g_pmBoneWorld_Mesh;
ID3D10EffectMatrixVariable* g_pmBonePrev_Mesh;
ID3D10EffectVectorVariable* g_pvLightDir_Mesh;
ID3D10EffectVectorVariable* g_pvEyePt_Mesh;
ID3D10EffectShaderResourceVariable* g_ptxDiffuse_Mesh;
ID3D10EffectShaderResourceVariable* g_ptxNormal_Mesh;
ID3D10EffectShaderResourceVariable* g_ptxSpecular_Mesh;
ID3D10EffectShaderResourceVariable* g_ptxPaint_Mesh;
// render to volume fx
ID3D10EffectTechnique* g_pRenderScene_Vol;
ID3D10EffectTechnique* g_pRenderAnimScene_Vol;
ID3D10EffectTechnique* g_pRenderAnimVelocity_Vol;
ID3D10EffectTechnique* g_pRenderVelocity_Vol;
ID3D10EffectMatrixVariable* g_pmWorldViewProj_Vol;
ID3D10EffectMatrixVariable* g_pmViewProj_Vol;
ID3D10EffectMatrixVariable* g_pmWorld_Vol;
ID3D10EffectMatrixVariable* g_pmWorldPrev_Vol;
ID3D10EffectMatrixVariable* g_pmBoneWorld_Vol;
ID3D10EffectMatrixVariable* g_pmBonePrev_Vol;
ID3D10EffectScalarVariable* g_pfElapsedTime_Vol;
ID3D10EffectScalarVariable* g_pfPlaneStart_Vol;
ID3D10EffectScalarVariable* g_pfPlaneStep_Vol;
ID3D10EffectVectorVariable* g_pvFarClipPlane_Vol;
ID3D10EffectVectorVariable* g_pvNearClipPlane_Vol;
// paint fx
ID3D10EffectTechnique* g_pRenderToUV_Paint;
ID3D10EffectTechnique* g_pRenderAnimToUV_Paint;
ID3D10EffectTechnique* g_pPaint_Paint;
ID3D10EffectMatrixVariable* g_pmWorld_Paint;
ID3D10EffectMatrixVariable* g_pmBoneWorld_Paint;
ID3D10EffectScalarVariable* g_pNumParticles_Paint;
ID3D10EffectScalarVariable* g_pParticleStart_Paint;
ID3D10EffectScalarVariable* g_pParticleStep_Paint;
ID3D10EffectScalarVariable* g_pfParticleRadiusSq_Paint;
ID3D10EffectVectorVariable* g_pvParticleColor_Paint;
ID3D10EffectShaderResourceVariable* g_ptxDiffuse_Paint;
ID3D10EffectShaderResourceVariable* g_pParticleBuffer_Paint;
// for the dynamic mesh
struct PARTICLE_VERTEX
{
D3DXVECTOR4 pos;
D3DXVECTOR4 lastpos;
D3DXVECTOR4 color;
D3DXVECTOR3 vel;
UINT ID;
};
#define MAX_PARTICLES 5000
UINT g_OptimalParticlesPerShader = 200;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN 1
#define IDC_TOGGLEREF 3
#define IDC_CHANGEDEVICE 4
#define IDC_TOGGLEWARP 5
// sample UI
#define IDC_TOGGLEMESH 49
#define IDC_PAINTTOGGLE 50
#define IDC_PARTICLECOLOR 51
#define IDC_PARTICLEOPACITY_STATIC 52
#define IDC_PARTICLEOPACITY 53
#define IDC_RANDOMIZECOLOR 54
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext );
void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext );
void CALLBACK OnD3D10DestroyDevice( void* pUserContext );
void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
void InitApp();
void RenderText();
HRESULT CreateParticleBuffer( ID3D10Device* pd3dDevice );
HRESULT CreateRandomTexture( ID3D10Device* pd3dDevice );
HRESULT CreateVolumeTexture( ID3D10Device* pd3dDevice );
HRESULT CreatePositionTextures( ID3D10Device* pd3dDevice, MESH* pMesh );
HRESULT CreateMeshTexture( ID3D10Device* pd3dDevice, UINT width, UINT height, MESH* pMesh );
HRESULT CreateQuadVB( ID3D10Device* pd3dDevice );
void HandleKeys( float fElapsedTime );
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// DXUT will create and use the best device (either D3D9 or D3D10)
// that is available on the system depending on which D3D callbacks are set below
// Set DXUT callbacks
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( KeyboardProc );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable );
DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice );
DXUTSetCallbackD3D10SwapChainResized( OnD3D10SwapChainResized );
DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10SwapChainReleasing );
DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice );
DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender );
InitApp();
DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"AdvancedParticles" );
DXUTCreateDevice( true, 800, 600 );
DXUTMainLoop(); // Enter into the DXUT render loop
}
float RPercent()
{
float ret = ( float )( ( rand() % 20000 ) - 10000 );
return ret / 10000.0f;
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
g_iParticleStep = MAX_PARTICLES / g_OptimalParticlesPerShader;
g_D3DSettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_SampleUI.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent ); int iY = 10;
g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 );
g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 );
g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 );
g_HUD.AddButton( IDC_TOGGLEWARP, L"Toggle WARP (F4)", 35, iY += 24, 125, 22, VK_F4 );
int iX = 35;
iY = 0;
g_SampleUI.SetCallback( OnGUIEvent ); iY = 10;
g_SampleUI.AddButton( IDC_TOGGLEMESH, L"Toggle Active Mesh", iX, iY += 24, 125, 22 );
iY += 30;
g_SampleUI.AddCheckBox( IDC_PAINTTOGGLE, L"Toggle Painting", iX, iY, 125, 22 );
g_SampleUI.AddButton( IDC_PARTICLECOLOR, L"Particle Color", iX, iY += 24, 125, 22 );
WCHAR str[MAX_PATH];
swprintf_s( str, MAX_PATH, L"Particle Opacity %.2f", g_fParticleOpacity );
g_SampleUI.AddStatic( IDC_PARTICLEOPACITY_STATIC, str, iX, iY += 24, 125, 22 );
g_SampleUI.AddSlider( IDC_PARTICLEOPACITY, iX - 20, iY += 24, 125, 22, 0,
100, ( int )( 100 * g_fParticleOpacity ) );
g_SampleUI.AddCheckBox( IDC_RANDOMIZECOLOR, L"Randomize Color", iX, iY += 24, 125, 22 );
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
pDeviceSettings->d3d10.SyncInterval = DXGI_SWAP_EFFECT_DISCARD;
g_D3DSettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetEnabled( false );
// For the first device created if its a REF device, optionally display a warning dialog box
static bool s_bFirstTime = true;
if( s_bFirstTime )
{
s_bFirstTime = false;
if( ( DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) ||
( DXUT_D3D10_DEVICE == pDeviceSettings->ver &&
pDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE ) )
DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
}
return true;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
static double fLastRandomize = 0.0;
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
if( g_bRandomizeColor )
{
if( fTime - fLastRandomize > 2.0 )
{
g_vParticleColor.x = fabs( RPercent() );
g_vParticleColor.y = fabs( RPercent() );
g_vParticleColor.z = fabs( RPercent() );
fLastRandomize = fTime;
}
}
HandleKeys( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
// Pass messages to dialog resource manager calls so GUI state is updated correctly
*pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass messages to settings dialog if its active
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
return 0;
}
// Give the dialogs a chance to handle the message first
*pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
*pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
static COLORREF g_customColors[16] = {0};
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
switch( nControlID )
{
case IDC_TOGGLEFULLSCREEN:
DXUTToggleFullScreen(); break;
case IDC_TOGGLEREF:
DXUTToggleREF(); break;
case IDC_CHANGEDEVICE:
g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break;
case IDC_TOGGLEWARP:
DXUTToggleWARP(); break;
case IDC_TOGGLEMESH:
{
g_iControlMesh ++;
if( g_iControlMesh >= NUM_MESHES )
g_iControlMesh = 0;
}
break;
case IDC_PAINTTOGGLE:
g_bPaint = !g_bPaint;
break;
case IDC_PARTICLECOLOR:
{
CHOOSECOLOR chcol;
ZeroMemory( &chcol, sizeof( CHOOSECOLOR ) );
chcol.lStructSize = sizeof( CHOOSECOLOR );
chcol.rgbResult = RGB( ( BYTE )( g_vParticleColor.x * 255.0f ), ( BYTE )( g_vParticleColor.y * 255.0f ),
( BYTE )( g_vParticleColor.z * 255.0f ) );
chcol.Flags = CC_RGBINIT | CC_FULLOPEN;
chcol.lpCustColors = g_customColors;
DXUTPause( true, true );
if( ChooseColor( &chcol ) )
{
g_vParticleColor.x = GetRValue( chcol.rgbResult ) / 255.0f;
g_vParticleColor.y = GetGValue( chcol.rgbResult ) / 255.0f;
g_vParticleColor.z = GetBValue( chcol.rgbResult ) / 255.0f;
}
DXUTPause( false, false );
}
break;
case IDC_PARTICLEOPACITY:
{
g_fParticleOpacity = g_SampleUI.GetSlider( IDC_PARTICLEOPACITY )->GetValue() / 100.0f;
WCHAR str[MAX_PATH];
swprintf_s( str, MAX_PATH, L"Particle Opacity %.2f", g_fParticleOpacity );
g_SampleUI.GetStatic( IDC_PARTICLEOPACITY_STATIC )->SetText( str );
}
break;
case IDC_RANDOMIZECOLOR:
g_bRandomizeColor = !g_bRandomizeColor;
break;
}
}
//--------------------------------------------------------------------------------------
// Reject any D3D10 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D10 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) );
V_RETURN( g_D3DSettingsDlg.OnD3D10CreateDevice( pd3dDevice ) );
V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
L"Arial", &g_pFont10 ) );
V_RETURN( D3DX10CreateSprite( pd3dDevice, 512, &g_pSprite10 ) );
g_pTxtHelper = new CDXUTTextHelper( NULL, NULL, g_pFont10, g_pSprite10, 15 );
// Read the D3DX effect file
WCHAR str[MAX_PATH];
UINT uFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_DEBUG;
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"AdvancedParticles.fx" ) );
V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", uFlags, 0, pd3dDevice, NULL,
NULL, &g_pParticleEffect10, NULL, NULL ) );
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Meshes.fx" ) );
V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", uFlags, 0, pd3dDevice, NULL,
NULL, &g_pMeshEffect10, NULL, NULL ) );
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"RenderToVolume.fx" ) );
V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", uFlags, 0, pd3dDevice, NULL,
NULL, &g_pVolEffect10, NULL, NULL ) );
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Paint.fx" ) );
V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", uFlags, 0, pd3dDevice, NULL,
NULL, &g_pPaintEffect10, NULL, NULL ) );
// Obtain the technique handles for particle fx
g_pRenderParticles_Particle = g_pParticleEffect10->GetTechniqueByName( "RenderParticles" );
g_pAdvanceParticles_Particle = g_pParticleEffect10->GetTechniqueByName( "AdvanceParticles" );
// Obtain the parameter handles for particle fx
g_pmWorldViewProj_Particle = g_pParticleEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix();
g_pmInvView_Particle = g_pParticleEffect10->GetVariableByName( "g_mInvView" )->AsMatrix();
g_pfGlobalTime_Particle = g_pParticleEffect10->GetVariableByName( "g_fGlobalTime" )->AsScalar();
g_pfElapsedTime_Particle = g_pParticleEffect10->GetVariableByName( "g_fElapsedTime" )->AsScalar();
g_pfVolumeSize_Particle = g_pParticleEffect10->GetVariableByName( "g_fVolumeSize" )->AsScalar();
g_pfEmitterSize_Particle = g_pParticleEffect10->GetVariableByName( "g_fEmitterSize" )->AsScalar();
g_pvVolumeOffsets_Particle = g_pParticleEffect10->GetVariableByName( "g_vVolumeOffsets" )->AsVector();
g_pvFrameGravity_Particle = g_pParticleEffect10->GetVariableByName( "g_vFrameGravity" )->AsVector();
g_pvParticleColor_Particle = g_pParticleEffect10->GetVariableByName( "g_vParticleColor" )->AsVector();
g_pvEmitterPos_Particle = g_pParticleEffect10->GetVariableByName( "g_vEmitterPos" )->AsVector();
g_ptxDiffuse_Particle = g_pParticleEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource();
g_ptxRandom_Particle = g_pParticleEffect10->GetVariableByName( "g_txRandom" )->AsShaderResource();
g_ptxVolume_Particle = g_pParticleEffect10->GetVariableByName( "g_txVolume" )->AsShaderResource();
g_ptxVelocity_Particle = g_pParticleEffect10->GetVariableByName( "g_txVelocity" )->AsShaderResource();
// Obtain the technique handles for meshes fx
g_pRenderScene_Mesh = g_pMeshEffect10->GetTechniqueByName( "RenderScene" );
g_pRenderAnimScene_Mesh = g_pMeshEffect10->GetTechniqueByName( "RenderAnimScene" );
// Obtain the parameter handles for meshes fx
g_pmWorldViewProj_Mesh = g_pMeshEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix();
g_pmViewProj_Mesh = g_pMeshEffect10->GetVariableByName( "g_mViewProj" )->AsMatrix();
g_pmWorld_Mesh = g_pMeshEffect10->GetVariableByName( "g_mWorld" )->AsMatrix();
g_pmBoneWorld_Mesh = g_pMeshEffect10->GetVariableByName( "g_mBoneWorld" )->AsMatrix();
g_pmBonePrev_Mesh = g_pMeshEffect10->GetVariableByName( "g_mBonePrev" )->AsMatrix();
g_pvLightDir_Mesh = g_pMeshEffect10->GetVariableByName( "g_vLightDir" )->AsVector();
g_pvEyePt_Mesh = g_pMeshEffect10->GetVariableByName( "g_vEyePt" )->AsVector();
g_ptxDiffuse_Mesh = g_pMeshEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource();
g_ptxNormal_Mesh = g_pMeshEffect10->GetVariableByName( "g_txNormal" )->AsShaderResource();
g_ptxSpecular_Mesh = g_pMeshEffect10->GetVariableByName( "g_txSpecular" )->AsShaderResource();
g_ptxPaint_Mesh = g_pMeshEffect10->GetVariableByName( "g_txPaint" )->AsShaderResource();
// Obtain the technique handles for volume fx
g_pRenderScene_Vol = g_pVolEffect10->GetTechniqueByName( "RenderScene" );
g_pRenderAnimScene_Vol = g_pVolEffect10->GetTechniqueByName( "RenderAnimScene" );
g_pRenderVelocity_Vol = g_pVolEffect10->GetTechniqueByName( "RenderVelocity" );
g_pRenderAnimVelocity_Vol = g_pVolEffect10->GetTechniqueByName( "RenderAnimVelocity" );
// Obtain the parameter handles for volume fx
g_pmWorldViewProj_Vol = g_pVolEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix();
g_pmViewProj_Vol = g_pVolEffect10->GetVariableByName( "g_mViewProj" )->AsMatrix();
g_pmWorld_Vol = g_pVolEffect10->GetVariableByName( "g_mWorld" )->AsMatrix();
g_pmWorldPrev_Vol = g_pVolEffect10->GetVariableByName( "g_mWorldPrev" )->AsMatrix();
g_pmBoneWorld_Vol = g_pVolEffect10->GetVariableByName( "g_mBoneWorld" )->AsMatrix();
g_pmBonePrev_Vol = g_pVolEffect10->GetVariableByName( "g_mBonePrev" )->AsMatrix();
g_pfElapsedTime_Vol = g_pVolEffect10->GetVariableByName( "g_fElapsedTime" )->AsScalar();
g_pfPlaneStart_Vol = g_pVolEffect10->GetVariableByName( "g_fPlaneStart" )->AsScalar();
g_pfPlaneStep_Vol = g_pVolEffect10->GetVariableByName( "g_fPlaneStep" )->AsScalar();
g_pvFarClipPlane_Vol = g_pVolEffect10->GetVariableByName( "g_vFarClipPlane" )->AsVector();
g_pvNearClipPlane_Vol = g_pVolEffect10->GetVariableByName( "g_vNearClipPlane" )->AsVector();
// Obtain the technique handles for paint fx
g_pRenderToUV_Paint = g_pPaintEffect10->GetTechniqueByName( "RenderToUV" );
g_pRenderAnimToUV_Paint = g_pPaintEffect10->GetTechniqueByName( "RenderAnimToUV" );
g_pPaint_Paint = g_pPaintEffect10->GetTechniqueByName( "Paint" );
// Obtain the parameter handles for paint fx
g_pmWorld_Paint = g_pPaintEffect10->GetVariableByName( "g_mWorld" )->AsMatrix();
g_pmBoneWorld_Paint = g_pPaintEffect10->GetVariableByName( "g_mBoneWorld" )->AsMatrix();
g_pNumParticles_Paint = g_pPaintEffect10->GetVariableByName( "g_NumParticles" )->AsScalar();
g_pParticleStart_Paint = g_pPaintEffect10->GetVariableByName( "g_ParticleStart" )->AsScalar();
g_pParticleStep_Paint = g_pPaintEffect10->GetVariableByName( "g_ParticleStep" )->AsScalar();
g_pfParticleRadiusSq_Paint = g_pPaintEffect10->GetVariableByName( "g_fParticleRadiusSq" )->AsScalar();
g_pvParticleColor_Paint = g_pPaintEffect10->GetVariableByName( "g_vParticleColor" )->AsVector();
g_ptxDiffuse_Paint = g_pPaintEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource();
g_pParticleBuffer_Paint = g_pPaintEffect10->GetVariableByName( "g_ParticleBuffer" )->AsShaderResource();
// Create our vertex input layout for particles
const D3D10_INPUT_ELEMENT_DESC particlelayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "LASTPOSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 32, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "VELOCITY", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 48, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "ID", 0, DXGI_FORMAT_R32_UINT, 0, 60, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
D3D10_PASS_DESC PassDesc;
g_pAdvanceParticles_Particle->GetPassByIndex( 0 )->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( particlelayout, sizeof( particlelayout ) / sizeof( particlelayout[0] ),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pParticleVertexLayout ) );
// Create our vertex input layout for meshes
const D3D10_INPUT_ELEMENT_DESC meshlayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
g_pRenderScene_Mesh->GetPassByIndex( 0 )->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( meshlayout, sizeof( meshlayout ) / sizeof( meshlayout[0] ),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pMeshVertexLayout ) );
const D3D10_INPUT_ELEMENT_DESC skinnedlayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "WEIGHTS", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "BONES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 40, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
g_pRenderAnimScene_Mesh->GetPassByIndex( 0 )->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( skinnedlayout, sizeof( skinnedlayout ) / sizeof( skinnedlayout[0] ),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pAnimVertexLayout ) );
g_pRenderAnimToUV_Paint->GetPassByIndex( 0 )->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( skinnedlayout, sizeof( skinnedlayout ) / sizeof( skinnedlayout[0] ),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pPaintAnimVertexLayout ) );
// Create our vertex input layout for screen quads
const D3D10_INPUT_ELEMENT_DESC quadlayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
g_pPaint_Paint->GetPassByIndex( 0 )->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( quadlayout, sizeof( quadlayout ) / sizeof( quadlayout[0] ),
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &g_pQuadVertexLayout ) );
// Load meshes
V_RETURN( g_WorldMesh[0].Mesh.Create( pd3dDevice, L"advancedparticles\\lizardSIG.sdkmesh" ) );
V_RETURN( g_WorldMesh[0].Mesh.LoadAnimation( L"advancedparticles\\lizardSIG.sdkmesh_anim" ) );
V_RETURN( CreateMeshTexture( pd3dDevice, 256, 256, &g_WorldMesh[0] ) );
D3DXMATRIX mIdentity;
D3DXMatrixIdentity( &mIdentity );
g_WorldMesh[0].Mesh.TransformBindPose( &mIdentity );
V_RETURN( g_WorldMesh[1].Mesh.Create( pd3dDevice, L"advancedparticles\\blocktest.sdkmesh" ) );
V_RETURN( CreateMeshTexture( pd3dDevice, 256, 256, &g_WorldMesh[1] ) );
// Create the seeding particle
V_RETURN( CreateParticleBuffer( pd3dDevice ) );
// Load the Particle Texture
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"misc\\Particle.dds" ) );
V_RETURN( D3DX10CreateShaderResourceViewFromFile( pd3dDevice, str, NULL, NULL, &g_pParticleTexRV, NULL ) );
// Create the random texture that fuels our random vector generator in the effect
V_RETURN( CreateRandomTexture( pd3dDevice ) );
// Create the volume texture and render target views, etc
V_RETURN( CreateVolumeTexture( pd3dDevice ) );
// Create position texture for the mesh
for( UINT i = 0; i < NUM_MESHES; i++ )
V_RETURN( CreatePositionTextures( pd3dDevice, &g_WorldMesh[i] ) );
// Let the app know that this if the first time drawing particles
g_bFirst = true;
V_RETURN( CreateQuadVB( pd3dDevice ) );
// Setup the camera's view parameters
D3DXVECTOR3 vecEye( 0.0f, 0.6f, -5.0f );
D3DXVECTOR3 vecAt ( 0.0f, 0.6f, 0.0f );
g_Camera.SetViewParams( &vecEye, &vecAt );
// Move the block into position
g_WorldMesh[1].vRotation.x = 0;
g_WorldMesh[1].vRotation.y = 0;
g_WorldMesh[1].vRotation.z = -30.0f * ( 180.0f / 3.14159f );
g_WorldMesh[1].vPosition.x = 0.4f;
g_WorldMesh[1].vPosition.y = 0.90f;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D10 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr = S_OK;
V_RETURN( g_DialogResourceManager.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
V_RETURN( g_D3DSettingsDlg.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
// Setup the camera's projection parameters
float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 5000.0f );
g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
g_Camera.SetButtonMasks( 0, MOUSE_WHEEL, MOUSE_LEFT_BUTTON | MOUSE_MIDDLE_BUTTON | MOUSE_RIGHT_BUTTON );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
g_SampleUI.SetSize( 170, 300 );
BOOL bFullscreen = FALSE;
pSwapChain->GetFullscreenState( &bFullscreen, NULL );
g_SampleUI.GetButton( IDC_PARTICLECOLOR )->SetEnabled( !bFullscreen );
return hr;
}
//--------------------------------------------------------------------------------------
bool AdvanceParticles( ID3D10Device* pd3dDevice, float fGlobalTime, float fElapsedTime )
{
// Set the Vertex Layout
pd3dDevice->IASetInputLayout( g_pParticleVertexLayout );
// Set IA parameters
ID3D10Buffer* pBuffers[1];
if( g_bFirst )
pBuffers[0] = g_pParticleStart;
else
pBuffers[0] = g_pParticleDrawFrom;
UINT stride[1] = { sizeof( PARTICLE_VERTEX ) };
UINT offset[1] = { 0 };
pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, stride, offset );
pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_POINTLIST );
// Point to the correct output buffer
pBuffers[0] = g_pParticleStreamTo;
pd3dDevice->SOSetTargets( 1, pBuffers, offset );
D3DXVECTOR4 vColor;
vColor.x = g_vParticleColor.x;
vColor.y = g_vParticleColor.y;
vColor.z = g_vParticleColor.z;
vColor.w = g_fParticleOpacity;
// Set Effects Parameters
g_pfGlobalTime_Particle->SetFloat( fGlobalTime );
g_pfElapsedTime_Particle->SetFloat( fElapsedTime );
g_pvFrameGravity_Particle->SetFloatVector( ( float* )&g_vGravity );
g_pvParticleColor_Particle->SetFloatVector( ( float* )&vColor );
D3DXVECTOR4 vEmitterPos( g_vEmitterPos, 1 );
g_pvEmitterPos_Particle->SetFloatVector( ( float* )&vEmitterPos );
g_ptxRandom_Particle->SetResource( g_pRandomTexRV );
// set volume params
g_ptxVolume_Particle->SetResource( g_pVolumeTexRV );
g_ptxVelocity_Particle->SetResource( g_pVelocityTexRV );
g_pfVolumeSize_Particle->SetFloat( g_VolumeSize );
g_pfEmitterSize_Particle->SetFloat( g_fEmitterSize );
D3DXVECTOR4 vOffsets( 0.5f / g_VolumeWidth, 0.5f / g_VolumeHeight, 0.5f / g_VolumeDepth, 0 );
g_pvVolumeOffsets_Particle->SetFloatVector( ( float* )vOffsets );
// Draw
D3D10_TECHNIQUE_DESC techDesc;
g_pAdvanceParticles_Particle->GetDesc( &techDesc );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
g_pAdvanceParticles_Particle->GetPassByIndex( p )->Apply( 0 );
if( g_bFirst )
pd3dDevice->Draw( MAX_PARTICLES, 0 );
else
pd3dDevice->DrawAuto();
}
// Get back to normal
pBuffers[0] = NULL;
pd3dDevice->SOSetTargets( 1, pBuffers, offset );
// Swap particle buffers
ID3D10Buffer* pTemp = g_pParticleDrawFrom;
g_pParticleDrawFrom = g_pParticleStreamTo;
g_pParticleStreamTo = pTemp;
ID3D10ShaderResourceView* pTempRV = g_pParticleDrawFromRV;
g_pParticleDrawFromRV = g_pParticleStreamToRV;
g_pParticleStreamToRV = pTempRV;
g_bFirst = false;
return true;
}
//--------------------------------------------------------------------------------------
bool RenderParticles( ID3D10Device* pd3dDevice, D3DXMATRIX& mView, D3DXMATRIX& mProj )
{
D3DXMATRIX mWorldView;
D3DXMATRIX mWorldViewProj;
// Set the Vertex Layout
pd3dDevice->IASetInputLayout( g_pParticleVertexLayout );
// Set IA parameters
ID3D10Buffer* pBuffers[1] = { g_pParticleDrawFrom };
UINT stride[1] = { sizeof( PARTICLE_VERTEX ) };
UINT offset[1] = { 0 };
pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, stride, offset );
pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_POINTLIST );
// Set Effects Parameters
D3DXMatrixMultiply( &mWorldViewProj, &mView, &mProj );
g_pmWorldViewProj_Particle->SetMatrix( ( float* )&mWorldViewProj );
g_ptxDiffuse_Particle->SetResource( g_pParticleTexRV );
D3DXMATRIX mInvView;
D3DXMatrixInverse( &mInvView, NULL, &mView );
g_pmInvView_Particle->SetMatrix( ( float* )&mInvView );
// set volume params
g_ptxVolume_Particle->SetResource( g_pVolumeTexRV );
g_ptxVelocity_Particle->SetResource( g_pVelocityTexRV );
g_pfVolumeSize_Particle->SetFloat( g_VolumeSize );
D3DXVECTOR4 vOffsets( 0.5f / g_VolumeWidth, 0.5f / g_VolumeHeight, 0.5f / g_VolumeDepth, 0 );
g_pvVolumeOffsets_Particle->SetFloatVector( ( float* )vOffsets );
// Draw
D3D10_TECHNIQUE_DESC techDesc;
g_pRenderParticles_Particle->GetDesc( &techDesc );
for( UINT p = 0; p < techDesc.Passes; ++p )
{
g_pRenderParticles_Particle->GetPassByIndex( p )->Apply( 0 );
pd3dDevice->DrawAuto();
}
return true;
}
//--------------------------------------------------------------------------------------
bool RenderAnimatedMeshes( ID3D10Device* pd3dDevice,
D3DXMATRIX& mView,
D3DXMATRIX& mProj,
ID3D10EffectTechnique* pTechnique,
double fTime,
float fElapsedTime,
bool bVolume )
{
// Set the Vertex Layout
pd3dDevice->IASetInputLayout( g_pAnimVertexLayout );
for( UINT i = 0; i < 1; i++ )
{
D3DXMATRIX mWorldViewProj;
D3DXMATRIX mViewProj;
mWorldViewProj = g_WorldMesh[i].mWorld * mView * mProj;
mViewProj = mView * mProj;
CDXUTSDKMesh* pMesh = &g_WorldMesh[i].Mesh;
// Set Effects Parameters
if( bVolume )
{
g_pmWorldViewProj_Vol->SetMatrix( ( float* )&mWorldViewProj );
g_pmViewProj_Vol->SetMatrix( ( float* )&mViewProj );
g_pmWorld_Vol->SetMatrix( ( float* )&g_WorldMesh[i].mWorld );
g_pmWorldPrev_Vol->SetMatrix( ( float* )&g_WorldMesh[i].mWorldPrev );
UINT NumInfluences = pMesh->GetNumInfluences( 0 );
if( NumInfluences > 0 )
{
// Transform current position
pMesh->TransformMesh( &g_WorldMesh[i].mWorld, fTime );
for( UINT g = 0; g < NumInfluences; g++ )
{
const D3DXMATRIX* pMat = pMesh->GetMeshInfluenceMatrix( 0, g );
g_pmBoneWorld_Vol->SetMatrixArray( ( float* )pMat, g, 1 );
}
// Transform previous position
pMesh->TransformMesh( &g_WorldMesh[i].mWorldPrev, fTime - fElapsedTime );
for( UINT g = 0; g < NumInfluences; g++ )
{
const D3DXMATRIX* pMat = pMesh->GetMeshInfluenceMatrix( 0, g );
g_pmBonePrev_Vol->SetMatrixArray( ( float* )pMat, g, 1 );
}
}
ID3D10Buffer* pBuffer = pMesh->GetVB10( 0, 0 );
UINT iStride = pMesh->GetVertexStride( 0, 0 );
UINT iOffset = 0;
pd3dDevice->IASetVertexBuffers( 0, 1, &pBuffer, &iStride, &iOffset );
pd3dDevice->IASetIndexBuffer( pMesh->GetIB10( 0 ), pMesh->GetIBFormat10( 0 ), iOffset );
D3D10_TECHNIQUE_DESC techDesc;
pTechnique->GetDesc( &techDesc );
SDKMESH_SUBSET* pSubset = NULL;
D3D10_PRIMITIVE_TOPOLOGY PrimType;
for( UINT p = 0; p < techDesc.Passes; ++p )
{
for( UINT subset = 0; subset < pMesh->GetNumSubsets( 0 ); subset++ )
{
pSubset = pMesh->GetSubset( 0, subset );
PrimType = pMesh->GetPrimitiveType10( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
pd3dDevice->IASetPrimitiveTopology( PrimType );
pTechnique->GetPassByIndex( p )->Apply( 0 );
UINT IndexCount = ( UINT )pSubset->IndexCount;
UINT IndexStart = ( UINT )pSubset->IndexStart;
UINT VertexStart = ( UINT )pSubset->VertexStart;
pd3dDevice->DrawIndexedInstanced( IndexCount, g_VolumeDepth, IndexStart, VertexStart, 0 );
}
}
}
else
{
g_pmWorldViewProj_Mesh->SetMatrix( ( float* )&mWorldViewProj );
g_pmViewProj_Mesh->SetMatrix( ( float* )&mViewProj );
g_pmWorld_Mesh->SetMatrix( ( float* )&g_WorldMesh[i].mWorld );
D3DXVECTOR4 vLightDir( 0,1,0,0 );
g_pvLightDir_Mesh->SetFloatVector( ( float* )&vLightDir );
D3DXVECTOR4 vEye = D3DXVECTOR4( *g_Camera.GetEyePt(), 1 );
g_pvEyePt_Mesh->SetFloatVector( ( float* )&vEye );
UINT NumInfluences = pMesh->GetNumInfluences( 0 );
if( NumInfluences > 0 )
{
// Transform current position
pMesh->TransformMesh( &g_WorldMesh[i].mWorld, fTime );
for( UINT g = 0; g < NumInfluences; g++ )
{
const D3DXMATRIX* pMat = pMesh->GetMeshInfluenceMatrix( 0, g );
g_pmBoneWorld_Mesh->SetMatrixArray( ( float* )pMat, g, 1 );
}
// Transform previous position
pMesh->TransformMesh( &g_WorldMesh[i].mWorldPrev, fTime - fElapsedTime );
for( UINT g = 0; g < NumInfluences; g++ )
{
const D3DXMATRIX* pMat = pMesh->GetMeshInfluenceMatrix( 0, g );
g_pmBonePrev_Mesh->SetMatrixArray( ( float* )pMat, g, 1 );
}
}
g_ptxPaint_Mesh->SetResource( g_WorldMesh[i].pMeshRV );
pMesh->Render( pd3dDevice, pTechnique, g_ptxDiffuse_Mesh, g_ptxNormal_Mesh, g_ptxSpecular_Mesh );
}
}
return true;
}
//--------------------------------------------------------------------------------------
bool RenderMeshes( ID3D10Device* pd3dDevice,
D3DXMATRIX& mView,
D3DXMATRIX& mProj,
ID3D10EffectTechnique* pTechnique,
bool bVolume )
{
// Set the Vertex Layout
pd3dDevice->IASetInputLayout( g_pMeshVertexLayout );
for( UINT i = 1; i < NUM_MESHES; i++ )
{
D3DXMATRIX mWorldViewProj;
D3DXMATRIX mViewProj;
mWorldViewProj = g_WorldMesh[i].mWorld * mView * mProj;
mViewProj = mView * mProj;
CDXUTSDKMesh* pMesh = &g_WorldMesh[i].Mesh;
// Set Effects Parameters
if( bVolume )
{
g_pmWorldViewProj_Vol->SetMatrix( ( float* )&mWorldViewProj );
g_pmViewProj_Vol->SetMatrix( ( float* )&mViewProj );
g_pmWorld_Vol->SetMatrix( ( float* )&g_WorldMesh[i].mWorld );
g_pmWorldPrev_Vol->SetMatrix( ( float* )&g_WorldMesh[i].mWorldPrev );
ID3D10Buffer* pBuffer = pMesh->GetVB10( 0, 0 );
UINT iStride = pMesh->GetVertexStride( 0, 0 );
UINT iOffset = 0;
pd3dDevice->IASetVertexBuffers( 0, 1, &pBuffer, &iStride, &iOffset );
pd3dDevice->IASetIndexBuffer( pMesh->GetIB10( 0 ), pMesh->GetIBFormat10( 0 ), iOffset );
D3D10_TECHNIQUE_DESC techDesc;
pTechnique->GetDesc( &techDesc );
SDKMESH_SUBSET* pSubset = NULL;
D3D10_PRIMITIVE_TOPOLOGY PrimType;
for( UINT p = 0; p < techDesc.Passes; ++p )
{
for( UINT subset = 0; subset < pMesh->GetNumSubsets( 0 ); subset++ )
{
pSubset = pMesh->GetSubset( 0, subset );
PrimType = pMesh->GetPrimitiveType10( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
pd3dDevice->IASetPrimitiveTopology( PrimType );
pTechnique->GetPassByIndex( p )->Apply( 0 );
UINT IndexCount = ( UINT )pSubset->IndexCount;
UINT IndexStart = ( UINT )pSubset->IndexStart;
UINT VertexStart = ( UINT )pSubset->VertexStart;
pd3dDevice->DrawIndexedInstanced( IndexCount, g_VolumeDepth, IndexStart, VertexStart, 0 );
}
}
//pMesh->Render( pd3dDevice, pTechnique );
}
else
{
g_pmWorldViewProj_Mesh->SetMatrix( ( float* )&mWorldViewProj );
g_pmViewProj_Mesh->SetMatrix( ( float* )&mViewProj );
g_pmWorld_Mesh->SetMatrix( ( float* )&g_WorldMesh[i].mWorld );
D3DXVECTOR4 vLightDir( 0,1,0,0 );
g_pvLightDir_Mesh->SetFloatVector( ( float* )&vLightDir );
g_ptxDiffuse_Mesh->SetResource( g_WorldMesh[i].pMeshRV );
pMesh->Render( pd3dDevice, pTechnique, NULL, g_ptxNormal_Mesh, g_ptxSpecular_Mesh );
}
}
return true;
}
//--------------------------------------------------------------------------------------
void ClearVolume( ID3D10Device* pd3dDevice )
{
// clear the render target
float ClearColor[4] = { 0.0f,0.0f,0.0f,0.0f };
pd3dDevice->ClearRenderTargetView( g_pVolumeTexTotalRTV, ClearColor );
pd3dDevice->ClearRenderTargetView( g_pVelocityTexTotalRTV, ClearColor );
}
//--------------------------------------------------------------------------------------
bool RenderMeshesIntoVolume( ID3D10Device* pd3dDevice, ID3D10EffectTechnique* pTechnique, double fTime,
float fElapsedTime, bool bAnimated )
{
// store the old render target and DS
ID3D10RenderTargetView* pOldRTV;
ID3D10DepthStencilView* pOldDSV;
pd3dDevice->OMGetRenderTargets( 1, &pOldRTV, &pOldDSV );
// store the old viewport
D3D10_VIEWPORT oldViewport;
UINT NumViewports = 1;
pd3dDevice->RSGetViewports( &NumViewports, &oldViewport );
// set the new viewport
D3D10_VIEWPORT newViewport;
newViewport.TopLeftX = 0;
newViewport.TopLeftY = 0;
newViewport.Width = g_VolumeWidth;
newViewport.Height = g_VolumeHeight;
newViewport.MinDepth = 0.0f;
newViewport.MaxDepth = 1.0f;
pd3dDevice->RSSetViewports( 1, &newViewport );
// setup and orthogonal view from the top
D3DXMATRIX mView;
D3DXMATRIX mProj;
D3DXVECTOR3 vEye( 0,100,0 );
D3DXVECTOR3 vAt( 0,0,0 );
D3DXVECTOR3 vUp( 0,0,1 );
D3DXMatrixLookAtLH( &mView, &vEye, &vAt, &vUp );
D3DXMatrixOrthoLH( &mProj, g_VolumeSize, g_VolumeSize, 0.1f, 1000.0f );
float fSliceSize = g_VolumeSize / ( float )( g_VolumeDepth + 1 );
float fSliceStart = 0.0f;
// Set the render target
pd3dDevice->OMSetRenderTargets( 1, &g_pVolumeTexTotalRTV, NULL );
// Set effect variables
g_pfPlaneStart_Vol->SetFloat( fSliceStart );
g_pfPlaneStep_Vol->SetFloat( fSliceSize );
g_pfElapsedTime_Vol->SetFloat( fElapsedTime );
// render the scene
if( bAnimated )
RenderAnimatedMeshes( pd3dDevice, mView, mProj, pTechnique, fTime, fElapsedTime, true );
else
RenderMeshes( pd3dDevice, mView, mProj, pTechnique, true );
// restore the old viewport
pd3dDevice->RSSetViewports( 1, &oldViewport );
// restore old render target and DS
pd3dDevice->OMSetRenderTargets( 1, &pOldRTV, pOldDSV );
SAFE_RELEASE( pOldRTV );
SAFE_RELEASE( pOldDSV );
return true;
}
//--------------------------------------------------------------------------------------
bool RenderVelocitiesIntoVolume( ID3D10Device* pd3dDevice, ID3D10EffectTechnique* pTechnique, double fTime,
float fElapsedTime, bool bAnimated )
{
// store the old render target and DS
ID3D10RenderTargetView* pOldRTV;
ID3D10DepthStencilView* pOldDSV;
pd3dDevice->OMGetRenderTargets( 1, &pOldRTV, &pOldDSV );
// store the old viewport
D3D10_VIEWPORT oldViewport;
UINT NumViewports = 1;
pd3dDevice->RSGetViewports( &NumViewports, &oldViewport );
// set the new viewport
D3D10_VIEWPORT newViewport;
newViewport.TopLeftX = 0;
newViewport.TopLeftY = 0;
newViewport.Width = g_VolumeWidth;
newViewport.Height = g_VolumeHeight;
newViewport.MinDepth = 0.0f;
newViewport.MaxDepth = 1.0f;
pd3dDevice->RSSetViewports( 1, &newViewport );
// setup and orthogonal view from the top
D3DXMATRIX mView;
D3DXMATRIX mProj;
D3DXVECTOR3 vEye( 0,100,0 );
D3DXVECTOR3 vAt( 0,0,0 );
D3DXVECTOR3 vUp( 0,0,1 );
D3DXMatrixLookAtLH( &mView, &vEye, &vAt, &vUp );
D3DXMatrixOrthoLH( &mProj, g_VolumeSize, g_VolumeSize, 0.1f, 1000.0f );
float fSliceSize = g_VolumeSize / ( float )( g_VolumeDepth + 1 );
float fSliceStart = 0.0f;
// Set the render target
pd3dDevice->OMSetRenderTargets( 1, &g_pVelocityTexTotalRTV, NULL );
// Calc clip planes
D3DXVECTOR4 vFarClip( 0,1,0,0 );
D3DXVECTOR4 vNearClip( 0,-1,0,0 );
vFarClip.w = -fSliceStart;
vNearClip.w = ( fSliceStart + fSliceSize );
// Set effect variables
g_pfPlaneStart_Vol->SetFloat( 0.0f );
g_pfPlaneStep_Vol->SetFloat( fSliceSize );
g_pfElapsedTime_Vol->SetFloat( fElapsedTime );
// render the scene
if( bAnimated )
RenderAnimatedMeshes( pd3dDevice, mView, mProj, pTechnique, fTime, fElapsedTime, true );
else
RenderMeshes( pd3dDevice, mView, mProj, pTechnique, true );
// restore the old viewport
pd3dDevice->RSSetViewports( 1, &oldViewport );
// restore old render target and DS
pd3dDevice->OMSetRenderTargets( 1, &pOldRTV, pOldDSV );
SAFE_RELEASE( pOldRTV );
SAFE_RELEASE( pOldDSV );
return true;
}
//--------------------------------------------------------------------------------------
bool RenderPositionIntoTexture( ID3D10Device* pd3dDevice, MESH* pMesh, double fTime )
{
// store the old render target and DS
ID3D10RenderTargetView* pOldRTV;
ID3D10DepthStencilView* pOldDSV;
pd3dDevice->OMGetRenderTargets( 1, &pOldRTV, &pOldDSV );
// store the old viewport
D3D10_VIEWPORT oldViewport;
UINT NumViewports = 1;
pd3dDevice->RSGetViewports( &NumViewports, &oldViewport );
// set the new viewport
D3D10_VIEWPORT newViewport;
newViewport.TopLeftX = 0;
newViewport.TopLeftY = 0;
newViewport.Width = g_PositionWidth;
newViewport.Height = g_PositionHeight;
newViewport.MinDepth = 0.0f;
newViewport.MaxDepth = 1.0f;
pd3dDevice->RSSetViewports( 1, &newViewport );
float ClearColor[4] = { 0,0,0,0 };
pd3dDevice->ClearRenderTargetView( pMesh->pMeshPositionRTV, ClearColor );
// Set the render target
pd3dDevice->OMSetRenderTargets( 1, &pMesh->pMeshPositionRTV, NULL );
// Set effect variables
g_pmWorld_Paint->SetMatrix( ( float* )&pMesh->mWorld );
ID3D10EffectTechnique* pTech = NULL;
UINT NumInfluences = pMesh->Mesh.GetNumInfluences( 0 );
if( NumInfluences > 0 )
{
pd3dDevice->IASetInputLayout( g_pPaintAnimVertexLayout );
pTech = g_pRenderAnimToUV_Paint;
// Transform current position
pMesh->Mesh.TransformMesh( &pMesh->mWorld, fTime );
for( UINT g = 0; g < NumInfluences; g++ )
{
const D3DXMATRIX* pMat = pMesh->Mesh.GetMeshInfluenceMatrix( 0, g );
g_pmBoneWorld_Paint->SetMatrixArray( ( float* )pMat, g, 1 );
}
}
else
{
pd3dDevice->IASetInputLayout( g_pMeshVertexLayout );
pTech = g_pRenderToUV_Paint;
}
// render the mesh
pMesh->Mesh.Render( pd3dDevice, pTech );
// restore the old viewport
pd3dDevice->RSSetViewports( 1, &oldViewport );
// restore old render target and DS
pd3dDevice->OMSetRenderTargets( 1, &pOldRTV, pOldDSV );
SAFE_RELEASE( pOldRTV );
SAFE_RELEASE( pOldDSV );
return true;
}
bool PaintWithParticles( ID3D10Device* pd3dDevice, MESH* pMesh )
{
// store the old render target and DS
ID3D10RenderTargetView* pOldRTV;
ID3D10DepthStencilView* pOldDSV;
pd3dDevice->OMGetRenderTargets( 1, &pOldRTV, &pOldDSV );
// store the old viewport
D3D10_VIEWPORT oldViewport;
UINT NumViewports = 1;
pd3dDevice->RSGetViewports( &NumViewports, &oldViewport );
// set the new viewport
D3D10_VIEWPORT newViewport;
newViewport.TopLeftX = 0;
newViewport.TopLeftY = 0;
newViewport.Width = pMesh->MeshTextureWidth;
newViewport.Height = pMesh->MeshTextureHeight;
newViewport.MinDepth = 0.0f;
newViewport.MaxDepth = 1.0f;
pd3dDevice->RSSetViewports( 1, &newViewport );
// Set the render target
pd3dDevice->OMSetRenderTargets( 1, &pMesh->pMeshRTV, NULL );
// Set effect variables
g_pNumParticles_Paint->SetInt( MAX_PARTICLES );
g_pParticleStart_Paint->SetInt( g_iParticleStart );
g_pParticleStep_Paint->SetInt( g_iParticleStep );
g_pfParticleRadiusSq_Paint->SetFloat( g_fParticlePaintRadSq );
D3DXVECTOR4 vParticleColor( 0,1,0,1 );
g_pvParticleColor_Paint->SetFloatVector( ( float* )&vParticleColor );
g_ptxDiffuse_Paint->SetResource( pMesh->pMeshPositionRV );
g_pParticleBuffer_Paint->SetResource( g_pParticleDrawFromRV );
// Set the Vertex Layout
pd3dDevice->IASetInputLayout( g_pQuadVertexLayout );
// Set IA params
UINT offsets = 0;
UINT strides = sizeof( QUAD_VERTEX );
pd3dDevice->IASetVertexBuffers( 0, 1, &g_pQuadVB, &strides, &offsets );
pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );
// set the technique
D3D10_TECHNIQUE_DESC techDesc;
g_pPaint_Paint->GetDesc( &techDesc );
// render the quad
for( UINT p = 0; p < techDesc.Passes; p++ )
{
g_pPaint_Paint->GetPassByIndex( p )->Apply( 0 );
pd3dDevice->Draw( 4, 0 );
}
// restore the old viewport
pd3dDevice->RSSetViewports( 1, &oldViewport );
// restore old render target and DS
pd3dDevice->OMSetRenderTargets( 1, &pOldRTV, pOldDSV );
SAFE_RELEASE( pOldRTV );
SAFE_RELEASE( pOldDSV );
return true;
}
//--------------------------------------------------------------------------------------
void ClearShaderResources( ID3D10Device* pd3dDevice )
{
// unbind resources
ID3D10ShaderResourceView* pNULLViews[8] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};
pd3dDevice->VSSetShaderResources( 0, 8, pNULLViews );
pd3dDevice->GSSetShaderResources( 0, 8, pNULLViews );
pd3dDevice->PSSetShaderResources( 0, 8, pNULLViews );
}
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
float ClearColor[4] = { 0.0, 0.0, 0.0, 0.0 };
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.OnRender( fElapsedTime );
return;
}
// calc world matrix for dynamic object
D3DXMATRIX mScale;
D3DXMATRIX mRotX, mRotY, mRotZ;
D3DXMATRIX mTrans;
for( UINT i = 0; i < NUM_MESHES; i++ )
{
D3DXMatrixScaling( &mScale, 0.2f, 0.2f, 0.2f );
D3DXMatrixRotationX( &mRotX, g_WorldMesh[i].vRotation.x );
D3DXMatrixRotationY( &mRotY, g_WorldMesh[i].vRotation.y );
D3DXMatrixRotationZ( &mRotZ, g_WorldMesh[i].vRotation.z );
D3DXMatrixTranslation( &mTrans, g_WorldMesh[i].vPosition.x, g_WorldMesh[i].vPosition.y,
g_WorldMesh[i].vPosition.z );
g_WorldMesh[i].mWorld = mScale * mRotX * mRotY * mRotZ * mTrans;
}
ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
pd3dDevice->ClearRenderTargetView( pRTV, ClearColor );
ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 );
// Rendet the mesh position into a texture
if( g_bPaint )
{
for( UINT i = 0; i < NUM_MESHES; i++ )
{
RenderPositionIntoTexture( pd3dDevice, &g_WorldMesh[i], fTime );
}
}
// Clear the volume
ClearVolume( pd3dDevice );
// Render meshes into the volume
RenderMeshesIntoVolume( pd3dDevice, g_pRenderScene_Vol, fTime, fElapsedTime, false );
RenderVelocitiesIntoVolume( pd3dDevice, g_pRenderVelocity_Vol, fTime, fElapsedTime, false );
// Render animated meshes into the volume
RenderMeshesIntoVolume( pd3dDevice, g_pRenderAnimScene_Vol, fTime, fElapsedTime, true );
RenderVelocitiesIntoVolume( pd3dDevice, g_pRenderAnimVelocity_Vol, fTime, fElapsedTime, true );
// Advance the Particles
AdvanceParticles( pd3dDevice, ( float )fTime, fElapsedTime );
D3DXMATRIX mView;
D3DXMATRIX mProj;
// Get the projection & view matrix from the camera class
mProj = *g_Camera.GetProjMatrix();
mView = *g_Camera.GetViewMatrix();
// Render scene meshes
RenderMeshes( pd3dDevice, mView, mProj, g_pRenderScene_Mesh, false );
RenderAnimatedMeshes( pd3dDevice, mView, mProj, g_pRenderAnimScene_Mesh, fTime, fElapsedTime, false );
ClearShaderResources( pd3dDevice );
// Render the particles
RenderParticles( pd3dDevice, mView, mProj );
if( g_bPaint )
{
// Paint the scene meshes with the particles
for( UINT i = 0; i < NUM_MESHES; i++ )
PaintWithParticles( pd3dDevice, &g_WorldMesh[i] );
// step up
g_iParticleStart ++;
if( g_iParticleStart >= g_iParticleStep )
g_iParticleStart = 0;
}
ClearShaderResources( pd3dDevice );
DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
RenderText();
g_HUD.OnRender( fElapsedTime );
g_SampleUI.OnRender( fElapsedTime );
DXUT_EndPerfEvent();
// store the previous world
for( UINT i = 0; i < NUM_MESHES; i++ )
g_WorldMesh[i].mWorldPrev = g_WorldMesh[i].mWorld;
}
//--------------------------------------------------------------------------------------
// Render the help and statistics text
//--------------------------------------------------------------------------------------
void RenderText()
{
g_pTxtHelper->Begin();
g_pTxtHelper->SetInsertionPos( 2, 0 );
g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( true ) );
g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 0.5f, 0.0f, 1.0f ) );
g_pTxtHelper->DrawTextLine( L"Use A,D,W,S,Q,E keys to move the active mesh" );
g_pTxtHelper->DrawTextLine( L"Use SHIFT + A,D,W,S,Q,E keys to rotate the active mesh" );
g_pTxtHelper->End();
}
//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnD3D10ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext )
{
g_DialogResourceManager.OnD3D10ReleasingSwapChain();
}
//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnD3D10CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D10DestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D10DestroyDevice();
g_D3DSettingsDlg.OnD3D10DestroyDevice();
DXUTGetGlobalResourceCache().OnDestroyDevice();
SAFE_RELEASE( g_pFont10 );
SAFE_RELEASE( g_pSprite10 );
SAFE_DELETE( g_pTxtHelper );
SAFE_RELEASE( g_pParticleEffect10 );
SAFE_RELEASE( g_pMeshEffect10 );
SAFE_RELEASE( g_pVolEffect10 );
SAFE_RELEASE( g_pPaintEffect10 );
SAFE_RELEASE( g_pQuadVB );
SAFE_RELEASE( g_pParticleVertexLayout );
SAFE_RELEASE( g_pMeshVertexLayout );
SAFE_RELEASE( g_pQuadVertexLayout );
SAFE_RELEASE( g_pAnimVertexLayout );
SAFE_RELEASE( g_pPaintAnimVertexLayout );
for( UINT i = 0; i < NUM_MESHES; i++ )
{
SAFE_RELEASE( g_WorldMesh[i].pMeshPositionTexture );
SAFE_RELEASE( g_WorldMesh[i].pMeshPositionRV );
SAFE_RELEASE( g_WorldMesh[i].pMeshPositionRTV );
SAFE_RELEASE( g_WorldMesh[i].pMeshTexture );
SAFE_RELEASE( g_WorldMesh[i].pMeshRV );
SAFE_RELEASE( g_WorldMesh[i].pMeshRTV );
g_WorldMesh[i].Mesh.Destroy();
}
// particles
SAFE_RELEASE( g_pParticleStart );
SAFE_RELEASE( g_pParticleStreamTo );
SAFE_RELEASE( g_pParticleDrawFrom );
SAFE_RELEASE( g_pParticleStreamToRV );
SAFE_RELEASE( g_pParticleDrawFromRV );
SAFE_RELEASE( g_pParticleTexRV );
SAFE_RELEASE( g_pRandomTexture );
SAFE_RELEASE( g_pRandomTexRV );
// volume
if( g_pVolumeTexRTVs )
{
for( UINT i = 0; i < g_VolumeDepth; i++ )
{
SAFE_RELEASE( g_pVolumeTexRTVs[i] );
}
SAFE_DELETE_ARRAY( g_pVolumeTexRTVs );
}
SAFE_RELEASE( g_pVolumeTexRV );
SAFE_RELEASE( g_pVolumeTexture );
SAFE_RELEASE( g_pVolumeTexTotalRTV );
if( g_pVelocityTexRTVs )
{
for( UINT i = 0; i < g_VolumeDepth; i++ )
{
SAFE_RELEASE( g_pVelocityTexRTVs[i] );
}
SAFE_DELETE_ARRAY( g_pVelocityTexRTVs );
}
SAFE_RELEASE( g_pVelocityTexRV );
SAFE_RELEASE( g_pVelocityTexture );
SAFE_RELEASE( g_pVelocityTexTotalRTV );
}
//--------------------------------------------------------------------------------------
// This helper function creates 3 vertex buffers. The first is used to seed the
// particle system. The second two are used as output and intput buffers alternatively
// for the GS particle system. Since a buffer cannot be both an input to the GS and an
// output of the GS, we must ping-pong between the two.
//--------------------------------------------------------------------------------------
HRESULT CreateParticleBuffer( ID3D10Device* pd3dDevice )
{
HRESULT hr = S_OK;
D3D10_BUFFER_DESC vbdesc =
{
MAX_PARTICLES * sizeof( PARTICLE_VERTEX ),
D3D10_USAGE_DEFAULT,
D3D10_BIND_VERTEX_BUFFER,
0,
0
};
D3D10_SUBRESOURCE_DATA vbInitData;
ZeroMemory( &vbInitData, sizeof( D3D10_SUBRESOURCE_DATA ) );
srand( 100 );
PARTICLE_VERTEX* pVertices = new PARTICLE_VERTEX[ MAX_PARTICLES ];
for( UINT i = 0; i < MAX_PARTICLES; i++ )
{
pVertices[i].pos.x = g_vEmitterPos.x + RPercent() * g_fEmitterSize;
pVertices[i].pos.y = g_vEmitterPos.y + RPercent() * g_fEmitterSize;
pVertices[i].pos.z = g_vEmitterPos.z + RPercent() * g_fEmitterSize;
pVertices[i].pos.w = 1.0f;
pVertices[i].lastpos = pVertices[i].pos;
pVertices[i].color = D3DXVECTOR4( 1, 0, 0, 1 );
pVertices[i].vel = D3DXVECTOR3( 0, 0, 0 );
pVertices[i].ID = i;
}
vbInitData.pSysMem = pVertices;
V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &vbInitData, &g_pParticleStart ) );
SAFE_DELETE_ARRAY( vbInitData.pSysMem );
vbdesc.ByteWidth = MAX_PARTICLES * sizeof( PARTICLE_VERTEX );
vbdesc.BindFlags |= D3D10_BIND_STREAM_OUTPUT | D3D10_BIND_SHADER_RESOURCE;
V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleDrawFrom ) );
V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleStreamTo ) );
// create resource views
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
SRVDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_BUFFER;
SRVDesc.Buffer.ElementOffset = 0;
SRVDesc.Buffer.ElementWidth = MAX_PARTICLES * ( sizeof( PARTICLE_VERTEX ) / sizeof( D3DXVECTOR4 ) );
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pParticleStreamTo, &SRVDesc, &g_pParticleDrawFromRV ) );
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pParticleDrawFrom, &SRVDesc, &g_pParticleStreamToRV ) );
return hr;
}
//--------------------------------------------------------------------------------------
// This helper function creates a 1D texture full of random vectors. The shader uses
// the current time value to index into this texture to get a random vector.
//--------------------------------------------------------------------------------------
HRESULT CreateRandomTexture( ID3D10Device* pd3dDevice )
{
HRESULT hr = S_OK;
int iNumRandValues = 4096;
srand( timeGetTime() );
//create the data
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = new float[iNumRandValues * 4];
if( !InitData.pSysMem )
return E_OUTOFMEMORY;
InitData.SysMemPitch = iNumRandValues * 4 * sizeof( float );
InitData.SysMemSlicePitch = iNumRandValues * 4 * sizeof( float );
for( int i = 0; i < iNumRandValues * 4; i++ )
{
( ( float* )InitData.pSysMem )[i] = float( ( rand() % 10000 ) - 5000 );
}
// Create the texture
D3D10_TEXTURE1D_DESC dstex;
dstex.Width = iNumRandValues;
dstex.MipLevels = 1;
dstex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
dstex.Usage = D3D10_USAGE_DEFAULT;
dstex.BindFlags = D3D10_BIND_SHADER_RESOURCE;
dstex.CPUAccessFlags = 0;
dstex.MiscFlags = 0;
dstex.ArraySize = 1;
V_RETURN( pd3dDevice->CreateTexture1D( &dstex, &InitData, &g_pRandomTexture ) );
SAFE_DELETE_ARRAY( InitData.pSysMem );
// Create the resource view
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = dstex.Format;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE1D;
SRVDesc.Texture2D.MipLevels = dstex.MipLevels;
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pRandomTexture, &SRVDesc, &g_pRandomTexRV ) );
return hr;
}
HRESULT CreateVolumeTexture( ID3D10Device* pd3dDevice )
{
HRESULT hr = S_OK;
// Create the texture
D3D10_TEXTURE3D_DESC dstex;
dstex.Width = g_VolumeWidth;
dstex.Height = g_VolumeHeight;
dstex.Depth = g_VolumeDepth;
dstex.MipLevels = 1;
dstex.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
dstex.Usage = D3D10_USAGE_DEFAULT;
dstex.BindFlags = D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET;
dstex.CPUAccessFlags = 0;
dstex.MiscFlags = 0;
V_RETURN( pd3dDevice->CreateTexture3D( &dstex, NULL, &g_pVolumeTexture ) );
V_RETURN( pd3dDevice->CreateTexture3D( &dstex, NULL, &g_pVelocityTexture ) );
// Create the resource view
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = dstex.Format;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE3D;
SRVDesc.Texture3D.MostDetailedMip = 0;
SRVDesc.Texture3D.MipLevels = 1;
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pVolumeTexture, &SRVDesc, &g_pVolumeTexRV ) );
V_RETURN( pd3dDevice->CreateShaderResourceView( g_pVelocityTexture, &SRVDesc, &g_pVelocityTexRV ) );
// Create the render target views
D3D10_RENDER_TARGET_VIEW_DESC RTVDesc;
RTVDesc.Format = dstex.Format;
RTVDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE3D;
RTVDesc.Texture3D.MipSlice = 0;
RTVDesc.Texture3D.FirstWSlice = 0;
RTVDesc.Texture3D.WSize = 1;
g_pVolumeTexRTVs = new ID3D10RenderTargetView*[g_VolumeDepth];
g_pVelocityTexRTVs = new ID3D10RenderTargetView*[g_VolumeDepth];
for( UINT i = 0; i < g_VolumeDepth; i++ )
{
RTVDesc.Texture3D.FirstWSlice = i;
V_RETURN( pd3dDevice->CreateRenderTargetView( g_pVolumeTexture, &RTVDesc, &g_pVolumeTexRTVs[i] ) );
V_RETURN( pd3dDevice->CreateRenderTargetView( g_pVelocityTexture, &RTVDesc, &g_pVelocityTexRTVs[i] ) );
}
RTVDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE3D;
RTVDesc.Texture3D.MipSlice = 0;
RTVDesc.Texture3D.FirstWSlice = 0;
RTVDesc.Texture3D.WSize = g_VolumeDepth;
V_RETURN( pd3dDevice->CreateRenderTargetView( g_pVolumeTexture, &RTVDesc, &g_pVolumeTexTotalRTV ) );
V_RETURN( pd3dDevice->CreateRenderTargetView( g_pVelocityTexture, &RTVDesc, &g_pVelocityTexTotalRTV ) );
return hr;
}
HRESULT CreatePositionTextures( ID3D10Device* pd3dDevice, MESH* pMesh )
{
HRESULT hr = S_OK;
// Create the texture
D3D10_TEXTURE2D_DESC dstex;
dstex.Width = g_PositionWidth;
dstex.Height = g_PositionHeight;
dstex.MipLevels = 1;
dstex.ArraySize = 1;
dstex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
dstex.SampleDesc.Count = 1;
dstex.SampleDesc.Quality = 0;
dstex.Usage = D3D10_USAGE_DEFAULT;
dstex.BindFlags = D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET;
dstex.CPUAccessFlags = 0;
dstex.MiscFlags = 0;
V_RETURN( pd3dDevice->CreateTexture2D( &dstex, NULL, &pMesh->pMeshPositionTexture ) );
// Create the resource view
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = dstex.Format;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MostDetailedMip = 0;
SRVDesc.Texture2D.MipLevels = 1;
V_RETURN( pd3dDevice->CreateShaderResourceView( pMesh->pMeshPositionTexture, &SRVDesc, &pMesh->pMeshPositionRV ) );
// Create the render target view
D3D10_RENDER_TARGET_VIEW_DESC RTVDesc;
RTVDesc.Format = dstex.Format;
RTVDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
RTVDesc.Texture2D.MipSlice = 0;
V_RETURN( pd3dDevice->CreateRenderTargetView( pMesh->pMeshPositionTexture, &RTVDesc, &pMesh->pMeshPositionRTV ) );
return hr;
}
HRESULT CreateMeshTexture( ID3D10Device* pd3dDevice, UINT width, UINT height, MESH* pMesh )
{
HRESULT hr = S_OK;
D3D10_TEXTURE2D_DESC dstex;
pMesh->MeshTextureWidth = width;
pMesh->MeshTextureHeight = height;
// Create the texture
dstex.Width = width;
dstex.Height = height;
dstex.ArraySize = 1;
dstex.MipLevels = 1;
dstex.CPUAccessFlags = 0;
dstex.MiscFlags = 0;
dstex.SampleDesc.Count = 1;
dstex.SampleDesc.Quality = 0;
dstex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
dstex.Usage = D3D10_USAGE_DEFAULT;
dstex.BindFlags = D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET;
V_RETURN( pd3dDevice->CreateTexture2D( &dstex, NULL, &pMesh->pMeshTexture ) );
// Create the resource view
D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc;
ZeroMemory( &SRVDesc, sizeof( SRVDesc ) );
SRVDesc.Format = dstex.Format;
SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MostDetailedMip = 0;
SRVDesc.Texture2D.MipLevels = 1;
V_RETURN( pd3dDevice->CreateShaderResourceView( pMesh->pMeshTexture, &SRVDesc, &pMesh->pMeshRV ) );
// Create the render target view
D3D10_RENDER_TARGET_VIEW_DESC RTVDesc;
RTVDesc.Format = dstex.Format;
RTVDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
RTVDesc.Texture2D.MipSlice = 0;
V_RETURN( pd3dDevice->CreateRenderTargetView( pMesh->pMeshTexture, &RTVDesc, &pMesh->pMeshRTV ) );
float ClearColor[4] = {1,1,1,0};
pd3dDevice->ClearRenderTargetView( pMesh->pMeshRTV, ClearColor );
return hr;
}
HRESULT CreateQuadVB( ID3D10Device* pd3dDevice )
{
HRESULT hr = S_OK;
QUAD_VERTEX Verts[4];
Verts[0].Pos = D3DXVECTOR3( -1, -1, 0 );
Verts[0].Tex = D3DXVECTOR2( 0, 0 );
Verts[1].Pos = D3DXVECTOR3( -1, 1, 0 );
Verts[1].Tex = D3DXVECTOR2( 0, 1 );
Verts[2].Pos = D3DXVECTOR3( 1, -1, 0 );
Verts[2].Tex = D3DXVECTOR2( 1, 0 );
Verts[3].Pos = D3DXVECTOR3( 1, 1, 0 );
Verts[3].Tex = D3DXVECTOR2( 1, 1 );
D3D10_BUFFER_DESC vbdesc =
{
4 * sizeof( QUAD_VERTEX ),
D3D10_USAGE_IMMUTABLE,
D3D10_BIND_VERTEX_BUFFER,
0,
0
};
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = Verts;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, &InitData, &g_pQuadVB ) );
return hr;
}
void HandleKeys( float fElapsedTime )
{
float fMoveAmt = 1.0f * fElapsedTime;
float fRotateAmt = D3DX_PI * fElapsedTime;
if( GetAsyncKeyState( VK_SHIFT ) & 0x8000 )
{
if( GetAsyncKeyState( 'W' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.x += fRotateAmt;
}
if( GetAsyncKeyState( 'S' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.x -= fRotateAmt;
}
if( GetAsyncKeyState( 'D' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.y += fRotateAmt;
}
if( GetAsyncKeyState( 'A' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.y -= fRotateAmt;
}
if( GetAsyncKeyState( 'E' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.z += fRotateAmt;
}
if( GetAsyncKeyState( 'Q' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vRotation.z -= fRotateAmt;
}
}
else
{
if( GetAsyncKeyState( 'W' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.z += fMoveAmt;
}
if( GetAsyncKeyState( 'S' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.z -= fMoveAmt;
}
if( GetAsyncKeyState( 'D' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.x += fMoveAmt;
}
if( GetAsyncKeyState( 'A' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.x -= fMoveAmt;
}
if( GetAsyncKeyState( 'E' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.y += fMoveAmt;
}
if( GetAsyncKeyState( 'Q' ) & 0x8000 )
{
g_WorldMesh[g_iControlMesh].vPosition.y -= fMoveAmt;
}
}
}
| 41.653261 | 119 | 0.635317 | billionare |
b0b9194ff681cc3b74fd6134acd7dda99ed56769 | 1,392 | cpp | C++ | BOJ_solve/17678.cpp | biyotte/Code_of_gunwookim | b8b679ea56b8684ec44a7911211edee1fb558a96 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | BOJ_solve/17678.cpp | biyotte/Code_of_gunwookim | b8b679ea56b8684ec44a7911211edee1fb558a96 | [
"MIT"
] | null | null | null | BOJ_solve/17678.cpp | biyotte/Code_of_gunwookim | b8b679ea56b8684ec44a7911211edee1fb558a96 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 1e16;
const long long mod = 998244353;
const long long hashmod = 100003;
const int MAXN = 100000;
const int MAXM = 1000000;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
map <int,int> sz[500005];
int idx[500005],ans;
int n,k,co[500005],mx[500005];
vec v[500005];
int dfs(int x,int pr) {
int sum = 0; idx[x] = x;
if(++sz[x][co[x]] == mx[co[x]]) sz[x].erase(co[x]);
for(int i : v[x]) {
if(i == pr) continue;
sum += dfs(i,x);
if(sz[idx[x]].size() < sz[idx[i]].size()) swap(idx[x],idx[i]);
for(auto i : sz[idx[i]]) {
sz[idx[x]][i.x] += i.y;
if(sz[idx[x]][i.x] == mx[i.x]) sz[idx[x]].erase(i.x);
}
}
if(!sz[idx[x]].empty()) return sum;
sum += (x != 1), ans += (sum == 1);
return (sum > 0);
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> k;
for(int i = 1;i < n;i++) {
int x,y; cin >> x >> y;
v[x].pb(y), v[y].pb(x);
}
for(int i = 1;i <= n;i++) {
cin >> co[i];
mx[co[i]]++;
}
dfs(1,-1);
cout << (ans+1)/2;
} | 23.59322 | 64 | 0.586925 | biyotte |
b0b9381b29db8aa72f31f4d304c52846d76b5fd0 | 287 | hxx | C++ | admin/burnslib/src/headers.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/burnslib/src/headers.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/burnslib/src/headers.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // Copyright (c) 1997-1999 Microsoft Corporation
//
// precompiled header for support code
//
// 8-14-97 sburns
#ifndef HEADERS_HXX_INCLUDED
#define HEADERS_HXX_INCLUDED
#include "burnslib.hpp"
#include <activeds.h>
#endif // HEADERS_HXX_INCLUDED
| 11.958333 | 49 | 0.665505 | npocmaka |
b0bdf8782d63bbc53d457dfc9bf3839c02f1bbe5 | 7,473 | cpp | C++ | src/chaincontrol/viewmanager.cpp | bille18/SuperBitcoin | f0145d53ec99decbcb571165b926f283c17e32bd | [
"MIT"
] | null | null | null | src/chaincontrol/viewmanager.cpp | bille18/SuperBitcoin | f0145d53ec99decbcb571165b926f283c17e32bd | [
"MIT"
] | null | null | null | src/chaincontrol/viewmanager.cpp | bille18/SuperBitcoin | f0145d53ec99decbcb571165b926f283c17e32bd | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// CViewManger.cpp
// Implementation of the Class CViewManger
// Created on: 2-2-2018 16:40:58
// Original author: ranger
///////////////////////////////////////////////////////////
#include <interface/ichaincomponent.h>
#include "sbtcd/baseimpl.hpp"
#include "viewmanager.h"
#include "config/argmanager.h"
#include "sbtccore/block/undo.h"
SET_CPP_SCOPED_LOG_CATEGORY(CID_BLOCK_CHAIN);
CViewManager &CViewManager::Instance()
{
static CViewManager viewManager;
return viewManager;
}
CViewManager::CViewManager()
{
}
CViewManager::~CViewManager()
{
}
int CViewManager::InitCoinsDB(int64_t iCoinDBCacheSize, bool bReset)
{
NLogFormat("initialize view manager");
delete pCoinsTip;
delete pCoinsViewDB;
delete pCoinsCatcher;
pCoinsViewDB = new CCoinsViewDB(iCoinDBCacheSize, false, bReset);
if (!pCoinsViewDB->Upgrade())
{
return false;
}
return true;
}
void CViewManager::InitCoinsCache()
{
pCoinsCatcher = new CCoinsViewErrorCatcher(pCoinsViewDB);
pCoinsTip = new CCoinsViewCache(pCoinsCatcher);
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* When FAILED is returned, view is left in an indeterminate state. */
DisconnectResult
CViewManager::DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
{
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
{
ELogFormat("no undo data available");
return DISCONNECT_FAILED;
}
if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
{
ELogFormat("failure reading undo data");
return DISCONNECT_FAILED;
}
if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
{
ELogFormat("block and undo data inconsistent");
return DISCONNECT_FAILED;
}
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--)
{
const CTransaction &tx = *(block.vtx[i]);
uint256 hash = tx.GetHash();
bool is_coinbase = tx.IsCoinBase();
// Check that all outputs are available and match the outputs in the block itself
// exactly.
for (size_t o = 0; o < tx.vout.size(); o++)
{
if (!tx.vout[o].scriptPubKey.IsUnspendable())
{
COutPoint out(hash, o);
Coin coin;
bool is_spent = view.SpendCoin(out, &coin);
if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight ||
is_coinbase != coin.fCoinBase)
{
fClean = false; // transaction output mismatch
}
}
}
// restore inputs
if (i > 0)
{ // not coinbases
CTxUndo &txundo = blockUndo.vtxundo[i - 1];
if (txundo.vprevout.size() != tx.vin.size())
{
ELogFormat("transaction and undo data inconsistent");
return DISCONNECT_FAILED;
}
for (unsigned int j = tx.vin.size(); j-- > 0;)
{
const COutPoint &out = tx.vin[j].prevout;
int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
if (res == DISCONNECT_FAILED)
return DISCONNECT_FAILED;
fClean = fClean && res != DISCONNECT_UNCLEAN;
}
// At this point, all of txundo.vprevout should have been moved out.
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
//sbtc-vm
GET_CONTRACT_INTERFACE(ifContractObj);
ifContractObj->UpdateState(pindex->pprev->hashStateRoot, pindex->pprev->hashUTXORoot);
GET_CHAIN_INTERFACE(ifChainObj);
if (pfClean == NULL && ifChainObj->IsLogEvents())
{
ifContractObj->DeleteResults(block.vtx);
ifChainObj->GetBlockTreeDB()->EraseHeightIndex(pindex->nHeight);
}
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
/** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
bool CViewManager::ConnectBlock(const CBlock &block, const CBlockIndex *pIndex, CCoinsViewCache &viewCache)
{
for (const CTransactionRef &tx : block.vtx)
{
if (!tx->IsCoinBase())
{
for (const CTxIn &txin : tx->vin)
{
viewCache.SpendCoin(txin.prevout);
}
}
// Pass check = true as every addition may be an overwrite.
AddCoins(viewCache, *tx, pIndex->nHeight, true);
}
return true;
}
CCoinsView *CViewManager::GetCoinViewDB()
{
return pCoinsViewDB;
}
CCoinsViewCache *CViewManager::GetCoinsTip()
{
return pCoinsTip;
}
std::vector<uint256> CViewManager::getHeads()
{
assert(pCoinsViewDB);
return pCoinsViewDB->GetHeadBlocks();
};
bool CViewManager::Flush()
{
pCoinsTip->Flush();
return true;
}
void CViewManager::UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase())
{
txundo.vprevout.reserve(tx.vin.size());
for (const CTxIn &txin : tx.vin)
{
txundo.vprevout.emplace_back();
bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
assert(is_spent);
}
}
// add outputs
AddCoins(inputs, tx, nHeight);
}
void CViewManager::UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
{
CTxUndo txundo;
UpdateCoins(tx, inputs, txundo, nHeight);
}
void CViewManager::RequestShutdown()
{
if (pCoinsViewDB)
{
pCoinsViewDB->RequestShutdown();
}
}
/**
* Restore the UTXO in a Coin at a given COutPoint
* @param undo The Coin to be restored.
* @param view The coins view to which to apply the changes.
* @param out The out point that corresponds to the tx input.
* @return A DisconnectResult as an int
*/
int CViewManager::ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
{
bool fClean = true;
if (view.HaveCoin(out))
fClean = false; // overwriting transaction output
if (undo.nHeight == 0)
{
// Missing undo metadata (height and coinbase). Older versions included this
// information only in undo records for the last spend of a transactions'
// outputs. This implies that it must be present for some other output of the same tx.
const Coin &alternate = AccessByTxid(view, out.hash);
if (!alternate.IsSpent())
{
undo.nHeight = alternate.nHeight;
undo.fCoinBase = alternate.fCoinBase;
} else
{
return DISCONNECT_FAILED; // adding output for transaction without known metadata
}
}
// The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
// sure that the coin did not already exist in the cache. As we have queried for that above
// using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
// it is an overwrite.
view.AddCoin(out, std::move(undo), !fClean);
return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
}
| 29.305882 | 115 | 0.617824 | bille18 |
b0c29f1a7269c26de4df0655f33e7a9443c5ebdd | 601 | cc | C++ | vize/src/vize/tool/import_raw_tool.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 47 | 2020-03-30T14:36:46.000Z | 2022-03-06T07:44:54.000Z | vize/src/vize/tool/import_raw_tool.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | null | null | null | vize/src/vize/tool/import_raw_tool.cc | oprogramadorreal/vize | 042c16f96d8790303563be6787200558e1ec00b2 | [
"MIT"
] | 8 | 2020-04-01T01:22:45.000Z | 2022-01-02T13:06:09.000Z | #include "vize/tool/import_raw_tool.hpp"
#include "vize/factory/impl/raw_volume_factory.hpp"
#include <QFileDialog>
namespace vize {
ImportRawTool::ImportRawTool(VolumeDocument& document, QWidget* parent)
: ImportVolumeTool(document, std::make_unique<RawVolumeFactory>()), _parent(parent)
{ }
ImportRawTool::~ImportRawTool() = default;
void ImportRawTool::_activateImpl() {
const auto dialogTitle = std::string("Import RAW");
const auto selectedFiles = QFileDialog::getOpenFileNames(_parent, QString::fromStdString(dialogTitle), QString(""));
_buildDocument(selectedFiles, dialogTitle);
}
} | 28.619048 | 117 | 0.778702 | oprogramadorreal |