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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
073b4edfb7d5c65ba6509a0b0a5ae8010b1a704c | 302 | cxx | C++ | source/game/host_system/SceneManager.cxx | stblr/mkw-cs | 520254ee41c262332fd2fe429a9364202fd02dc0 | [
"MIT"
] | 12 | 2021-06-30T20:05:33.000Z | 2022-01-15T23:10:53.000Z | source/game/host_system/SceneManager.cxx | stblr/mkw-cs | 520254ee41c262332fd2fe429a9364202fd02dc0 | [
"MIT"
] | 13 | 2021-07-04T10:06:07.000Z | 2021-11-07T22:41:34.000Z | source/game/host_system/SceneManager.cxx | stblr/mkw-cs | 520254ee41c262332fd2fe429a9364202fd02dc0 | [
"MIT"
] | null | null | null | #include "SceneManager.hxx"
namespace System {
void SceneManager::my_changeSceneWithCreator(s32 sceneId, EGG::SceneCreator *creator) {
m_creator = creator;
changeSiblingScene(sceneId);
}
} // namespace System
REPLACE(changeSceneWithCreator__Q26System12SceneManagerFlPQ23EGG12SceneCreator);
| 23.230769 | 87 | 0.804636 | stblr |
073bbe665f0eb80791d35a3390cbca720c51f76f | 1,683 | cpp | C++ | LAB6/LAB6/Circuit.cpp | florinERotaru/oop-et-al | 750af01be09967e4112e7c783439fe2bdc0a11ce | [
"MIT"
] | null | null | null | LAB6/LAB6/Circuit.cpp | florinERotaru/oop-et-al | 750af01be09967e4112e7c783439fe2bdc0a11ce | [
"MIT"
] | null | null | null | LAB6/LAB6/Circuit.cpp | florinERotaru/oop-et-al | 750af01be09967e4112e7c783439fe2bdc0a11ce | [
"MIT"
] | null | null | null | #include "Circuit.h"
#include <iostream>
Circuit::Circuit() {
carsNumber = 0;
// stoppedNumber = 0;
}
void Circuit::AddCar(Car* model) {
cars[carsNumber++] = model;
//pun adresa direct
}
//void Circuit::AddStopped(Car* model) {
// stopped[stoppedNumber++] = model;
//}
void Circuit::SetWeather(int weather) {
this->weather= weather;
}
void Circuit::SetLength(int length) {
this->length = length;
}
void Circuit::Race() {
int last = carsNumber;
while (last != 0) {
int n = last;
last = 0;
for (int i = 0; i < n - 1; i++)
if ((Result(cars[i]) > 0) && Result(cars[i]) > Result(cars[i + 1])) {
Car* temp;
temp = cars[i];
cars[i] = cars[i + 1];
cars[i + 1] = temp;
last=i;
}
}
}
void Circuit::ShowFinalRanks() {
int poz = 1;
for (int i = 0; i < carsNumber; i++)
if (Result(cars[i]) > 0)
std::cout << "Pe locul " << poz++ << " "<< cars[i]->name << " timp: " << Result(cars[i])<<" ore " << std::endl;
}
float Circuit::Result(Car* candidate) {
float consum = length / 100;
int fuelUsed = candidate->getFuelCons()*consum;
if (fuelUsed > candidate->getFuelCap())
return -1;
return (float)(length / candidate->avgSpeed(weather));
}
void Circuit::ShowWhoDidNotFinish() {
std::cout << "Nu au reusit:" << std::endl;
for (int i = 0; i < carsNumber; i++)
if (Result(cars[i]) < 0)
std::cout << cars[i]->name << "(capac.: " << cars[i]->getFuelCap() << "litri, are nevoide de "<<(float)cars[i]->getFuelCons()*(length/100)<<")"<<std::endl;
}
| 26.714286 | 167 | 0.52347 | florinERotaru |
073d220e276741a6a49cf1e9c500ce08d329e39b | 5,929 | cpp | C++ | ojcpp/leetcode/400/450_m_delnodeinbst.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | 3 | 2019-05-04T03:26:02.000Z | 2019-08-29T01:20:44.000Z | ojcpp/leetcode/400/450_m_delnodeinbst.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | ojcpp/leetcode/400/450_m_delnodeinbst.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | //
// Created by Rui Zhou on 27/3/18.
//
/*
* https://leetcode.com/problems/delete-node-in-a-bst/description/
* Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
5
/ \
4 6
/ \
2 7
Another valid answer is [5,2,6,null,4,null,7].
5
/ \
2 6
\ \
4 7
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <codech/codech_def.h>
#include <codech/algo_common.h>
using namespace CODECH;
namespace {
class Solution0 {
public:
// from introduction to algo, slow....
TreeNode * root_;
TreeNode* deleteNode0(TreeNode* root, int key) {
root_ = root;
TreeNode *cur = root;
TreeNode *pre = nullptr;
while (cur!=nullptr && cur->val!=key) {
pre = cur;
if (key < cur->val) {
cur = cur->left;
} else if (key > cur->val) {
cur = cur->right;
}
}
deleteTreeNode(pre, cur);
return root_;
}
void transplant(TreeNode *parent, TreeNode*delNode,TreeNode *newNode) {
if (parent == nullptr) {
root_ = newNode;
} else if (parent->left == delNode) {
parent->left = newNode;
} else {
parent->right = newNode;
}
}
void deleteTreeNode(TreeNode *parent, TreeNode *delNode) {
if (delNode == nullptr)
return;
if (delNode->left == nullptr) {
transplant(parent, delNode, delNode->right);
} else if (delNode->right == nullptr) {
transplant(parent, delNode, delNode->left);
} else {
// find minimum in right subtree
TreeNode* next = delNode->right;
TreeNode* pre = delNode;
for(; next->left != nullptr; pre = next, next = next->left);
if (pre != delNode) {
transplant(pre, next, next->right);
next->right = delNode->right;
}
transplant(parent, delNode, next);
next->left = delNode->left;
}
}
// -----------------------------
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root)
return nullptr;
if (key < root->val) {
root->left = deleteNode(root->left, key);
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
} else { // find the node
if (!root->left) {
return root->right;
} else if (!root->right) {
return root->left;
} else {
// find the minimum successor in right tree
TreeNode *next = root->right;
while (next->left) {
next = next->left;
}
root->val = next->val;
root->right = deleteNode(root->right, root->val);
}
}
return root;
}
};
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root== nullptr) {
return nullptr;
}
if (root->val == key) {
TreeNode *left = root->left;
TreeNode *right = root->right;
if (left==nullptr) {
return right;
} else if (right == nullptr) {
return left;
}
TreeNode *p=root->right;
while (p->left) {
p = p->left;
}
p->left = left;
return right;
} else {
if (root->val > key) {
root->left = deleteNode(root->left, key);
} else if (root->val < key) {
root->right = deleteNode(root->right, key);
}
return root;
}
}
};
}
DEFINE_CODE_TEST(450_delnodeinbst)
{
Solution obj;
{
TreeNode *root = LCREATE_TREENODE({2,0,33,null,1,25,40,null,null,11,31,34,45,10,18,29,32,null,36,43,46,4,null,12,24,26,30,null,null,35,39,42,44,null,48,3,9,null,14,22,null,null,27,null,null,null,null,38,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,37,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,null,null,7,null,16,null,null,20,6});
//TREE_BYLEVEL(root);
VERIFY_CASE(TREE_BYLEVEL(obj.deleteNode(root, 33)),"2,0,34,null,1,25,40,null,null,11,31,36,45,10,18,29,32,35,39,43,46,4,null,12,24,26,30,null,null,null,null,38,null,42,44,null,48,3,9,null,14,22,null,null,27,null,null,37,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,null,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,7,null,16,null,null,20,null,null,null,null,null,null,");
}
/*
{
TreeNode *root = CREATE_TREENODE(0,{5,3,6,2,4,null,7});
TREE_PREORDER(obj.deleteNode(root, 3));
}*/
} | 31.705882 | 443 | 0.492663 | softarts |
0741ce49e8ea2c827bec247be56a22381a89299a | 923 | hpp | C++ | inference-engine/tools/calibration_tool/statistics_collector/utils.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 3 | 2020-02-09T23:25:37.000Z | 2021-01-19T09:44:12.000Z | inference-engine/tools/calibration_tool/statistics_collector/utils.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | null | null | null | inference-engine/tools/calibration_tool/statistics_collector/utils.hpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 2 | 2020-04-18T16:24:39.000Z | 2021-01-19T09:42:19.000Z | // Copyright (C) 2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <deque>
#include <string>
#include <ie_blob.h>
std::string getFullName(const std::string& name, const std::string& dir);
/**
* @brief Looking for regular file in directory
* @param dir - path to the target directory
* @param obj_number - desired number of regular files
* @param includePath - image file name
* @return detected files paths as deque
*/
std::deque<std::string> getDirRegContents(const std::string& dir, size_t obj_number, bool includePath = true);
std::deque<std::string> getDatasetEntries(const std::string& path, size_t obj_number = 0lu);
InferenceEngine::Blob::Ptr convertBlobFP32toFP16(InferenceEngine::Blob::Ptr blob);
InferenceEngine::Blob::Ptr convertBlobFP16toFP32(InferenceEngine::Blob::Ptr blob);
bool isFile(const std::string& path);
bool isDirectory(const std::string& path);
| 28.84375 | 110 | 0.748646 | zhoub |
074357f99cac48070d29f37d6bdf8191dbe7d9e3 | 65,289 | cpp | C++ | src/Backends/Helmholtz/TransportRoutines.cpp | friederikeboehm/CoolProp | 44325d9e6abd9e6f88f428720f4f64a0c1962784 | [
"MIT"
] | null | null | null | src/Backends/Helmholtz/TransportRoutines.cpp | friederikeboehm/CoolProp | 44325d9e6abd9e6f88f428720f4f64a0c1962784 | [
"MIT"
] | null | null | null | src/Backends/Helmholtz/TransportRoutines.cpp | friederikeboehm/CoolProp | 44325d9e6abd9e6f88f428720f4f64a0c1962784 | [
"MIT"
] | null | null | null |
#include "TransportRoutines.h"
#include "CoolPropFluid.h"
namespace CoolProp {
CoolPropDbl TransportRoutines::viscosity_dilute_kinetic_theory(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k;
CoolPropDbl sigma_nm = HEOS.components[0].transport.sigma_eta * 1e9; // 1e9 to convert from m to nm
CoolPropDbl molar_mass_kgkmol = HEOS.molar_mass() * 1000; // 1000 to convert from kg/mol to kg/kmol
// The nondimensional empirical collision integral from Neufeld
// Neufeld, P. D.; Janzen, A. R.; Aziz, R. A. Empirical Equations to Calculate 16 of the Transport Collision Integrals (l,s)*
// for the Lennard-Jones (12-6) Potential. J. Chem. Phys. 1972, 57, 1100-1102
CoolPropDbl OMEGA22 =
1.16145 * pow(Tstar, static_cast<CoolPropDbl>(-0.14874)) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar);
// The dilute gas component -
return 26.692e-9 * sqrt(molar_mass_kgkmol * HEOS.T()) / (pow(sigma_nm, 2) * OMEGA22); // Pa-s
} else {
throw NotImplementedError("TransportRoutines::viscosity_dilute_kinetic_theory is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_dilute_collision_integral(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityDiluteGasCollisionIntegralData& data = HEOS.components[0].transport.viscosity_dilute.collision_integral;
const std::vector<CoolPropDbl>&a = data.a, &t = data.t;
const CoolPropDbl C = data.C, molar_mass = data.molar_mass;
CoolPropDbl S;
// Unit conversions and variable definitions
const CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k;
const CoolPropDbl sigma_nm = HEOS.components[0].transport.sigma_eta * 1e9; // 1e9 to convert from m to nm
const CoolPropDbl molar_mass_kgkmol = molar_mass * 1000; // 1000 to convert from kg/mol to kg/kmol
/// Both the collision integral \f$\mathfrak{S}^*\f$ and effective cross section \f$\Omega^{(2,2)}\f$ have the same form,
/// in general we don't care which is used. The are related through \f$\Omega^{(2,2)} = (5/4)\mathfrak{S}^*\f$
/// see Vesovic(JPCRD, 1990) for CO\f$_2\f$ for further information
CoolPropDbl summer = 0, lnTstar = log(Tstar);
for (std::size_t i = 0; i < a.size(); ++i) {
summer += a[i] * pow(lnTstar, t[i]);
}
S = exp(summer);
// The dilute gas component
return C * sqrt(molar_mass_kgkmol * HEOS.T()) / (pow(sigma_nm, 2) * S); // Pa-s
} else {
throw NotImplementedError("TransportRoutines::viscosity_dilute_collision_integral is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_dilute_powers_of_T(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityDiluteGasPowersOfT& data = HEOS.components[0].transport.viscosity_dilute.powers_of_T;
const std::vector<CoolPropDbl>&a = data.a, &t = data.t;
CoolPropDbl summer = 0, T = HEOS.T();
for (std::size_t i = 0; i < a.size(); ++i) {
summer += a[i] * pow(T, t[i]);
}
return summer;
} else {
throw NotImplementedError("TransportRoutines::viscosity_dilute_powers_of_T is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_dilute_powers_of_Tr(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityDiluteGasPowersOfTr& data = HEOS.components[0].transport.viscosity_dilute.powers_of_Tr;
const std::vector<CoolPropDbl>&a = data.a, &t = data.t;
CoolPropDbl summer = 0, Tr = HEOS.T() / data.T_reducing;
for (std::size_t i = 0; i < a.size(); ++i) {
summer += a[i] * pow(Tr, t[i]);
}
return summer;
} else {
throw NotImplementedError("TransportRoutines::viscosity_dilute_powers_of_Tr is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_dilute_collision_integral_powers_of_T(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityDiluteCollisionIntegralPowersOfTstarData& data =
HEOS.components[0].transport.viscosity_dilute.collision_integral_powers_of_Tstar;
const std::vector<CoolPropDbl>&a = data.a, &t = data.t;
CoolPropDbl summer = 0, Tstar = HEOS.T() / data.T_reducing;
for (std::size_t i = 0; i < a.size(); ++i) {
summer += a[i] * pow(Tstar, t[i]);
}
return data.C * sqrt(HEOS.T()) / summer;
} else {
throw NotImplementedError("TransportRoutines::viscosity_dilute_collision_integral_powers_of_T is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_higher_order_modified_Batschinski_Hildebrand(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
CoolProp::ViscosityModifiedBatschinskiHildebrandData& HO =
HEOS.components[0].transport.viscosity_higher_order.modified_Batschinski_Hildebrand;
CoolPropDbl delta = HEOS.rhomolar() / HO.rhomolar_reduce, tau = HO.T_reduce / HEOS.T();
// The first term that is formed of powers of tau (Tc/T) and delta (rho/rhoc)
CoolPropDbl S = 0;
for (unsigned int i = 0; i < HO.a.size(); ++i) {
S += HO.a[i] * pow(delta, HO.d1[i]) * pow(tau, HO.t1[i]) * exp(HO.gamma[i] * pow(delta, HO.l[i]));
}
// For the terms that multiplies the bracketed term with delta and delta0
CoolPropDbl F = 0;
for (unsigned int i = 0; i < HO.f.size(); ++i) {
F += HO.f[i] * pow(delta, HO.d2[i]) * pow(tau, HO.t2[i]);
}
// for delta_0
CoolPropDbl summer_numer = 0;
for (unsigned int i = 0; i < HO.g.size(); ++i) {
summer_numer += HO.g[i] * pow(tau, HO.h[i]);
}
CoolPropDbl summer_denom = 0;
for (unsigned int i = 0; i < HO.p.size(); ++i) {
summer_denom += HO.p[i] * pow(tau, HO.q[i]);
}
CoolPropDbl delta0 = summer_numer / summer_denom;
// The higher-order-term component
return S + F * (1 / (delta0 - delta) - 1 / delta0); // Pa-s
} else {
throw NotImplementedError("TransportRoutines::viscosity_higher_order_modified_Batschinski_Hildebrand is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_initial_density_dependence_Rainwater_Friend(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityRainWaterFriendData& data = HEOS.components[0].transport.viscosity_initial.rainwater_friend;
const std::vector<CoolPropDbl>&b = data.b, &t = data.t;
CoolPropDbl B_eta, B_eta_star;
CoolPropDbl Tstar = HEOS.T() / HEOS.components[0].transport.epsilon_over_k; // [no units]
CoolPropDbl sigma = HEOS.components[0].transport.sigma_eta; // [m]
CoolPropDbl summer = 0;
for (unsigned int i = 0; i < b.size(); ++i) {
summer += b[i] * pow(Tstar, t[i]);
}
B_eta_star = summer; // [no units]
B_eta = 6.02214129e23 * pow(sigma, 3) * B_eta_star; // [m^3/mol]
return B_eta; // [m^3/mol]
} else {
throw NotImplementedError("TransportRoutines::viscosity_initial_density_dependence_Rainwater_Friend is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_initial_density_dependence_empirical(HelmholtzEOSMixtureBackend& HEOS) {
// Inspired by the form from Tariq, JPCRD, 2014
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ViscosityInitialDensityEmpiricalData& data = HEOS.components[0].transport.viscosity_initial.empirical;
const std::vector<CoolPropDbl>&n = data.n, &d = data.d, &t = data.t;
CoolPropDbl tau = data.T_reducing / HEOS.T(); // [no units]
CoolPropDbl delta = HEOS.rhomolar() / data.rhomolar_reducing; // [no units]
CoolPropDbl summer = 0;
for (unsigned int i = 0; i < n.size(); ++i) {
summer += n[i] * pow(delta, d[i]) * pow(tau, t[i]);
}
return summer; // [Pa-s]
} else {
throw NotImplementedError("TransportRoutines::viscosity_initial_density_dependence_empirical is only for pure and pseudo-pure");
}
}
static void visc_Helper(double Tbar, double rhobar, double* mubar_0, double* mubar_1) {
std::vector<std::vector<CoolPropDbl>> H(6, std::vector<CoolPropDbl>(7, 0));
double sum;
int i, j;
// Dilute-gas component
*mubar_0 = 100.0 * sqrt(Tbar) / (1.67752 + 2.20462 / Tbar + 0.6366564 / powInt(Tbar, 2) - 0.241605 / powInt(Tbar, 3));
//Fill in zeros in H
for (i = 0; i <= 5; i++) {
for (j = 0; j <= 6; j++) {
H[i][j] = 0;
}
}
//Set non-zero parameters of H
H[0][0] = 5.20094e-1;
H[1][0] = 8.50895e-2;
H[2][0] = -1.08374;
H[3][0] = -2.89555e-1;
H[0][1] = 2.22531e-1;
H[1][1] = 9.99115e-1;
H[2][1] = 1.88797;
H[3][1] = 1.26613;
H[5][1] = 1.20573e-1;
H[0][2] = -2.81378e-1;
H[1][2] = -9.06851e-1;
H[2][2] = -7.72479e-1;
H[3][2] = -4.89837e-1;
H[4][2] = -2.57040e-1;
H[0][3] = 1.61913e-1;
H[1][3] = 2.57399e-1;
H[0][4] = -3.25372e-2;
H[3][4] = 6.98452e-2;
H[4][5] = 8.72102e-3;
H[3][6] = -4.35673e-3;
H[5][6] = -5.93264e-4;
// Finite density component
sum = 0;
for (i = 0; i <= 5; i++) {
for (j = 0; j <= 6; j++) {
sum += powInt(1 / Tbar - 1, i) * (H[i][j] * powInt(rhobar - 1, j));
}
}
*mubar_1 = exp(rhobar * sum);
}
CoolPropDbl TransportRoutines::viscosity_heavywater_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
double Tbar = HEOS.T() / 643.847, rhobar = HEOS.rhomass() / 358;
double A[] = {1.000000, 0.940695, 0.578377, -0.202044};
int I[] = {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 0, 1, 2, 5, 0, 1, 2, 3, 0, 1, 3, 5, 0, 1, 5, 3};
int J[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6};
double Bij[] = {0.4864192, -0.2448372, -0.8702035, 0.8716056, -1.051126, 0.3458395, 0.3509007, 1.315436, 1.297752,
1.353448, -0.2847572, -1.037026, -1.287846, -0.02148229, 0.07013759, 0.4660127, 0.2292075, -0.4857462,
0.01641220, -0.02884911, 0.1607171, -0.009603846, -0.01163815, -0.008239587, 0.004559914, -0.003886659};
double mu0 = sqrt(Tbar) / (A[0] + A[1] / Tbar + A[2] / POW2(Tbar) + A[3] / POW3(Tbar));
double summer = 0;
for (int i = 0; i < 26; ++i) {
summer += Bij[i] * pow(1 / Tbar - 1, I[i]) * pow(rhobar - 1, J[i]);
}
double mu1 = exp(rhobar * summer);
double mubar = mu0 * mu1;
return 55.2651e-6 * mubar;
}
CoolPropDbl TransportRoutines::viscosity_water_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
double x_mu = 0.068, qc = 1 / 1.9, qd = 1 / 1.1, nu = 0.630, gamma = 1.239, zeta_0 = 0.13, LAMBDA_0 = 0.06, Tbar_R = 1.5, pstar, Tstar, rhostar;
double delta, tau, mubar_0, mubar_1, mubar_2, drhodp, drhodp_R, DeltaChibar, zeta, w, L, Y, psi_D, Tbar, rhobar;
double drhobar_dpbar, drhobar_dpbar_R, R_Water;
pstar = 22.064e6; // [Pa]
Tstar = 647.096; // [K]
rhostar = 322; // [kg/m^3]
Tbar = HEOS.T() / Tstar;
rhobar = HEOS.rhomass() / rhostar;
R_Water = HEOS.gas_constant() / HEOS.molar_mass(); // [J/kg/K]
// Dilute and finite gas portions
visc_Helper(Tbar, rhobar, &mubar_0, &mubar_1);
// **********************************************************************
// ************************ Critical Enhancement ************************
// **********************************************************************
delta = rhobar;
// "Normal" calculation
drhodp = 1 / (R_Water * HEOS.T() * (1 + 2 * delta * HEOS.dalphar_dDelta() + delta * delta * HEOS.d2alphar_dDelta2()));
drhobar_dpbar = pstar / rhostar * drhodp;
// "Reducing" calculation
tau = 1 / Tbar_R;
drhodp_R = 1
/ (R_Water * Tbar_R * Tstar
* (1 + 2 * rhobar * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, tau, delta)
+ delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, tau, delta)));
drhobar_dpbar_R = pstar / rhostar * drhodp_R;
DeltaChibar = rhobar * (drhobar_dpbar - drhobar_dpbar_R * Tbar_R / Tbar);
if (DeltaChibar < 0) DeltaChibar = 0;
zeta = zeta_0 * pow(DeltaChibar / LAMBDA_0, nu / gamma);
if (zeta < 0.3817016416) {
Y = 1.0 / 5.0 * qc * zeta * powInt(qd * zeta, 5) * (1 - qc * zeta + powInt(qc * zeta, 2) - 765.0 / 504.0 * powInt(qd * zeta, 2));
} else {
psi_D = acos(pow(1 + powInt(qd * zeta, 2), -1.0 / 2.0));
w = sqrt(std::abs((qc * zeta - 1) / (qc * zeta + 1))) * tan(psi_D / 2.0);
if (qc * zeta > 1) {
L = log((1 + w) / (1 - w));
} else {
L = 2 * atan(std::abs(w));
}
Y = 1.0 / 12.0 * sin(3 * psi_D) - 1 / (4 * qc * zeta) * sin(2 * psi_D)
+ 1.0 / powInt(qc * zeta, 2) * (1 - 5.0 / 4.0 * powInt(qc * zeta, 2)) * sin(psi_D)
- 1.0 / powInt(qc * zeta, 3) * ((1 - 3.0 / 2.0 * powInt(qc * zeta, 2)) * psi_D - pow(std::abs(powInt(qc * zeta, 2) - 1), 3.0 / 2.0) * L);
}
mubar_2 = exp(x_mu * Y);
return (mubar_0 * mubar_1 * mubar_2) / 1e6;
}
CoolPropDbl TransportRoutines::viscosity_toluene_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl Tr = HEOS.T() / 591.75, rhor = HEOS.keyed_output(CoolProp::iDmass) / 291.987;
CoolPropDbl c[] = {19.919216, -2.6557905, -135.904211, -7.9962719, -11.014795, -10.113817};
return 1e-6 * pow(static_cast<double>(rhor), 2.0 / 3.0) * sqrt(Tr)
* ((c[0] * rhor + c[1] * pow(rhor, 4)) / Tr + c[2] * rhor * rhor * rhor / (rhor * rhor + c[3] + c[4] * Tr) + c[5] * rhor);
}
CoolPropDbl TransportRoutines::viscosity_hydrogen_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl Tr = HEOS.T() / 33.145, rhor = HEOS.keyed_output(CoolProp::iDmass) * 0.011;
CoolPropDbl c[] = {0, 6.43449673e-6, 4.56334068e-2, 2.32797868e-1, 9.58326120e-1, 1.27941189e-1, 3.63576595e-1};
return c[1] * pow(rhor, 2) * exp(c[2] * Tr + c[3] / Tr + c[4] * pow(rhor, 2) / (c[5] + Tr) + c[6] * pow(rhor, 6));
}
CoolPropDbl TransportRoutines::viscosity_benzene_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl Tr = HEOS.T() / 562.02, rhor = HEOS.rhomass() / 304.792;
CoolPropDbl c[] = {-9.98945, 86.06260, 2.74872, 1.11130, -1.0, -134.1330, -352.473, 6.60989, 88.4174};
return 1e-6 * pow(rhor, static_cast<CoolPropDbl>(2.0 / 3.0)) * sqrt(Tr)
* (c[0] * pow(rhor, 2) + c[1] * rhor / (c[2] + c[3] * Tr + c[4] * rhor)
+ (c[5] * rhor + c[6] * pow(rhor, 2)) / (c[7] + c[8] * pow(rhor, 2)));
}
CoolPropDbl TransportRoutines::viscosity_hexane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl Tr = HEOS.T() / 507.82, rhor = HEOS.keyed_output(CoolProp::iDmass) / 233.182;
// Output is in Pa-s
double c[] = {2.53402335 / 1e6, -9.724061002 / 1e6, 0.469437316, 158.5571631, 72.42916856 / 1e6,
10.60751253, 8.628373915, -6.61346441, -2.212724566};
return pow(rhor, static_cast<CoolPropDbl>(2.0 / 3.0)) * sqrt(Tr)
* (c[0] / Tr + c[1] / (c[2] + Tr + c[3] * rhor * rhor)
+ c[4] * (1 + rhor) / (c[5] + c[6] * Tr + c[7] * rhor + rhor * rhor + c[8] * rhor * Tr));
}
CoolPropDbl TransportRoutines::viscosity_heptane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
/// From Michailidou-JPCRD-2014-Heptane
CoolPropDbl Tr = HEOS.T() / 540.13, rhor = HEOS.rhomass() / 232;
// Output is in Pa-s
double c[] = {0, 22.15000 / 1e6, -15.00870 / 1e6, 3.71791 / 1e6, 77.72818 / 1e6, 9.73449, 9.51900, -6.34076, -2.51909};
return pow(rhor, static_cast<CoolPropDbl>(2.0L / 3.0L)) * sqrt(Tr)
* (c[1] * rhor + c[2] * pow(rhor, 2) + c[3] * pow(rhor, 3)
+ c[4] * rhor / (c[5] + c[6] * Tr + c[7] * rhor + rhor * rhor + c[8] * rhor * Tr));
}
CoolPropDbl TransportRoutines::viscosity_higher_order_friction_theory(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
CoolProp::ViscosityFrictionTheoryData& F = HEOS.components[0].transport.viscosity_higher_order.friction_theory;
CoolPropDbl tau = F.T_reduce / HEOS.T(), kii = 0, krrr = 0, kaaa = 0, krr, kdrdr;
double psi1 = exp(tau) - F.c1;
double psi2 = exp(pow(tau, 2)) - F.c2;
double ki = (F.Ai[0] + F.Ai[1] * psi1 + F.Ai[2] * psi2) * tau;
double ka = (F.Aa[0] + F.Aa[1] * psi1 + F.Aa[2] * psi2) * pow(tau, F.Na);
double kr = (F.Ar[0] + F.Ar[1] * psi1 + F.Ar[2] * psi2) * pow(tau, F.Nr);
double kaa = (F.Aaa[0] + F.Aaa[1] * psi1 + F.Aaa[2] * psi2) * pow(tau, F.Naa);
if (F.Arr.empty()) {
krr = 0;
kdrdr = (F.Adrdr[0] + F.Adrdr[1] * psi1 + F.Adrdr[2] * psi2) * pow(tau, F.Nrr);
} else {
krr = (F.Arr[0] + F.Arr[1] * psi1 + F.Arr[2] * psi2) * pow(tau, F.Nrr);
kdrdr = 0;
}
if (!F.Aii.empty()) {
kii = (F.Aii[0] + F.Aii[1] * psi1 + F.Aii[2] * psi2) * pow(tau, F.Nii);
}
if (!F.Arrr.empty() && !F.Aaaa.empty()) {
krrr = (F.Arrr[0] + F.Arrr[1] * psi1 + F.Arrr[2] * psi2) * pow(tau, F.Nrrr);
kaaa = (F.Aaaa[0] + F.Aaaa[1] * psi1 + F.Aaaa[2] * psi2) * pow(tau, F.Naaa);
}
double p = HEOS.p() / 1e5; // [bar]; 1e5 for conversion from Pa -> bar
double pr =
HEOS.T() * HEOS.first_partial_deriv(CoolProp::iP, CoolProp::iT, CoolProp::iDmolar) / 1e5; // [bar/K]; 1e5 for conversion from Pa -> bar
double pa = p - pr; //[bar]
double pid = HEOS.rhomolar() * HEOS.gas_constant() * HEOS.T() / 1e5; // [bar]; 1e5 for conversion from Pa -> bar
double deltapr = pr - pid;
double eta_f = ka * pa + kr * deltapr + ki * pid + kaa * pa * pa + kdrdr * deltapr * deltapr + krr * pr * pr + kii * pid * pid
+ krrr * pr * pr * pr + kaaa * pa * pa * pa;
return eta_f; //[Pa-s]
} else {
throw NotImplementedError("TransportRoutines::viscosity_higher_order_friction_theory is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::viscosity_helium_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
double eta_0, eta_0_slash, eta_E_slash, B, C, D, ln_eta, x;
//
// Arp, V.D., McCarty, R.D., and Friend, D.G.,
// "Thermophysical Properties of Helium-4 from 0.8 to 1500 K with Pressures to 2000 MPa",
// NIST Technical Note 1334 (revised), 1998.
//
// Using Arp NIST report
// Report is not clear on viscosity, referring to REFPROP source code for clarity
// Correlation wants density in g/cm^3; kg/m^3 --> g/cm^3, divide by 1000
CoolPropDbl rho = HEOS.keyed_output(CoolProp::iDmass) / 1000.0, T = HEOS.T();
if (T <= 300) {
x = log(T);
} else {
x = log(300.0);
}
// Evaluate the terms B,C,D
B = -47.5295259 / x + 87.6799309 - 42.0741589 * x + 8.33128289 * x * x - 0.589252385 * x * x * x;
C = 547.309267 / x - 904.870586 + 431.404928 * x - 81.4504854 * x * x + 5.37008433 * x * x * x;
D = -1684.39324 / x + 3331.08630 - 1632.19172 * x + 308.804413 * x * x - 20.2936367 * x * x * x;
eta_0_slash = -0.135311743 / x + 1.00347841 + 1.20654649 * x - 0.149564551 * x * x + 0.012520841 * x * x * x;
eta_E_slash = rho * B + rho * rho * C + rho * rho * rho * D;
if (T <= 100) {
ln_eta = eta_0_slash + eta_E_slash;
// Correlation yields viscosity in micro g/(cm-s); to get Pa-s, divide by 10 to get micro Pa-s, then another 1e6 to get Pa-s
return exp(ln_eta) / 10.0 / 1e6;
} else {
ln_eta = eta_0_slash + eta_E_slash;
eta_0 = 196 * pow(T, static_cast<CoolPropDbl>(0.71938)) * exp(12.451 / T - 295.67 / T / T - 4.1249);
// Correlation yields viscosity in micro g/(cm-s); to get Pa-s, divide by 10 to get micro Pa-s, then another 1e6 to get Pa-s
return (exp(ln_eta) + eta_0 - exp(eta_0_slash)) / 10.0 / 1e6;
}
}
CoolPropDbl TransportRoutines::viscosity_methanol_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl B_eta, C_eta, epsilon_over_k = 577.87, /* [K]*/
sigma0 = 0.3408e-9, /* [m] */
delta = 0.4575, /* NOT the reduced density, that is rhor here*/
N_A = 6.02214129e23, M = 32.04216, /* kg/kmol */
T = HEOS.T();
CoolPropDbl rhomolar = HEOS.rhomolar();
CoolPropDbl B_eta_star, C_eta_star;
CoolPropDbl Tstar = T / epsilon_over_k; // [no units]
CoolPropDbl rhor = HEOS.rhomass() / 273;
CoolPropDbl Tr = T / 512.6;
// Rainwater-Friend initial density terms
{ // Scoped here so that we can re-use the b variable
CoolPropDbl b[9] = {-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158};
CoolPropDbl t[9] = {0, -0.25, -0.5, -0.75, -1.0, -1.25, -1.5, -2.5, -5.5};
CoolPropDbl summer = 0;
for (unsigned int i = 0; i < 9; ++i) {
summer += b[i] * pow(Tstar, t[i]);
}
B_eta_star = summer; // [no units]
B_eta = N_A * pow(sigma0, 3) * B_eta_star; // [m^3/mol]
CoolPropDbl c[2] = {1.86222085e-3, 9.990338};
C_eta_star = c[0] * pow(Tstar, 3) * exp(c[1] * pow(Tstar, static_cast<CoolPropDbl>(-0.5))); // [no units]
C_eta = pow(N_A * pow(sigma0, 3), 2) * C_eta_star; // [m^6/mol^2]
}
CoolPropDbl eta_g = 1 + B_eta * rhomolar + C_eta * rhomolar * rhomolar;
CoolPropDbl a[13] = {1.16145, -0.14874, 0.52487, -0.77320, 2.16178, -2.43787, 0.95976e-3,
0.10225, -0.97346, 0.10657, -0.34528, -0.44557, -2.58055};
CoolPropDbl d[7] = {-1.181909, 0.5031030, -0.6268461, 0.5169312, -0.2351349, 5.3980235e-2, -4.9069617e-3};
CoolPropDbl e[10] = {0, 4.018368, -4.239180, 2.245110, -0.5750698, 2.3021026e-2, 2.5696775e-2, -6.8372749e-3, 7.2707189e-4, -2.9255711e-5};
CoolPropDbl OMEGA_22_star_LJ = a[0] * pow(Tstar, a[1]) + a[2] * exp(a[3] * Tstar) + a[4] * exp(a[5] * Tstar);
CoolPropDbl OMEGA_22_star_delta = a[7] * pow(Tstar, a[8]) + a[9] * exp(a[10] * Tstar) + a[11] * exp(a[12] * Tstar);
CoolPropDbl OMEGA_22_star_SM = OMEGA_22_star_LJ * (1 + pow(delta, 2) / (1 + a[6] * pow(delta, 6)) * OMEGA_22_star_delta);
CoolPropDbl eta_0 = 2.66957e-26 * sqrt(M * T) / (pow(sigma0, 2) * OMEGA_22_star_SM);
CoolPropDbl summerd = 0;
for (int i = 0; i < 7; ++i) {
summerd += d[i] / pow(Tr, i);
}
for (int j = 1; j < 10; ++j) {
summerd += e[j] * pow(rhor, j);
}
CoolPropDbl sigmac = 0.7193422e-9; // [m]
CoolPropDbl sigma_HS = summerd * sigmac; // [m]
CoolPropDbl b = 2 * M_PI * N_A * pow(sigma_HS, 3) / 3; // [m^3/mol]
CoolPropDbl zeta = b * rhomolar / 4; // [-]
CoolPropDbl g_sigma_HS = (1 - 0.5 * zeta) / pow(1 - zeta, 3); // [-]
CoolPropDbl eta_E = 1 / g_sigma_HS + 0.8 * b * rhomolar + 0.761 * g_sigma_HS * pow(b * rhomolar, 2); // [-]
CoolPropDbl f = 1 / (1 + exp(5 * (rhor - 1)));
return eta_0 * (f * eta_g + (1 - f) * eta_E);
}
CoolPropDbl TransportRoutines::viscosity_R23_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
double C1 = 1.3163, //
C2 = 0.1832, DeltaGstar = 771.23, rhoL = 32.174, rhocbar = 7.5114, Tc = 299.2793, DELTAeta_max = 3.967, Ru = 8.31451, molar_mass = 70.014;
double a[] = {0.4425728, -0.5138403, 0.1547566, -0.02821844, 0.001578286};
double e_k = 243.91, sigma = 0.4278;
double Tstar = HEOS.T() / e_k;
double logTstar = log(Tstar);
double Omega = exp(a[0] + a[1] * logTstar + a[2] * pow(logTstar, 2) + a[3] * pow(logTstar, 3) + a[4] * pow(logTstar, 4));
double eta_DG = 1.25 * 0.021357 * sqrt(molar_mass * HEOS.T()) / (sigma * sigma * Omega); // uPa-s
double rhobar = HEOS.rhomolar() / 1000; // [mol/L]
double eta_L = C2 * (rhoL * rhoL) / (rhoL - rhobar) * sqrt(HEOS.T()) * exp(rhobar / (rhoL - rhobar) * DeltaGstar / (Ru * HEOS.T()));
double chi = rhobar - rhocbar;
double tau = HEOS.T() - Tc;
double DELTAeta_c = 4 * DELTAeta_max / ((exp(chi) + exp(-chi)) * (exp(tau) + exp(-tau)));
return (pow((rhoL - rhobar) / rhoL, C1) * eta_DG + pow(rhobar / rhoL, C1) * eta_L + DELTAeta_c) / 1e6;
}
CoolPropDbl TransportRoutines::viscosity_o_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
// From CAO, JPCRD, 2016
double D[] = {-2.05581e-3, 2.38762, 0, 10.4497, 15.9587};
double n[] = {10.3, 3.3, 25, 0.7, 0.4};
double E[] = {2.65651e-3, 0, 1.77616e-12, -18.2446, 0};
double k[] = {0.8, 0, 4.4};
double Tr = HEOS.T() / 630.259, rhor = HEOS.rhomolar() / 1000.0 / 2.6845;
double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T();
double ln_Seta = A0 + B0 / T + C0 / (T * T);
double eta0 = 0.22225 * sqrt(T) / exp(ln_Seta); // [uPa-s]
double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0;
double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s]
double f = (D[0] + E[0] * pow(Tr, -k[0])) * pow(rhor, n[0]) + D[1] * pow(rhor, n[1]) + E[2] * pow(rhor, n[2]) / pow(Tr, k[2])
+ (D[3] * rhor + E[3] * Tr) * pow(rhor, n[3]) + D[4] * pow(rhor, n[4]);
double DELTAeta = pow(rhor, 2.0 / 3.0) * sqrt(Tr) * f; // [uPa-s]
return (eta0 + eta1 + DELTAeta) / 1e6;
}
CoolPropDbl TransportRoutines::viscosity_m_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
// From CAO, JPCRD, 2016
double D[] = {-0.268950, -0.0290018, 0, 14.7728, 17.1128};
double n[] = {6.8, 3.3, 22.0, 0.6, 0.4};
double E[] = {0.320971, 0, 1.72866e-10, -18.9852, 0};
double k[] = {0.3, 0, 3.2};
double Tr = HEOS.T() / 616.89, rhor = HEOS.rhomolar() / 1000.0 / 2.665;
double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T();
double ln_Seta = A0 + B0 / T + C0 / (T * T);
double eta0 = 0.22115 * sqrt(T) / exp(ln_Seta); // [uPa-s]
double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0;
double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s]
double f = (D[0] + E[0] * pow(Tr, -k[0])) * pow(rhor, n[0]) + D[1] * pow(rhor, n[1]) + E[2] * pow(rhor, n[2]) / pow(Tr, k[2])
+ (D[3] * rhor + E[3] * Tr) * pow(rhor, n[3]) + D[4] * pow(rhor, n[4]);
double DELTAeta = pow(rhor, 2.0 / 3.0) * sqrt(Tr) * f; // [uPa-s]
return (eta0 + eta1 + DELTAeta) / 1e6; // [Pa-s]
}
CoolPropDbl TransportRoutines::viscosity_p_xylene_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
// From Balogun, JPCRD, 2016
double Tr = HEOS.T() / 616.168, rhor = HEOS.rhomolar() / 1000.0 / 2.69392;
double A0 = -1.4933, B0 = 473.2, C0 = -57033, T = HEOS.T();
double ln_Seta = A0 + B0 / T + C0 / (T * T);
double eta0 = 0.22005 * sqrt(T) / exp(ln_Seta); // [uPa-s]
double A1 = 13.2814, B1 = -10862.4, C1 = 1664060, rho_molL = HEOS.rhomolar() / 1000.0;
double eta1 = (A1 + B1 / T + C1 / (T * T)) * rho_molL; // [uPa-s]
double sum1 = 122.919 * pow(rhor, 1.5) - 282.329 * pow(rhor, 2) + 279.348 * pow(rhor, 3) - 146.776 * pow(rhor, 4) + 28.361 * pow(rhor, 5)
- 0.004585 * pow(rhor, 11);
double sum2 = 15.337 * pow(rhor, 1.5) - 0.0004382 * pow(rhor, 11) + 0.00002307 * pow(rhor, 15);
double DELTAeta = pow(rhor, 2.0 / 3.0) * (sum1 + 1 / sqrt(Tr) * sum2);
return (eta0 + eta1 + DELTAeta) / 1e6; // [Pa-s]
}
CoolPropDbl TransportRoutines::viscosity_dilute_ethane(HelmholtzEOSMixtureBackend& HEOS) {
double C[] = {
0, -3.0328138281, 16.918880086, -37.189364917, 41.288861858, -24.615921140, 8.9488430959, -1.8739245042, 0.20966101390, -9.6570437074e-3};
double OMEGA_2_2 = 0, e_k = 245, Tstar;
Tstar = HEOS.T() / e_k;
for (int i = 1; i <= 9; i++) {
OMEGA_2_2 += C[i] * pow(Tstar, (i - 1) / 3.0 - 1);
}
return 12.0085 * sqrt(Tstar) * OMEGA_2_2 / 1e6; //[Pa-s]
}
CoolPropDbl TransportRoutines::viscosity_dilute_cyclohexane(HelmholtzEOSMixtureBackend& HEOS) {
// From Tariq, JPCRD, 2014
CoolPropDbl T = HEOS.T();
CoolPropDbl S_eta = exp(-1.5093 + 364.87 / T - 39537 / pow(T, 2)); //[nm^2]
return 0.19592 * sqrt(T) / S_eta / 1e6; //[Pa-s]
}
CoolPropDbl TransportRoutines::viscosity_ethane_higher_order_hardcoded(HelmholtzEOSMixtureBackend& HEOS) {
double r[] = {0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 1, 1};
double s[] = {0, 0, 1, 0, 1, 1.5, 0, 2, 0, 1, 0, 1};
double g[] = {0, 0.47177003, -0.23950311, 0.39808301, -0.27343335, 0.35192260,
-0.21101308, -0.00478579, 0.07378129, -0.030435255, -0.30435286, 0.001215675};
double sum1 = 0, sum2 = 0, tau = 305.33 / HEOS.T(), delta = HEOS.rhomolar() / 6870;
for (int i = 1; i <= 9; ++i) {
sum1 += g[i] * pow(delta, r[i]) * pow(tau, s[i]);
}
for (int i = 10; i <= 11; ++i) {
sum2 += g[i] * pow(delta, r[i]) * pow(tau, s[i]);
}
return 15.977 * sum1 / (1 + sum2) / 1e6;
}
CoolPropDbl TransportRoutines::viscosity_Chung(HelmholtzEOSMixtureBackend& HEOS) {
// Retrieve values from the state class
CoolProp::ViscosityChungData& data = HEOS.components[0].transport.viscosity_Chung;
double a0[] = {0, 6.32402, 0.12102e-2, 5.28346, 6.62263, 19.74540, -1.89992, 24.27450, 0.79716, -0.23816, 0.68629e-1};
double a1[] = {0, 50.41190, -0.11536e-2, 254.20900, 38.09570, 7.63034, -12.53670, 3.44945, 1.11764, 0.67695e-1, 0.34793};
double a2[] = {0, -51.68010, -0.62571e-2, -168.48100, -8.46414, -14.35440, 4.98529, -11.29130, 0.12348e-1, -0.81630, 0.59256};
double a3[] = {0, 1189.02000, 0.37283e-1, 3898.27000, 31.41780, 31.52670, -18.15070, 69.34660, -4.11661, 4.02528, -0.72663};
double A[11];
if (HEOS.is_pure_or_pseudopure) {
double Vc_cm3mol = 1 / (data.rhomolar_critical / 1e6); // [cm^3/mol]
double acentric = data.acentric; // [-]
double M_gmol = data.molar_mass * 1000.0; // [g/mol]
double Tc = data.T_critical; // [K]
double mu_D = data.dipole_moment_D; // [D]
double kappa = 0;
double mu_r = 131.3 * mu_D / sqrt(Vc_cm3mol * Tc); // [-]
for (int i = 1; i <= 10; ++i) {
A[i] = a0[i] + a1[i] * acentric + a2[i] * pow(mu_r, 4) + a3[i] * kappa;
}
double F_c = 1 - 0.2756 * acentric + 0.059035 * pow(mu_r, 4) + kappa; // [-]
double epsilon_over_k = Tc / 1.2593; // [K]
double rho_molcm3 = HEOS.rhomolar() / 1e6;
double T = HEOS.T();
double Tstar = T / epsilon_over_k;
double Omega_2_2 = 1.16145 * pow(Tstar, -0.14874) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar)
- 6.435e-4 * pow(Tstar, 0.14874) * sin(18.0323 * pow(Tstar, -0.76830) - 7.27371); // [-]
double eta0_P = 4.0785e-5 * sqrt(M_gmol * T) / (pow(Vc_cm3mol, 2.0 / 3.0) * Omega_2_2) * F_c; // [P]
double Y = rho_molcm3 * Vc_cm3mol / 6.0;
double G_1 = (1.0 - 0.5 * Y) / pow(1 - Y, 3);
double G_2 = (A[1] * (1 - exp(-A[4] * Y)) / Y + A[2] * G_1 * exp(A[5] * Y) + A[3] * G_1) / (A[1] * A[4] + A[2] + A[3]);
double eta_k_P = eta0_P * (1 / G_2 + A[6] * Y); // [P]
double eta_p_P = (36.344e-6 * sqrt(M_gmol * Tc) / pow(Vc_cm3mol, 2.0 / 3.0)) * A[7] * pow(Y, 2) * G_2
* exp(A[8] + A[9] / Tstar + A[10] / pow(Tstar, 2)); // [P]
return (eta_k_P + eta_p_P) / 10.0; // [P] -> [Pa*s]
} else {
throw NotImplementedError("TransportRoutines::viscosity_Chung is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::conductivity_dilute_ratio_polynomials(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ConductivityDiluteRatioPolynomialsData& data = HEOS.components[0].transport.conductivity_dilute.ratio_polynomials;
CoolPropDbl summer1 = 0, summer2 = 0, Tr = HEOS.T() / data.T_reducing;
for (std::size_t i = 0; i < data.A.size(); ++i) {
summer1 += data.A[i] * pow(Tr, data.n[i]);
}
for (std::size_t i = 0; i < data.B.size(); ++i) {
summer2 += data.B[i] * pow(Tr, data.m[i]);
}
return summer1 / summer2;
} else {
throw NotImplementedError("TransportRoutines::conductivity_dilute_ratio_polynomials is only for pure and pseudo-pure");
}
};
CoolPropDbl TransportRoutines::conductivity_residual_polynomial(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ConductivityResidualPolynomialData& data = HEOS.components[0].transport.conductivity_residual.polynomials;
CoolPropDbl summer = 0, tau = data.T_reducing / HEOS.T(), delta = HEOS.keyed_output(CoolProp::iDmass) / data.rhomass_reducing;
for (std::size_t i = 0; i < data.B.size(); ++i) {
summer += data.B[i] * pow(tau, data.t[i]) * pow(delta, data.d[i]);
}
return summer;
} else {
throw NotImplementedError("TransportRoutines::conductivity_residual_polynomial is only for pure and pseudo-pure");
}
};
CoolPropDbl TransportRoutines::conductivity_residual_polynomial_and_exponential(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Retrieve values from the state class
CoolProp::ConductivityResidualPolynomialAndExponentialData& data =
HEOS.components[0].transport.conductivity_residual.polynomial_and_exponential;
CoolPropDbl summer = 0, tau = HEOS.tau(), delta = HEOS.delta();
for (std::size_t i = 0; i < data.A.size(); ++i) {
summer += data.A[i] * pow(tau, data.t[i]) * pow(delta, data.d[i]) * exp(-data.gamma[i] * pow(delta, data.l[i]));
}
return summer;
} else {
throw NotImplementedError("TransportRoutines::conductivity_residual_polynomial_and_exponential is only for pure and pseudo-pure");
}
};
CoolPropDbl TransportRoutines::conductivity_critical_simplified_Olchowy_Sengers(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
// Olchowy and Sengers cross-over term
// Retrieve values from the state class
CoolProp::ConductivityCriticalSimplifiedOlchowySengersData& data = HEOS.components[0].transport.conductivity_critical.Olchowy_Sengers;
double k = data.k, R0 = data.R0, nu = data.nu, gamma = data.gamma, GAMMA = data.GAMMA, zeta0 = data.zeta0, qD = data.qD,
Tc = HEOS.get_reducing_state().T, // [K]
rhoc = HEOS.get_reducing_state().rhomolar, // [mol/m^3]
Pcrit = HEOS.get_reducing_state().p, // [Pa]
Tref, // [K]
cp, cv, delta, num, zeta, mu, pi = M_PI, OMEGA_tilde, OMEGA_tilde0;
if (ValidNumber(data.T_ref))
Tref = data.T_ref;
else
Tref = 1.5 * Tc;
delta = HEOS.delta();
double dp_drho = HEOS.gas_constant() * HEOS.T() * (1 + 2 * delta * HEOS.dalphar_dDelta() + delta * delta * HEOS.d2alphar_dDelta2());
double X = Pcrit / pow(rhoc, 2) * HEOS.rhomolar() / dp_drho;
double tau_ref = Tc / Tref;
double dp_drho_ref = HEOS.gas_constant() * Tref
* (1 + 2 * delta * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, tau_ref, delta)
+ delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, tau_ref, delta));
double Xref = Pcrit / pow(rhoc, 2) * HEOS.rhomolar() / dp_drho_ref * Tref / HEOS.T();
num = X - Xref;
// No critical enhancement if numerator is negative, zero, or just a tiny bit positive due to roundoff
// See also Lemmon, IJT, 2004, page 27
if (num < DBL_EPSILON * 10)
return 0.0;
else
zeta = zeta0 * pow(num / GAMMA, nu / gamma); //[m]
cp = HEOS.cpmolar(); //[J/mol/K]
cv = HEOS.cvmolar(); //[J/mol/K]
mu = HEOS.viscosity(); //[Pa-s]
OMEGA_tilde = 2.0 / pi * ((cp - cv) / cp * atan(zeta * qD) + cv / cp * (zeta * qD)); //[-]
OMEGA_tilde0 = 2.0 / pi * (1.0 - exp(-1.0 / (1.0 / (qD * zeta) + 1.0 / 3.0 * (zeta * qD) * (zeta * qD) / delta / delta))); //[-]
double lambda = HEOS.rhomolar() * cp * R0 * k * HEOS.T() / (6 * pi * mu * zeta) * (OMEGA_tilde - OMEGA_tilde0); //[W/m/K]
return lambda; //[W/m/K]
} else {
throw NotImplementedError("TransportRoutines::conductivity_critical_simplified_Olchowy_Sengers is only for pure and pseudo-pure");
}
};
CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_R123(HelmholtzEOSMixtureBackend& HEOS) {
double a13 = 0.486742e-2, a14 = -100, a15 = -7.08535;
return a13 * exp(a14 * pow(HEOS.tau() - 1, 4) + a15 * pow(HEOS.delta() - 1, 2));
};
CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_CO2_ScalabrinJPCRD2006(HelmholtzEOSMixtureBackend& HEOS) {
CoolPropDbl nc = 0.775547504e-3 * 4.81384, Tr = HEOS.T() / 304.1282, alpha, rhor = HEOS.keyed_output(iDmass) / 467.6;
static CoolPropDbl a[] = {0.0, 3.0, 6.70697, 0.94604, 0.30, 0.30, 0.39751, 0.33791, 0.77963, 0.79857, 0.90, 0.02, 0.20};
// Equation 6 from Scalabrin
alpha = 1 - a[10] * acosh(1 + a[11] * pow(pow(1 - Tr, 2), a[12]));
// Equation 5 from Scalabrin
CoolPropDbl numer = rhor * exp(-pow(rhor, a[1]) / a[1] - pow(a[2] * (Tr - 1), 2) - pow(a[3] * (rhor - 1), 2));
CoolPropDbl braced = (1 - 1 / Tr) + a[4] * pow(pow(rhor - 1, 2), 0.5 / a[5]);
CoolPropDbl denom = pow(pow(pow(braced, 2), a[6]) + pow(pow(a[7] * (rhor - alpha), 2), a[8]), a[9]);
return nc * numer / denom;
}
CoolPropDbl TransportRoutines::conductivity_dilute_hardcoded_CO2(HelmholtzEOSMixtureBackend& HEOS) {
double e_k = 251.196, Tstar;
double b[] = {0.4226159, 0.6280115, -0.5387661, 0.6735941, 0, 0, -0.4362677, 0.2255388};
double c[] = {0, 2.387869e-2, 4.350794, -10.33404, 7.981590, -1.940558};
//Vesovic Eq. 31 [no units]
double summer = 0;
for (int i = 1; i <= 5; i++)
summer += c[i] * pow(HEOS.T() / 100.0, 2 - i);
double cint_k = 1.0 + exp(-183.5 / HEOS.T()) * summer;
//Vesovic Eq. 12 [no units]
double r = sqrt(2.0 / 5.0 * cint_k);
// According to REFPROP, 1+r^2 = cp-2.5R. This is unclear to me but seems to suggest that cint/k is the difference
// between the ideal gas specific heat and a monatomic specific heat of 5/2*R. Using the form of cint/k from Vesovic
// does not yield exactly the correct values
Tstar = HEOS.T() / e_k;
//Vesovic Eq. 30 [no units]
summer = 0;
for (int i = 0; i <= 7; i++)
summer += b[i] / pow(Tstar, i);
double Gstar_lambda = summer;
//Vesovic Eq. 29 [W/m/K]
double lambda_0 = 0.475598e-3 * sqrt(HEOS.T()) * (1 + r * r) / Gstar_lambda;
return lambda_0;
}
CoolPropDbl TransportRoutines::conductivity_dilute_hardcoded_ethane(HelmholtzEOSMixtureBackend& HEOS) {
double e_k = 245.0;
double tau = 305.33 / HEOS.T(), Tstar = HEOS.T() / e_k;
double fint = 1.7104147 - 0.6936482 / Tstar;
double lambda_0 = 0.276505e-3 * (HEOS.calc_viscosity_dilute() * 1e6) * (3.75 - fint * (tau * tau * HEOS.d2alpha0_dTau2() + 1.5)); //[W/m/K]
return lambda_0;
}
CoolPropDbl TransportRoutines::conductivity_dilute_eta0_and_poly(HelmholtzEOSMixtureBackend& HEOS) {
if (HEOS.is_pure_or_pseudopure) {
CoolProp::ConductivityDiluteEta0AndPolyData& E = HEOS.components[0].transport.conductivity_dilute.eta0_and_poly;
double eta0_uPas = HEOS.calc_viscosity_dilute() * 1e6; // [uPa-s]
double summer = E.A[0] * eta0_uPas;
for (std::size_t i = 1; i < E.A.size(); ++i)
summer += E.A[i] * pow(static_cast<CoolPropDbl>(HEOS.tau()), E.t[i]);
return summer;
} else {
throw NotImplementedError("TransportRoutines::conductivity_dilute_eta0_and_poly is only for pure and pseudo-pure");
}
}
CoolPropDbl TransportRoutines::conductivity_hardcoded_heavywater(HelmholtzEOSMixtureBackend& HEOS) {
double Tbar = HEOS.T() / 643.847, rhobar = HEOS.rhomass() / 358;
double A[] = {1.00000, 37.3223, 22.5485, 13.0465, 0, -2.60735};
double lambda0 = A[0] + A[1] * Tbar + A[2] * POW2(Tbar) + A[3] * POW3(Tbar) + A[4] * POW4(Tbar) + A[5] * POW5(Tbar);
double Be = -2.506, B[] = {-167.310, 483.656, -191.039, 73.0358, -7.57467};
double DELTAlambda = B[0] * (1 - exp(Be * rhobar)) + B[1] * rhobar + B[2] * POW2(rhobar) + B[3] * POW3(rhobar) + B[4] * POW4(rhobar);
double f_1 = exp(0.144847 * Tbar + -5.64493 * POW2(Tbar));
double f_2 = exp(-2.80000 * POW2(rhobar - 1)) - 0.080738543 * exp(-17.9430 * POW2(rhobar - 0.125698));
double tau = Tbar / (std::abs(Tbar - 1.1) + 1.1);
double f_3 = 1 + exp(60 * (tau - 1) + 20);
double f_4 = 1 + exp(100 * (tau - 1) + 15);
double DELTAlambda_c = 35429.6 * f_1 * f_2 * (1 + POW2(f_2) * (5000.0e6 * POW4(f_1) / f_3 + 3.5 * f_2 / f_4));
double DELTAlambda_L = -741.112 * pow(f_1, 1.2) * (1 - exp(-pow(rhobar / 2.5, 10)));
double lambdabar = lambda0 + DELTAlambda + DELTAlambda_c + DELTAlambda_L;
return lambdabar * 0.742128e-3;
}
CoolPropDbl TransportRoutines::conductivity_hardcoded_water(HelmholtzEOSMixtureBackend& HEOS) {
double L[5][6] = {{1.60397357, -0.646013523, 0.111443906, 0.102997357, -0.0504123634, 0.00609859258},
{2.33771842, -2.78843778, 1.53616167, -0.463045512, 0.0832827019, -0.00719201245},
{2.19650529, -4.54580785, 3.55777244, -1.40944978, 0.275418278, -0.0205938816},
{-1.21051378, 1.60812989, -0.621178141, 0.0716373224, 0, 0},
{-2.7203370, 4.57586331, -3.18369245, 1.1168348, -0.19268305, 0.012913842}};
double lambdabar_0, lambdabar_1, lambdabar_2, rhobar, Tbar, sum;
double Tstar = 647.096, rhostar = 322, pstar = 22064000, lambdastar = 1e-3, mustar = 1e-6;
double xi;
int i, j;
double R = 461.51805; //[J/kg/K]
Tbar = HEOS.T() / Tstar;
rhobar = HEOS.keyed_output(CoolProp::iDmass) / rhostar;
// Dilute gas contribution
lambdabar_0 =
sqrt(Tbar) / (2.443221e-3 + 1.323095e-2 / Tbar + 6.770357e-3 / pow(Tbar, 2) - 3.454586e-3 / pow(Tbar, 3) + 4.096266e-4 / pow(Tbar, 4));
sum = 0;
for (i = 0; i <= 4; i++) {
for (j = 0; j <= 5; j++) {
sum += L[i][j] * powInt(1.0 / Tbar - 1.0, i) * powInt(rhobar - 1, j);
}
}
// Finite density contribution
lambdabar_1 = exp(rhobar * sum);
double nu = 0.630, GAMMA = 177.8514, gamma = 1.239, xi_0 = 0.13, Lambda_0 = 0.06, Tr_bar = 1.5, qd_bar = 1 / 0.4, pi = 3.141592654,
delta = HEOS.delta();
double drhodp = 1 / (R * HEOS.T() * (1 + 2 * rhobar * HEOS.dalphar_dDelta() + rhobar * rhobar * HEOS.d2alphar_dDelta2()));
double drhobar_dpbar = pstar / rhostar * drhodp;
double drhodp_Trbar = 1
/ (R * Tr_bar * Tstar
* (1 + 2 * rhobar * HEOS.calc_alphar_deriv_nocache(0, 1, HEOS.mole_fractions, 1 / Tr_bar, delta)
+ delta * delta * HEOS.calc_alphar_deriv_nocache(0, 2, HEOS.mole_fractions, 1 / Tr_bar, delta)));
double drhobar_dpbar_Trbar = pstar / rhostar * drhodp_Trbar;
double cp = HEOS.cpmass(); // [J/kg/K]
double cv = HEOS.cvmass(); // [J/kg/K]
double cpbar = cp / R; //[-]
double mubar = HEOS.viscosity() / mustar;
double DELTAchibar_T = rhobar * (drhobar_dpbar - drhobar_dpbar_Trbar * Tr_bar / Tbar);
if (DELTAchibar_T < 0)
xi = 0;
else
xi = xi_0 * pow(DELTAchibar_T / Lambda_0, nu / gamma);
double y = qd_bar * xi;
double Z;
double kappa = cp / cv;
if (y < 1.2e-7)
Z = 0;
else
Z = 2 / (pi * y) * (((1 - 1 / kappa) * atan(y) + y / kappa) - (1 - exp(-1 / (1 / y + y * y / 3 / rhobar / rhobar))));
lambdabar_2 = GAMMA * rhobar * cpbar * Tbar / mubar * Z;
return (lambdabar_0 * lambdabar_1 + lambdabar_2) * lambdastar;
}
CoolPropDbl TransportRoutines::conductivity_hardcoded_R23(HelmholtzEOSMixtureBackend& HEOS) {
double B1 = -2.5370, // [mW/m/K]
B2 = 0.05366, // [mW/m/K^2]
C1 = 0.94215, // [-]
C2 = 0.14914, // [mW/m/K^2]
DeltaGstar = 2508.58, //[J/mol]
rhoL = 68.345, // [mol/dm^3] = [mol/L]
rhocbar = 7.5114, // [mol/dm^3]
DELTAlambda_max = 25, //[mW/m/K]
Ru = 8.31451, // [J/mol/K]
Tc = 299.2793, //[K]
T = HEOS.T(); //[K]
double lambda_DG = B1 + B2 * T;
double rhobar = HEOS.rhomolar() / 1000; // [mol/L]
double lambda_L = C2 * (rhoL * rhoL) / (rhoL - rhobar) * sqrt(T) * exp(rhobar / (rhoL - rhobar) * DeltaGstar / (Ru * T));
double chi = rhobar - rhocbar;
double tau = T - Tc;
double DELTAlambda_c = 4 * DELTAlambda_max / ((exp(chi) + exp(-chi)) * (exp(tau) + exp(-tau)));
return (pow((rhoL - rhobar) / rhoL, C1) * lambda_DG + pow(rhobar / rhoL, C1) * lambda_L + DELTAlambda_c) / 1e3;
}
CoolPropDbl TransportRoutines::conductivity_critical_hardcoded_ammonia(HelmholtzEOSMixtureBackend& HEOS) {
/*
From "Thermal Conductivity of Ammonia in a Large
Temperature and Pressure Range Including the Critical Region"
by R. Tufeu, D.Y. Ivanov, Y. Garrabos, B. Le Neindre,
Bereicht der Bunsengesellschaft Phys. Chem. 88 (1984) 422-427
*/
double T = HEOS.T(), Tc = 405.4, rhoc = 235, rho;
double LAMBDA = 1.2, nu = 0.63, gamma = 1.24, DELTA = 0.50, t, zeta_0_plus = 1.34e-10, a_zeta = 1, GAMMA_0_plus = 0.423e-8;
double pi = 3.141592654, a_chi, k_B = 1.3806504e-23, X_T, DELTA_lambda, dPdT, eta_B, DELTA_lambda_id, DELTA_lambda_i;
rho = HEOS.keyed_output(CoolProp::iDmass);
t = std::abs((T - Tc) / Tc);
a_chi = a_zeta / 0.7;
eta_B = (2.60 + 1.6 * t) * 1e-5;
dPdT = (2.18 - 0.12 / exp(17.8 * t)) * 1e5; // [Pa-K]
X_T = 0.61 * rhoc + 16.5 * log(t);
// Along the critical isochore (only a function of temperature) (Eq. 9)
DELTA_lambda_i = LAMBDA * (k_B * T * T) / (6 * pi * eta_B * (zeta_0_plus * pow(t, -nu) * (1 + a_zeta * pow(t, DELTA)))) * dPdT * dPdT
* GAMMA_0_plus * pow(t, -gamma) * (1 + a_chi * pow(t, DELTA));
DELTA_lambda_id = DELTA_lambda_i * exp(-36 * t * t);
if (rho < 0.6 * rhoc) {
DELTA_lambda = DELTA_lambda_id * (X_T * X_T) / (X_T * X_T + powInt(0.6 * rhoc - 0.96 * rhoc, 2)) * powInt(rho, 2) / powInt(0.6 * rhoc, 2);
} else {
DELTA_lambda = DELTA_lambda_id * (X_T * X_T) / (X_T * X_T + powInt(rho - 0.96 * rhoc, 2));
}
return DELTA_lambda;
}
CoolPropDbl TransportRoutines::conductivity_hardcoded_helium(HelmholtzEOSMixtureBackend& HEOS) {
/*
What an incredibly annoying formulation! Implied coefficients?? Not cool.
*/
double rhoc = 68.0, lambda_e, lambda_c, T = HEOS.T(), rho = HEOS.rhomass();
double summer = 3.739232544 / T - 2.620316969e1 / T / T + 5.982252246e1 / T / T / T - 4.926397634e1 / T / T / T / T;
double lambda_0 = 2.7870034e-3 * pow(T, 7.034007057e-1) * exp(summer);
double c[] = {1.862970530e-4, -7.275964435e-7, -1.427549651e-4, 3.290833592e-5, -5.213335363e-8, 4.492659933e-8,
-5.924416513e-9, 7.087321137e-6, -6.013335678e-6, 8.067145814e-7, 3.995125013e-7};
// Equation 17
lambda_e = (c[0] + c[1] * T + c[2] * pow(T, 1 / 3.0) + c[3] * pow(T, 2.0 / 3.0)) * rho
+ (c[4] + c[5] * pow(T, 1.0 / 3.0) + c[6] * pow(T, 2.0 / 3.0)) * rho * rho * rho
+ (c[7] + c[8] * pow(T, 1.0 / 3.0) + c[9] * pow(T, 2.0 / 3.0) + c[10] / T) * rho * rho * log(rho / rhoc);
// Critical component
lambda_c = 0.0;
if (3.5 < T && T < 12) {
double x0 = 0.392, E1 = 2.8461, E2 = 0.27156, beta = 0.3554, gamma = 1.1743, delta = 4.304, rhoc_crit = 69.158, Tc = 5.18992, pc = 2.2746e5;
double DeltaT = std::abs(1 - T / Tc), DeltaRho = std::abs(1 - rho / rhoc_crit);
double eta = HEOS.viscosity(); // [Pa-s]
double K_T = HEOS.isothermal_compressibility(), K_Tprime, K_Tbar;
double dpdT = HEOS.first_partial_deriv(CoolProp::iP, CoolProp::iT, CoolProp::iDmolar);
double W = pow(DeltaT / 0.2, 2) + pow(DeltaRho / 0.25, 2);
if (W > 1) {
K_Tbar = K_T;
} else {
double x = pow(DeltaT / DeltaRho, 1 / beta);
double h = E1 * (1 + x / x0) * pow(1 + E2 * pow(1 + x / x0, 2 / beta), (gamma - 1) / (2 * beta));
/**
dh/dx derived using sympy:
E1,x,x0,E2,beta,gamma = symbols('E1,x,x0,E2,beta,gamma')
h = E1*(1 + x/x0)*pow(1 + E2*pow(1 + x/x0, 2/beta), (gamma-1)/(2*beta))
ccode(simplify(diff(h,x)))
*/
double dhdx =
E1
* (E2 * pow((x + x0) / x0, 2 / beta) * (gamma - 1) * pow(E2 * pow((x + x0) / x0, 2 / beta) + 1, (1.0 / 2.0) * (gamma - 1) / beta)
+ pow(beta, 2) * pow(E2 * pow((x + x0) / x0, 2 / beta) + 1, (1.0 / 2.0) * (2 * beta + gamma - 1) / beta))
/ (pow(beta, 2) * x0 * (E2 * pow((x + x0) / x0, 2 / beta) + 1));
// Right-hand-side of Equation 9
double RHS = pow(DeltaRho, delta - 1) * (delta * h - x / beta * dhdx);
K_Tprime = 1 / (RHS * pow(rho / rhoc_crit, 2) * pc);
K_Tbar = W * K_T + (1 - W) * K_Tprime;
}
// 3.4685233d-17 and 3.726229668d0 are "magical" coefficients that are present in the REFPROP source to yield the right values. Not clear why these values are needed.
// Also, the form of the critical term in REFPROP does not agree with Hands paper. EL and MH from NIST are not sure where these coefficients come from.
lambda_c =
3.4685233e-17 * 3.726229668 * sqrt(K_Tbar) * pow(T, 2) / rho / eta * pow(dpdT, 2) * exp(-18.66 * pow(DeltaT, 2) - 4.25 * pow(DeltaRho, 4));
}
return lambda_0 + lambda_e + lambda_c;
}
CoolPropDbl TransportRoutines::conductivity_hardcoded_methane(HelmholtzEOSMixtureBackend& HEOS) {
double delta = HEOS.rhomolar() / 10139.0, tau = 190.55 / HEOS.T();
double lambda_dilute, lambda_residual, lambda_critical;
// Viscosity formulation from Friend, JPCRD, 1989
// Dilute
double C[] = {
0, -3.0328138281, 16.918880086, -37.189364917, 41.288861858, -24.615921140, 8.9488430959, -1.8739245042, 0.20966101390, -9.6570437074e-3};
double OMEGA22_summer = 0;
double t = HEOS.T() / 174.0;
for (int i = 1; i <= 9; ++i) {
OMEGA22_summer += C[i] * pow(t, (i - 1.0) / 3.0 - 1.0);
}
double eta_dilute = 10.50 * sqrt(t) * OMEGA22_summer;
double re[] = {0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 1, 1};
double se[] = {0, 0, 1, 0, 1, 1.5, 0, 2, 0, 1, 0, 1};
double ge[] = {0, 0.41250137, -0.14390912, 0.10366993, 0.40287464, -0.24903524,
-0.12953131, 0.06575776, 0.02566628, -0.03716526, -0.38798341, 0.03533815};
double summer1 = 0, summer2 = 0;
for (int i = 1; i <= 9; ++i) {
summer1 += ge[i] * pow(delta, re[i]) * pow(tau, se[i]);
}
for (int i = 10; i <= 11; ++i) {
summer2 += ge[i] * pow(delta, re[i]) * pow(tau, se[i]);
}
double eta_residual = 12.149 * summer1 / (1 + summer2);
double eta = eta_residual + eta_dilute;
// Dilute
double f_int = 1.458850 - 0.4377162 / t;
lambda_dilute = 0.51828 * eta_dilute * (3.75 - f_int * (POW2(HEOS.tau()) * HEOS.d2alpha0_dTau2() + 1.5)); // [mW/m/K]
// Residual
double rl[] = {0, 1, 3, 4, 4, 5, 5, 2};
double sl[] = {0, 0, 0, 0, 1, 0, 1, 0};
double jl[] = {0, 2.4149207, 0.55166331, -0.52837734, 0.073809553, 0.24465507, -0.047613626, 1.5554612};
double summer = 0;
for (int i = 1; i <= 6; ++i) {
summer += jl[i] * pow(delta, rl[i]) * pow(tau, sl[i]);
}
double delta_sigma_star = 1.0; // Looks like a typo in Friend - should be 1 instead of 11
if (HEOS.T() < HEOS.T_critical() && HEOS.rhomolar() < HEOS.rhomolar_critical()) {
delta_sigma_star = HEOS.saturation_ancillary(iDmolar, 1, iT, HEOS.T()) / HEOS.keyed_output(CoolProp::irhomolar_critical);
}
lambda_residual = 6.29638 * (summer + jl[7] * POW2(delta) / delta_sigma_star); // [mW/m/K]
// Critical region
double Tstar = 1 - 1 / tau;
double rhostar = 1 - delta;
double F_T = 2.646, F_rho = 2.678, F_A = -0.637;
double F = exp(-F_T * sqrt(std::abs(Tstar)) - F_rho * POW2(rhostar) - F_A * rhostar);
double CHI_T_star;
if (std::abs(Tstar) < 0.03) {
if (std::abs(rhostar) < 1e-16) {
// Equation 26
const double LAMBDA = 0.0801, gamma = 1.190;
CHI_T_star = LAMBDA * pow(std::abs(Tstar), -gamma);
} else if (std::abs(rhostar) < 0.03) {
// Equation 23
const double beta = 0.355, W = -1.401, S = -6.098, E = 0.287, a = 3.352, b = 0.732, R = 0.535, Q = 0.1133;
double OMEGA = W * Tstar * pow(std::abs(rhostar), -1 / beta);
double theta = 1;
if (Tstar < -pow(std::abs(rhostar), -1 / beta) / S) {
theta = 1 + E * pow(1 + S * Tstar * pow(std::abs(rhostar), -1 / beta), 2 * beta);
}
CHI_T_star = Q * pow(std::abs(rhostar), -a) * pow(theta, b) / (theta + OMEGA * (theta + R));
} else {
// Equation 19a
CHI_T_star = 0.28631 * delta * tau / (1 + 2 * delta * HEOS.dalphar_dDelta() + POW2(delta) * HEOS.d2alphar_dDelta2());
}
} else {
// Equation 19a
CHI_T_star = 0.28631 * delta * tau / (1 + 2 * delta * HEOS.dalphar_dDelta() + POW2(delta) * HEOS.d2alphar_dDelta2());
}
lambda_critical = 91.855 / (eta * POW2(tau)) * POW2(1 + delta * HEOS.dalphar_dDelta() - delta * tau * HEOS.d2alphar_dDelta_dTau())
* pow(CHI_T_star, 0.4681) * F; //[mW/m/K]
return (lambda_dilute + lambda_residual + lambda_critical) * 0.001;
}
void TransportRoutines::conformal_state_solver(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference, CoolPropDbl& T0,
CoolPropDbl& rhomolar0) {
int iter = 0;
double resid = 9e30, resid_old = 9e30;
CoolPropDbl alphar = HEOS.alphar();
CoolPropDbl Z = HEOS.keyed_output(iZ);
Eigen::Vector2d r;
Eigen::Matrix2d J;
HEOS_Reference.specify_phase(iphase_gas); // Something homogeneous, not checked
// Update the reference fluid with the conformal state
HEOS_Reference.update_DmolarT_direct(rhomolar0, T0);
do {
CoolPropDbl dtau_dT = -HEOS_Reference.T_critical() / (T0 * T0);
CoolPropDbl ddelta_drho = 1 / HEOS_Reference.rhomolar_critical();
// Independent variables are T0 and rhomolar0, residuals are matching alphar and Z
r(0) = HEOS_Reference.alphar() - alphar;
r(1) = HEOS_Reference.keyed_output(iZ) - Z;
J(0, 0) = HEOS_Reference.dalphar_dTau() * dtau_dT;
J(0, 1) = HEOS_Reference.dalphar_dDelta() * ddelta_drho;
// Z = 1+delta*dalphar_ddelta(tau,delta)
// dZ_dT
J(1, 0) = HEOS_Reference.delta() * HEOS_Reference.d2alphar_dDelta_dTau() * dtau_dT;
// dZ_drho
J(1, 1) = (HEOS_Reference.delta() * HEOS_Reference.d2alphar_dDelta2() + HEOS_Reference.dalphar_dDelta()) * ddelta_drho;
// Step in v obtained from Jv = -r
Eigen::Vector2d v = J.colPivHouseholderQr().solve(-r);
bool good_solution = false;
double T0_init = HEOS_Reference.T(), rhomolar0_init = HEOS_Reference.rhomolar();
// Calculate the old residual after the last step
resid_old = sqrt(POW2(r(0)) + POW2(r(1)));
for (double frac = 1.0; frac > 0.001; frac /= 2) {
try {
// Calculate new values
double T_new = T0_init + frac * v(0);
double rhomolar_new = rhomolar0_init + frac * v(1);
// Update state with step
HEOS_Reference.update_DmolarT_direct(rhomolar_new, T_new);
resid = sqrt(POW2(HEOS_Reference.alphar() - alphar) + POW2(HEOS_Reference.keyed_output(iZ) - Z));
if (resid > resid_old) {
continue;
}
good_solution = true;
T0 = T_new;
rhomolar0 = rhomolar_new;
break;
} catch (...) {
continue;
}
}
if (!good_solution) {
throw ValueError(format("Not able to get a solution"));
}
iter++;
if (iter > 50) {
throw ValueError(format("conformal_state_solver took too many iterations; residual is %g; prior was %g", resid, resid_old));
}
} while (std::abs(resid) > 1e-9);
}
CoolPropDbl TransportRoutines::viscosity_ECS(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference) {
// Collect some parameters
CoolPropDbl M = HEOS.molar_mass(), M0 = HEOS_Reference.molar_mass(), Tc = HEOS.T_critical(), Tc0 = HEOS_Reference.T_critical(),
rhocmolar = HEOS.rhomolar_critical(), rhocmolar0 = HEOS_Reference.rhomolar_critical();
// Get a reference to the ECS data
CoolProp::ViscosityECSVariables& ECS = HEOS.components[0].transport.viscosity_ecs;
// The correction polynomial psi_eta
double psi = 0;
for (std::size_t i = 0; i < ECS.psi_a.size(); i++) {
psi += ECS.psi_a[i] * pow(HEOS.rhomolar() / ECS.psi_rhomolar_reducing, ECS.psi_t[i]);
}
// The dilute gas portion for the fluid of interest [Pa-s]
CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS);
// ************************************
// Start with a guess for theta and phi
// ************************************
CoolPropDbl theta = 1;
CoolPropDbl phi = 1;
// The equivalent substance reducing ratios
CoolPropDbl f = Tc / Tc0 * theta;
CoolPropDbl h = rhocmolar0 / rhocmolar * phi; // Must be the ratio of MOLAR densities!!
// To be solved for
CoolPropDbl T0 = HEOS.T() / f;
CoolPropDbl rhomolar0 = HEOS.rhomolar() * h;
// **************************
// Solver for conformal state
// **************************
//
HEOS_Reference.specify_phase(iphase_gas); // something homogeneous
conformal_state_solver(HEOS, HEOS_Reference, T0, rhomolar0);
// Update the reference fluid with the updated conformal state
HEOS_Reference.update_DmolarT_direct(rhomolar0 * psi, T0);
// Recalculate ESRR
f = HEOS.T() / T0;
h = rhomolar0 / HEOS.rhomolar(); // Must be the ratio of MOLAR densities!!
// **********************
// Remaining calculations
// **********************
// The reference fluid's contribution to the viscosity [Pa-s]
CoolPropDbl eta_resid = HEOS_Reference.calc_viscosity_background();
// The F factor
CoolPropDbl F_eta = sqrt(f) * pow(h, -static_cast<CoolPropDbl>(2.0L / 3.0L)) * sqrt(M / M0);
// The total viscosity considering the contributions of the fluid of interest and the reference fluid [Pa-s]
CoolPropDbl eta = eta_dilute + eta_resid * F_eta;
return eta;
}
CoolPropDbl TransportRoutines::viscosity_rhosr(HelmholtzEOSMixtureBackend& HEOS) {
// Get a reference to the data
const CoolProp::ViscosityRhoSrVariables& data = HEOS.components[0].transport.viscosity_rhosr;
// The dilute gas portion for the fluid of interest [Pa-s]
CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS);
// Calculate x
double x = HEOS.rhomolar() * HEOS.gas_constant() * (HEOS.tau() * HEOS.dalphar_dTau() - HEOS.alphar()) / data.rhosr_critical;
// Crossover variable
double psi_liq = 1 / (1 + exp(-100.0 * (x - 2)));
// Evaluated using Horner's method
const std::vector<double>&cL = data.c_liq, cV = data.c_vap;
double f_liq = cL[0] + x * (cL[1] + x * (cL[2] + x * (cL[3])));
double f_vap = cV[0] + x * (cV[1] + x * (cV[2] + x * (cV[3])));
// Evaluate the reference fluid
double etastar_ref = exp(psi_liq * f_liq + (1 - psi_liq) * f_vap);
// Get the non-dimensionalized viscosity
double etastar_fluid = 1 + data.C * (etastar_ref - 1);
return etastar_fluid * eta_dilute;
}
CoolPropDbl TransportRoutines::conductivity_ECS(HelmholtzEOSMixtureBackend& HEOS, HelmholtzEOSMixtureBackend& HEOS_Reference) {
// Collect some parameters
CoolPropDbl M = HEOS.molar_mass(), M_kmol = M * 1000, M0 = HEOS_Reference.molar_mass(), Tc = HEOS.T_critical(), Tc0 = HEOS_Reference.T_critical(),
rhocmolar = HEOS.rhomolar_critical(), rhocmolar0 = HEOS_Reference.rhomolar_critical(), R_u = HEOS.gas_constant(),
R = HEOS.gas_constant() / HEOS.molar_mass(), //[J/kg/K]
R_kJkgK = R_u / M_kmol;
// Get a reference to the ECS data
CoolProp::ConductivityECSVariables& ECS = HEOS.components[0].transport.conductivity_ecs;
// The correction polynomial psi_eta in rho/rho_red
double psi = 0;
for (std::size_t i = 0; i < ECS.psi_a.size(); ++i) {
psi += ECS.psi_a[i] * pow(HEOS.rhomolar() / ECS.psi_rhomolar_reducing, ECS.psi_t[i]);
}
// The correction polynomial f_int in T/T_red
double fint = 0;
for (std::size_t i = 0; i < ECS.f_int_a.size(); ++i) {
fint += ECS.f_int_a[i] * pow(HEOS.T() / ECS.f_int_T_reducing, ECS.f_int_t[i]);
}
// The dilute gas density for the fluid of interest [uPa-s]
CoolPropDbl eta_dilute = viscosity_dilute_kinetic_theory(HEOS) * 1e6;
// The mass specific ideal gas constant-pressure specific heat [J/kg/K]
CoolPropDbl cp0 = HEOS.calc_cpmolar_idealgas() / HEOS.molar_mass();
// The internal contribution to the thermal conductivity [W/m/K]
CoolPropDbl lambda_int = fint * eta_dilute * (cp0 - 2.5 * R) / 1e3;
// The dilute gas contribution to the thermal conductivity [W/m/K]
CoolPropDbl lambda_dilute = 15.0e-3 / 4.0 * R_kJkgK * eta_dilute;
// ************************************
// Start with a guess for theta and phi
// ************************************
CoolPropDbl theta = 1;
CoolPropDbl phi = 1;
// The equivalent substance reducing ratios
CoolPropDbl f = Tc / Tc0 * theta;
CoolPropDbl h = rhocmolar0 / rhocmolar * phi; // Must be the ratio of MOLAR densities!!
// Initial values for the conformal state
CoolPropDbl T0 = HEOS.T() / f;
CoolPropDbl rhomolar0 = HEOS.rhomolar() * h;
// **************************
// Solver for conformal state
// **************************
try {
conformal_state_solver(HEOS, HEOS_Reference, T0, rhomolar0);
} catch (std::exception& e) {
throw ValueError(format("Conformal state solver failed; error was %s", e.what()));
}
// Update the reference fluid with the conformal state
HEOS_Reference.update(DmolarT_INPUTS, rhomolar0 * psi, T0);
// Recalculate ESRR
f = HEOS.T() / T0;
h = rhomolar0 / HEOS.rhomolar(); // Must be the ratio of MOLAR densities!!
// The reference fluid's contribution to the conductivity [W/m/K]
CoolPropDbl lambda_resid = HEOS_Reference.calc_conductivity_background();
// The F factor
CoolPropDbl F_lambda = sqrt(f) * pow(h, static_cast<CoolPropDbl>(-2.0 / 3.0)) * sqrt(M0 / M);
// The critical contribution from the fluid of interest [W/m/K]
CoolPropDbl lambda_critical = conductivity_critical_simplified_Olchowy_Sengers(HEOS);
// The total thermal conductivity considering the contributions of the fluid of interest and the reference fluid [Pa-s]
CoolPropDbl lambda = lambda_int + lambda_dilute + lambda_resid * F_lambda + lambda_critical;
return lambda;
}
}; /* namespace CoolProp */
| 48.942279 | 174 | 0.578489 | friederikeboehm |
07435cfeb75f5c3e1334bad63d90566a9506acfc | 7,109 | cpp | C++ | test/moddims.cpp | ckeitz/arrayfire | a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b | [
"BSD-3-Clause"
] | null | null | null | test/moddims.cpp | ckeitz/arrayfire | a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b | [
"BSD-3-Clause"
] | null | null | null | test/moddims.cpp | ckeitz/arrayfire | a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;
template<typename T>
class Moddims : public ::testing::Test
{
public:
virtual void SetUp() {
subMat.push_back({1,2,1});
subMat.push_back({1,3,1});
}
vector<af_seq> subMat;
};
// create a list of types to be tested
// TODO: complex types tests have to be added
typedef ::testing::Types<float, double, int, unsigned, char, unsigned char> TestTypes;
// register the type list
TYPED_TEST_CASE(Moddims, TestTypes);
template<typename T>
void moddimsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T>> in;
vector<vector<T>> tests;
readTests<T,T,int>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
T *outData;
if (isSubRef) {
af_array inArray = 0;
af_array subArray = 0;
af_array outArray = 0;
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));
ASSERT_EQ(AF_SUCCESS, af_index(&subArray,inArray,seqv->size(),&seqv->front()));
af::dim4 newDims(1);
newDims[0] = 2;
newDims[1] = 3;
ASSERT_EQ(AF_SUCCESS, af_moddims(&outArray,subArray,newDims.ndims(),newDims.get()));
dim_type nElems;
ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems,outArray));
outData = new T[nElems];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(subArray));
} else {
af_array inArray = 0;
af_array outArray = 0;
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));
af::dim4 newDims(1);
newDims[0] = dims[1];
newDims[1] = dims[0]*dims[2];
ASSERT_EQ(AF_SUCCESS, af_moddims(&outArray,inArray,newDims.ndims(),newDims.get()));
outData = new T[dims.elements()];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray));
}
for (size_t testIter=0; testIter<tests.size(); ++testIter) {
vector<T> currGoldBar = tests[testIter];
size_t nElems = currGoldBar.size();
for (size_t elIter=0; elIter<nElems; ++elIter) {
ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl;
}
}
delete[] outData;
}
TYPED_TEST(Moddims,Basic)
{
moddimsTest<TypeParam>(string(TEST_DIR"/moddims/basic.test"));
}
TYPED_TEST(Moddims,Subref)
{
moddimsTest<TypeParam>(string(TEST_DIR"/moddims/subref.test"),true,&(this->subMat));
}
template<typename T>
void moddimsArgsTest(string pTestFile)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T>> in;
vector<vector<T>> tests;
readTests<T,T,int>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
af_array inArray = 0;
af_array outArray = 0;
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));
af::dim4 newDims(1);
newDims[0] = dims[1];
newDims[1] = dims[0]*dims[2];
ASSERT_EQ(AF_ERR_ARG, af_moddims(&outArray,inArray,0,newDims.get()));
ASSERT_EQ(AF_ERR_ARG, af_moddims(&outArray,inArray,newDims.ndims(),nullptr));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
}
TYPED_TEST(Moddims,InvalidArgs)
{
moddimsArgsTest<TypeParam>(string(TEST_DIR"/moddims/basic.test"));
}
template<typename T>
void moddimsMismatchTest(string pTestFile)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T>> in;
vector<vector<T>> tests;
readTests<T,T,int>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
af_array inArray = 0;
af_array outArray = 0;
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));
af::dim4 newDims(1);
newDims[0] = dims[1]-1;
newDims[1] = (dims[0]-1)*dims[2];
ASSERT_EQ(AF_ERR_SIZE, af_moddims(&outArray,inArray,newDims.ndims(),newDims.get()));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
}
TYPED_TEST(Moddims,Mismatch)
{
moddimsMismatchTest<TypeParam>(string(TEST_DIR"/moddims/basic.test"));
}
/////////////////////////////////// CPP ///////////////////////////////////
//
template<typename T>
void cppModdimsTest(string pTestFile, bool isSubRef=false, const vector<af_seq> *seqv=nullptr)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T>> in;
vector<vector<T>> tests;
readTests<T,T,int>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
T *outData;
if (isSubRef) {
af::array input(dims, &(in[0].front()));
af::array subArray = input(seqv->at(0), seqv->at(1));
af::dim4 newDims(1);
newDims[0] = 2;
newDims[1] = 3;
af::array output = af::moddims(subArray, newDims.ndims(), newDims.get());
dim_type nElems = output.elements();
outData = new T[nElems];
output.host((void*)outData);
} else {
af::array input(dims, &(in[0].front()));
af::dim4 newDims(1);
newDims[0] = dims[1];
newDims[1] = dims[0]*dims[2];
af::array output = af::moddims(input, newDims.ndims(), newDims.get());
outData = new T[dims.elements()];
output.host((void*)outData);
}
for (size_t testIter=0; testIter<tests.size(); ++testIter) {
vector<T> currGoldBar = tests[testIter];
size_t nElems = currGoldBar.size();
for (size_t elIter=0; elIter<nElems; ++elIter) {
ASSERT_EQ(currGoldBar[elIter],outData[elIter])<< "at: " << elIter<< std::endl;
}
}
delete[] outData;
}
TEST(Moddims,Basic_CPP)
{
cppModdimsTest<float>(string(TEST_DIR"/moddims/basic.test"));
}
TEST(Moddims,Subref_CPP)
{
vector<af_seq> subMat;
subMat.push_back({1,2,1});
subMat.push_back({1,3,1});
cppModdimsTest<float>(string(TEST_DIR"/moddims/subref.test"),true,&subMat);
}
| 29.135246 | 142 | 0.620059 | ckeitz |
07439ae178f5d7834cc88f2c47ef09141dc3f310 | 1,644 | cpp | C++ | work/day14_figure.cpp | eatyouzi/AH | 2beb8252f967d8492a63498c5866d5268eaed4af | [
"Unlicense"
] | null | null | null | work/day14_figure.cpp | eatyouzi/AH | 2beb8252f967d8492a63498c5866d5268eaed4af | [
"Unlicense"
] | null | null | null | work/day14_figure.cpp | eatyouzi/AH | 2beb8252f967d8492a63498c5866d5268eaed4af | [
"Unlicense"
] | null | null | null | #include<iostream>
#include <cstdio>
#include <fstream>
#include <stdlib.h>
using namespace std;
class Figure{
public:
Figure();
Figure(string name)
:_typename(name)
{
}
virtual double getArea( )=0;
virtual string getName( )=0;
virtual void show()=0; //打印图形的相关信息
protected:
string _typename ;
};
class Cicle
:virtual public Figure
{
public:
Cicle():_radix(0.0){} //初始化为0
Cicle(double radix)
:_radix(radix)
,Figure("Cicle")
{
}
double getRadius( ) {
return _radix;
}//获取圆的半径
double getPerimeter(){
return 2*3.14*_radix;
} //获取圆的周长
virtual double getArea() {
return 3.14*_radix*_radix;
} //获取圆的面积
virtual string getName(){
return _typename;
} //获取圆的名字
virtual void show(){
cout<<"name "<<getName()
<<" radix "<<getRadius()
<<" perimeter "<<getPerimeter()
<<" area "<<getArea()
<<endl;
}
protected:
double _radix ;
};
class Cylinder
:public Cicle
{
public:
Cylinder(double r, double h)
:Cicle(r)
,Figure("Cylinder")
,_high(h)
{
}
virtual double getArea(){
return 2 *Cicle::getArea()+ getPerimeter()*_high;
}
virtual string getName(){
return _typename;
}
double getHeight(){
return _high;
} //获取圆柱体的高
double getVolume(){
return Cicle::getArea()*_high;
} //获取圆柱体的体积
void show(){
cout<<"name "<<_typename
<<" high "<<_high
<<" area "<<getArea()
<<" volume "<<getVolume()
<<endl;
} //将圆柱体的高、表面积、体积输出到屏幕
private:
double _high;
};
int main(){
Figure *f1, *f2;
Cicle ci1(10.0);
Cylinder cy1(10.0, 2.0);
f1 = &ci1;
f2 = &cy1;
f1->show();
f2->show();
system("pause");
return 0;
} | 15.807692 | 51 | 0.607664 | eatyouzi |
0743b6b5e08885bcbeeb031436fd67c4ba897a65 | 124 | cpp | C++ | vortex/assert.cpp | LeDYoM/sgh | 66a56d0df5c0acc8a3f47212a91da7ea889695de | [
"MIT"
] | null | null | null | vortex/assert.cpp | LeDYoM/sgh | 66a56d0df5c0acc8a3f47212a91da7ea889695de | [
"MIT"
] | null | null | null | vortex/assert.cpp | LeDYoM/sgh | 66a56d0df5c0acc8a3f47212a91da7ea889695de | [
"MIT"
] | null | null | null | #include "include/assert.hpp"
#include "common_def_priv.hpp"
namespace vtx
{
Assert::Assert() {}
Assert::~Assert() {}
}
| 12.4 | 30 | 0.677419 | LeDYoM |
0743bb506b4373046e27d38d925a41bbcc7ff2d7 | 8,847 | cc | C++ | chrome/browser/chrome_main_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/chrome_main_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/chrome_main_browsertest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/process/launch.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "net/base/filename_util.h"
// These tests don't apply to Mac or Lacros; see GetCommandLineForRelaunch
// for details.
#if defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_LACROS)
#error Not supported on this platform.
#endif
class ChromeMainTest : public InProcessBrowserTest {
public:
ChromeMainTest() {}
void Relaunch(const base::CommandLine& new_command_line) {
base::LaunchProcess(new_command_line, base::LaunchOptionsForTest());
}
Profile* CreateProfile(const base::FilePath& basename) {
Profile* created_profile = nullptr;
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath profile_path =
profile_manager->user_data_dir().Append(basename);
base::RunLoop run_loop;
profile_manager->CreateProfileAsync(
profile_path, base::BindLambdaForTesting(
[&run_loop, &created_profile](
Profile* profile, Profile::CreateStatus status) {
if (status != Profile::CREATE_STATUS_INITIALIZED)
return;
created_profile = profile;
run_loop.Quit();
}));
run_loop.Run();
return created_profile;
}
// Gets the relaunch command line with the kProfileEmail switch.
base::CommandLine GetCommandLineForRelaunchWithEmail(
const std::string& email) {
base::CommandLine command_line = GetCommandLineForRelaunch();
command_line.AppendArg(
base::StringPrintf("--profile-email=%s", email.c_str()));
return command_line;
}
};
// Make sure that the second invocation creates a new window.
IN_PROC_BROWSER_TEST_F(ChromeMainTest, SecondLaunch) {
Relaunch(GetCommandLineForRelaunch());
ui_test_utils::WaitForBrowserToOpen();
ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) {
base::FilePath test_file_path = ui_test_utils::GetTestFilePath(
base::FilePath(), base::FilePath().AppendASCII("empty.html"));
base::CommandLine new_command_line(GetCommandLineForRelaunch());
new_command_line.AppendArgPath(test_file_path);
Relaunch(new_command_line);
ui_test_utils::TabAddedWaiter(browser()).Wait();
GURL url = net::FilePathToFileURL(test_file_path);
content::WebContents* tab =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_EQ(url, tab->GetVisibleURL());
}
// ChromeMainTest.SecondLaunchWithIncognitoUrl is flaky on Win and Linux.
// http://crbug.com/130395
#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS)
#define MAYBE_SecondLaunchWithIncognitoUrl DISABLED_SecondLaunchWithIncognitoUrl
#else
#define MAYBE_SecondLaunchWithIncognitoUrl SecondLaunchWithIncognitoUrl
#endif
IN_PROC_BROWSER_TEST_F(ChromeMainTest, MAYBE_SecondLaunchWithIncognitoUrl) {
// We should start with one normal window.
ASSERT_EQ(1u, chrome::GetTabbedBrowserCount(browser()->profile()));
// Run with --incognito switch and an URL specified.
base::FilePath test_file_path = ui_test_utils::GetTestFilePath(
base::FilePath(), base::FilePath().AppendASCII("empty.html"));
base::CommandLine new_command_line(GetCommandLineForRelaunch());
new_command_line.AppendSwitch(switches::kIncognito);
new_command_line.AppendArgPath(test_file_path);
Relaunch(new_command_line);
// There should be one normal and one incognito window now.
Relaunch(new_command_line);
ui_test_utils::WaitForBrowserToOpen();
ASSERT_EQ(2u, chrome::GetTotalBrowserCount());
ASSERT_EQ(1u, chrome::GetTabbedBrowserCount(browser()->profile()));
}
IN_PROC_BROWSER_TEST_F(ChromeMainTest, SecondLaunchFromIncognitoWithNormalUrl) {
Profile* const profile = browser()->profile();
// We should start with one normal window.
ASSERT_EQ(1u, chrome::GetTabbedBrowserCount(profile));
// Create an incognito window.
chrome::NewIncognitoWindow(profile);
ASSERT_EQ(2u, chrome::GetTotalBrowserCount());
ASSERT_EQ(1u, chrome::GetTabbedBrowserCount(profile));
// Close the first window.
CloseBrowserSynchronously(browser());
// There should only be the incognito window open now.
ASSERT_EQ(1u, chrome::GetTotalBrowserCount());
ASSERT_EQ(0u, chrome::GetTabbedBrowserCount(profile));
// Run with just an URL specified, no --incognito switch.
base::FilePath test_file_path = ui_test_utils::GetTestFilePath(
base::FilePath(), base::FilePath().AppendASCII("empty.html"));
base::CommandLine new_command_line(GetCommandLineForRelaunch());
new_command_line.AppendArgPath(test_file_path);
Relaunch(new_command_line);
ui_test_utils::WaitForBrowserToOpen();
// There should be one normal and one incognito window now.
ASSERT_EQ(2u, chrome::GetTotalBrowserCount());
ASSERT_EQ(1u, chrome::GetTabbedBrowserCount(profile));
}
// Multi-profile is not supported on Ash.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
IN_PROC_BROWSER_TEST_F(ChromeMainTest, SecondLaunchWithProfileDir) {
const base::FilePath kProfileDir(FILE_PATH_LITERAL("Other"));
Profile* other_profile = CreateProfile(kProfileDir);
ASSERT_TRUE(other_profile);
// Pass the other profile path on the command line.
base::CommandLine other_command_line = GetCommandLineForRelaunch();
other_command_line.AppendSwitchPath(switches::kProfileDirectory, kProfileDir);
size_t original_browser_count = chrome::GetTotalBrowserCount();
Relaunch(other_command_line);
Browser* other_browser = ui_test_utils::WaitForBrowserToOpen();
ASSERT_TRUE(other_browser);
EXPECT_EQ(other_browser->profile(), other_profile);
EXPECT_EQ(original_browser_count + 1, chrome::GetTotalBrowserCount());
}
IN_PROC_BROWSER_TEST_F(ChromeMainTest, SecondLaunchWithProfileEmail) {
const base::FilePath kProfileDir1(FILE_PATH_LITERAL("Profile1"));
const base::FilePath kProfileDir2(FILE_PATH_LITERAL("Profile2"));
const std::string kProfileEmail1 = "example@gmail.com";
// Unicode emails are supported.
const std::string kProfileEmail2 =
"\xe4\xbd\xa0\xe5\xa5\xbd\x40\x67\x6d\x61\x69\x6c\x2e\x63\x6f\x6d\x0a";
ProfileAttributesStorage* storage =
&g_browser_process->profile_manager()->GetProfileAttributesStorage();
Profile* profile1 = CreateProfile(kProfileDir1);
ASSERT_TRUE(profile1);
storage->GetProfileAttributesWithPath(profile1->GetPath())
->SetAuthInfo("gaia_id_1", base::UTF8ToUTF16(kProfileEmail1),
/*is_consented_primary_account=*/false);
Profile* profile2 = CreateProfile(kProfileDir2);
ASSERT_TRUE(profile2);
storage->GetProfileAttributesWithPath(profile2->GetPath())
->SetAuthInfo("gaia_id_2", base::UTF8ToUTF16(kProfileEmail2),
/*is_consented_primary_account=*/false);
base::RunLoop run_loop;
g_browser_process->FlushLocalStateAndReply(
base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); }));
run_loop.Run();
// Normal email.
size_t original_browser_count = chrome::GetTotalBrowserCount();
Relaunch(GetCommandLineForRelaunchWithEmail(kProfileEmail1));
Browser* new_browser = ui_test_utils::WaitForBrowserToOpen();
ASSERT_TRUE(new_browser);
EXPECT_EQ(new_browser->profile(), profile1);
EXPECT_EQ(original_browser_count + 1, chrome::GetTotalBrowserCount());
// Non-ASCII email.
Relaunch(GetCommandLineForRelaunchWithEmail(kProfileEmail2));
new_browser = ui_test_utils::WaitForBrowserToOpen();
ASSERT_TRUE(new_browser);
EXPECT_EQ(new_browser->profile(), profile2);
EXPECT_EQ(original_browser_count + 2, chrome::GetTotalBrowserCount());
}
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
| 41.731132 | 80 | 0.756076 | zealoussnow |
0745802cf61c83a6b3b707eb4973f77385475d5a | 836 | cpp | C++ | external/FW1FontWrapper/Source/FW1FontWrapper.cpp | CptLucky8/OpenXR-Toolkit | 82bfe926d64faa119556725ab5e8bcd2cd7dbab5 | [
"MIT"
] | 54 | 2018-12-18T01:43:15.000Z | 2022-02-13T09:37:41.000Z | external/FW1FontWrapper/Source/FW1FontWrapper.cpp | CptLucky8/OpenXR-Toolkit | 82bfe926d64faa119556725ab5e8bcd2cd7dbab5 | [
"MIT"
] | 162 | 2021-12-29T09:27:33.000Z | 2022-03-31T02:59:04.000Z | external/FW1FontWrapper/Source/FW1FontWrapper.cpp | CptLucky8/OpenXR-Toolkit | 82bfe926d64faa119556725ab5e8bcd2cd7dbab5 | [
"MIT"
] | 17 | 2018-12-16T12:16:35.000Z | 2022-02-15T18:58:01.000Z | // FW1FontWrapper.cpp
#include "FW1Precompiled.h"
#include "CFW1Factory.h"
#ifndef FW1_DELAYLOAD_DWRITE_DLL
#pragma comment (lib, "DWrite.lib")
#endif
#ifndef FW1_DELAYLOAD_D3DCOMPILER_XX_DLL
#pragma comment (lib, "DWrite.lib")
#endif
#ifdef FW1_COMPILETODLL
#ifndef _M_X64
#pragma comment (linker, "/EXPORT:FW1CreateFactory=_FW1CreateFactory@8,@1")
#endif
#endif
// Create FW1 factory
extern "C" HRESULT STDMETHODCALLTYPE FW1CreateFactory(UINT32 Version, IFW1Factory **ppFactory) {
if(Version != FW1_VERSION)
return E_FAIL;
if(ppFactory == NULL)
return E_INVALIDARG;
FW1FontWrapper::CFW1Factory *pFactory = new FW1FontWrapper::CFW1Factory;
HRESULT hResult = pFactory->initFactory();
if(FAILED(hResult)) {
pFactory->Release();
}
else {
*ppFactory = pFactory;
hResult = S_OK;
}
return hResult;
}
| 19.44186 | 96 | 0.740431 | CptLucky8 |
074aa629651f56e34920eceb191d702d723480cf | 10,284 | cpp | C++ | src/d_effect.cpp | Krzysiek-K/dxfw | ca8010fd1dc3969a5cdeee062c4ca43090b0815a | [
"BSD-4-Clause"
] | 1 | 2019-01-17T22:57:40.000Z | 2019-01-17T22:57:40.000Z | src/d_effect.cpp | Krzysiek-K/dxfw | ca8010fd1dc3969a5cdeee062c4ca43090b0815a | [
"BSD-4-Clause"
] | null | null | null | src/d_effect.cpp | Krzysiek-K/dxfw | ca8010fd1dc3969a5cdeee062c4ca43090b0815a | [
"BSD-4-Clause"
] | null | null | null |
#include "dxfw.h"
using namespace std;
using namespace base;
static bool _load_scrambled(const char *path,vector<byte> &data)
{
if(!NFS.GetFileBytes(path,data))
return false;
unsigned int key = 1716253875;
for(int i=0;i<(int)data.size();i++)
{
data[i] ^= (key>>24);
key = key*134775813 + 13;
}
return true;
}
static bool _save_scrambled(const char *path,const vector<byte> &data)
{
vector<byte> cdata = data;
if(cdata.size()<=0)
return false;
unsigned int key = 1716253875;
for(int i=0;i<(int)cdata.size();i++)
{
cdata[i] ^= (key>>24);
key = key*134775813 + 13;
}
return NFS.DumpRawVector(path,cdata);
}
// **************** DevEffect ****************
DevEffect::DevEffect(const char *path,DevEffect::DefGenerator *dg,int _flags) : fx(NULL), pool(NULL)
{
do_preload = false;
pass = -2;
def_generator = dg;
flags = _flags;
file_time = 0;
compile_flags = D3DXSHADER_AVOID_FLOW_CONTROL;
if( flags & FXF_FLOW_CONTROL_MEDIUM ) compile_flags &= ~D3DXSHADER_AVOID_FLOW_CONTROL;
if( flags & FXF_FLOW_CONTROL_HIGH ) compile_flags |= D3DXSHADER_PREFER_FLOW_CONTROL;
if( flags & FXF_PARTIAL_PRECISION ) compile_flags |= D3DXSHADER_PARTIALPRECISION;
if( flags & FXF_OPTIMIZATION_3 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL3;
else if( flags & FXF_OPTIMIZATION_0 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL0;
else if( flags & FXF_OPTIMIZATION_1 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
else if( flags & FXF_OPTIMIZATION_2 ) compile_flags |= D3DXSHADER_OPTIMIZATION_LEVEL2;
if( flags & FXF_LEGACY ) compile_flags |= D3DXSHADER_USE_LEGACY_D3DX9_31_DLL;
if(Dev.GetIsReady()) Load(path,dg);
else do_preload = true, p_path = path;
}
bool DevEffect::Load(const char *path,DevEffect::DefGenerator *dg)
{
// clear effect
ClearEffect();
file_time = GetFileTime(path);
p_path = string(path).c_str();
// load file
vector<char> data;
if(!ScrambleLoad(path,data))
return false;
// compute partial hash
MD5Hash md5;
md5.Update((byte*)&data[0],(int)data.size());
// build skip list
string skip_list;
BuildSkipList(&data[0],skip_list);
// build defines
vector<string> defs;
if(dg) dg(defs);
else defs.push_back(":");
// create pool
if(defs.size()>=2)
{
if(FAILED(D3DXCreateEffectPool(&pool)))
{
return false;
}
}
// compile
for(int i=0;i<(int)defs.size();i++)
{
vector<D3DXMACRO> macros;
vector<byte> bin;
MD5Hash hash = md5;
byte bhash[16];
// build final hash
defs[i].push_back(0);
hash.Update((byte*)&defs[i][0],(int)defs.size());
hash.Final(bhash);
// get macros
ShatterDefsList(&defs[i][0],macros);
// build binary path
string bpath = FilePathGetPart((string("shaders/")+path).c_str(),true,true,false);
if(defs[i].c_str()[0])
{
bpath += "-";
bpath += defs[i].c_str();
}
bpath += ".fxx";
// precompile effect
if(!GetPrecompiledBinary(data,defs[i].c_str(),path,bpath.c_str(),macros,bhash,bin))
return false;
if(!CompileVersion(defs[i].c_str(),path,bin,macros,skip_list.c_str()))
return false;
}
if(fx_list.size()<=0)
return false;
fx = fx_list[0];
// load textures
D3DXHANDLE h, ha;
const char *str;
int id = 0;
while( (h = fx->GetParameter(NULL,id)) )
{
ha = fx->GetAnnotationByName(h,"Load");
if(ha)
if(SUCCEEDED(fx->GetString(ha,&str)))
{
DevTexture *t = new DevTexture();
t->Load(str);
fx->SetTexture(h,t->GetTexture());
textures.push_back(t);
}
id++;
}
return true;
}
const char *DevEffect::GetTechniqueName(int id)
{
D3DXHANDLE h;
D3DXTECHNIQUE_DESC desc;
if(!fx) return NULL;
h = fx->GetTechnique(id);
if(!h) return NULL;
if(SUCCEEDED(fx->GetTechniqueDesc(h,&desc)))
return desc.Name;
return NULL;
}
const char *DevEffect::GetTechniqueInfo(const char *name,const char *param)
{
D3DXHANDLE h, ha;
const char *str;
if(!fx) return NULL;
h = fx->GetTechniqueByName(name);
if(!h) return "";
ha = fx->GetAnnotationByName(h,param);
if(!ha) return "";
if(SUCCEEDED(fx->GetString(ha,&str)))
return str;
return "";
}
bool DevEffect::SelectVersionStr(const char *version)
{
map<string,int>::iterator p = version_index.find(version);
if(p==version_index.end()) { fx = NULL; return false; }
fx = fx_list[p->second];
return true;
}
bool DevEffect::SelectVersion(int version)
{
if(version<0 || version>=(int)fx_list.size()) { fx = NULL; return false; }
fx = fx_list[version];
return true;
}
int DevEffect::GetVersionIndex(const char *version)
{
map<string,int>::iterator p = version_index.find(version);
if(p==version_index.end()) return -1;
return p->second;
}
bool DevEffect::StartTechnique(const char *name)
{
if(!fx)
return false;
if(FAILED(fx->SetTechnique(name)))
{
pass = -2;
return false;
}
pass = -1;
return true;
}
bool DevEffect::StartPass()
{
if(!fx || pass==-2)
return false;
if(pass<0) fx->Begin((UINT*)&n_passes,0);
else fx->EndPass();
pass++;
if(pass>=n_passes)
{
fx->End();
pass = -2;
return false;
}
fx->BeginPass(pass);
return true;
}
void DevEffect::OnBeforeReset()
{
for(int i=0;i<(int)fx_list.size();i++)
fx_list[i]->OnLostDevice();
}
void DevEffect::OnAfterReset()
{
for(int i=0;i<(int)fx_list.size();i++)
fx_list[i]->OnResetDevice();
}
void DevEffect::ClearEffect()
{
for(int i=0;i<(int)fx_list.size();i++)
fx_list[i]->Release();
fx_list.clear();
fx = NULL;
if(pool)
{
pool->Release();
pool = NULL;
}
version_index.clear();
do_preload = false;
pass = -2;
last_error.clear();
}
bool DevEffect::ScrambleLoad(const char *path,vector<char> &data)
{
bool scrambled = false;
if(!NFS.GetFileBytes(path,*(vector<byte>*)&data) || data.size()==0)
{
if(!_load_scrambled(format("shaders/%ss",path).c_str(),*(vector<byte>*)&data) || data.size()==0)
{
last_error = format("Can't find file %s!",path);
if(!(flags&FXF_NO_ERROR_POPUPS))
if(MessageBox(NULL,last_error.c_str(),path,MB_OKCANCEL)==IDCANCEL)
ExitProcess(0);
return false;
}
else
scrambled = true;
}
if(!scrambled)
_save_scrambled(format("shaders/%ss",path).c_str(),*(vector<byte>*)&data);
data.push_back(0);
return true;
}
void DevEffect::BuildSkipList(const char *d,string &skip_list)
{
while(*d)
{
if(d[0]=='/' && d[1]=='*' && d[2]=='$' && d[3]=='*' && d[4]=='/' && d[5]==' ')
{
const char *p = d+6;
if(skip_list.size()>0) skip_list.push_back(';');
while((*p>='a' && *p<='z') || (*p>='A' && *p<='Z') || (*p>='0' && *p<='9') || *p=='_')
skip_list.push_back(*p++);
}
d++;
}
}
void DevEffect::ShatterDefsList(char *s,vector<D3DXMACRO> ¯os)
{
// parse version identifier
const char *id = s;
while(*s && *s!=':') s++;
// parse macros
while(*s)
{
D3DXMACRO m = { NULL, NULL };
// terminate previous string
*s++ = 0;
// read name
m.Name = s;
while(*s && *s!='=') s++;
if(!*s) break;
*s++ = 0;
// read definition
m.Definition = s;
while(*s && *s!=';') s++;
macros.push_back(m);
}
// terminate macro list
D3DXMACRO m = { NULL, NULL };
macros.push_back(m);
}
bool DevEffect::GetPrecompiledBinary(
vector<char> &data, const char *id, const char *path, const char *bpath,
vector<D3DXMACRO> ¯os, byte hash[16], vector<byte> &bin)
{
ID3DXEffectCompiler *fxc = NULL;
ID3DXBuffer *binbuff = NULL;
ID3DXBuffer *errors = NULL;
if(_load_scrambled(bpath,*(vector<byte>*)&bin) && bin.size()>16)
{
if(memcmp(&bin[0],hash,16)==0)
{
bin.erase(bin.begin(),bin.begin()+16);
return true;
}
}
for(int pass=0;pass<2;pass++)
{
HRESULT r;
bool error;
if( pass == 0 )
{
r = D3DXCreateEffectCompiler(&data[0],(DWORD)data.size(),¯os[0],NULL,
compile_flags,&fxc,&errors);
error = !fxc;
}
else
{
r = fxc->CompileEffect(compile_flags,&binbuff,&errors);
error = !binbuff;
}
if(FAILED(r) || errors || error)
{
if(errors)
{
last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer());
if(!(flags&FXF_NO_ERROR_POPUPS))
if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
ExitProcess(0);
errors->Release();
if(fxc) fxc->Release();
if(binbuff) binbuff->Release();
return false;
}
else
{
last_error = format("%s:%s: Unknown error!",path,id);
if(!(flags&FXF_NO_ERROR_POPUPS))
if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
ExitProcess(0);
if(fxc) fxc->Release();
if(binbuff) binbuff->Release();
return false;
}
}
}
bin.clear();
bin.insert(bin.end(),hash,hash+16);
bin.insert(bin.end(),(byte*)binbuff->GetBufferPointer(),((byte*)binbuff->GetBufferPointer())+binbuff->GetBufferSize());
fxc->Release();
binbuff->Release();
_save_scrambled(bpath,bin);
bin.erase(bin.begin(),bin.begin()+16);
return true;
}
bool DevEffect::CompileVersion(
const char *id, const char *path, vector<byte> &bin,
vector<D3DXMACRO> ¯os, const char *skip_list )
{
ID3DXEffect *fx = NULL;
ID3DXBuffer *errors = NULL;
HRESULT r = D3DXCreateEffectEx(Dev.GetDevice(),&bin[0],(DWORD)bin.size(),¯os[0],NULL,skip_list,
compile_flags,pool,&fx,&errors);
if(FAILED(r) || errors)
{
if(errors)
{
last_error = format("%s:%s: %s",path,id,(char*)errors->GetBufferPointer());
if(!(flags&FXF_NO_ERROR_POPUPS))
if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
ExitProcess(0);
errors->Release();
return false;
}
else
{
last_error = format("%s:%s: Unknown error!",path,id);
if(!(flags&FXF_NO_ERROR_POPUPS))
if(MessageBox(NULL,last_error.c_str(),format("%s:%s",path,id).c_str(),MB_OKCANCEL)==IDCANCEL)
ExitProcess(0);
return false;
}
}
version_index[id] = (int)fx_list.size();
fx_list.push_back(fx);
return true;
}
| 22.405229 | 121 | 0.615908 | Krzysiek-K |
074aba4ac8cd17f5b576a985f4a93691da34d019 | 8,760 | cpp | C++ | game/bg_slidemove.cpp | kugelrund/Elite-Reinforce | a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca | [
"DOC"
] | 10 | 2017-07-04T14:38:48.000Z | 2022-03-08T22:46:39.000Z | game/bg_slidemove.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | null | null | null | game/bg_slidemove.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | 2 | 2017-04-23T18:24:44.000Z | 2021-11-19T23:27:03.000Z | #include "q_shared.h"
#include "bg_public.h"
#include "bg_local.h"
/*
input: origin, velocity, bounds, groundPlane, trace function
output: origin, velocity, impacts, stairup boolean
*/
/*
==================
PM_SlideMove
Returns qtrue if the velocity was clipped in some way
==================
*/
#define MAX_CLIP_PLANES 5
qboolean PM_SlideMove( qboolean gravity ) {
int bumpcount, numbumps;
vec3_t dir;
float d;
int numplanes;
vec3_t planes[MAX_CLIP_PLANES];
vec3_t primal_velocity;
vec3_t clipVelocity;
int i, j, k;
trace_t trace;
vec3_t end;
float time_left;
float into;
vec3_t endVelocity;
vec3_t endClipVelocity;
numbumps = 4;
VectorCopy (pm->ps->velocity, primal_velocity);
if ( gravity ) {
VectorCopy( pm->ps->velocity, endVelocity );
endVelocity[2] -= pm->ps->gravity * pml.frametime;
pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5;
primal_velocity[2] = endVelocity[2];
if ( pml.groundPlane ) {
// slide along the ground plane
PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal,
pm->ps->velocity, OVERCLIP );
}
}
time_left = pml.frametime;
// never turn against the ground plane
if ( pml.groundPlane ) {
numplanes = 1;
VectorCopy( pml.groundTrace.plane.normal, planes[0] );
} else {
numplanes = 0;
}
// never turn against original velocity
VectorNormalize2( pm->ps->velocity, planes[numplanes] );
numplanes++;
for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) {
// calculate position we are trying to move to
VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end );
// see if we can make it there
pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask);
if (trace.allsolid) {
// entity is completely trapped in another solid
pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration
return qtrue;
}
if (trace.fraction > 0) {
// actually covered some distance
VectorCopy (trace.endpos, pm->ps->origin);
}
if (trace.fraction == 1) {
break; // moved the entire distance
}
pm->ps->pm_flags |= PMF_BUMPED;
// save entity for contact
PM_AddTouchEnt( trace.entityNum );
time_left -= time_left * trace.fraction;
if (numplanes >= MAX_CLIP_PLANES) {
// this shouldn't really happen
VectorClear( pm->ps->velocity );
return qtrue;
}
//
// if this is the same plane we hit before, nudge velocity
// out along it, which fixes some epsilon issues with
// non-axial planes
//
for ( i = 0 ; i < numplanes ; i++ ) {
if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) {
VectorAdd( trace.plane.normal, pm->ps->velocity, pm->ps->velocity );
break;
}
}
if ( i < numplanes ) {
continue;
}
VectorCopy (trace.plane.normal, planes[numplanes]);
numplanes++;
//
// modify velocity so it parallels all of the clip planes
//
// find a plane that it enters
for ( i = 0 ; i < numplanes ; i++ ) {
into = DotProduct( pm->ps->velocity, planes[i] );
if ( into >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// see how hard we are hitting things
if ( -into > pml.impactSpeed ) {
pml.impactSpeed = -into;
}
// slide along the plane
PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP );
// slide along the plane
PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP );
// see if there is a second plane that the new move enters
for ( j = 0 ; j < numplanes ; j++ ) {
if ( j == i ) {
continue;
}
if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// try clipping the move to the plane
PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP );
PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP );
// see if it goes back into the first clip plane
if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) {
continue;
}
// slide the original velocity along the crease
CrossProduct (planes[i], planes[j], dir);
VectorNormalize( dir );
d = DotProduct( dir, pm->ps->velocity );
VectorScale( dir, d, clipVelocity );
CrossProduct (planes[i], planes[j], dir);
VectorNormalize( dir );
d = DotProduct( dir, endVelocity );
VectorScale( dir, d, endClipVelocity );
// see if there is a third plane the the new move enters
for ( k = 0 ; k < numplanes ; k++ ) {
if ( k == i || k == j ) {
continue;
}
if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// stop dead at a tripple plane interaction
VectorClear( pm->ps->velocity );
return qtrue;
}
}
// if we have fixed all interactions, try another move
VectorCopy( clipVelocity, pm->ps->velocity );
VectorCopy( endClipVelocity, endVelocity );
break;
}
}
if ( gravity ) {
VectorCopy( endVelocity, pm->ps->velocity );
}
// don't change velocity if in a timer (FIXME: is this correct?)
if ( pm->ps->pm_time ) {
VectorCopy( primal_velocity, pm->ps->velocity );
}
return ( bumpcount != 0 );
}
/*
==================
PM_StepSlideMove
==================
*/
void PM_StepSlideMove( qboolean gravity )
{
vec3_t start_o, start_v;
vec3_t down_o, down_v;
vec3_t slideMove, stepUpMove;
trace_t trace;
vec3_t up, down;
qboolean cantStepUpFwd;
VectorCopy (pm->ps->origin, start_o);
VectorCopy (pm->ps->velocity, start_v);
if ( PM_SlideMove( gravity ) == 0 ) {
return; // we got exactly where we wanted to go first try
}//else Bumped into something, see if we can step over it
//Q3Final addition...
VectorCopy(start_o, down);
down[2] -= STEPSIZE;
pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
VectorSet(up, 0, 0, 1);
// never step up when you still have up velocity
if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 ||
DotProduct(trace.plane.normal, up) < 0.7)) {
return;
}
if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] )
{//All our velocity was cancelled sliding
return;
}
VectorCopy (pm->ps->origin, down_o);
VectorCopy (pm->ps->velocity, down_v);
VectorCopy (start_o, up);
up[2] += STEPSIZE;
// test the player position if they were a stepheight higher
pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask);
if ( trace.allsolid || trace.startsolid || trace.fraction == 0) {
if ( pm->debugLevel ) {
Com_Printf("%i:bend can't step\n", c_pmove);
}
return; // can't step up
}
// try slidemove from this position
VectorCopy (trace.endpos, pm->ps->origin);
VectorCopy (start_v, pm->ps->velocity);
cantStepUpFwd = PM_SlideMove( gravity );
//compare the initial slidemove and this slidemove from a step up position
VectorSubtract( down_o, start_o, slideMove );
VectorSubtract( trace.endpos, pm->ps->origin, stepUpMove );
if ( fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared( slideMove ) > VectorLengthSquared( stepUpMove ) )
{
//slideMove was better, use it
VectorCopy (down_o, pm->ps->origin);
VectorCopy (down_v, pm->ps->velocity);
}
else
{
// push down the final amount
VectorCopy (pm->ps->origin, down);
down[2] -= STEPSIZE;
pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask);
if ( !trace.allsolid ) {
VectorCopy (trace.endpos, pm->ps->origin);
}
if ( trace.fraction < 1.0 ) {
PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP );
}
}
if(cantStepUpFwd && pm->ps->origin[2] < start_o[2] + STEPSIZE && pm->ps->origin[2] >= start_o[2])
{//We bumped into something we could not step up
pm->ps->pm_flags |= PMF_BLOCKED;
}
else
{//We did step up, clear the bumped flag
pm->ps->pm_flags &= ~PMF_BUMPED;
}
#if 0
// if the down trace can trace back to the original position directly, don't step
pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, start_o, pm->ps->clientNum, pm->tracemask);
if ( trace.fraction == 1.0 ) {
// use the original move
VectorCopy (down_o, pm->ps->origin);
VectorCopy (down_v, pm->ps->velocity);
if ( pm->debugLevel ) {
Com_Printf("%i:bend\n", c_pmove);
}
} else
#endif
{
// use the step move
float delta;
delta = pm->ps->origin[2] - start_o[2];
if ( delta > 2 ) {
if ( delta < 7 ) {
PM_AddEvent( EV_STEP_4 );
} else if ( delta < 11 ) {
PM_AddEvent( EV_STEP_8 );
} else if ( delta < 15 ) {
PM_AddEvent( EV_STEP_12 );
} else {
PM_AddEvent( EV_STEP_16 );
}
}
if ( pm->debugLevel ) {
Com_Printf("%i:stepped\n", c_pmove);
}
}
}
| 26.465257 | 134 | 0.638128 | kugelrund |
074bda5fb0986fa2c221fd1829df4b2502550247 | 9,107 | cpp | C++ | PIPS-IPM/Drivers/statgdx/p3Custom2.cpp | dRehfeldt/PIPS | 24d3ea89a0a1aa77c133cfc698a568eb685c9fdb | [
"BSD-3-Clause-LBNL"
] | 6 | 2020-10-29T15:14:14.000Z | 2021-07-14T13:31:54.000Z | PIPS-IPM/Drivers/statgdx/p3Custom2.cpp | dRehfeldt/PIPS | 24d3ea89a0a1aa77c133cfc698a568eb685c9fdb | [
"BSD-3-Clause-LBNL"
] | null | null | null | PIPS-IPM/Drivers/statgdx/p3Custom2.cpp | dRehfeldt/PIPS | 24d3ea89a0a1aa77c133cfc698a568eb685c9fdb | [
"BSD-3-Clause-LBNL"
] | 1 | 2019-02-15T16:30:44.000Z | 2019-02-15T16:30:44.000Z | /* $Id: p3Custom2.cpp 52165 2015-05-19 13:33:37Z sdirkse $
* This code is sensitive to the order of the #defines, so inlining is not OK
*/
#if defined(__linux) && ! defined(_GNU_SOURCE)
# define _GNU_SOURCE /* required for dladdr() but no desired globally */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN /* google it */
# include <windows.h>
# define snprintf _snprintf
#else
# include <unistd.h>
#endif
#if defined(__linux) || defined(__sun)
# include <dlfcn.h>
#endif
#if defined(__APPLE__)
# include <dlfcn.h>
# include <libproc.h>
#endif
#if defined(__HOS_AIX__)
# include <procinfo.h>
# include <sys/procfs.h>
# include <dlfcn.h>
# include <sys/types.h>
# include <sys/ldr.h>
#endif
#include "p3Custom2.h"
/* local use only: be sure to call with enough space for the sprintf */
static void myStrError (int n, char *buf, size_t bufSiz)
{
#if defined(_WIN32)
if (strerror_s (buf, bufSiz, n))
(void) sprintf (buf, "errno = %d", n);
#else
if (strerror_r (n, buf, bufSiz))
(void) sprintf (buf, "errno = %d", n);
#endif
} /* myStrError */
static void pchar2SS (unsigned char *ss, const char *p)
{
char *d = (char *)ss+1;
const char *s = p;
const char *end = s + 255;
while (*s && (s < end))
*d++ = *s++;
*ss = (unsigned char) (s - p);
} /* pchar2SS */
int xGetExecName (unsigned char *execName, unsigned char *msg)
{
char execBuf[4096];
char msgBuf[2048];
char tmpBuf[2048];
int rc;
*msgBuf = '\0';
rc = 8;
#if defined(__APPLE__)
{
int k;
pid_t pid = getpid();
k = proc_pidpath (pid, execBuf, sizeof(execBuf));
if (k <= 0) {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"proc_pidpath(pid=%ld) failed: %s",
(long int) pid, tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 4;
}
else
rc = 0;
}
#elif defined(__HOS_AIX__)
{
char procPath[128];
struct stat statData;
struct psinfo psinfoData;
ssize_t ssz;
pid_t pid;
int k, fd;
pid = getpid();
sprintf (procPath, "/proc/%ld/psinfo", (long int) pid);
k = stat (procPath, &statData);
if (k) { /* error */
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf), "stat(%s,...) failure: %s",
procPath, tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 4;
}
else {
fd = open (procPath, O_RDONLY);
if (fd <= 0) { /* error */
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"open(%s, O_RDONLY) failure: %s", procPath, tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 5;
}
else {
ssz = read (fd, &psinfoData, sizeof(psinfoData));
close (fd);
if (ssz < 0) { /* error */
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"reading %ld bytes of psinfoData from %s failed: %s",
sizeof(psinfoData), procPath, tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 6;
}
else {
const char *argv0;
argv0 = ((const char ***) psinfoData.pr_argv)[0][0];
if (realpath(argv0,execBuf)) /* success */
rc = 0;
else {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"realpath() failure: %s", tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 7;
}
} /* read worked OK */
} /* open worked OK */
} /* stat worked OK */
}
#elif defined(__linux)
{
ssize_t ssz;
ssz = readlink ("/proc/self/exe", execBuf, sizeof(execBuf));
if (ssz < 0) {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"readlink(/proc/self/exe,...) failure: %s", tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 4;
}
else {
if (ssz >= (ssize_t) sizeof(execBuf))
ssz = (ssize_t) sizeof(execBuf) - 1;
execBuf[ssz] = '\0';
rc = 0;
}
}
#elif defined(__sun)
{
const char *execname;
execname = getexecname();
if (NULL == execname) {
sprintf (msgBuf, "getexecname() failure");
*execBuf = '\0';
rc = 4;
}
else {
if (realpath(execname,execBuf))
rc = 0;
else {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf), "realpath() failure: %s",
tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*execBuf = '\0';
rc = 5;
}
}
}
#elif defined(_WIN32)
{
HMODULE h;
int k = GetModuleFileName (NULL, execBuf, sizeof(execBuf));
if (0 == k) {
sprintf (msgBuf, "GetModuleFileName() failure: rc=%d", k);
*execBuf = '\0';
rc = 4;
}
else
rc = 0;
}
#else
*execBuf = '\0';
(void) strcpy (msgBuf, "not implemented for this platform");
rc = 8;
#endif
pchar2SS (execName, execBuf);
pchar2SS (msg, msgBuf);
if ((0 == rc) && (strlen(execBuf) > 255))
rc = 1;
return rc;
} /* xGetExecName */
int xGetLibName (unsigned char *libName, unsigned char *msg)
{
char libBuf[4096];
char msgBuf[2048+20];
char tmpBuf[2048];
int rc, k;
*msgBuf = '\0';
rc = 8;
#if defined(__linux) || defined(__sun) || defined(__APPLE__)
{
Dl_info dlInfo;
k = dladdr((void *)(&xGetLibName), &dlInfo);
if (k > 0) {
strncpy (tmpBuf, dlInfo.dli_fname, sizeof(tmpBuf));
tmpBuf[sizeof(tmpBuf)-1] = '\0';
if (realpath(tmpBuf,libBuf))
rc = 0;
else {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
sprintf (msgBuf, "realpath() failure: %s", tmpBuf);
*libBuf = '\0';
rc = 5;
}
}
else {
sprintf (msgBuf, "dladdr() failure");
*libBuf = '\0';
rc = 4;
}
}
#elif defined(__HOS_AIX__)
{
/* some truly ugly code to get the shared library name:
* so ugly it's beautiful */
const size_t bufSize = 8192;
char buf[bufSize], *pBuf;
struct ld_info *pldi = (struct ld_info *) buf;
void *pMe, *pLo, *pUp;
k = loadquery (L_GETINFO, pldi, bufSize);
if (k) {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf), "loadquery() failure: %s",
tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*libBuf = '\0';
rc = 4;
}
else { /* loadquery OK */
int done = 0;
/* pMe = &xGetLibName; */
/* on AIX &xGetLibName is a TOC (Table-Of-Contents) pointer, must dereference
* For more on this, I found this URL helpful:
* http://physinfo.ulb.ac.be/divers_html/powerpc_programming_info/intro_to_ppc/ppc4_runtime4.html
*/
pMe = (void *) * (unsigned long *) (void *) &xGetLibName;
pBuf = buf;
while (! done) {
pLo = pldi->ldinfo_textorg;
pUp = (void *) ((char *)pLo + pldi->ldinfo_textsize);
/* printf ("DEBUG AIX dllPath: rng= [%p %p] : %s len=%ld\n",
pLo, pUp, pldi->ldinfo_filename, pldi->ldinfo_next); */
if ((pLo <= pMe) && (pMe < pUp)) {
if (realpath(pldi->ldinfo_filename,libBuf))
rc = 0;
else {
myStrError (errno, tmpBuf, sizeof(tmpBuf));
(void) snprintf (msgBuf, sizeof(msgBuf),
"realpath() failure: %s", tmpBuf);
msgBuf[sizeof(msgBuf)-1] = '\0';
*libBuf = '\0';
rc = 5;
}
done = 1;
}
if (0 == pldi->ldinfo_next)
done = 1;
else {
pBuf += pldi->ldinfo_next;
pldi = (struct ld_info *) pBuf;
}
} /* while not done */
} /* loadquery OK */
}
#elif defined(_WIN32)
{
HMODULE h;
k = GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)&xGetLibName, &h);
if (k) { /* OK: got a handle */
k = GetModuleFileName (h, libBuf, sizeof(libBuf));
if (0 == k) {
sprintf (msgBuf, "GetModuleFileName() failure: rc=%d", k);
*libBuf = '\0';
rc = 5;
}
else {
rc = 0;
}
}
else {
sprintf (msgBuf, "GetModuleHandleEx() failure: rc=%d", k);
*libBuf = '\0';
rc = 4;
}
}
#else
*libBuf = '\0';
(void) strcpy (msgBuf, "not implemented for this platform");
rc = 8;
#endif
pchar2SS (libName, libBuf);
pchar2SS (msg, msgBuf);
if ((0 == rc) && (strlen(libBuf) > 255))
rc = 1;
return rc;
} /* xGetLibName */
| 26.16954 | 103 | 0.527616 | dRehfeldt |
074ee619919e35a87faa43567db8bba57c56a062 | 747 | cpp | C++ | sorting/bubbleSort.cpp | slowy07/c-lesson | 89f3b90c75301d59f64a6659eb8da8a3f8be1582 | [
"MIT"
] | 2 | 2020-06-02T17:32:09.000Z | 2020-11-29T01:24:52.000Z | sorting/bubbleSort.cpp | slowy07/c-lesson | 89f3b90c75301d59f64a6659eb8da8a3f8be1582 | [
"MIT"
] | null | null | null | sorting/bubbleSort.cpp | slowy07/c-lesson | 89f3b90c75301d59f64a6659eb8da8a3f8be1582 | [
"MIT"
] | 2 | 2020-09-23T14:40:28.000Z | 2020-11-26T12:32:44.000Z | #include<stdio.h>
#include<iostream>
using namespace std;
void bubbleSort(int arr[], int n)
{
int i, j;
bool changed;
for (i = 0; i < n-1; i++)
{
changed = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j],arr[j+1]);
changed = true;
}
}
if (changed == false)
break;
}
}
int main()
{
int n;
cout<<"Input the total size :"<<endl;
cin>>n;
int arr[n];
cout<<"Input the number one-by-one :"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
bubbleSort(arr,n);
cout<<"Sorted array:"<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
| 16.6 | 48 | 0.433735 | slowy07 |
074ef64e1adb81315179e0c97678b58f80be9f71 | 8,342 | cpp | C++ | arimaa_com.cpp | TFiFiE/4steps | fa0830bea3187dd49d5e8ad1476a8ad29a676cdf | [
"Apache-2.0"
] | 9 | 2018-01-12T08:22:35.000Z | 2022-01-05T01:31:39.000Z | arimaa_com.cpp | TFiFiE/4steps | fa0830bea3187dd49d5e8ad1476a8ad29a676cdf | [
"Apache-2.0"
] | 4 | 2018-02-05T21:57:39.000Z | 2018-12-01T23:38:31.000Z | arimaa_com.cpp | TFiFiE/4steps | fa0830bea3187dd49d5e8ad1476a8ad29a676cdf | [
"Apache-2.0"
] | 2 | 2018-02-05T23:18:51.000Z | 2021-12-17T18:42:02.000Z | #include <QNetworkReply>
#include <QNetworkCookieJar>
#include <QNetworkCookie>
#include <QCheckBox>
#include <QDesktopServices>
#include "arimaa_com.hpp"
#include "asip1.hpp"
#include "asip2.hpp"
#include "server.hpp"
#include "io.hpp"
#include "bots.hpp"
template<class Base>
Arimaa_com<Base>::Arimaa_com(QNetworkAccessManager& networkAccessManager,const QString& serverURL,QObject* const parent,typename Base::Data startingData) :
Base(networkAccessManager,serverURL,parent,startingData),
ratedMode(true)
{
Base::connect(this,&Base::sendGameList,[this](const typename Base::GameListCategory gameListCategory,const std::vector<typename Base::GameInfo>& games) {
auto& fixedCatGames=fixedGames[gameListCategory];
fixedCatGames.clear();
const bool alreadyJoined=(gameListCategory!=Base::INVITED_GAMES && gameListCategory!=Base::OPEN_GAMES);
for (const auto& game:games) {
if (alreadyJoined || !game.rated || std::none_of(std::begin(game.players),std::end(game.players),isBotName))
fixedCatGames.emplace(game.id);
}
});
}
template<class Base>
std::unique_ptr<::ASIP> Arimaa_com<Base>::create(QNetworkAccessManager& networkAccessManager,const QString& serverURL,QObject* const parent,typename Base::Data startingData) const
{
using namespace std;
return make_unique<Arimaa_com<Base> >(networkAccessManager,serverURL,parent,startingData);
}
template<class Base>
typename Base::Data Arimaa_com<Base>::processReply(QNetworkReply& networkReply)
{
return Base::processReply(networkReply);
}
template<>
typename ASIP::Data Arimaa_com<ASIP2>::processReply(QNetworkReply& networkReply)
{
try {
return ASIP::processReply(networkReply);
}
catch (const std::exception&) {
if (networkReply.property("action")=="cancelopengame") // SERVER BUG: Cancelling with ASIP 2.0 triggers error.
return ASIP::Data({{"ok","1"}});
throw;
}
}
template<class Base>
void Arimaa_com<Base>::enterGame(QObject* const requester,const QString& gameID,const Side side,const std::function<void(QNetworkReply*)> networkReplyAction)
{
Base::enterGame(requester,gameID,side,networkReplyAction);
}
template<>
void Arimaa_com<ASIP2>::enterGame(QObject* const requester,const QString& gameID,const Side side,const std::function<void(QNetworkReply*)> networkReplyAction)
{
if (side==NO_SIDE) { // SERVER BUG: Can't spectate with ASIP 2.0.
QReadLocker readLocker(&mostRecentData_mutex);
ASIP1 asip1(networkAccessManager,serverDirectory().toString()+"client1gr.cgi",nullptr,mostRecentData);
readLocker.unlock();
asip1.enterGame(requester,gameID,side,networkReplyAction);
synchronizeData(asip1);
return;
}
else if (possiblyDerateable(gameID)) {
const auto possible=doMeDependingAction([=] {
QReadLocker readLocker(&mostRecentData_mutex);
const auto me=mostRecentData.value("me").value<QVariantHash>();
const auto sid=mostRecentData.value("sid");
readLocker.unlock();
const auto server=serverDirectory();
const auto cookieJar=networkAccessManager.cookieJar();
const auto oldCookies=cookieJar->cookiesForUrl(server);
cookieJar->setCookiesFromUrl({QNetworkCookie("unrated"+me["id"].toByteArray(),"1"),QNetworkCookie("sid",sid.toByteArray())},server);
const auto networkReply=networkAccessManager.get(QNetworkRequest(QUrl(server.toString()+"opengamewin.cgi?gameid="+gameID+"&side="+QString(toLetter(side)))));
networkReply->setParent(this);
for (const auto& cookie:cookieJar->cookiesForUrl(server))
cookieJar->deleteCookie(cookie);
cookieJar->setCookiesFromUrl(oldCookies,server);
connect(networkReply,&QNetworkReply::finished,this,[=] {
networkReply->deleteLater();
ASIP::enterGame(requester,gameID,side,networkReplyAction);
});
});
if (possible)
return;
}
ASIP::enterGame(requester,gameID,side,networkReplyAction);
}
template<class Base>
std::unique_ptr<::ASIP> Arimaa_com<Base>::getGame(QNetworkReply& networkReply)
{
return Base::getGame(networkReply);
}
template<>
std::unique_ptr<::ASIP> Arimaa_com<ASIP2>::getGame(QNetworkReply& networkReply)
{
if (networkReply.property("role")=="v" && networkReply.property("action")=="reserveseat") { // SERVER BUG: Can't spectate with ASIP 2.0.
QReadLocker readLocker(&mostRecentData_mutex);
ASIP1 asip1(networkAccessManager,serverDirectory().toString()+"client1gr.cgi",nullptr,mostRecentData);
readLocker.unlock();
asip1.processReply(networkReply);
synchronizeData(asip1);
}
else
processReply(networkReply);
QWriteLocker writeLocker(&mostRecentData_mutex);
auto gsurl=mostRecentData.value("gsurl").toString();
if (QUrl(gsurl).isRelative()) // SERVER BUG: Joining with ASIP 2.0 returns partial game server URL.
gsurl=serverDirectory().toString()+"../java/ys/ms4/v5/"+gsurl;
gsurl=QUrl(gsurl).adjusted(QUrl::RemoveFilename).toString()+"client2gs.cgi"; // SERVER BUG: Returned game server always uses ASIP 1.0.
mostRecentData.insert("gsurl",gsurl);
writeLocker.unlock();
return ASIP::getGame();
}
template<class Base>
bool Arimaa_com<Base>::possiblyDerateable(const QString& gameID) const
{
if (ratedMode)
return false;
for (const auto& category:fixedGames)
if (category.second.find(gameID)!=category.second.end())
return false;
return true;
}
template<class Base>
std::unique_ptr<QWidget> Arimaa_com<Base>::siteWidget(Server& server)
{
const auto mainLayout=new QHBoxLayout;
mainLayout->addWidget(botWidget(server.mainWindow).release());
if (std::is_same<Base,ASIP2>::value) {
const auto ratedBox=new QCheckBox("Keep joined bot games rated");
mainLayout->addWidget(ratedBox,0,Qt::AlignCenter);
ratedBox->setChecked(ratedMode);
Base::connect(ratedBox,&QCheckBox::toggled,[this](const bool checked) {ratedMode=checked;});
mainLayout->addWidget(chatroomWidget().release());
}
using namespace std;
auto widget=make_unique<QWidget>();
widget->setLayout(mainLayout);
return widget;
}
template<class Base>
bool Arimaa_com<Base>::isBotName(const QString& playerName)
{
return playerName.indexOf("bot_")==0;
}
template<class Base>
QUrl Arimaa_com<Base>::serverDirectory() const
{
return Base::serverURL().adjusted(QUrl::RemoveFilename);
}
template<class Base> template<class Function>
bool Arimaa_com<Base>::doMeDependingAction(Function action)
{
static_cast<void>(action);
return false;
}
template<> template<class Function>
bool Arimaa_com<ASIP2>::doMeDependingAction(Function action)
{
QReadLocker readLocker(&mostRecentData_mutex);
if (mostRecentData.contains("me")) {
readLocker.unlock();
action();
}
else {
readLocker.unlock();
const auto networkReplies=state();
connect(networkReplies.front(),&QNetworkReply::finished,this,[this,action] {
const QReadLocker readLocker(&mostRecentData_mutex);
action();
});
}
return true;
}
template<class Base>
std::unique_ptr<QWidget> Arimaa_com<Base>::chatroomWidget()
{
return nullptr;
}
template<>
std::unique_ptr<QWidget> Arimaa_com<ASIP2>::chatroomWidget()
{
using namespace std;
auto chatroom=make_unique<QPushButton>("Enter chat room");
connect(chatroom.get(),&QPushButton::clicked,this,[this] {
doMeDependingAction([this] {
const auto me=mostRecentData.value("me").value<QVariantHash>();
const auto url=serverDirectory().toString()+"../chat/chat.php?user="+username()+"&auth="+me["auth"].toString();
QDesktopServices::openUrl(url);
});
});
return chatroom;
}
template<class Base>
std::unique_ptr<QWidget> Arimaa_com<Base>::botWidget(MainWindow& mainWindow)
{
using namespace std;
auto bots=make_unique<QPushButton>("Bot launcher");
const auto url=serverDirectory().toString()+"botLadderAll.cgi";
Base::connect(bots.get(),&QPushButton::clicked,this,[this,url,&mainWindow] {
#if 1
new Bots(*this,url+"?u="+Base::username(),mainWindow);
#else
const bool possible=doMeDependingAction([this,url,&mainWindow] {
const auto me=Base::mostRecentData.value("me").template value<QVariantHash>();
new Bots(*this,url+"?u="+me["id"].toString(),mainWindow);
});
if (!possible)
new Bots(*this,url,mainWindow);
#endif
});
return bots;
}
template class Arimaa_com<ASIP1>;
template class Arimaa_com<ASIP2>;
| 33.502008 | 179 | 0.729921 | TFiFiE |
074fe694149040fd783f4924745efdb59c55ddfa | 413 | cpp | C++ | llvm-2.9/tools/clang/test/SemaTemplate/instantiate-expr-basic.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-2.9/tools/clang/test/SemaTemplate/instantiate-expr-basic.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-2.9/tools/clang/test/SemaTemplate/instantiate-expr-basic.cpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -std=c++0x %s
template <typename T>
struct S {
void f() {
__func__; // PredefinedExpr
10; // IntegerLiteral
10.5; // FloatingLiteral
'c'; // CharacterLiteral
"hello"; // StringLiteral
true; // CXXBooleanLiteralExpr
nullptr; // CXXNullPtrLiteralExpr
__null; // GNUNullExpr
}
};
template struct S<int>;
| 22.944444 | 64 | 0.610169 | vidkidz |
07523f5e62cb8bfa9024884c587f485ffb63e4b2 | 267 | hpp | C++ | flocking_simulation/src/engine/systems/entity/planet_mesh.hpp | jotask/Flocking-Simulation | 7607e9f100963ef11980d9f91468e22e034c94bd | [
"MIT"
] | null | null | null | flocking_simulation/src/engine/systems/entity/planet_mesh.hpp | jotask/Flocking-Simulation | 7607e9f100963ef11980d9f91468e22e034c94bd | [
"MIT"
] | null | null | null | flocking_simulation/src/engine/systems/entity/planet_mesh.hpp | jotask/Flocking-Simulation | 7607e9f100963ef11980d9f91468e22e034c94bd | [
"MIT"
] | null | null | null | #pragma once
#include "engine/systems/entity/mesh.hpp"
#include "Horde3D.h"
namespace aiko
{
class Entity;
class PlanetMesh : public Mesh
{
public:
PlanetMesh(Entity& owner);
virtual void init() override;
private:
};
} | 11.608696 | 41 | 0.614232 | jotask |
0754f28f523f0241dceb47eec5faa20c19e5dd21 | 484 | cpp | C++ | src/utils.cpp | KarateSnoopy/vcv-karatesnoopy | 4168a22c4fd90790697f8a2416472fe257153294 | [
"MIT"
] | 25 | 2017-10-26T12:44:09.000Z | 2019-11-19T16:56:05.000Z | src/utils.cpp | KarateSnoopy/vcv-snoopy | 4168a22c4fd90790697f8a2416472fe257153294 | [
"MIT"
] | 10 | 2017-10-27T06:17:58.000Z | 2021-02-05T15:42:43.000Z | src/utils.cpp | KarateSnoopy/vcv-snoopy | 4168a22c4fd90790697f8a2416472fe257153294 | [
"MIT"
] | 2 | 2017-11-09T09:06:23.000Z | 2018-03-01T00:32:33.000Z | #include "utils.h"
static long _stepCount = 0;
void log_increase_step_number()
{
_stepCount++;
}
void write_log(long freq, const char *format, ...)
{
if (freq == 0)
freq++;
if (_stepCount % freq == 0) // log every "freq". eg pass in 10000 to issue this log every 10k steps
{
va_list args;
va_start(args, format);
printf("%ld: ", _stepCount);
vprintf(format, args);
fflush(stdout);
va_end(args);
}
}
| 16.689655 | 104 | 0.566116 | KarateSnoopy |
075a3596da6b58797cace9ac32894b335d51b1f5 | 1,464 | cpp | C++ | Medusa/Medusa/Node/Action/Animation/SkeletonSlotAttachmentNameTimeline.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/Medusa/Node/Action/Animation/SkeletonSlotAttachmentNameTimeline.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/Medusa/Node/Action/Animation/SkeletonSlotAttachmentNameTimeline.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2021-06-30T14:08:03.000Z | 2021-06-30T14:08:03.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "SkeletonSlotAttachmentNameTimeline.h"
#include "Node/INode.h"
#include "Resource/Timeline/StringTimelineModel.h"
#include "Node/Skeleton/SkeletonSlot.h"
#include "Core/Log/Log.h"
MEDUSA_BEGIN;
SkeletonSlotAttachmentNameTimeline::SkeletonSlotAttachmentNameTimeline(StringTimelineModel* model, bool isRepeatForever /*= false*/)
:ITimeline(model, isRepeatForever)
{
}
SkeletonSlotAttachmentNameTimeline::~SkeletonSlotAttachmentNameTimeline()
{
}
bool SkeletonSlotAttachmentNameTimeline::Initialize(void* target)
{
RETURN_FALSE_IF_FALSE(ITimeline::Initialize(target));
INode* node = (INode*)mTarget;
if (!node->IsA<SkeletonSlot>())
{
Log::AssertFailed("SkeletonSlotAttachmentTimeline only accept target inherit from SkeletonSlot");
return false;
}
return true;
}
bool SkeletonSlotAttachmentNameTimeline::OnUpdate(float prevElapsed, float dt, float blend /*= 1.f*/)
{
StringTimelineModel* model = (StringTimelineModel*)mModel;
SkeletonSlot* slot = (SkeletonSlot*)mTarget;
StringRef slotName= slot->Name();
float time = Elapsed();
intp index = model->GetSteppedFrameIndex(time);
if (index < 0)
{
slot->SetAttachmentFromModel();
}
else
{
StringRef val = model->GetString(index);
slot->SetAttachment(val);
}
return true;
}
MEDUSA_END;
| 24.4 | 132 | 0.764344 | JamesLinus |
075c6da5785e389ddbebf04c64bf0e0eb79df09e | 640 | hpp | C++ | test/vector/vml/v_max.hpp | rigarash/monolish-debian-package | 70b4917370184bcf07378e1907c5239a1ad9579b | [
"Apache-2.0"
] | 172 | 2021-04-05T10:04:40.000Z | 2022-03-28T14:30:38.000Z | test/vector/vml/v_max.hpp | rigarash/monolish-debian-package | 70b4917370184bcf07378e1907c5239a1ad9579b | [
"Apache-2.0"
] | 96 | 2021-04-06T01:53:44.000Z | 2022-03-09T07:27:09.000Z | test/vector/vml/v_max.hpp | termoshtt/monolish | 1cba60864002b55bc666da9baa0f8c2273578e01 | [
"Apache-2.0"
] | 8 | 2021-04-05T13:21:07.000Z | 2022-03-09T23:24:06.000Z | #include "../../test_utils.hpp"
template <typename T> T ans_vmax(monolish::vector<T> &ans) {
return *(std::max_element(ans.begin(), ans.end()));
}
template <typename T> bool test_send_vmax(const size_t size, double tol) {
monolish::vector<T> x(size, 0.1, 10.0);
T ans = ans_vmax(x);
monolish::util::send(x);
T result = monolish::vml::max(x);
return ans_check<T>(__func__, result, ans, tol);
}
template <typename T> bool test_vmax(const size_t size, double tol) {
monolish::vector<T> x(size, 0.1, 10.0);
T ans = ans_vmax(x);
T result = monolish::vml::max(x);
return ans_check<T>(__func__, result, ans, tol);
}
| 22.068966 | 74 | 0.65625 | rigarash |
075d179f3323a3b75a0e8da989d723b44ae57668 | 1,489 | cpp | C++ | data/shaders/ssao.cpp | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-10-16T22:26:01.000Z | 2022-03-29T14:32:15.000Z | data/shaders/ssao.cpp | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 1 | 2015-12-08T00:27:10.000Z | 2016-10-30T21:59:50.000Z | data/shaders/ssao.cpp | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-07-18T21:42:10.000Z | 2019-12-16T01:33:20.000Z |
#pragma vertex_shader_glx2
uniform mat4 gphModelMatrix;
void main()
{
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
gl_FrontColor = gl_Color;
}
#pragma fragment_shader_glx2
uniform sampler2D gphTexture0;
uniform sampler2D gphTexture1;
uniform sampler2D gphTexture2;
vec2 rand2(vec2 co){
float d = dot(co.xy ,vec2(12.9898,78.233));
return (vec2(fract(sin(d) * 43758.5453),fract(cos(d) * 43758.5453))-vec2(0.5)) * 2.0;
}
void main()
{
float max_dist = 5.0;
float min_dist = 1.0;
vec2 uv = gl_TexCoord[0].xy;
vec4 ref_color = texture2D(gphTexture0,uv);
vec3 ref_pos = texture2D(gphTexture1,uv).xyz;
vec3 ref_nor = normalize(texture2D(gphTexture2,uv).xyz);
float max_samples = 32.0;
float r = 0.0;
vec3 m_nor = vec3(0.0);
float ssao_params = 0.1;
for(float i=0.0;i<max_samples;i+=1.0)
{
float d = mix(min_dist,max_dist,i/max_samples);
vec2 sample_uv = uv + (d * max_dist * rand2(uv*i)) / vec2(1000.0,600.0);
vec3 sample_pos = texture2D(gphTexture1,sample_uv).xyz;
vec3 dir = sample_pos - ref_pos;
float len = length(dir);
float f = dot(dir, ref_nor);
if (f > 0.05 * len)
r += f * 1.0 / (len * (1.0 + len * len * ssao_params));
}
r /= max_samples;
r = pow(1.0 - r,2.0);
gl_FragColor = vec4((vec3(0.2) + ref_color.xyz * 0.8)* r ,1.0);
}
| 22.223881 | 89 | 0.605776 | nczeroshift |
075f30d00377f3e0a27342f4fdf1ab7d5535e71b | 2,829 | cpp | C++ | Source/Objects/Shop.cpp | DrStrangelove42/DearmOfaRidiculousMan | a19af08c0a044ed4a30194ffdfac912475618b14 | [
"MIT"
] | null | null | null | Source/Objects/Shop.cpp | DrStrangelove42/DearmOfaRidiculousMan | a19af08c0a044ed4a30194ffdfac912475618b14 | [
"MIT"
] | 7 | 2020-11-20T08:57:10.000Z | 2021-03-22T20:40:04.000Z | Source/Objects/Shop.cpp | DrStrangelove42/DreamOfaRidiculousMan | a19af08c0a044ed4a30194ffdfac912475618b14 | [
"MIT"
] | null | null | null | #include "Shop.h"
//#include "../Characters/Player.h"
Shop::Shop(string id, string name, string speech, int posx, int posy, RenderContext& renderer, Map* map) :
NPC(id, name, speech, posx, posy, "shop", renderer, map, false), player(NULL)
{
}
Shop::~Shop()
{
for (auto& entry : contents)
{
delete entry.first;
}
contents.clear();
}
Shop::Shop(string headerline, int* uniqueId, int posx, int posy, RenderContext& renderer) :
Shop("", "", "", posx, posy, renderer, NULL)
{
size_t pos = headerline.find(" ");
id = headerline.substr(0, pos);
headerline.erase(0, pos + 1);
name = EatToken(headerline);
speech = EatToken(headerline);
setTexture(renderer);
// After the identifier, the items in the chest are described between brackets [ and ] with count and price, one after the other.
while (headerline.length() > 0 && headerline[0] == '[')
{
size_t nextpar = headerline.find('[', 1);
string currentObject = headerline.substr(1, nextpar - 1);
headerline.erase(0, nextpar);
nextpar = currentObject.find(']');
string objString = currentObject.substr(0, nextpar);
currentObject.erase(0, nextpar + 1);
PickableObject* obj = (PickableObject*)Map::parseObject(objString, renderer, uniqueId, -1, -1);
size_t a;
int count = stoi(currentObject, &a);
currentObject.erase(0, a + 1);
int price = stoi(currentObject);
addObjectToSell(obj, count, price);
}
buildButtons(renderer);
}
bool Shop::updateObject(GAME* g)
{
if (player == NULL)
player = g->player;
if (!isPlayerNearby(g->player))
{
g->currentMap->unregisterTopMostTexture("ShopBtnInfoTip");
}
return NPC::updateObject(g);
}
string Shop::objectToString() const
{
string text = id;
for (auto& entry : contents)
{
text += "[" + entry.first->objectToString() + "] " + to_string(entry.second.first) + " " + to_string(entry.second.second) + " ";
}
return text;
}
void Shop::buildButtons(RenderContext& r)
{
int id = 0;
for (auto& entry : contents)
{
//todo image+text
Button* b = new InfoTipButton(
r.LoadStringWithIcon("x" + to_string(entry.second.first) + " : " + to_string(entry.second.second) + " gold", entry.first->getTextureID(), 0xD39206FF),
r,
-1, -1 /*x and y will be set with addChoice()*/,
id,
[this, entry](int i)
{
if (player != NULL)
{
if (player->getMoney() >= entry.second.second)
{
//the player can buy the object
player->addMoney(-entry.second.second);
//Clone the object
PickableObject* p = entry.first->clone();
//Add the cloned object to the player
player->pickUpObject(p, entry.second.first);
}
}
},
entry.first->getInfo()
);
addChoice(b);
index.push_back(entry.first);
id++;
}
}
void Shop::addObjectToSell(PickableObject* pObj, int count, int price)
{
contents[pObj] = { count,price };
}
| 24.179487 | 153 | 0.653588 | DrStrangelove42 |
0760d04fd5fbbfcc0ef8e580bc1211275043e0e8 | 1,378 | cpp | C++ | MineGame_Lib/View/ConfigForm.cpp | xinhuang/mUI | 69d4835cdc88abafc47574471eee7bb20e67bd2f | [
"Apache-2.0"
] | 3 | 2016-02-14T03:43:40.000Z | 2018-07-26T17:05:54.000Z | MineGame_Lib/View/ConfigForm.cpp | xinhuang/mUI | 69d4835cdc88abafc47574471eee7bb20e67bd2f | [
"Apache-2.0"
] | null | null | null | MineGame_Lib/View/ConfigForm.cpp | xinhuang/mUI | 69d4835cdc88abafc47574471eee7bb20e67bd2f | [
"Apache-2.0"
] | null | null | null | #include "ConfigForm.h"
struct ConfigForm::Data
{
Label widthLabel;
Label heightLabel;
Label mineTotalLabel;
TextBox widthTextBox;
};
ConfigForm::ConfigForm()
: _d(new Data())
{
InitializeComponents();
}
ConfigForm::~ConfigForm()
{
delete _d;
}
void ConfigForm::InitializeComponents()
{
set_Size(Size(100, 70));
int gap = 3;
Controls.Add(_d->widthLabel);
_d->widthLabel.set_AutoSize(true);
_d->widthLabel.set_Text(L"Width:");
_d->widthLabel.set_Anchor(AnchorStyles::Left);
Controls.Add(_d->widthTextBox);
_d->widthTextBox.set_Location(Point(_d->widthLabel.get_Right(), _d->widthLabel.get_Location().Y));
_d->widthTextBox.set_Size(Size(get_Width() - _d->widthTextBox.get_Left() - 5, _d->widthLabel.get_Height()));
_d->widthTextBox.set_Anchor(AnchorStyles::LeftRight);
_d->widthTextBox.set_BorderStyle(FormBorderStyle::FixedSingle);
Controls.Add(_d->heightLabel);
_d->heightLabel.set_Text(L"Height:");
_d->heightLabel.set_AutoSize(true);
_d->heightLabel.set_Location(Point(0, _d->widthLabel.get_Height() + gap));
_d->heightLabel.set_Anchor(AnchorStyles::Left);
Controls.Add(_d->mineTotalLabel);
_d->mineTotalLabel.set_Text(L"Mines:");
_d->mineTotalLabel.set_AutoSize(true);
_d->mineTotalLabel.set_Location(Point(0, _d->heightLabel.get_Top() + _d->heightLabel.get_Height() + gap));
_d->mineTotalLabel.set_Anchor(AnchorStyles::Left);
}
| 27.019608 | 109 | 0.744557 | xinhuang |
076188d3b38034867405a8190c6ff683f53f0bf6 | 2,177 | cpp | C++ | ex01-09.cpp | GabrielScalici/UVA | e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f | [
"MIT"
] | null | null | null | ex01-09.cpp | GabrielScalici/UVA | e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f | [
"MIT"
] | null | null | null | ex01-09.cpp | GabrielScalici/UVA | e5a56b1ad10df8f1e3d1d6f8fd6d32348a16349f | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <queue>
#include <math.h>
#define MAX 100
#define GRANDE 100000.0
#define TAM 2
using namespace std;
int main(int argc, char const *argv[]){
double P[MAX][TAM];
int i;
int T, n;
//Pegando a quantidade
scanf("%d", &T);
//Pegsndo a quantidade de casos
scanf("%d", &n);
//Percorrendo a quantidade de casos
for(int i = 0; i < n; i++){
//pegando os valores
float num1;
scanf("%f\n", &num1);
P[i][0] = num1;
float num2;
scanf("%f\n", &num2);
P[i][1] = num2;
}
//Fazendo Dijkstra
float dist[MAX];
int arv[MAX];
memset(arv, 0, sizeof(arv));
//iniciando com uma distancia grande
for(i = 0; i < MAX; i++){
if(i == 0){
dist[i] = 0;
}else{
dist[i] = GRANDE;
}
}
//variaveis para o codigo abaixo
int aux = 0;
double total = 0;
//percorrendo enquanto for valido (nao visitado)
while(arv[aux] == 0){
arv[aux] = 1;
total = total + dist[aux];
//percorrendo n vezes para ver todos os nos
for(i = 0; i < n; i++){
if(arv[i] == 0){
//variaveis com as contas
int resul1 = pow(P[aux][0]-P[i][0],2);
int resul2 = pow(P[aux][1]-P[i][1],2);
//realizando as contas
float resul_total = sqrt(resul1 + resul2);
//analisando a dist minima
if(resul_total < dist[i]){
dist[i] = resul_total;
}
}
}
//inicia com valor grande para analise
int min = GRANDE;
//percorrendo todos os possiveis (n)
for(i = 0; i < n; i++){
if(arv[i] == 0){
if(min > dist[i]){
//atualizando o aux e o valor min
aux = i;
min = dist[i];
}
}
}
}
//imprimindo para o usuario
printf("%.2f\n",total);
return 0;
}
| 21.989899 | 58 | 0.47175 | GabrielScalici |
79e45a3459f7bccf1f06af827911d93a3425021c | 233 | cpp | C++ | 0744_find_smallest_letter_greater_than_target.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | 2 | 2020-06-04T13:20:20.000Z | 2020-06-04T14:49:10.000Z | 0744_find_smallest_letter_greater_than_target.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | null | null | null | 0744_find_smallest_letter_greater_than_target.cpp | fxshan/LeetCode | a54bbe22bc335dcb3c7efffcc34357cab7641492 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
for (int i = 0; i < letters.size(); i++) {
if ((int)target < (int)letters[i]) return letters[i];
}
return letters[0];
}
};
| 23.3 | 63 | 0.596567 | fxshan |
79ed1e5b281d02b10c8e8d7bb46485a4f357abdf | 86,647 | cc | C++ | src/app/common/proto/data.pb.cc | mloves0824/Antalk | fdca57697fb69a6e14bfc12ff2878da419aef793 | [
"MIT"
] | null | null | null | src/app/common/proto/data.pb.cc | mloves0824/Antalk | fdca57697fb69a6e14bfc12ff2878da419aef793 | [
"MIT"
] | null | null | null | src/app/common/proto/data.pb.cc | mloves0824/Antalk | fdca57697fb69a6e14bfc12ff2878da419aef793 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: data.proto
#include "data.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace antalk {
namespace data {
class GetUserInfoReqDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<GetUserInfoReq>
_instance;
} _GetUserInfoReq_default_instance_;
class GetUserInfoResDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<GetUserInfoRes>
_instance;
} _GetUserInfoRes_default_instance_;
class SetUserStatusReqDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<SetUserStatusReq>
_instance;
} _SetUserStatusReq_default_instance_;
class SetUserStatusRespDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<SetUserStatusResp>
_instance;
} _SetUserStatusResp_default_instance_;
class SaveMsgReqDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<SaveMsgReq>
_instance;
} _SaveMsgReq_default_instance_;
class SaveMsgRespDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<SaveMsgResp>
_instance;
} _SaveMsgResp_default_instance_;
} // namespace data
} // namespace antalk
namespace protobuf_data_2eproto {
void InitDefaultsGetUserInfoReqImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::antalk::data::_GetUserInfoReq_default_instance_;
new (ptr) ::antalk::data::GetUserInfoReq();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::GetUserInfoReq::InitAsDefaultInstance();
}
void InitDefaultsGetUserInfoReq() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGetUserInfoReqImpl);
}
void InitDefaultsGetUserInfoResImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_common_2eproto::InitDefaultsUserInfo();
{
void* ptr = &::antalk::data::_GetUserInfoRes_default_instance_;
new (ptr) ::antalk::data::GetUserInfoRes();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::GetUserInfoRes::InitAsDefaultInstance();
}
void InitDefaultsGetUserInfoRes() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGetUserInfoResImpl);
}
void InitDefaultsSetUserStatusReqImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::antalk::data::_SetUserStatusReq_default_instance_;
new (ptr) ::antalk::data::SetUserStatusReq();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::SetUserStatusReq::InitAsDefaultInstance();
}
void InitDefaultsSetUserStatusReq() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSetUserStatusReqImpl);
}
void InitDefaultsSetUserStatusRespImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::antalk::data::_SetUserStatusResp_default_instance_;
new (ptr) ::antalk::data::SetUserStatusResp();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::SetUserStatusResp::InitAsDefaultInstance();
}
void InitDefaultsSetUserStatusResp() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSetUserStatusRespImpl);
}
void InitDefaultsSaveMsgReqImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_common_2eproto::InitDefaultsMsgInfo();
{
void* ptr = &::antalk::data::_SaveMsgReq_default_instance_;
new (ptr) ::antalk::data::SaveMsgReq();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::SaveMsgReq::InitAsDefaultInstance();
}
void InitDefaultsSaveMsgReq() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSaveMsgReqImpl);
}
void InitDefaultsSaveMsgRespImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::antalk::data::_SaveMsgResp_default_instance_;
new (ptr) ::antalk::data::SaveMsgResp();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::antalk::data::SaveMsgResp::InitAsDefaultInstance();
}
void InitDefaultsSaveMsgResp() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSaveMsgRespImpl);
}
::google::protobuf::Metadata file_level_metadata[6];
const ::google::protobuf::ServiceDescriptor* file_level_service_descriptors[2];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, saas_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoReq, uid_),
1,
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::GetUserInfoRes, user_info_),
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, uid_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, dev_type_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, session_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, status_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusReq, login_info_),
0,
3,
1,
4,
2,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SetUserStatusResp, result_),
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgReq, msg_info_),
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, msg_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::antalk::data::SaveMsgResp, result_code_),
0,
1,
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 7, sizeof(::antalk::data::GetUserInfoReq)},
{ 9, 15, sizeof(::antalk::data::GetUserInfoRes)},
{ 16, 26, sizeof(::antalk::data::SetUserStatusReq)},
{ 31, 37, sizeof(::antalk::data::SetUserStatusResp)},
{ 38, 44, sizeof(::antalk::data::SaveMsgReq)},
{ 45, 52, sizeof(::antalk::data::SaveMsgResp)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_GetUserInfoReq_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_GetUserInfoRes_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SetUserStatusReq_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SetUserStatusResp_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SaveMsgReq_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::antalk::data::_SaveMsgResp_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"data.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, file_level_service_descriptors);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 6);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\ndata.proto\022\013antalk.data\032\014common.proto\""
".\n\016GetUserInfoReq\022\017\n\007saas_id\030\001 \001(\r\022\013\n\003ui"
"d\030\002 \001(\t\"<\n\016GetUserInfoRes\022*\n\tuser_info\030\001"
" \001(\0132\027.antalk.common.UserInfo\"f\n\020SetUser"
"StatusReq\022\013\n\003uid\030\001 \001(\t\022\020\n\010dev_type\030\002 \001(\005"
"\022\017\n\007session\030\003 \001(\t\022\016\n\006status\030\004 \001(\005\022\022\n\nlog"
"in_info\030\005 \001(\t\">\n\021SetUserStatusResp\022)\n\006re"
"sult\030\001 \001(\0162\031.antalk.common.ResultType\"6\n"
"\nSaveMsgReq\022(\n\010msg_info\030\001 \001(\0132\026.antalk.c"
"ommon.MsgInfo\"M\n\013SaveMsgResp\022\016\n\006msg_id\030\001"
" \001(\003\022.\n\013result_code\030\002 \001(\0162\031.antalk.commo"
"n.ResultType2\254\001\n\021UserStatusService\022G\n\013Ge"
"tUserInfo\022\033.antalk.data.GetUserInfoReq\032\033"
".antalk.data.GetUserInfoRes\022N\n\rSetUserSt"
"atus\022\035.antalk.data.SetUserStatusReq\032\036.an"
"talk.data.SetUserStatusResp2J\n\nMsgServic"
"e\022<\n\007SaveMsg\022\027.antalk.data.SaveMsgReq\032\030."
"antalk.data.SaveMsgRespB\022\n\rcom.antalk.pb"
"\200\001\001"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 723);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"data.proto", &protobuf_RegisterTypes);
::protobuf_common_2eproto::AddDescriptors();
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_data_2eproto
namespace antalk {
namespace data {
// ===================================================================
void GetUserInfoReq::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GetUserInfoReq::kSaasIdFieldNumber;
const int GetUserInfoReq::kUidFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GetUserInfoReq::GetUserInfoReq()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsGetUserInfoReq();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.GetUserInfoReq)
}
GetUserInfoReq::GetUserInfoReq(const GetUserInfoReq& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_uid()) {
uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_);
}
saas_id_ = from.saas_id_;
// @@protoc_insertion_point(copy_constructor:antalk.data.GetUserInfoReq)
}
void GetUserInfoReq::SharedCtor() {
_cached_size_ = 0;
uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
saas_id_ = 0u;
}
GetUserInfoReq::~GetUserInfoReq() {
// @@protoc_insertion_point(destructor:antalk.data.GetUserInfoReq)
SharedDtor();
}
void GetUserInfoReq::SharedDtor() {
uid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void GetUserInfoReq::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* GetUserInfoReq::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const GetUserInfoReq& GetUserInfoReq::default_instance() {
::protobuf_data_2eproto::InitDefaultsGetUserInfoReq();
return *internal_default_instance();
}
GetUserInfoReq* GetUserInfoReq::New(::google::protobuf::Arena* arena) const {
GetUserInfoReq* n = new GetUserInfoReq;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void GetUserInfoReq::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.GetUserInfoReq)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!uid_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*uid_.UnsafeRawStringPointer())->clear();
}
saas_id_ = 0u;
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool GetUserInfoReq::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.GetUserInfoReq)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional uint32 saas_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_saas_id();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &saas_id_)));
} else {
goto handle_unusual;
}
break;
}
// optional string uid = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_uid()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::PARSE,
"antalk.data.GetUserInfoReq.uid");
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.GetUserInfoReq)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.GetUserInfoReq)
return false;
#undef DO_
}
void GetUserInfoReq::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.GetUserInfoReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional uint32 saas_id = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->saas_id(), output);
}
// optional string uid = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.GetUserInfoReq.uid");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->uid(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.GetUserInfoReq)
}
::google::protobuf::uint8* GetUserInfoReq::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.GetUserInfoReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional uint32 saas_id = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->saas_id(), target);
}
// optional string uid = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.GetUserInfoReq.uid");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->uid(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.GetUserInfoReq)
return target;
}
size_t GetUserInfoReq::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.GetUserInfoReq)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 3u) {
// optional string uid = 2;
if (has_uid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->uid());
}
// optional uint32 saas_id = 1;
if (has_saas_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->saas_id());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void GetUserInfoReq::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.GetUserInfoReq)
GOOGLE_DCHECK_NE(&from, this);
const GetUserInfoReq* source =
::google::protobuf::internal::DynamicCastToGenerated<const GetUserInfoReq>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.GetUserInfoReq)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.GetUserInfoReq)
MergeFrom(*source);
}
}
void GetUserInfoReq::MergeFrom(const GetUserInfoReq& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.GetUserInfoReq)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
set_has_uid();
uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_);
}
if (cached_has_bits & 0x00000002u) {
saas_id_ = from.saas_id_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void GetUserInfoReq::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.GetUserInfoReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GetUserInfoReq::CopyFrom(const GetUserInfoReq& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.GetUserInfoReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GetUserInfoReq::IsInitialized() const {
return true;
}
void GetUserInfoReq::Swap(GetUserInfoReq* other) {
if (other == this) return;
InternalSwap(other);
}
void GetUserInfoReq::InternalSwap(GetUserInfoReq* other) {
using std::swap;
uid_.Swap(&other->uid_);
swap(saas_id_, other->saas_id_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GetUserInfoReq::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void GetUserInfoRes::InitAsDefaultInstance() {
::antalk::data::_GetUserInfoRes_default_instance_._instance.get_mutable()->user_info_ = const_cast< ::antalk::common::UserInfo*>(
::antalk::common::UserInfo::internal_default_instance());
}
void GetUserInfoRes::clear_user_info() {
if (user_info_ != NULL) user_info_->Clear();
clear_has_user_info();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GetUserInfoRes::kUserInfoFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GetUserInfoRes::GetUserInfoRes()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsGetUserInfoRes();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.GetUserInfoRes)
}
GetUserInfoRes::GetUserInfoRes(const GetUserInfoRes& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_user_info()) {
user_info_ = new ::antalk::common::UserInfo(*from.user_info_);
} else {
user_info_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:antalk.data.GetUserInfoRes)
}
void GetUserInfoRes::SharedCtor() {
_cached_size_ = 0;
user_info_ = NULL;
}
GetUserInfoRes::~GetUserInfoRes() {
// @@protoc_insertion_point(destructor:antalk.data.GetUserInfoRes)
SharedDtor();
}
void GetUserInfoRes::SharedDtor() {
if (this != internal_default_instance()) delete user_info_;
}
void GetUserInfoRes::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* GetUserInfoRes::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const GetUserInfoRes& GetUserInfoRes::default_instance() {
::protobuf_data_2eproto::InitDefaultsGetUserInfoRes();
return *internal_default_instance();
}
GetUserInfoRes* GetUserInfoRes::New(::google::protobuf::Arena* arena) const {
GetUserInfoRes* n = new GetUserInfoRes;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void GetUserInfoRes::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.GetUserInfoRes)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(user_info_ != NULL);
user_info_->Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool GetUserInfoRes::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.GetUserInfoRes)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .antalk.common.UserInfo user_info = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_user_info()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.GetUserInfoRes)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.GetUserInfoRes)
return false;
#undef DO_
}
void GetUserInfoRes::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.GetUserInfoRes)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.UserInfo user_info = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->user_info_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.GetUserInfoRes)
}
::google::protobuf::uint8* GetUserInfoRes::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.GetUserInfoRes)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.UserInfo user_info = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, *this->user_info_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.GetUserInfoRes)
return target;
}
size_t GetUserInfoRes::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.GetUserInfoRes)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// optional .antalk.common.UserInfo user_info = 1;
if (has_user_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->user_info_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void GetUserInfoRes::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.GetUserInfoRes)
GOOGLE_DCHECK_NE(&from, this);
const GetUserInfoRes* source =
::google::protobuf::internal::DynamicCastToGenerated<const GetUserInfoRes>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.GetUserInfoRes)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.GetUserInfoRes)
MergeFrom(*source);
}
}
void GetUserInfoRes::MergeFrom(const GetUserInfoRes& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.GetUserInfoRes)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_user_info()) {
mutable_user_info()->::antalk::common::UserInfo::MergeFrom(from.user_info());
}
}
void GetUserInfoRes::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.GetUserInfoRes)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void GetUserInfoRes::CopyFrom(const GetUserInfoRes& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.GetUserInfoRes)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool GetUserInfoRes::IsInitialized() const {
return true;
}
void GetUserInfoRes::Swap(GetUserInfoRes* other) {
if (other == this) return;
InternalSwap(other);
}
void GetUserInfoRes::InternalSwap(GetUserInfoRes* other) {
using std::swap;
swap(user_info_, other->user_info_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata GetUserInfoRes::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void SetUserStatusReq::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SetUserStatusReq::kUidFieldNumber;
const int SetUserStatusReq::kDevTypeFieldNumber;
const int SetUserStatusReq::kSessionFieldNumber;
const int SetUserStatusReq::kStatusFieldNumber;
const int SetUserStatusReq::kLoginInfoFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SetUserStatusReq::SetUserStatusReq()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsSetUserStatusReq();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.SetUserStatusReq)
}
SetUserStatusReq::SetUserStatusReq(const SetUserStatusReq& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_uid()) {
uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_);
}
session_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_session()) {
session_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.session_);
}
login_info_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_login_info()) {
login_info_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.login_info_);
}
::memcpy(&dev_type_, &from.dev_type_,
static_cast<size_t>(reinterpret_cast<char*>(&status_) -
reinterpret_cast<char*>(&dev_type_)) + sizeof(status_));
// @@protoc_insertion_point(copy_constructor:antalk.data.SetUserStatusReq)
}
void SetUserStatusReq::SharedCtor() {
_cached_size_ = 0;
uid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
session_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
login_info_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&dev_type_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&status_) -
reinterpret_cast<char*>(&dev_type_)) + sizeof(status_));
}
SetUserStatusReq::~SetUserStatusReq() {
// @@protoc_insertion_point(destructor:antalk.data.SetUserStatusReq)
SharedDtor();
}
void SetUserStatusReq::SharedDtor() {
uid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
session_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
login_info_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void SetUserStatusReq::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SetUserStatusReq::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SetUserStatusReq& SetUserStatusReq::default_instance() {
::protobuf_data_2eproto::InitDefaultsSetUserStatusReq();
return *internal_default_instance();
}
SetUserStatusReq* SetUserStatusReq::New(::google::protobuf::Arena* arena) const {
SetUserStatusReq* n = new SetUserStatusReq;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SetUserStatusReq::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.SetUserStatusReq)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 7u) {
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!uid_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*uid_.UnsafeRawStringPointer())->clear();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(!session_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*session_.UnsafeRawStringPointer())->clear();
}
if (cached_has_bits & 0x00000004u) {
GOOGLE_DCHECK(!login_info_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*login_info_.UnsafeRawStringPointer())->clear();
}
}
if (cached_has_bits & 24u) {
::memset(&dev_type_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&status_) -
reinterpret_cast<char*>(&dev_type_)) + sizeof(status_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool SetUserStatusReq::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.SetUserStatusReq)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string uid = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_uid()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::PARSE,
"antalk.data.SetUserStatusReq.uid");
} else {
goto handle_unusual;
}
break;
}
// optional int32 dev_type = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_dev_type();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &dev_type_)));
} else {
goto handle_unusual;
}
break;
}
// optional string session = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_session()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->session().data(), static_cast<int>(this->session().length()),
::google::protobuf::internal::WireFormat::PARSE,
"antalk.data.SetUserStatusReq.session");
} else {
goto handle_unusual;
}
break;
}
// optional int32 status = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_status();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &status_)));
} else {
goto handle_unusual;
}
break;
}
// optional string login_info = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_login_info()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->login_info().data(), static_cast<int>(this->login_info().length()),
::google::protobuf::internal::WireFormat::PARSE,
"antalk.data.SetUserStatusReq.login_info");
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.SetUserStatusReq)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.SetUserStatusReq)
return false;
#undef DO_
}
void SetUserStatusReq::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.SetUserStatusReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional string uid = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.uid");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->uid(), output);
}
// optional int32 dev_type = 2;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->dev_type(), output);
}
// optional string session = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->session().data(), static_cast<int>(this->session().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.session");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->session(), output);
}
// optional int32 status = 4;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(4, this->status(), output);
}
// optional string login_info = 5;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->login_info().data(), static_cast<int>(this->login_info().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.login_info");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
5, this->login_info(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.SetUserStatusReq)
}
::google::protobuf::uint8* SetUserStatusReq::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.SetUserStatusReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional string uid = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->uid().data(), static_cast<int>(this->uid().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.uid");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->uid(), target);
}
// optional int32 dev_type = 2;
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->dev_type(), target);
}
// optional string session = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->session().data(), static_cast<int>(this->session().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.session");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
3, this->session(), target);
}
// optional int32 status = 4;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(4, this->status(), target);
}
// optional string login_info = 5;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->login_info().data(), static_cast<int>(this->login_info().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"antalk.data.SetUserStatusReq.login_info");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
5, this->login_info(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.SetUserStatusReq)
return target;
}
size_t SetUserStatusReq::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.SetUserStatusReq)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 31u) {
// optional string uid = 1;
if (has_uid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->uid());
}
// optional string session = 3;
if (has_session()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->session());
}
// optional string login_info = 5;
if (has_login_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->login_info());
}
// optional int32 dev_type = 2;
if (has_dev_type()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->dev_type());
}
// optional int32 status = 4;
if (has_status()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->status());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SetUserStatusReq::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SetUserStatusReq)
GOOGLE_DCHECK_NE(&from, this);
const SetUserStatusReq* source =
::google::protobuf::internal::DynamicCastToGenerated<const SetUserStatusReq>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SetUserStatusReq)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SetUserStatusReq)
MergeFrom(*source);
}
}
void SetUserStatusReq::MergeFrom(const SetUserStatusReq& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SetUserStatusReq)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 31u) {
if (cached_has_bits & 0x00000001u) {
set_has_uid();
uid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.uid_);
}
if (cached_has_bits & 0x00000002u) {
set_has_session();
session_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.session_);
}
if (cached_has_bits & 0x00000004u) {
set_has_login_info();
login_info_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.login_info_);
}
if (cached_has_bits & 0x00000008u) {
dev_type_ = from.dev_type_;
}
if (cached_has_bits & 0x00000010u) {
status_ = from.status_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void SetUserStatusReq::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SetUserStatusReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SetUserStatusReq::CopyFrom(const SetUserStatusReq& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SetUserStatusReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetUserStatusReq::IsInitialized() const {
return true;
}
void SetUserStatusReq::Swap(SetUserStatusReq* other) {
if (other == this) return;
InternalSwap(other);
}
void SetUserStatusReq::InternalSwap(SetUserStatusReq* other) {
using std::swap;
uid_.Swap(&other->uid_);
session_.Swap(&other->session_);
login_info_.Swap(&other->login_info_);
swap(dev_type_, other->dev_type_);
swap(status_, other->status_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SetUserStatusReq::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void SetUserStatusResp::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SetUserStatusResp::kResultFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SetUserStatusResp::SetUserStatusResp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsSetUserStatusResp();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.SetUserStatusResp)
}
SetUserStatusResp::SetUserStatusResp(const SetUserStatusResp& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
result_ = from.result_;
// @@protoc_insertion_point(copy_constructor:antalk.data.SetUserStatusResp)
}
void SetUserStatusResp::SharedCtor() {
_cached_size_ = 0;
result_ = 0;
}
SetUserStatusResp::~SetUserStatusResp() {
// @@protoc_insertion_point(destructor:antalk.data.SetUserStatusResp)
SharedDtor();
}
void SetUserStatusResp::SharedDtor() {
}
void SetUserStatusResp::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SetUserStatusResp::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SetUserStatusResp& SetUserStatusResp::default_instance() {
::protobuf_data_2eproto::InitDefaultsSetUserStatusResp();
return *internal_default_instance();
}
SetUserStatusResp* SetUserStatusResp::New(::google::protobuf::Arena* arena) const {
SetUserStatusResp* n = new SetUserStatusResp;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SetUserStatusResp::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.SetUserStatusResp)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
result_ = 0;
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool SetUserStatusResp::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.SetUserStatusResp)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .antalk.common.ResultType result = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
if (::antalk::common::ResultType_IsValid(value)) {
set_result(static_cast< ::antalk::common::ResultType >(value));
} else {
mutable_unknown_fields()->AddVarint(
1, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.SetUserStatusResp)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.SetUserStatusResp)
return false;
#undef DO_
}
void SetUserStatusResp::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.SetUserStatusResp)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.ResultType result = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
1, this->result(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.SetUserStatusResp)
}
::google::protobuf::uint8* SetUserStatusResp::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.SetUserStatusResp)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.ResultType result = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
1, this->result(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.SetUserStatusResp)
return target;
}
size_t SetUserStatusResp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.SetUserStatusResp)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// optional .antalk.common.ResultType result = 1;
if (has_result()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->result());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SetUserStatusResp::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SetUserStatusResp)
GOOGLE_DCHECK_NE(&from, this);
const SetUserStatusResp* source =
::google::protobuf::internal::DynamicCastToGenerated<const SetUserStatusResp>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SetUserStatusResp)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SetUserStatusResp)
MergeFrom(*source);
}
}
void SetUserStatusResp::MergeFrom(const SetUserStatusResp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SetUserStatusResp)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_result()) {
set_result(from.result());
}
}
void SetUserStatusResp::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SetUserStatusResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SetUserStatusResp::CopyFrom(const SetUserStatusResp& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SetUserStatusResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SetUserStatusResp::IsInitialized() const {
return true;
}
void SetUserStatusResp::Swap(SetUserStatusResp* other) {
if (other == this) return;
InternalSwap(other);
}
void SetUserStatusResp::InternalSwap(SetUserStatusResp* other) {
using std::swap;
swap(result_, other->result_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SetUserStatusResp::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void SaveMsgReq::InitAsDefaultInstance() {
::antalk::data::_SaveMsgReq_default_instance_._instance.get_mutable()->msg_info_ = const_cast< ::antalk::common::MsgInfo*>(
::antalk::common::MsgInfo::internal_default_instance());
}
void SaveMsgReq::clear_msg_info() {
if (msg_info_ != NULL) msg_info_->Clear();
clear_has_msg_info();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SaveMsgReq::kMsgInfoFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SaveMsgReq::SaveMsgReq()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsSaveMsgReq();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.SaveMsgReq)
}
SaveMsgReq::SaveMsgReq(const SaveMsgReq& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_msg_info()) {
msg_info_ = new ::antalk::common::MsgInfo(*from.msg_info_);
} else {
msg_info_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:antalk.data.SaveMsgReq)
}
void SaveMsgReq::SharedCtor() {
_cached_size_ = 0;
msg_info_ = NULL;
}
SaveMsgReq::~SaveMsgReq() {
// @@protoc_insertion_point(destructor:antalk.data.SaveMsgReq)
SharedDtor();
}
void SaveMsgReq::SharedDtor() {
if (this != internal_default_instance()) delete msg_info_;
}
void SaveMsgReq::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SaveMsgReq::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SaveMsgReq& SaveMsgReq::default_instance() {
::protobuf_data_2eproto::InitDefaultsSaveMsgReq();
return *internal_default_instance();
}
SaveMsgReq* SaveMsgReq::New(::google::protobuf::Arena* arena) const {
SaveMsgReq* n = new SaveMsgReq;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SaveMsgReq::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.SaveMsgReq)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(msg_info_ != NULL);
msg_info_->Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool SaveMsgReq::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.SaveMsgReq)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .antalk.common.MsgInfo msg_info = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_msg_info()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.SaveMsgReq)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.SaveMsgReq)
return false;
#undef DO_
}
void SaveMsgReq::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.SaveMsgReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.MsgInfo msg_info = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->msg_info_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.SaveMsgReq)
}
::google::protobuf::uint8* SaveMsgReq::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.SaveMsgReq)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .antalk.common.MsgInfo msg_info = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, *this->msg_info_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.SaveMsgReq)
return target;
}
size_t SaveMsgReq::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.SaveMsgReq)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// optional .antalk.common.MsgInfo msg_info = 1;
if (has_msg_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->msg_info_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SaveMsgReq::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SaveMsgReq)
GOOGLE_DCHECK_NE(&from, this);
const SaveMsgReq* source =
::google::protobuf::internal::DynamicCastToGenerated<const SaveMsgReq>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SaveMsgReq)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SaveMsgReq)
MergeFrom(*source);
}
}
void SaveMsgReq::MergeFrom(const SaveMsgReq& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SaveMsgReq)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_msg_info()) {
mutable_msg_info()->::antalk::common::MsgInfo::MergeFrom(from.msg_info());
}
}
void SaveMsgReq::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SaveMsgReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SaveMsgReq::CopyFrom(const SaveMsgReq& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SaveMsgReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SaveMsgReq::IsInitialized() const {
return true;
}
void SaveMsgReq::Swap(SaveMsgReq* other) {
if (other == this) return;
InternalSwap(other);
}
void SaveMsgReq::InternalSwap(SaveMsgReq* other) {
using std::swap;
swap(msg_info_, other->msg_info_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SaveMsgReq::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void SaveMsgResp::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SaveMsgResp::kMsgIdFieldNumber;
const int SaveMsgResp::kResultCodeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SaveMsgResp::SaveMsgResp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_data_2eproto::InitDefaultsSaveMsgResp();
}
SharedCtor();
// @@protoc_insertion_point(constructor:antalk.data.SaveMsgResp)
}
SaveMsgResp::SaveMsgResp(const SaveMsgResp& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&msg_id_, &from.msg_id_,
static_cast<size_t>(reinterpret_cast<char*>(&result_code_) -
reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_));
// @@protoc_insertion_point(copy_constructor:antalk.data.SaveMsgResp)
}
void SaveMsgResp::SharedCtor() {
_cached_size_ = 0;
::memset(&msg_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&result_code_) -
reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_));
}
SaveMsgResp::~SaveMsgResp() {
// @@protoc_insertion_point(destructor:antalk.data.SaveMsgResp)
SharedDtor();
}
void SaveMsgResp::SharedDtor() {
}
void SaveMsgResp::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SaveMsgResp::descriptor() {
::protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SaveMsgResp& SaveMsgResp::default_instance() {
::protobuf_data_2eproto::InitDefaultsSaveMsgResp();
return *internal_default_instance();
}
SaveMsgResp* SaveMsgResp::New(::google::protobuf::Arena* arena) const {
SaveMsgResp* n = new SaveMsgResp;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SaveMsgResp::Clear() {
// @@protoc_insertion_point(message_clear_start:antalk.data.SaveMsgResp)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
::memset(&msg_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&result_code_) -
reinterpret_cast<char*>(&msg_id_)) + sizeof(result_code_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool SaveMsgResp::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:antalk.data.SaveMsgResp)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int64 msg_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_msg_id();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &msg_id_)));
} else {
goto handle_unusual;
}
break;
}
// optional .antalk.common.ResultType result_code = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
if (::antalk::common::ResultType_IsValid(value)) {
set_result_code(static_cast< ::antalk::common::ResultType >(value));
} else {
mutable_unknown_fields()->AddVarint(
2, static_cast< ::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:antalk.data.SaveMsgResp)
return true;
failure:
// @@protoc_insertion_point(parse_failure:antalk.data.SaveMsgResp)
return false;
#undef DO_
}
void SaveMsgResp::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:antalk.data.SaveMsgResp)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional int64 msg_id = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->msg_id(), output);
}
// optional .antalk.common.ResultType result_code = 2;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
2, this->result_code(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:antalk.data.SaveMsgResp)
}
::google::protobuf::uint8* SaveMsgResp::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:antalk.data.SaveMsgResp)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional int64 msg_id = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->msg_id(), target);
}
// optional .antalk.common.ResultType result_code = 2;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
2, this->result_code(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:antalk.data.SaveMsgResp)
return target;
}
size_t SaveMsgResp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:antalk.data.SaveMsgResp)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (_has_bits_[0 / 32] & 3u) {
// optional int64 msg_id = 1;
if (has_msg_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->msg_id());
}
// optional .antalk.common.ResultType result_code = 2;
if (has_result_code()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->result_code());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SaveMsgResp::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:antalk.data.SaveMsgResp)
GOOGLE_DCHECK_NE(&from, this);
const SaveMsgResp* source =
::google::protobuf::internal::DynamicCastToGenerated<const SaveMsgResp>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:antalk.data.SaveMsgResp)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:antalk.data.SaveMsgResp)
MergeFrom(*source);
}
}
void SaveMsgResp::MergeFrom(const SaveMsgResp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:antalk.data.SaveMsgResp)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
msg_id_ = from.msg_id_;
}
if (cached_has_bits & 0x00000002u) {
result_code_ = from.result_code_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void SaveMsgResp::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:antalk.data.SaveMsgResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SaveMsgResp::CopyFrom(const SaveMsgResp& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:antalk.data.SaveMsgResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SaveMsgResp::IsInitialized() const {
return true;
}
void SaveMsgResp::Swap(SaveMsgResp* other) {
if (other == this) return;
InternalSwap(other);
}
void SaveMsgResp::InternalSwap(SaveMsgResp* other) {
using std::swap;
swap(msg_id_, other->msg_id_);
swap(result_code_, other->result_code_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SaveMsgResp::GetMetadata() const {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_data_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
UserStatusService::~UserStatusService() {}
const ::google::protobuf::ServiceDescriptor* UserStatusService::descriptor() {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_data_2eproto::file_level_service_descriptors[0];
}
const ::google::protobuf::ServiceDescriptor* UserStatusService::GetDescriptor() {
return descriptor();
}
void UserStatusService::GetUserInfo(::google::protobuf::RpcController* controller,
const ::antalk::data::GetUserInfoReq*,
::antalk::data::GetUserInfoRes*,
::google::protobuf::Closure* done) {
controller->SetFailed("Method GetUserInfo() not implemented.");
done->Run();
}
void UserStatusService::SetUserStatus(::google::protobuf::RpcController* controller,
const ::antalk::data::SetUserStatusReq*,
::antalk::data::SetUserStatusResp*,
::google::protobuf::Closure* done) {
controller->SetFailed("Method SetUserStatus() not implemented.");
done->Run();
}
void UserStatusService::CallMethod(const ::google::protobuf::MethodDescriptor* method,
::google::protobuf::RpcController* controller,
const ::google::protobuf::Message* request,
::google::protobuf::Message* response,
::google::protobuf::Closure* done) {
GOOGLE_DCHECK_EQ(method->service(), protobuf_data_2eproto::file_level_service_descriptors[0]);
switch(method->index()) {
case 0:
GetUserInfo(controller,
::google::protobuf::down_cast<const ::antalk::data::GetUserInfoReq*>(request),
::google::protobuf::down_cast< ::antalk::data::GetUserInfoRes*>(response),
done);
break;
case 1:
SetUserStatus(controller,
::google::protobuf::down_cast<const ::antalk::data::SetUserStatusReq*>(request),
::google::protobuf::down_cast< ::antalk::data::SetUserStatusResp*>(response),
done);
break;
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
break;
}
}
const ::google::protobuf::Message& UserStatusService::GetRequestPrototype(
const ::google::protobuf::MethodDescriptor* method) const {
GOOGLE_DCHECK_EQ(method->service(), descriptor());
switch(method->index()) {
case 0:
return ::antalk::data::GetUserInfoReq::default_instance();
case 1:
return ::antalk::data::SetUserStatusReq::default_instance();
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
return *::google::protobuf::MessageFactory::generated_factory()
->GetPrototype(method->input_type());
}
}
const ::google::protobuf::Message& UserStatusService::GetResponsePrototype(
const ::google::protobuf::MethodDescriptor* method) const {
GOOGLE_DCHECK_EQ(method->service(), descriptor());
switch(method->index()) {
case 0:
return ::antalk::data::GetUserInfoRes::default_instance();
case 1:
return ::antalk::data::SetUserStatusResp::default_instance();
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
return *::google::protobuf::MessageFactory::generated_factory()
->GetPrototype(method->output_type());
}
}
UserStatusService_Stub::UserStatusService_Stub(::google::protobuf::RpcChannel* channel)
: channel_(channel), owns_channel_(false) {}
UserStatusService_Stub::UserStatusService_Stub(
::google::protobuf::RpcChannel* channel,
::google::protobuf::Service::ChannelOwnership ownership)
: channel_(channel),
owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}
UserStatusService_Stub::~UserStatusService_Stub() {
if (owns_channel_) delete channel_;
}
void UserStatusService_Stub::GetUserInfo(::google::protobuf::RpcController* controller,
const ::antalk::data::GetUserInfoReq* request,
::antalk::data::GetUserInfoRes* response,
::google::protobuf::Closure* done) {
channel_->CallMethod(descriptor()->method(0),
controller, request, response, done);
}
void UserStatusService_Stub::SetUserStatus(::google::protobuf::RpcController* controller,
const ::antalk::data::SetUserStatusReq* request,
::antalk::data::SetUserStatusResp* response,
::google::protobuf::Closure* done) {
channel_->CallMethod(descriptor()->method(1),
controller, request, response, done);
}
// ===================================================================
MsgService::~MsgService() {}
const ::google::protobuf::ServiceDescriptor* MsgService::descriptor() {
protobuf_data_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_data_2eproto::file_level_service_descriptors[1];
}
const ::google::protobuf::ServiceDescriptor* MsgService::GetDescriptor() {
return descriptor();
}
void MsgService::SaveMsg(::google::protobuf::RpcController* controller,
const ::antalk::data::SaveMsgReq*,
::antalk::data::SaveMsgResp*,
::google::protobuf::Closure* done) {
controller->SetFailed("Method SaveMsg() not implemented.");
done->Run();
}
void MsgService::CallMethod(const ::google::protobuf::MethodDescriptor* method,
::google::protobuf::RpcController* controller,
const ::google::protobuf::Message* request,
::google::protobuf::Message* response,
::google::protobuf::Closure* done) {
GOOGLE_DCHECK_EQ(method->service(), protobuf_data_2eproto::file_level_service_descriptors[1]);
switch(method->index()) {
case 0:
SaveMsg(controller,
::google::protobuf::down_cast<const ::antalk::data::SaveMsgReq*>(request),
::google::protobuf::down_cast< ::antalk::data::SaveMsgResp*>(response),
done);
break;
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
break;
}
}
const ::google::protobuf::Message& MsgService::GetRequestPrototype(
const ::google::protobuf::MethodDescriptor* method) const {
GOOGLE_DCHECK_EQ(method->service(), descriptor());
switch(method->index()) {
case 0:
return ::antalk::data::SaveMsgReq::default_instance();
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
return *::google::protobuf::MessageFactory::generated_factory()
->GetPrototype(method->input_type());
}
}
const ::google::protobuf::Message& MsgService::GetResponsePrototype(
const ::google::protobuf::MethodDescriptor* method) const {
GOOGLE_DCHECK_EQ(method->service(), descriptor());
switch(method->index()) {
case 0:
return ::antalk::data::SaveMsgResp::default_instance();
default:
GOOGLE_LOG(FATAL) << "Bad method index; this should never happen.";
return *::google::protobuf::MessageFactory::generated_factory()
->GetPrototype(method->output_type());
}
}
MsgService_Stub::MsgService_Stub(::google::protobuf::RpcChannel* channel)
: channel_(channel), owns_channel_(false) {}
MsgService_Stub::MsgService_Stub(
::google::protobuf::RpcChannel* channel,
::google::protobuf::Service::ChannelOwnership ownership)
: channel_(channel),
owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}
MsgService_Stub::~MsgService_Stub() {
if (owns_channel_) delete channel_;
}
void MsgService_Stub::SaveMsg(::google::protobuf::RpcController* controller,
const ::antalk::data::SaveMsgReq* request,
::antalk::data::SaveMsgResp* response,
::google::protobuf::Closure* done) {
channel_->CallMethod(descriptor()->method(0),
controller, request, response, done);
}
// @@protoc_insertion_point(namespace_scope)
} // namespace data
} // namespace antalk
// @@protoc_insertion_point(global_scope)
| 36.421606 | 131 | 0.708057 | mloves0824 |
79ed8886bd48c8320f7f94ad19dce2f56980b498 | 301 | hpp | C++ | include/Interpreter/Import.hpp | ferhatgec/flascript | e9db83422b7e008b2fd64a62d763dbedf1d5d1d2 | [
"MIT"
] | 15 | 2020-07-30T17:29:12.000Z | 2021-08-19T04:05:49.000Z | include/Interpreter/Import.hpp | FerhatGec/flascript | e9db83422b7e008b2fd64a62d763dbedf1d5d1d2 | [
"MIT"
] | null | null | null | include/Interpreter/Import.hpp | FerhatGec/flascript | e9db83422b7e008b2fd64a62d763dbedf1d5d1d2 | [
"MIT"
] | 2 | 2020-09-18T12:36:22.000Z | 2021-05-14T05:24:20.000Z | /* MIT License
#
# Copyright (c) 2020 Ferhat Geçdoğan All Rights Reserved.
# Distributed under the terms of the MIT License.
#
# */
#ifndef IMPORT_HPP
#define IMPORT_HPP
#include <iostream>
#include <cstring>
class FImport {
public:
void Import(std::string, std::string);
};
#endif // IMPORT_HPP
| 15.05 | 57 | 0.717608 | ferhatgec |
79ee93b07a364b66815622c71430f589c4b034da | 1,294 | cpp | C++ | alica_tests/src/test/test_success_spam.cpp | rapyuta-robotics/alica | 4235004015f3ecd5c98426712117997f0ceb4aea | [
"MIT"
] | 22 | 2018-03-08T05:43:45.000Z | 2022-03-28T15:03:49.000Z | alica_tests/src/test/test_success_spam.cpp | rapyuta-robotics/alica | 4235004015f3ecd5c98426712117997f0ceb4aea | [
"MIT"
] | 50 | 2018-03-30T10:32:01.000Z | 2022-03-22T11:58:34.000Z | alica_tests/src/test/test_success_spam.cpp | rapyuta-robotics/alica | 4235004015f3ecd5c98426712117997f0ceb4aea | [
"MIT"
] | 6 | 2019-03-04T12:28:27.000Z | 2022-02-10T04:09:01.000Z | #include "test_alica.h"
#include "BehaviourCreator.h"
#include "ConditionCreator.h"
#include "ConstraintCreator.h"
#include <alica_tests/CounterClass.h>
#include "UtilityFunctionCreator.h"
#include <alica/test/Util.h>
#include <engine/Assignment.h>
#include <engine/BasicBehaviour.h>
#include <engine/BehaviourPool.h>
#include <engine/DefaultUtilityFunction.h>
#include <engine/IAlicaCommunication.h>
#include <engine/PlanBase.h>
#include <engine/PlanRepository.h>
#include <engine/TeamObserver.h>
#include <engine/model/Behaviour.h>
#include <engine/model/Plan.h>
#include <engine/model/RuntimeCondition.h>
#include <engine/model/State.h>
#include <engine/AlicaClock.h>
#include <engine/AlicaEngine.h>
#include <gtest/gtest.h>
namespace alica
{
namespace
{
class AlicaSpamSuccess : public AlicaTestFixture
{
protected:
const char* getRoleSetName() const override { return "Roleset"; }
const char* getMasterPlanName() const override { return "BehaviorSuccessSpamMaster"; }
};
/**
* Tests whether it is possible to run a behaviour in a primitive plan.
*/
TEST_F(AlicaSpamSuccess, runBehaviour)
{
ASSERT_NO_SIGNAL
ae->start();
for (int i = 0; i < 30 * 6; ++i) {
ac->stepEngine();
}
EXPECT_TRUE(alica::test::Util::isPlanActive(ae, 1522377375148));
}
}
} | 24.884615 | 90 | 0.738794 | rapyuta-robotics |
79ef41d0c35c576c2f0aad5e54868f50983bad0e | 897 | cpp | C++ | src/Protein.cpp | pelafustan/aed_u1g0 | 69342941c1dc22f6641b39a80ce35e2fe9076fbd | [
"MIT"
] | null | null | null | src/Protein.cpp | pelafustan/aed_u1g0 | 69342941c1dc22f6641b39a80ce35e2fe9076fbd | [
"MIT"
] | null | null | null | src/Protein.cpp | pelafustan/aed_u1g0 | 69342941c1dc22f6641b39a80ce35e2fe9076fbd | [
"MIT"
] | null | null | null | #include "../include/Protein.h"
// default constructor
Protein::Protein() {
// default attributes
this->Name = "";
this->ID = "";
}
// specific constructor
Protein::Protein(std::string name, std::string id) {
// user defined attributes
this->Name = name;
this->ID = id;
}
// overloaded specific constructor
Protein::Protein(std::string name, std::string id, std::list<Chain> chains) {
// user defined attributes
this->Name = name;
this->ID = id;
this->Chains = chains;
}
// mutators
void Protein::setName(std::string name) { this->Name = name; }
void Protein::setID(std::string id) { this->ID = id; }
void Protein::addChain(Chain chain) { this->Chains.push_back(chain); }
// accessors
std::string Protein::getName() { return this->Name; }
std::string Protein::getID() { return this->ID; }
std::list<Chain> Protein::getChains() { return this->Chains; }
| 26.382353 | 77 | 0.654404 | pelafustan |
79f4c2940f75053ea6f5a9d091814cfbf11c2d42 | 4,748 | cpp | C++ | Doom/src/Doom/Doom.cpp | Shturm0weak/OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 126 | 2020-10-20T21:39:53.000Z | 2022-01-25T14:43:44.000Z | Doom/src/Doom/Doom.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 2 | 2021-01-07T17:29:19.000Z | 2021-08-14T14:04:28.000Z | Doom/src/Doom/Doom.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 16 | 2021-01-09T09:08:40.000Z | 2022-01-25T14:43:46.000Z | #include "pch.h"
#include "Core/World.h"
#include "Core/Core.h"
#include "Render/Renderer.h"
#include "Text/Character.h"
#include "Core/Timer.h"
#include "Render/Batch.h"
#include "Objects/Line.h"
#include "Objects/ParticleSystem.h"
#include "Audio/SoundManager.h"
#include "Core/Editor.h"
#include "Components/RectangleCollider2D.h"
#include "Components/PointLight.h"
#include "Lua/LuaState.h"
#include "Core/SceneSerializer.h"
#include "Input/Input.h"
#include "Rays/Ray3D.h"
#include "EntryPoint.h"
#include "Objects/GridLayOut.h"
#include "Objects/SkyBox.h"
#include "Core/Logger.h"
#include "Render/Mesh.h"
using namespace Doom;
DOOM_API std::mutex Mesh::s_Mtx;
DOOM_API std::unordered_map<std::string, Mesh*> Mesh::s_Meshes;
DOOM_API std::multimap<std::string, std::function<void(Mesh* m)>> Mesh::s_MeshQueue;
DOOM_API const char** Mesh::s_NamesOfMeshes;
DOOM_API std::tm* Logger::s_CurrentTime;
DOOM_API std::string Logger::s_TimeString;
DOOM_API std::vector<LuaState*> LuaState::s_LuaStates;
DOOM_API std::vector<CubeCollider3D*> CubeCollider3D::s_Colliders;
DOOM_API std::vector<SphereCollider*> SphereCollider::s_Spheres;
DOOM_API std::vector <SpriteRenderer*> Renderer::s_Objects2d;
DOOM_API std::vector <Renderer3D*> Renderer::s_Objects3d;
DOOM_API std::vector <Renderer3D*> Renderer::s_Objects3dTransparent;
DOOM_API std::vector <Renderer3D*> Renderer::s_OutLined3dObjects;
DOOM_API std::vector<std::string> SkyBox::s_Faces;
DOOM_API std::vector <char*> GameObject::s_FreeMemory;
DOOM_API std::map <char*, uint64_t> GameObject::s_MemoryPool;
DOOM_API std::vector <char*> Renderer3D::s_FreeMemory;
DOOM_API std::map <char*, uint64_t> Renderer3D::s_MemoryPool;
DOOM_API std::vector <char*> CubeCollider3D::s_FreeMemory;
DOOM_API std::map <char*, uint64_t> CubeCollider3D::s_MemoryPool;
DOOM_API std::vector <char*> RectangleCollider2D::s_FreeMemory;
DOOM_API std::map <char*, uint64_t> RectangleCollider2D::s_MemoryPool;
DOOM_API std::vector <char*> SpriteRenderer::s_FreeMemory;
DOOM_API std::map <char*, uint64_t> SpriteRenderer::s_MemoryPool;
DOOM_API std::vector <RectangleCollider2D*> RectangleCollider2D::s_Collision2d;
DOOM_API bool Renderer::s_PolygonMode = false;
DOOM_API Renderer::Stats Renderer::s_Stats;
DOOM_API Renderer::Bloom Renderer::s_Bloom;
DOOM_API Renderer::ShadowMap Renderer::s_ShadowMap;
DOOM_API std::vector<std::string> Editor::s_TexturesPath;
DOOM_API std::vector<Texture*> Editor::s_Texture;
DOOM_API std::vector<Texture*> Editor::s_TextureVecTemp;
DOOM_API std::vector<TexParameteri> Texture::s_TexParameters;
DOOM_API std::vector<Texture*> Texture::s_LoadedTextures;
DOOM_API std::multimap<std::string, std::function<void(Texture* t)>> Texture::s_WaitingForTextures;
DOOM_API std::mutex Texture::s_LockTextureLoadingMtx;
DOOM_API Texture* Texture::s_WhiteTexture;
DOOM_API std::unordered_map<std::string, Texture*> Texture::s_Textures;
DOOM_API double Timer::s_OutTime = 0;
DOOM_API ThreadPool* ThreadPool::s_Instance = nullptr;
DOOM_API bool ThreadPool::m_IsInitialized;
DOOM_API std::unordered_map<int, int> Input::s_Keys;
DOOM_API float DeltaTime::s_Time;
DOOM_API float DeltaTime::s_Lasttime = (float)glfwGetTime();
DOOM_API float DeltaTime::s_Deltatime = 1.0 / 1e8;
DOOM_API std::mutex DeltaTime::s_Mtx;
DOOM_API bool RectangleCollider2D::s_IsVisible = false;
DOOM_API vec4 COLORS::Red(1, 0, 0, 1);
DOOM_API vec4 COLORS::Yellow(1, 1, 0, 1);
DOOM_API vec4 COLORS::Blue(0, 0, 1, 1);
DOOM_API vec4 COLORS::Green(0, 1, 0, 1);
DOOM_API vec4 COLORS::Brown(0.5, 0.3, 0.1, 1);
DOOM_API vec4 COLORS::White(1, 1, 1, 1);
DOOM_API vec4 COLORS::Orange(1, 0.31, 0, 1);
DOOM_API vec4 COLORS::Gray(0.86, 0.86, 0.86, 1);
DOOM_API vec4 COLORS::Silver(0.75, 0.75, 0.75, 1);
DOOM_API vec4 COLORS::DarkGray(0.4, 0.4, 0.4, 1);
DOOM_API std::vector<Line*> Line::s_Lines;
DOOM_API float Line::s_Width = 1.0f;
DOOM_API std::unordered_map<std::string, TextureAtlas*> TextureAtlas::s_TextureAtlases;
DOOM_API const char** TextureAtlas::s_NamesOfTextureAtlases;
DOOM_API std::unordered_map<std::string, Shader*> Shader::s_Shaders;
DOOM_API std::vector<Particle*> Particle::s_Particles;
DOOM_API const char** Shader::s_NamesOfShaders;
DOOM_API std::vector<PointLight*> PointLight::s_PointLights;
DOOM_API std::vector<DirectionalLight*> DirectionalLight::s_DirLights;
DOOM_API std::vector<SpotLight*> SpotLight::s_SpotLights;
DOOM_API unsigned int SpriteRenderer::s_Indices2D[6] = { 0,1,2,3,2,0 };
DOOM_API float RectangleCollider2D::m_Vertices[8] = {-0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f };
DOOM_API std::vector<std::string> Ray3D::m_IgnoreMask;
DOOM_API std::vector<Line*> GridLayOut::s_GridLines;
DOOM_API std::string SceneSerializer::s_CurrentSceneFilePath = "src/Scenes/scene.yaml"; | 38.290323 | 108 | 0.771693 | Shturm0weak |
79fa92b27f3137bfbed6662649626a55c9f6671a | 9,104 | cpp | C++ | Mercury3/src/renderer/OpenVRRenderTarget.cpp | axlecrusher/hgengine3 | 7eed878015e47a3275e2dae53cac00e93b74dc19 | [
"MIT"
] | 4 | 2018-05-27T18:56:59.000Z | 2020-08-02T21:41:30.000Z | Mercury3/src/renderer/OpenVRRenderTarget.cpp | axlecrusher/hgengine3 | 7eed878015e47a3275e2dae53cac00e93b74dc19 | [
"MIT"
] | null | null | null | Mercury3/src/renderer/OpenVRRenderTarget.cpp | axlecrusher/hgengine3 | 7eed878015e47a3275e2dae53cac00e93b74dc19 | [
"MIT"
] | 2 | 2019-05-16T05:23:12.000Z | 2020-04-17T10:16:04.000Z | #include <OpenVRRenderTarget.h>
#include <HgUtils.h>
#include <HgCamera.h>
#include <MercuryWindow.h>
#include <RenderBackend.h>
#include <Win32Window.h>
#include <OGLFramebuffer.h>
#include <EventSystem.h>
#include <Logging.h>
OpenVRRenderTarget::OpenVRRenderTarget(OpenVrProxy* openvr)
:m_openvr(openvr), m_initalized(false), m_timerInited(false)
{
m_HMDPose = vectorial::mat4f::identity();
m_projectionLeftEye = vectorial::mat4f::identity();
m_projectionRightEye = vectorial::mat4f::identity();
//m_leftEyePos = vectorial::mat4f::identity();
//m_rightEyePos = vectorial::mat4f::identity();
memset(m_deviceClass, 0, sizeof(m_deviceClass));
}
bool OpenVRRenderTarget::Init()
{
// if (!m_openvr->Init()) return false;
auto strDriver = GetTrackedDeviceString(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String);
auto strDisplay = GetTrackedDeviceString(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String);
ENGINE::StartWindowSystem(MercuryWindow::Dimensions(1280, 720));
auto window = MercuryWindow::GetCurrentWindow();
int width = window->CurrentWidth();
int height = window->CurrentHeight();
float projection[16];
m_windowViewport.width = width;
m_windowViewport.height = height;
double renderWidth = width;
double renderHeight = height;
double aspect = renderWidth / renderHeight;
Perspective2(60, aspect, 0.03f, 100.0f, projection);
m_projection.load(projection);
m_openvr->InitCompositor();
initEyeFramebuffers();
m_projectionLeftEye = getHMDProjectionEye(vr::Eye_Left);
m_projectionRightEye = getHMDProjectionEye(vr::Eye_Right);
//m_leftEyePos = getHMDEyeTransform(vr::Eye_Left);
//m_rightEyePos = getHMDEyeTransform(vr::Eye_Right);
m_timerInited = false;
m_initalized = true;
return true;
}
void OpenVRRenderTarget::initEyeFramebuffers()
{
auto hmd = m_openvr->getDevice();
if (hmd == nullptr) return;
uint32_t width, height;
hmd->GetRecommendedRenderTargetSize(&width, &height);
m_framebufferViewport.width = width;
m_framebufferViewport.height = height;
m_leftEye = RENDERER()->CreateFrameBuffer();
m_leftEye->Init(width, height);
m_rightEye = RENDERER()->CreateFrameBuffer();
m_rightEye->Init(width, height);
}
void OpenVRRenderTarget::updateHMD()
{
auto hmd = m_openvr->getDevice();
if (hmd == nullptr) return;
vr::VRCompositor()->WaitGetPoses(m_rTrackedDevicePose, vr::k_unMaxTrackedDeviceCount, NULL, 0);
if (m_timerInited == false)
{
m_timerInited = true;
m_timer.start();
m_timeSinceLastPose = m_timeOfPose.msec(0);
}
else
{
const auto time = m_timer.getElasped();
m_timeSinceLastPose = time - m_timeOfPose;
m_timeOfPose = time;
}
for (int nDevice = 1; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice)
{
if (m_rTrackedDevicePose[nDevice].bPoseIsValid)
{
const auto pose = ConvertToMat4f(m_rTrackedDevicePose[nDevice].mDeviceToAbsoluteTracking);
if (m_deviceClass[nDevice] == vr::ETrackedDeviceClass::TrackedDeviceClass_Invalid)
{
auto type = hmd->GetTrackedDeviceClass(nDevice);
m_deviceClass[nDevice] = type;
}
if (m_deviceClass[nDevice] == vr::ETrackedDeviceClass::TrackedDeviceClass_Controller)
{
Events::VrControllerPoseUpdated poseUpdated;
ConstructPositionOrientationFromVrDevice(m_rTrackedDevicePose[nDevice].mDeviceToAbsoluteTracking, poseUpdated.position, poseUpdated.orientation);
poseUpdated.deviceIndex = nDevice;
EventSystem::PublishEvent(poseUpdated);
}
}
}
if (m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid)
{
m_HMDPose = ConvertToMat4f(m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
m_hmdCamera = ConstructCameraFromVrDevice(m_rTrackedDevicePose[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
Events::HMDPoseUpdated poseUpdated;
poseUpdated.position = m_hmdCamera.getWorldSpacePosition();
poseUpdated.orientation = m_hmdCamera.getWorldSpaceOrientation();
EventSystem::PublishEvent(poseUpdated);
}
}
HgMath::mat4f OpenVRRenderTarget::getWindowProjectionMatrix()
{
HgMath::mat4f projectionMatrix;
float projection[16];
const double width = m_windowViewport.width;
const double height = m_windowViewport.height;
const double aspect = width / height;
Perspective2(60, aspect, 0.1f, 100.0f, projection);
projectionMatrix.load(projection);
return projectionMatrix;
}
//const RenderParamsList& l
//void OpenVRRenderTarget::Render(HgCamera* camera, RenderQueue* queue, const HgMath::mat4f& projection)
void OpenVRRenderTarget::Render(const RenderParamsList& l)
{
if (!m_initalized) return;
RENDERER()->Clear();
RENDERER()->BeginFrame();
ViewportRenderTarget vprt(&m_windowViewport);
for (const RenderParams& i : l)
{
const auto hdmCamMatrix = i.camera->toViewMatrix();
const auto projection = i.projection->getProjectionMatrix(vprt);
Renderer::Render(m_windowViewport, hdmCamMatrix, projection, i.queue);
}
auto left = dynamic_cast<OGLFramebuffer*>(m_leftEye.get());
auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get());
{
left->Enable();
RENDERER()->Clear();
RENDERER()->BeginFrame();
const auto eyeTtransform = getHMDEyeTransform(vr::Eye_Left);
VrEyeRenderTarget rt(this, vr::EVREye::Eye_Left);
for (const RenderParams& i : l)
{
const auto projection = i.projection->getProjectionMatrix(rt);
RenderToEye(left, eyeTtransform, projection, i);
}
left->Disable();
left->Copy();
}
{
right->Enable();
RENDERER()->Clear();
RENDERER()->BeginFrame();
const auto eyeTtransform = getHMDEyeTransform(vr::Eye_Right);
VrEyeRenderTarget rt(this, vr::EVREye::Eye_Right);
for (const RenderParams& i : l)
{
const auto projection = i.projection->getProjectionMatrix(rt);
RenderToEye(left, eyeTtransform, projection, i);
}
right->Disable();
right->Copy();
}
////updateHMD();
//auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get());
////auto camMat = camera->toViewMatrix(); //replace with head matrix
//const auto hdmCamMatrix = m_hmdCamera.toViewMatrix();
//const auto leftEyeMat = m_leftEyePos * hdmCamMatrix;
//const auto rightEyeMat = m_rightEyePos * hdmCamMatrix;
//const auto leftProjection = m_projectionLeftEye * projection;
//const auto rightProjection = m_projectionRightEye * projection;
////render to window first
//Renderer::Render(m_windowViewport, hdmCamMatrix, projection, queue);
//m_leftEye->Enable();
//RENDERER()->Clear();
//RENDERER()->BeginFrame();
//Renderer::Render(m_framebufferViewport, leftEyeMat, leftProjection, queue); //eye 1
//m_leftEye->Disable();
//left->Copy();
//m_rightEye->Enable();
//RENDERER()->Clear();
//RENDERER()->BeginFrame();
//Renderer::Render(m_framebufferViewport, rightEyeMat, rightProjection, queue); //eye 2
//m_rightEye->Disable();
//right->Copy();
//auto left = dynamic_cast<OGLFramebuffer*>(m_leftEye.get());
//auto right = dynamic_cast<OGLFramebuffer*>(m_rightEye.get());
vr::Texture_t leftEyeTexture = { (void*)(uintptr_t)left->getResolveTextureID(), vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
auto e1 = vr::VRCompositor()->Submit(vr::Eye_Left, &leftEyeTexture);
if (e1 != vr::VRInitError_None)
{
LOG_ERROR("Failed to submit left eye: %d", e1);
}
vr::Texture_t rightEyeTexture = { (void*)(uintptr_t)right->getResolveTextureID(), vr::TextureType_OpenGL, vr::ColorSpace_Gamma };
auto e2 = vr::VRCompositor()->Submit(vr::Eye_Right, &rightEyeTexture);
if (e2 != vr::VRInitError_None)
{
LOG_ERROR("Failed to submit right eye: %d", e2);
}
}
void OpenVRRenderTarget::RenderToEye(IFramebuffer* eyeBuffer, const HgMath::mat4f& eyePosTransform,
const HgMath::mat4f& eyeProjection, const RenderParams& p)
{
const auto hdmCamMatrix = p.camera->toViewMatrix();
const auto eyeMatrix = eyePosTransform * hdmCamMatrix;
//const auto projection = eyeProjection * (*p.projection);
//frameBuffer->Enable();
//RENDERER()->Clear();
//RENDERER()->BeginFrame();
Renderer::Render(m_framebufferViewport, eyeMatrix, eyeProjection, p.queue);
//frameBuffer->Disable();
//frameBuffer->Copy();
}
void OpenVRRenderTarget::Finish()
{
}
HgMath::mat4f OpenVRRenderTarget::getOrthoMatrix() const
{
//return vectorial::transpose(HgMath::mat4f::translation(vectorial::vec3f(0, 0, 1)));
return HgMath::mat4f::translation(vectorial::vec3f(0, 0, 1));
// return vectorial::mat4f::identity();
}
//returns a projection matrix for the specified eye
HgMath::mat4f OpenVRRenderTarget::getHMDProjectionEye(vr::EVREye eye) const
{
auto hmd = m_openvr->getDevice();
if (!hmd) return HgMath::mat4f();
const vr::HmdMatrix44_t mat = hmd->GetProjectionMatrix(eye, 0.1, 100);
const auto r = vectorial::transpose(ConvertToMat4f(mat));
return r;
}
HgMath::mat4f OpenVRRenderTarget::getHMDEyeTransform(vr::EVREye eye)
{
auto hmd = m_openvr->getDevice();
if (!hmd) return HgMath::mat4f();
vr::HmdMatrix34_t mat = hmd->GetEyeToHeadTransform(eye);
//unsure why this is messed up
mat.m[0][3] *= -1.0;
return vectorial::transpose(ConvertToMat4f(mat));
}
REGISTER_EVENT_TYPE(Events::HMDPoseUpdated)
REGISTER_EVENT_TYPE(Events::VrControllerPoseUpdated) | 29.462783 | 149 | 0.745826 | axlecrusher |
79ff22d850d7e3df640a66fcaa1eb9c2a8b5e3e3 | 3,352 | cpp | C++ | src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | 13 | 2020-03-23T20:36:44.000Z | 2022-02-28T11:07:32.000Z | src/LuminoEngine/src/Graphics/RHIs/RHIResource.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include "Internal.hpp"
#include "GraphicsDeviceContext.hpp"
#include "RHIProfiler.hpp"
#include "RHIResource.hpp"
namespace ln {
namespace detail {
//=============================================================================
// RHIResource
RHIResource::RHIResource()
: m_type(RHIResourceType::Unknown)
, m_usage(GraphicsResourceUsage::Static)
, m_memorySize(0)
, m_extentSize{0, 0}
, m_textureFormat(TextureFormat::Unknown)
, m_mipmap(false)
, m_msaa(false)
{
LN_LOG_VERBOSE << "RHIResource [0x" << this << "] constructed.";
}
RHIResource::~RHIResource()
{
if (IGraphicsDevice* d = device()) {
switch (m_type)
{
case RHIResourceType::VertexBuffer:
d->profiler()->removeVertexBuffer(this);
break;
case RHIResourceType::IndexBuffer:
d->profiler()->removeIndexBuffer(this);
break;
case RHIResourceType::UniformBuffer:
d->profiler()->removeUniformBuffer(this);
break;
case RHIResourceType::Texture2D:
d->profiler()->removeTexture2D(this);
break;
case RHIResourceType::RenderTarget:
d->renderPassCache()->invalidate(static_cast<RHIResource*>(this));
d->profiler()->removeRenderTarget(this);
break;
default:
break;
}
}
}
bool RHIResource::initAsVertexBuffer(GraphicsResourceUsage usage, uint64_t memorySize)
{
m_type = RHIResourceType::VertexBuffer;
m_usage = usage;
m_memorySize = memorySize;
return true;
}
bool RHIResource::initAsIndexBuffer(GraphicsResourceUsage usage, IndexBufferFormat format, uint32_t indexCount)
{
m_type = RHIResourceType::IndexBuffer;
m_usage = usage;
int stride = 0;
if (format == IndexBufferFormat::UInt16) {
stride = 2;
}
else if (format == IndexBufferFormat::UInt32) {
stride = 4;
}
else {
LN_UNREACHABLE();
return false;
}
m_memorySize = stride * indexCount;
return true;
}
bool RHIResource::initAsUniformBuffer(GraphicsResourceUsage usage, uint64_t memorySize)
{
// 今のところ UniformBuffer は Dynamic (複数 DrawCall で共有しない) 前提
// TODO: OpenGL の Streaming みたいにもうひとつ用意して区別したほうがいいかも
if (LN_REQUIRE(usage == GraphicsResourceUsage::Dynamic)) return false;
m_type = RHIResourceType::UniformBuffer;
m_usage = usage;
m_memorySize = memorySize;
return true;
}
bool RHIResource::initAsTexture2D(GraphicsResourceUsage usage, uint32_t width, uint32_t height, TextureFormat format, bool mipmap)
{
//if (LN_REQUIRE(format == TextureFormat::Unknown)) return false;
m_type = RHIResourceType::Texture2D;
m_usage = usage;
m_extentSize.width = width;
m_extentSize.height = height;
m_memorySize = width * height * GraphicsHelper::getPixelSize(format);
m_textureFormat = format;
m_mipmap = mipmap;
return true;
}
bool RHIResource::initAsRenderTarget(uint32_t width, uint32_t height, TextureFormat format, bool mipmap, bool msaa)
{
//if (LN_REQUIRE(format == TextureFormat::Unknown)) return false;
m_type = RHIResourceType::RenderTarget;
m_usage = GraphicsResourceUsage::Static;
m_extentSize.width = width;
m_extentSize.height = height;
m_memorySize = width * height * GraphicsHelper::getPixelSize(format);
m_textureFormat = format;
m_mipmap = mipmap;
m_msaa = msaa;
return true;
}
void* RHIResource::map()
{
LN_UNREACHABLE();
return nullptr;
}
void RHIResource::unmap()
{
LN_UNREACHABLE();
}
RHIRef<RHIBitmap> RHIResource::readData()
{
LN_UNREACHABLE();
return nullptr;
}
} // namespace detail
} // namespace ln
| 24.115108 | 130 | 0.724642 | infinnie |
0301d55e286597f3520052d182d8971d0afa307d | 871 | cpp | C++ | standalone/main.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | standalone/main.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | standalone/main.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | // spdlog
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
// module
#include <module/base_listener.hpp>
#include <module/internal/kbd_remap_pointer_dep.hpp>
#include <module/module_run.hpp>
// C++ STL
#include <iostream>
class listener : public module::base_listener {
public:
void value_accessible_string(const std::string& _val) override {
SPDLOG_INFO("value_accessible");
}
void value_changed_string(const std::string& _val) override {
SPDLOG_INFO("value_changed");
}
};
int main() {
/* spdlog setup */
spdlog::set_level(spdlog::level::trace);
uintptr_t addr = 0x0;
module::internal::module_run _module;
_module.add_listener(std::make_shared<listener>());
_module.set_pointer(addr);
_module.set_address(addr);
_module.run();
} | 24.194444 | 68 | 0.711825 | sirofen |
03026d4887903c4c70d5da191529fa77062736ca | 9,454 | cpp | C++ | Half Robot/Model.cpp | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | Half Robot/Model.cpp | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | Half Robot/Model.cpp | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | #pragma once
#include "Model.h"
#include "Entity.h"
#include "Graphics.h"
#include "Physics.h"
#include "EntityInput.h"
#include "SDL.h"
#include "PlayerInput.h"
#include "GraphicsPlayer.h"
#include "PhysicsPlayer.h"
#include "GraphicsBullet.h"
#include "BulletInput.h"
#include "PhysicsBullet.h"
#include "AIInput.h"
#include "GraphicsAI.h"
#include "GraphicsAI2.h"
#include "BotEntity.h"
#include "PhysicsBot.h"
using namespace std;
Model::Model() : ticks(0) {
boss = nullptr;
}
Model::~Model() {
delete player;
}
BulletEntity* generateBullet() {
return new BulletEntity(new PhysicsBullet, new GraphicsBullet(), new BulletInput());
}
void Model::initWorld(int w_id) {
ticks = 0;
world_id = w_id;
xlock = true;
player = new PlayerEntity(new PhysicsPlayer(), new GraphicsPlayer(), new PlayerInput());
//player->setXY(950, 475);
player->setID(999);
spawnX = 20;
spawnY = 200;
clearWorld();
spawnAis(world_id);
player->setXY(spawnX, spawnY);
player->setDirection(1);
}
long Model::getTicks() {
return ticks;
}
void Model::clearWorld() {
while (!ais.empty()) {
delete ais.back();
ais.pop_back();
}
if (boss) {
delete boss;
boss = nullptr;
}
}
void Model::respawn() {
clearWorld();
player->setXY(spawnX, spawnY);
player->setHP(player->getMaxHP());
player->setLives(player->getLives() - 1);
player->getPhysics()->exitLadder();
player->setDead(false);
player->setStartedDying(false);
player->setDamaged(false);
spawnAis(world_id);
}
void Model::spawnAis(int _world_id) {
Entity* e;
player->setMaxHP(100);
if (_world_id == 1) {
spawnX = 50;
spawnY = 100;
e = new BotEntity(new PhysicsPlayer(), new GraphicsAI2(renderer), new AIInput(1),50);
e->setXY(450, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsPlayer(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(450, 60);
ais.push_back(e);
e = new BotEntity(new PhysicsPlayer(), new GraphicsAI(renderer), new AIInput(0), 1);
e->setXY(900, 400);
boss = e;
boss->setMaxHP(2250);
}
if (_world_id == 2) {
spawnX = 20;
spawnY = 200;
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(550, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(550, 130);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(550, 115);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(550, 80);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(600, 80);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(750, 80);
ais.push_back(e);
//e = new BotEntity(new PhysicsPlayer(), new GraphicsAI2(renderer), new AIInput(2), 50);
//e->setXY(700, 60);
//ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(0), 1);
e->setXY(1250, 400);
boss = e;
boss->setMaxHP(1350);
}
if (_world_id == 3) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(650, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(550, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(700, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(450, 100);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(0), 1);
e->setXY(900, 450);
boss = e;
boss->setMaxHP(3333);
}
if (_world_id == 4) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(80, 25);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(150, 25);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(200, 25);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(250, 25);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(290, 25);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(400, 350);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(420, 370);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(420, 322);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(5), 1);
e->setXY(20, 750);
boss = e;
boss->setMaxHP(1650);
}
if (_world_id == 5) {
for (int i = 0; i < 10; i++) {
if (i == 5)
i++;
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(26+i*32, 20);
ais.push_back(e);
}
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(426, 20);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(450, 50);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(760, 70);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(760, 120);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(760, 180);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(760, 220);
ais.push_back(e);
player->setMaxHP(140);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(7), 1);
e->setXY(850, 450);
boss = e;
boss->setMaxHP(1850);
}
if (_world_id == 6) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(1150, 20);
ais.push_back(e);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(6), 1);
e->setXY(850, 450);
boss = e;
boss->setMaxHP(1850);
}
if (_world_id == 7) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(1), 50);
e->setXY(30, 1100);
ais.push_back(e);
for (int i = 0; i < 5; i++) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(100+i*62, 1000);
ais.push_back(e);
}
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(6), 1);
e->setXY(450, 1300);
boss = e;
boss->setMaxHP(1850);
}
if (_world_id == 8) {
for (int i = 0; i < 7; i++) {
e = new BotEntity(new PhysicsBot(), new GraphicsAI2(renderer), new AIInput(2), 50);
e->setXY(430 + i * 50, 30);
ais.push_back(e);
}
player->setMaxHP(250);
e = new BotEntity(new PhysicsBot(), new GraphicsAI(renderer), new AIInput(6), 1);
e->setXY(1250, 500);
boss = e;
boss->setMaxHP(2000);
}
}
void Model::update() {
ticks++;
using namespace std;
player->update(*this);
player->checkCollisions(getAis());
player->checkACollision(*getBoss());
fireGun(*player);
if (player->startedDying() && !player->isDead()) {
player->setDead(true);
player->setStartedDying(false);
player->setLives(player->getLives() - 1);
}
if (player->isDead()) {
}
for (auto &bot : ais) {
bot->update(*this);
fireGun(*bot);
}
int test = abs(player->getX() - boss->getX()) + abs(player->getY() - boss->getY());
if (player->getX() / 400 == boss->getX() / 400 && player->getY() / 300 == boss->getY() / 300) {
boss->update(*this);
fireGun(*boss);
}
clearOrUpdate();
}
void Model::render(float lag, int xPos, int yPos) {
using namespace std;
//cout << xPos << " " << yPos << endl;
player->render2(renderer, lag, xPos, yPos, ticks);
for (auto const& b : bullets) {
b->render(renderer, lag, xPos, yPos);
}
for (auto const& a : ais) {
a->render(renderer, lag, xPos, yPos);
}
boss->render(renderer, lag, xPos, yPos);
}
void Model::clearOrUpdate() {
using namespace std;
vector<int> indexes;
vector<int> indexes2;
for (size_t i = 0; i < bullets.size(); i++) {
if (!bullets[i]->isDead())
bullets[i]->update(*this);
else {
indexes.push_back(i);
}
}
for (size_t i = 0; i < ais.size(); i++) {
if (!ais[i]->isDead())
ais[i]->update(*this);
else {
indexes2.push_back(i);
}
}
for (int i = indexes.size() - 1; i >= 0; i--) {
int ind = indexes[i];
delete bullets[ind];
bullets.erase(bullets.begin() + ind);
}
for (int i = indexes2.size() - 1; i >= 0; i--) {
int ind = indexes2[i];
delete ais[ind];
ais.erase(ais.begin() + ind);
}
}
void Model::fireGun(Entity& e) {
if (e.isWantFire()) {
e.setWantFire(false);
BulletEntity* b = generateBullet();
b->setID(e.getID());
if (e.getDirection()) {
b->setXY(e.getX2(), e.getY() + e.getWidth() / 2 - b->getWidth() / 2);
b->setDirection(1);
}
else {
b->setDirection(0);
b->setXY(e.getX() - b->getWidth(), e.getY() + e.getWidth() / 2 - b->getWidth() / 2);
}
bullets.push_back(b);
}
}
| 23.285714 | 96 | 0.636556 | marcus1337 |
0303818b3d61bf06e82889b364eee1d52f707e4e | 2,608 | cc | C++ | src/ragnarok/object_factory.cc | X-EcutiOnner/Bourgeon | c8f92df01f21846e994fac888508e40106205f1a | [
"MIT"
] | 20 | 2018-01-25T03:16:13.000Z | 2022-03-30T04:30:05.000Z | src/ragnarok/object_factory.cc | X-EcutiOnner/Bourgeon | c8f92df01f21846e994fac888508e40106205f1a | [
"MIT"
] | 6 | 2018-01-27T12:19:35.000Z | 2021-06-05T18:39:17.000Z | src/ragnarok/object_factory.cc | X-EcutiOnner/Bourgeon | c8f92df01f21846e994fac888508e40106205f1a | [
"MIT"
] | 13 | 2018-01-27T16:20:19.000Z | 2021-05-17T19:08:42.000Z | #include "ragnarok/object_factory.h"
#include "ragnarok/object_layouts/session/layouts.h"
#include "utils/log_console.h"
Session::Pointer ObjectFactory::CreateSession(
const YAML::Node& session_configuration) {
Session::Pointer result;
const auto session_layout = session_configuration["layout"];
if (!session_layout.IsDefined()) {
LogError("Missing required field 'layout' for Session");
return nullptr;
}
try {
switch (session_layout.as<uint32_t>()) {
case 20151102:
result = std::make_unique<Session_20151102>(session_configuration);
break;
case 20170613:
result = std::make_unique<Session_20170613>(session_configuration);
break;
case 20190116:
result = std::make_unique<Session_20190116>(session_configuration);
break;
default:
result = nullptr;
break;
}
return result;
} catch (std::exception& ex) {
LogError("CSession configuration is invalid: {}", ex.what());
return nullptr;
}
}
RagConnection::Pointer ObjectFactory::CreateRagConnection(
const YAML::Node& ragconnection_configuration) noexcept {
try {
return std::make_unique<RagConnection>(ragconnection_configuration);
} catch (std::exception& ex) {
LogError("CRagConnection configuration is invalid: {}", ex.what());
return nullptr;
}
}
UIWindowMgr::Pointer ObjectFactory::CreateUIWindowMgr(
const YAML::Node& uiwindowmgr_configuration) noexcept {
try {
return std::make_unique<UIWindowMgr>(uiwindowmgr_configuration);
} catch (std::exception& ex) {
LogError(std::string("UIWindowMgr configuration is invalid") + ex.what());
return nullptr;
}
}
ModeMgr::Pointer ObjectFactory::CreateModeMgr(
const YAML::Node& modemgr_configuration) noexcept {
try {
return std::make_unique<ModeMgr>(modemgr_configuration);
} catch (std::exception& ex) {
LogError("CModeMgr configuration is invalid: {}", ex.what());
return nullptr;
}
}
LoginMode::Pointer ObjectFactory::CreateLoginMode(
const YAML::Node& login_mode_configuration) noexcept {
try {
return std::make_unique<LoginMode>(login_mode_configuration);
} catch (std::exception& ex) {
LogError("CLoginMode configuration is invalid: {}", +ex.what());
return nullptr;
}
}
GameMode::Pointer ObjectFactory::CreateGameMode(
const YAML::Node& game_mode_configuration) noexcept {
try {
return std::make_unique<GameMode>(game_mode_configuration);
} catch (std::exception& ex) {
LogError("CGameMode configuration is invalid: {}", ex.what());
return nullptr;
}
} | 29.977011 | 78 | 0.700537 | X-EcutiOnner |
030760168ca9cfa92c8fa38ddbdbeadc8472a4dd | 32,100 | cpp | C++ | kernel/thor/generic/address-space.cpp | 64/managarm | 8250ae9110703e5db796011078d8d856b8119f3c | [
"MIT"
] | 1 | 2021-02-03T09:21:08.000Z | 2021-02-03T09:21:08.000Z | kernel/thor/generic/address-space.cpp | MichaelTrikergiotis/managarm | 7966d1ca02bf5295a51c56dbb5496c4ad4de9730 | [
"MIT"
] | null | null | null | kernel/thor/generic/address-space.cpp | MichaelTrikergiotis/managarm | 7966d1ca02bf5295a51c56dbb5496c4ad4de9730 | [
"MIT"
] | null | null | null |
#include <type_traits>
#include <thor-internal/coroutine.hpp>
#include <thor-internal/physical.hpp>
#include <thor-internal/fiber.hpp>
#include <frg/container_of.hpp>
#include <thor-internal/types.hpp>
namespace thor {
extern size_t kernelMemoryUsage;
namespace {
constexpr bool logCleanup = false;
constexpr bool logUsage = false;
void logRss(VirtualSpace *space) {
if(!logUsage)
return;
auto rss = space->rss();
if(!rss)
return;
auto b = 63 -__builtin_clz(rss);
if(b < 1)
return;
if(rss & ((1 << (b - 1)) - 1))
return;
infoLogger() << "thor: RSS of " << space << " increases above "
<< (rss / 1024) << " KiB" << frg::endlog;
infoLogger() << "thor: Physical usage: "
<< (physicalAllocator->numUsedPages() * 4) << " KiB, kernel usage: "
<< (kernelMemoryUsage / 1024) << " KiB" << frg::endlog;
}
}
MemorySlice::MemorySlice(smarter::shared_ptr<MemoryView> view,
ptrdiff_t view_offset, size_t view_size)
: _view{std::move(view)}, _viewOffset{view_offset}, _viewSize{view_size} {
assert(!(_viewOffset & (kPageSize - 1)));
assert(!(_viewSize & (kPageSize - 1)));
}
// --------------------------------------------------------
// HoleAggregator
// --------------------------------------------------------
bool HoleAggregator::aggregate(Hole *hole) {
size_t size = hole->length();
if(HoleTree::get_left(hole) && HoleTree::get_left(hole)->largestHole > size)
size = HoleTree::get_left(hole)->largestHole;
if(HoleTree::get_right(hole) && HoleTree::get_right(hole)->largestHole > size)
size = HoleTree::get_right(hole)->largestHole;
if(hole->largestHole == size)
return false;
hole->largestHole = size;
return true;
}
bool HoleAggregator::check_invariant(HoleTree &tree, Hole *hole) {
auto pred = tree.predecessor(hole);
auto succ = tree.successor(hole);
// Check largest hole invariant.
size_t size = hole->length();
if(tree.get_left(hole) && tree.get_left(hole)->largestHole > size)
size = tree.get_left(hole)->largestHole;
if(tree.get_right(hole) && tree.get_right(hole)->largestHole > size)
size = tree.get_right(hole)->largestHole;
if(hole->largestHole != size) {
infoLogger() << "largestHole violation: " << "Expected " << size
<< ", got " << hole->largestHole << "." << frg::endlog;
return false;
}
// Check non-overlapping memory areas invariant.
if(pred && hole->address() < pred->address() + pred->length()) {
infoLogger() << "Non-overlapping (left) violation" << frg::endlog;
return false;
}
if(succ && hole->address() + hole->length() > succ->address()) {
infoLogger() << "Non-overlapping (right) violation" << frg::endlog;
return false;
}
return true;
}
// --------------------------------------------------------
// Mapping
// --------------------------------------------------------
Mapping::Mapping(size_t length, MappingFlags flags,
smarter::shared_ptr<MemorySlice> slice_, uintptr_t viewOffset)
: length{length}, flags{flags},
slice{std::move(slice_)}, viewOffset{viewOffset} {
assert(viewOffset >= slice->offset());
assert(viewOffset + length <= slice->offset() + slice->length());
view = slice->getView();
}
Mapping::~Mapping() {
assert(state == MappingState::retired);
//infoLogger() << "\e[31mthor: Mapping is destructed\e[39m" << frg::endlog;
}
void Mapping::tie(smarter::shared_ptr<VirtualSpace> newOwner, VirtualAddr address) {
assert(!owner);
assert(newOwner);
owner = std::move(newOwner);
this->address = address;
}
void Mapping::protect(MappingFlags protectFlags) {
std::underlying_type_t<MappingFlags> newFlags = flags;
newFlags &= ~(MappingFlags::protRead | MappingFlags::protWrite | MappingFlags::protExecute);
newFlags |= protectFlags;
flags = static_cast<MappingFlags>(newFlags);
}
void Mapping::populateVirtualRange(uintptr_t offset, size_t size,
smarter::shared_ptr<WorkQueue> wq, PopulateVirtualRangeNode *node) {
async::detach_with_allocator(*kernelAlloc, [] (Mapping *self,
uintptr_t offset, size_t size,
smarter::shared_ptr<WorkQueue> wq, PopulateVirtualRangeNode *node) -> coroutine<void> {
size_t progress = 0;
while(progress < size) {
auto outcome = co_await self->touchVirtualPage(offset + progress, wq);
if(!outcome) {
node->result = outcome.error();
node->resume();
co_return;
}
progress += outcome.value().range.get<1>();
}
node->result = frg::success;
node->resume();
}(this, offset, size, std::move(wq), node));
}
uint32_t Mapping::compilePageFlags() {
uint32_t pageFlags = 0;
// TODO: Allow inaccessible mappings.
assert(flags & MappingFlags::protRead);
if(flags & MappingFlags::protWrite)
pageFlags |= page_access::write;
if(flags & MappingFlags::protExecute)
pageFlags |= page_access::execute;
return pageFlags;
}
void Mapping::lockVirtualRange(uintptr_t offset, size_t size,
smarter::shared_ptr<WorkQueue> wq, LockVirtualRangeNode *node) {
// This can be removed if we change the return type of asyncLockRange to frg::expected.
auto transformError = [node] (Error e) {
if(e == Error::success) {
node->result = {};
}else{
node->result = e;
}
node->resume();
};
async::detach_with_allocator(*kernelAlloc,
async::transform(view->asyncLockRange(viewOffset + offset, size, std::move(wq)),
transformError));
}
void Mapping::unlockVirtualRange(uintptr_t offset, size_t size) {
view->unlockRange(viewOffset + offset, size);
}
frg::tuple<PhysicalAddr, CachingMode>
Mapping::resolveRange(ptrdiff_t offset) {
assert(state == MappingState::active);
// TODO: This function should be rewritten.
assert((size_t)offset + kPageSize <= length);
auto bundle_range = view->peekRange(viewOffset + offset);
return frg::tuple<PhysicalAddr, CachingMode>{bundle_range.get<0>(), bundle_range.get<1>()};
}
void Mapping::touchVirtualPage(uintptr_t offset,
smarter::shared_ptr<WorkQueue> wq, TouchVirtualPageNode *node) {
assert(state == MappingState::active);
async::detach_with_allocator(*kernelAlloc, [] (Mapping *self, uintptr_t offset,
smarter::shared_ptr<WorkQueue> wq, TouchVirtualPageNode *node) -> coroutine<void> {
FetchFlags fetchFlags = 0;
if(self->flags & MappingFlags::dontRequireBacking)
fetchFlags |= FetchNode::disallowBacking;
if(auto e = co_await self->view->asyncLockRange(
(self->viewOffset + offset) & ~(kPageSize - 1), kPageSize,
wq); e != Error::success)
assert(!"asyncLockRange() failed");
auto [error, range, rangeFlags] = co_await self->view->fetchRange(
self->viewOffset + offset, wq);
// TODO: Update RSS, handle dirty pages, etc.
auto pageOffset = self->address + offset;
self->owner->_ops->unmapSingle4k(pageOffset & ~(kPageSize - 1));
self->owner->_ops->mapSingle4k(pageOffset & ~(kPageSize - 1),
range.get<0>() & ~(kPageSize - 1),
self->compilePageFlags(), range.get<2>());
self->owner->_residuentSize += kPageSize;
logRss(self->owner.get());
self->view->unlockRange((self->viewOffset + offset) & ~(kPageSize - 1), kPageSize);
node->result = TouchVirtualResult{range, false};
node->resume();
}(this, offset, std::move(wq), node));
}
coroutine<void> Mapping::runEvictionLoop() {
while(true) {
auto eviction = co_await view->pollEviction(&observer, cancelEviction);
if(!eviction)
break;
if(eviction.offset() + eviction.size() <= viewOffset
|| eviction.offset() >= viewOffset + length) {
eviction.done();
continue;
}
// Begin and end offsets of the region that we need to unmap.
auto shootBegin = frg::max(eviction.offset(), viewOffset);
auto shootEnd = frg::min(eviction.offset() + eviction.size(),
viewOffset + length);
// Offset from the beginning of the mapping.
auto shootOffset = shootBegin - viewOffset;
auto shootSize = shootEnd - shootBegin;
assert(shootSize);
assert(!(shootOffset & (kPageSize - 1)));
assert(!(shootSize & (kPageSize - 1)));
// Wait until we are allowed to evict existing pages.
// TODO: invent a more specialized synchronization mechanism for this.
{
auto irq_lock = frg::guard(&irqMutex());
auto lock = frg::guard(&evictMutex);
}
// TODO: Perform proper locking here!
// Unmap the memory range.
for(size_t pg = 0; pg < shootSize; pg += kPageSize) {
auto status = owner->_ops->unmapSingle4k(address + shootOffset + pg);
if(!(status & page_status::present))
continue;
if(status & page_status::dirty)
view->markDirty(viewOffset + shootOffset + pg, kPageSize);
owner->_residuentSize -= kPageSize;
}
co_await owner->_ops->shootdown(address + shootOffset, shootSize);
eviction.done();
}
evictionDoneEvent.raise();
}
// --------------------------------------------------------
// CowMapping
// --------------------------------------------------------
CowChain::CowChain(smarter::shared_ptr<CowChain> chain)
: _superChain{std::move(chain)}, _pages{*kernelAlloc} {
}
CowChain::~CowChain() {
if(logCleanup)
infoLogger() << "thor: Releasing CowChain" << frg::endlog;
for(auto it = _pages.begin(); it != _pages.end(); ++it) {
auto physical = it->load(std::memory_order_relaxed);
assert(physical != PhysicalAddr(-1));
physicalAllocator->free(physical, kPageSize);
}
}
// --------------------------------------------------------
// VirtualSpace
// --------------------------------------------------------
VirtualSpace::VirtualSpace(VirtualOperations *ops)
: _ops{ops} { }
void VirtualSpace::setupInitialHole(VirtualAddr address, size_t size) {
auto hole = frg::construct<Hole>(*kernelAlloc, address, size);
_holes.insert(hole);
}
VirtualSpace::~VirtualSpace() {
if(logCleanup)
infoLogger() << "\e[31mthor: VirtualSpace is destructed\e[39m" << frg::endlog;
while(_holes.get_root()) {
auto hole = _holes.get_root();
_holes.remove(hole);
frg::destruct(*kernelAlloc, hole);
}
}
void VirtualSpace::retire() {
if(logCleanup)
infoLogger() << "\e[31mthor: VirtualSpace is cleared\e[39m" << frg::endlog;
// TODO: Set some flag to make sure that no mappings are added/deleted.
auto mapping = _mappings.first();
while(mapping) {
assert(mapping->state == MappingState::active);
mapping->state = MappingState::zombie;
for(size_t progress = 0; progress < mapping->length; progress += kPageSize) {
VirtualAddr vaddr = mapping->address + progress;
auto status = _ops->unmapSingle4k(vaddr);
if(!(status & page_status::present))
continue;
if(status & page_status::dirty)
mapping->view->markDirty(mapping->viewOffset + progress, kPageSize);
_residuentSize -= kPageSize;
}
mapping = MappingTree::successor(mapping);
}
// TODO: It would be less ugly to run this in a non-detached way.
async::detach_with_allocator(*kernelAlloc, [] (smarter::shared_ptr<VirtualSpace> self)
-> coroutine<void> {
co_await self->_ops->retire();
while(self->_mappings.get_root()) {
auto mapping = self->_mappings.get_root();
self->_mappings.remove(mapping);
assert(mapping->state == MappingState::zombie);
mapping->state = MappingState::retired;
if(mapping->view->canEvictMemory()) {
mapping->cancelEviction.cancel();
co_await mapping->evictionDoneEvent.wait();
}
mapping->view->removeObserver(&mapping->observer);
mapping->selfPtr.ctr()->decrement();
}
}(selfPtr.lock()));
}
smarter::shared_ptr<Mapping> VirtualSpace::getMapping(VirtualAddr address) {
auto irq_lock = frg::guard(&irqMutex());
auto space_guard = frg::guard(&_mutex);
return _findMapping(address);
}
bool VirtualSpace::map(smarter::borrowed_ptr<MemorySlice> slice,
VirtualAddr address, size_t offset, size_t length, uint32_t flags,
MapNode *node) {
assert(length);
assert(!(length % kPageSize));
if(offset + length > slice->length()) {
node->nodeResult_.emplace(Error::bufferTooSmall);
return true;
}
VirtualAddr actualAddress;
{
auto irqLock = frg::guard(&irqMutex());
auto spaceLock = frg::guard(&_mutex);
if(flags & kMapFixed) {
assert(address);
assert((address % kPageSize) == 0);
actualAddress = _allocateAt(address, length);
}else{
actualAddress = _allocate(length, flags);
}
assert(actualAddress);
// infoLogger() << "Creating new mapping at " << (void *)actualAddress
// << ", length: " << (void *)length << frg::endlog;
// Setup a new Mapping object.
std::underlying_type_t<MappingFlags> mappingFlags = 0;
// TODO: The upgrading mechanism needs to be arch-specific:
// Some archs might only support RX, while other support X.
auto mask = kMapProtRead | kMapProtWrite | kMapProtExecute;
if((flags & mask) == (kMapProtRead | kMapProtWrite | kMapProtExecute)
|| (flags & mask) == (kMapProtWrite | kMapProtExecute)) {
// WX is upgraded to RWX.
mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite
| MappingFlags::protExecute;
}else if((flags & mask) == (kMapProtRead | kMapProtExecute)
|| (flags & mask) == kMapProtExecute) {
// X is upgraded to RX.
mappingFlags |= MappingFlags::protRead | MappingFlags::protExecute;
}else if((flags & mask) == (kMapProtRead | kMapProtWrite)
|| (flags & mask) == kMapProtWrite) {
// W is upgraded to RW.
mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite;
}else if((flags & mask) == kMapProtRead) {
mappingFlags |= MappingFlags::protRead;
}else{
assert(!(flags & mask));
}
if(flags & kMapDontRequireBacking)
mappingFlags |= MappingFlags::dontRequireBacking;
auto mapping = smarter::allocate_shared<Mapping>(Allocator{},
length, static_cast<MappingFlags>(mappingFlags),
slice.lock(), slice->offset() + offset);
mapping->selfPtr = mapping;
assert(!(flags & kMapPopulate));
// Install the new mapping object.
mapping->tie(selfPtr.lock(), actualAddress);
_mappings.insert(mapping.get());
assert(mapping->state == MappingState::null);
mapping->state = MappingState::active;
mapping->view->addObserver(&mapping->observer);
if(mapping->view->canEvictMemory())
async::detach_with_allocator(*kernelAlloc, mapping->runEvictionLoop());
uint32_t pageFlags = 0;
if((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protWrite)
pageFlags |= page_access::write;
if((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protExecute)
pageFlags |= page_access::execute;
// TODO: Allow inaccessible mappings.
assert((mappingFlags & MappingFlags::permissionMask) & MappingFlags::protRead);
{
// Synchronize with the eviction loop.
auto irqLock = frg::guard(&irqMutex());
auto lock = frg::guard(&mapping->evictMutex);
for(size_t progress = 0; progress < mapping->length; progress += kPageSize) {
auto physicalRange = mapping->view->peekRange(mapping->viewOffset + progress);
VirtualAddr vaddr = mapping->address + progress;
assert(!_ops->isMapped(vaddr));
if(physicalRange.get<0>() != PhysicalAddr(-1)) {
_ops->mapSingle4k(vaddr, physicalRange.get<0>(),
pageFlags, physicalRange.get<1>());
_residuentSize += kPageSize;
logRss(this);
}
}
}
mapping.release(); // VirtualSpace owns one reference.
}
node->nodeResult_.emplace(actualAddress);
return true;
}
bool VirtualSpace::protect(VirtualAddr address, size_t length,
uint32_t flags, AddressProtectNode *node) {
std::underlying_type_t<MappingFlags> mappingFlags = 0;
// TODO: The upgrading mechanism needs to be arch-specific:
// Some archs might only support RX, while other support X.
auto mask = kMapProtRead | kMapProtWrite | kMapProtExecute;
if((flags & mask) == (kMapProtRead | kMapProtWrite | kMapProtExecute)
|| (flags & mask) == (kMapProtWrite | kMapProtExecute)) {
// WX is upgraded to RWX.
mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite
| MappingFlags::protExecute;
}else if((flags & mask) == (kMapProtRead | kMapProtExecute)
|| (flags & mask) == kMapProtExecute) {
// X is upgraded to RX.
mappingFlags |= MappingFlags::protRead | MappingFlags::protExecute;
}else if((flags & mask) == (kMapProtRead | kMapProtWrite)
|| (flags & mask) == kMapProtWrite) {
// W is upgraded to RW.
mappingFlags |= MappingFlags::protRead | MappingFlags::protWrite;
}else if((flags & mask) == kMapProtRead) {
mappingFlags |= MappingFlags::protRead;
}else{
assert(!(flags & mask));
}
auto irq_lock = frg::guard(&irqMutex());
auto space_guard = frg::guard(&_mutex);
auto mapping = _findMapping(address);
assert(mapping);
// TODO: Allow shrinking of the mapping.
assert(mapping->address == address);
assert(mapping->length == length);
mapping->protect(static_cast<MappingFlags>(mappingFlags));
assert(mapping->state == MappingState::active);
uint32_t pageFlags = 0;
if((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protWrite)
pageFlags |= page_access::write;
if((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protExecute)
pageFlags |= page_access::execute;
// TODO: Allow inaccessible mappings.
assert((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protRead);
{
// Synchronize with the eviction loop.
auto irqLock = frg::guard(&irqMutex());
auto lock = frg::guard(&mapping->evictMutex);
for(size_t progress = 0; progress < mapping->length; progress += kPageSize) {
auto physicalRange = mapping->view->peekRange(mapping->viewOffset + progress);
VirtualAddr vaddr = mapping->address + progress;
auto status = _ops->unmapSingle4k(vaddr);
if(!(status & page_status::present))
continue;
if(status & page_status::dirty)
mapping->view->markDirty(mapping->viewOffset + progress, kPageSize);
if(physicalRange.get<0>() != PhysicalAddr(-1)) {
_ops->mapSingle4k(vaddr, physicalRange.get<0>(),
pageFlags, physicalRange.get<1>());
}else{
_residuentSize -= kPageSize;
}
}
}
async::detach_with_allocator(*kernelAlloc,
async::transform(_ops->shootdown(address, length), [=] () {
node->complete();
}));
return false;
}
bool VirtualSpace::unmap(VirtualAddr address, size_t length, AddressUnmapNode *node) {
smarter::shared_ptr<Mapping> mapping;
{
auto irqLock = frg::guard(&irqMutex());
auto lock = frg::guard(&_mutex);
mapping = _findMapping(address);
assert(mapping);
// TODO: Allow shrinking of the mapping.
assert(mapping->address == address);
assert(mapping->length == length);
assert(mapping->state == MappingState::active);
mapping->state = MappingState::zombie;
}
// Mark pages as dirty and unmap without holding a lock.
for(size_t progress = 0; progress < mapping->length; progress += kPageSize) {
VirtualAddr vaddr = mapping->address + progress;
auto status = _ops->unmapSingle4k(vaddr);
if(!(status & page_status::present))
continue;
if(status & page_status::dirty)
mapping->view->markDirty(mapping->viewOffset + progress, kPageSize);
_residuentSize -= kPageSize;
}
static constexpr auto deleteMapping = [] (VirtualSpace *space, Mapping *mapping) {
space->_mappings.remove(mapping);
assert(mapping->state == MappingState::zombie);
mapping->state = MappingState::retired;
if(mapping->view->canEvictMemory())
mapping->cancelEviction.cancel();
// TODO: It would be less ugly to run this in a non-detached way.
auto cleanUpObserver = [] (Mapping *mapping) -> coroutine<void> {
if(mapping->view->canEvictMemory())
co_await mapping->evictionDoneEvent.wait();
mapping->view->removeObserver(&mapping->observer);
mapping->selfPtr.ctr()->decrement();
};
async::detach_with_allocator(*kernelAlloc, cleanUpObserver(mapping));
};
static constexpr auto closeHole = [] (VirtualSpace *space, VirtualAddr address, size_t length) {
// Find the holes that preceede/succeede mapping.
Hole *pre;
Hole *succ;
auto current = space->_holes.get_root();
while(true) {
assert(current);
if(address < current->address()) {
if(HoleTree::get_left(current)) {
current = HoleTree::get_left(current);
}else{
pre = HoleTree::predecessor(current);
succ = current;
break;
}
}else{
assert(address >= current->address() + current->length());
if(HoleTree::get_right(current)) {
current = HoleTree::get_right(current);
}else{
pre = current;
succ = HoleTree::successor(current);
break;
}
}
}
// Try to merge the new hole and the existing ones.
if(pre && pre->address() + pre->length() == address
&& succ && address + length == succ->address()) {
auto hole = frg::construct<Hole>(*kernelAlloc, pre->address(),
pre->length() + length + succ->length());
space->_holes.remove(pre);
space->_holes.remove(succ);
space->_holes.insert(hole);
frg::destruct(*kernelAlloc, pre);
frg::destruct(*kernelAlloc, succ);
}else if(pre && pre->address() + pre->length() == address) {
auto hole = frg::construct<Hole>(*kernelAlloc,
pre->address(), pre->length() + length);
space->_holes.remove(pre);
space->_holes.insert(hole);
frg::destruct(*kernelAlloc, pre);
}else if(succ && address + length == succ->address()) {
auto hole = frg::construct<Hole>(*kernelAlloc,
address, length + succ->length());
space->_holes.remove(succ);
space->_holes.insert(hole);
frg::destruct(*kernelAlloc, succ);
}else{
auto hole = frg::construct<Hole>(*kernelAlloc,
address, length);
space->_holes.insert(hole);
}
};
async::detach_with_allocator(*kernelAlloc,
async::transform(_ops->shootdown(address, length), [=] () {
deleteMapping(this, mapping.get());
closeHole(this, address, length);
node->complete();
}));
return false;
}
void VirtualSpace::synchronize(VirtualAddr address, size_t size, SynchronizeNode *node) {
auto misalign = address & (kPageSize - 1);
auto alignedAddress = address & ~(kPageSize - 1);
auto alignedSize = (size + misalign + kPageSize - 1) & ~(kPageSize - 1);
async::detach_with_allocator(*kernelAlloc, [] (VirtualSpace *self,
VirtualAddr alignedAddress, size_t alignedSize,
SynchronizeNode *node) -> coroutine<void> {
size_t overallProgress = 0;
while(overallProgress < alignedSize) {
smarter::shared_ptr<Mapping> mapping;
{
auto irqLock = frg::guard(&irqMutex());
auto spaceGuard = frg::guard(&self->_mutex);
mapping = self->_findMapping(alignedAddress + overallProgress);
}
assert(mapping);
auto mappingOffset = alignedAddress + overallProgress - mapping->address;
auto mappingChunk = frg::min(alignedSize - overallProgress,
mapping->length - mappingOffset);
assert(mapping->state == MappingState::active);
assert(mappingOffset + mappingChunk <= mapping->length);
// Synchronize with the eviction loop.
{
auto irqLock = frg::guard(&irqMutex());
auto lock = frg::guard(&mapping->evictMutex);
for(size_t chunkProgress = 0; chunkProgress < mappingChunk;
chunkProgress += kPageSize) {
VirtualAddr vaddr = mapping->address + mappingOffset + chunkProgress;
auto status = self->_ops->cleanSingle4k(vaddr);
if(!(status & page_status::present))
continue;
if(status & page_status::dirty)
mapping->view->markDirty(mapping->viewOffset + chunkProgress, kPageSize);
}
}
overallProgress += mappingChunk;
}
co_await self->_ops->shootdown(alignedAddress, alignedSize);
node->resume();
}(this, alignedAddress, alignedSize, node));
}
frg::optional<bool>
VirtualSpace::handleFault(VirtualAddr address, uint32_t faultFlags,
smarter::shared_ptr<WorkQueue> wq, FaultNode *node) {
smarter::shared_ptr<Mapping> mapping;
{
auto irq_lock = frg::guard(&irqMutex());
auto space_guard = frg::guard(&_mutex);
mapping = _findMapping(address);
}
if(!mapping)
return false;
// Here we do the mapping-based fault handling.
if(faultFlags & VirtualSpace::kFaultWrite)
if(!((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protWrite)) {
return true;
}
if(faultFlags & VirtualSpace::kFaultExecute)
if(!((mapping->flags & MappingFlags::permissionMask) & MappingFlags::protExecute)) {
return true;
}
async::detach_with_allocator(*kernelAlloc, [] (smarter::shared_ptr<Mapping> mapping,
uintptr_t address,
smarter::shared_ptr<WorkQueue> wq, FaultNode *node) -> coroutine<void> {
auto faultPage = (address - mapping->address) & ~(kPageSize - 1);
auto outcome = co_await mapping->touchVirtualPage(faultPage, std::move(wq));
if(!outcome) {
node->complete(false);
co_return;
}
// Spurious page faults are the result of race conditions.
// They should be rare. If they happen too often, something is probably wrong!
if(outcome.value().spurious)
infoLogger() << "\e[33m" "thor: Spurious page fault"
"\e[39m" << frg::endlog;
node->complete(true);
}(std::move(mapping), address, std::move(wq), node));
return {};
}
smarter::shared_ptr<Mapping> VirtualSpace::_findMapping(VirtualAddr address) {
auto current = _mappings.get_root();
while(current) {
if(address < current->address) {
current = MappingTree::get_left(current);
}else if(address >= current->address + current->length) {
current = MappingTree::get_right(current);
}else{
assert(address >= current->address
&& address < current->address + current->length);
return current->selfPtr.lock();
}
}
return nullptr;
}
VirtualAddr VirtualSpace::_allocate(size_t length, MapFlags flags) {
assert(length > 0);
assert((length % kPageSize) == 0);
// infoLogger() << "Allocate virtual memory area"
// << ", size: 0x" << frg::hex_fmt(length) << frg::endlog;
if(_holes.get_root()->largestHole < length)
return 0; // TODO: Return something else here?
auto current = _holes.get_root();
while(true) {
if(flags & kMapPreferBottom) {
// Try to allocate memory at the bottom of the range.
if(HoleTree::get_left(current)
&& HoleTree::get_left(current)->largestHole >= length) {
current = HoleTree::get_left(current);
continue;
}
if(current->length() >= length) {
// Note that _splitHole can deallocate the hole!
auto address = current->address();
_splitHole(current, 0, length);
return address;
}
assert(HoleTree::get_right(current));
assert(HoleTree::get_right(current)->largestHole >= length);
current = HoleTree::get_right(current);
}else{
// Try to allocate memory at the top of the range.
assert(flags & kMapPreferTop);
if(HoleTree::get_right(current)
&& HoleTree::get_right(current)->largestHole >= length) {
current = HoleTree::get_right(current);
continue;
}
if(current->length() >= length) {
// Note that _splitHole can deallocate the hole!
auto offset = current->length() - length;
auto address = current->address() + offset;
_splitHole(current, offset, length);
return address;
}
assert(HoleTree::get_left(current));
assert(HoleTree::get_left(current)->largestHole >= length);
current = HoleTree::get_left(current);
}
}
}
VirtualAddr VirtualSpace::_allocateAt(VirtualAddr address, size_t length) {
assert(!(address % kPageSize));
assert(!(length % kPageSize));
auto current = _holes.get_root();
while(true) {
// TODO: Otherwise, this method fails.
assert(current);
if(address < current->address()) {
current = HoleTree::get_left(current);
}else if(address >= current->address() + current->length()) {
current = HoleTree::get_right(current);
}else{
assert(address >= current->address()
&& address < current->address() + current->length());
break;
}
}
_splitHole(current, address - current->address(), length);
return address;
}
void VirtualSpace::_splitHole(Hole *hole, VirtualAddr offset, size_t length) {
assert(length);
assert(offset + length <= hole->length());
_holes.remove(hole);
if(offset) {
auto predecessor = frg::construct<Hole>(*kernelAlloc, hole->address(), offset);
_holes.insert(predecessor);
}
if(offset + length < hole->length()) {
auto successor = frg::construct<Hole>(*kernelAlloc,
hole->address() + offset + length, hole->length() - (offset + length));
_holes.insert(successor);
}
frg::destruct(*kernelAlloc, hole);
}
// --------------------------------------------------------
// AddressSpace
// --------------------------------------------------------
void AddressSpace::activate(smarter::shared_ptr<AddressSpace, BindableHandle> space) {
auto pageSpace = &space->pageSpace_;
PageSpace::activate(smarter::shared_ptr<PageSpace>{space->selfPtr.lock(), pageSpace});
}
AddressSpace::AddressSpace()
: VirtualSpace{&ops_}, ops_{this} { }
AddressSpace::~AddressSpace() { }
void AddressSpace::dispose(BindableHandle) {
retire();
}
// --------------------------------------------------------
// MemoryViewLockHandle.
// --------------------------------------------------------
MemoryViewLockHandle::~MemoryViewLockHandle() {
if(_active)
_view->unlockRange(_offset, _size);
}
// --------------------------------------------------------
// AddressSpaceLockHandle
// --------------------------------------------------------
AddressSpaceLockHandle::AddressSpaceLockHandle(smarter::shared_ptr<AddressSpace, BindableHandle> space,
void *pointer, size_t length)
: _space{std::move(space)}, _address{reinterpret_cast<uintptr_t>(pointer)}, _length{length} {
if(!_length)
return;
assert(_address);
// TODO: Verify the mapping's size.
_mapping = _space->getMapping(_address);
assert(_mapping);
}
AddressSpaceLockHandle::~AddressSpaceLockHandle() {
if(!_length)
return;
if(_active)
_mapping->unlockVirtualRange(_address - _mapping->address, _length);
}
bool AddressSpaceLockHandle::acquire(smarter::shared_ptr<WorkQueue> wq, AcquireNode *node) {
if(!_length) {
_active = true;
return true;
}
async::detach_with_allocator(*kernelAlloc, [] (AddressSpaceLockHandle *self,
smarter::shared_ptr<WorkQueue> wq, AcquireNode *node) -> coroutine<void> {
auto misalign = self->_address & (kPageSize - 1);
auto lockOutcome = co_await self->_mapping->lockVirtualRange(
(self->_address - self->_mapping->address) & ~(kPageSize - 1),
(self->_length + misalign + kPageSize - 1) & ~(kPageSize - 1), wq);
assert(lockOutcome);
auto populateOutcome = co_await self->_mapping->populateVirtualRange(
(self->_address - self->_mapping->address) & ~(kPageSize - 1),
(self->_length + misalign + kPageSize - 1) & ~(kPageSize - 1), wq);
assert(populateOutcome);
self->_active = true;
node->complete();
}(this, std::move(wq), node));
return false;
}
PhysicalAddr AddressSpaceLockHandle::getPhysical(size_t offset) {
assert(_active);
assert(offset < _length);
return _resolvePhysical(_address + offset);
}
void AddressSpaceLockHandle::load(size_t offset, void *pointer, size_t size) {
assert(_active);
assert(offset + size <= _length);
size_t progress = 0;
while(progress < size) {
VirtualAddr write = (VirtualAddr)_address + offset + progress;
size_t misalign = (VirtualAddr)write % kPageSize;
size_t chunk = frg::min(kPageSize - misalign, size - progress);
PhysicalAddr page = _resolvePhysical(write - misalign);
assert(page != PhysicalAddr(-1));
PageAccessor accessor{page};
memcpy((char *)pointer + progress, (char *)accessor.get() + misalign, chunk);
progress += chunk;
}
}
Error AddressSpaceLockHandle::write(size_t offset, const void *pointer, size_t size) {
assert(_active);
assert(offset + size <= _length);
size_t progress = 0;
while(progress < size) {
VirtualAddr write = (VirtualAddr)_address + offset + progress;
size_t misalign = (VirtualAddr)write % kPageSize;
size_t chunk = frg::min(kPageSize - misalign, size - progress);
PhysicalAddr page = _resolvePhysical(write - misalign);
assert(page != PhysicalAddr(-1));
PageAccessor accessor{page};
memcpy((char *)accessor.get() + misalign, (char *)pointer + progress, chunk);
progress += chunk;
}
return Error::success;
}
PhysicalAddr AddressSpaceLockHandle::_resolvePhysical(VirtualAddr vaddr) {
auto range = _mapping->resolveRange(vaddr - _mapping->address);
return range.get<0>();
}
// --------------------------------------------------------
// NamedMemoryViewLock.
// --------------------------------------------------------
NamedMemoryViewLock::~NamedMemoryViewLock() { }
} // namespace thor
| 31.782178 | 103 | 0.673115 | 64 |
030c119e42ce28723ff3883ec3513ba8666b1d52 | 16,531 | cpp | C++ | dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 2 | 2020-08-20T03:40:24.000Z | 2021-02-07T20:31:43.000Z | dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | null | null | null | dev/spark/Gem/Code/Components/GameManagerSystemComponent.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z |
#include "spark_precompiled.h"
#include <ISystem.h>
#include <CryAction.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Component/Entity.h>
#include <AzFramework/Script/ScriptComponent.h>
#include <AzCore/Asset/AssetManagerBus.h>
#include <AzFramework/Entity/EntityContextBus.h>
#include <AzFramework/Entity/EntityContext.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/std/algorithm.h>
#include "GameManagerSystemComponent.h"
#include "Components/AbilityComponent.h"
#include "Components/UnitComponent.h"
#include "Components/GameManagerComponent.h"
#include "Components/CameraControllerComponent.h"
#include "Components/GameNetSyncComponent.h"
#include "Components/ProjectileManagerSystemComponent.h"
#include "Components/VariableManagerComponent.h"
#include <AzFramework/Network/NetBindingComponent.h>
#include "Busses/UnitBus.h"
#include "Utils/StringUtils.h"
#include "Utils/FileUtils.h"
#include <AzFramework/Entity/GameEntityContextBus.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include "Utils/JsonUtils.h"
#include "Utils/Log.h"
using namespace spark;
AZStd::vector<AZStd::string> GameManagerSystemComponent::s_filenames;
AZStd::vector<AZStd::string> GameManagerSystemComponent::s_directories;
void GameManagerSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
{
serialize->Class<GameManagerSystemComponent, AZ::Component>()
->Version(0)
;
if (AZ::EditContext* ec = serialize->GetEditContext())
{
ec->Class<GameManagerSystemComponent>("GameManagerSystemComponent", "Game utilities and management")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
// ->Attribute(AZ::Edit::Attributes::Category, "spark")
// ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game"));
//;
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System"))
->Attribute(AZ::Edit::Attributes::AutoExpand, true);
}
}
if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->EBus<GameManagerSystemRequestBus>("GameManagerSystemRequestBus")
->Event("ExecuteConsoleCommand", &GameManagerSystemRequestBus::Events::ExecuteConsoleCommand)
->Event("LoadGameFile", &GameManagerSystemRequestBus::Events::LoadGameFile)
->Event("LoadGameMode", &GameManagerSystemRequestBus::Events::LoadGameMode)
->Event("PlayGame", &GameManagerSystemRequestBus::Events::PlayGame);
}
}
void GameManagerSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("GameManagerSystemService"));
}
void GameManagerSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("GameManagerSystemService"));
}
void GameManagerSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
(void)required;
}
void GameManagerSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
(void)dependent;
}
void GameManagerSystemComponent::Init()
{
}
void GameManagerSystemComponent::Activate()
{
GameManagerSystemRequestBus::Handler::BusConnect();
GameManagerNotificationBus::Handler::BusConnect();
}
void GameManagerSystemComponent::Deactivate()
{
GameManagerNotificationBus::Handler::BusDisconnect();
GameManagerSystemRequestBus::Handler::BusDisconnect();
}
bool GameManagerSystemComponent::LoadGameFile(AZStd::string filename)
{
//"header" guard
if (!FileUtils::FileExists(filename))
{
// try some file extensions
if (FileUtils::FileExists(filename + ".json"))
{
filename = filename + ".json";
}
else if (FileUtils::FileExists(filename + ".txt"))
{
filename = filename + ".txt";
}
}
auto found = std::find(s_filenames.begin(), s_filenames.end(), filename);
if (found != s_filenames.end())
{
return false;
}
s_filenames.push_back(filename);
auto result = FileUtils::ReadJsonFile(filename);
if (!result.IsSuccess())
{
sWARNING("Unable to read game file \""+filename +"\" error:"+ result.GetError());
return false;
}
auto document = result.TakeValue();
//libraries
auto import = document.FindMember("import");
if (import != document.MemberEnd() && import->value.IsArray())
{
for (auto it = import->value.Begin(); it != import->value.End(); ++it)
{
if (it->IsString())
{
LoadGameMode(it->GetString());
}
}
document.EraseMember(import);
}
//other files
auto include = document.FindMember("include");
if (include != document.MemberEnd() && include->value.IsArray())
{
for (auto it = include->value.Begin(); it != include->value.End(); ++it)
{
if (it->IsString())
{
AZStd::string newfile(it->GetString());
StringUtils::trim(newfile);
AZStd::size_t found = filename.find_last_of("/\\");
AZStd::string path = filename.substr(0, found);
LoadGameFile(AZStd::string::format("%s/%s", path.c_str() , newfile.c_str()));
}
}
document.EraseMember(include);
}
JsonUtils::MergeObjects(document,m_gameDocument, document.GetAllocator());
m_gameDocument.Swap(document);
sLOG("GameManagerSystemComponent::LoadGameFile file loaded correctly : "+filename);
sLOG(JsonUtils::ToString(m_gameDocument));
return true;
}
bool GameManagerSystemComponent::LoadGameMode(AZStd::string gamemodeName)
{
AZStd::string gamemodePath = AZStd::string::format("%s/gamemode/%s", gEnv->pFileIO->GetAlias("@assets@"), gamemodeName.c_str());
bool result = LoadGameFile( gamemodePath + "/game.txt");
if (result)
{
s_directories.push_back(gamemodePath);
}
return result;
}
void GameManagerSystemComponent::PlayGame()
{
using namespace rapidjson;
if (!m_gameDocument.IsObject() || !m_gameDocument.HasMember("gamemode"))
{
sWARNING("gamemode was not defined");
return;
}
rapidjson::Value &info = m_gameDocument["gamemode"];
//load map
AZStd::string map_name = info.HasMember("map") ? info["map"].GetString() : "emptylevel";
//todo check for injection attack
ExecuteConsoleCommand(AZStd::string::format("map %s", map_name.c_str()));
////create camera
//const AZ::Data::AssetType& dynamicSliceAssetType = azrtti_typeid<AZ::DynamicPrefabAsset>();
//{
// AZ::Data::AssetId assetId;
// AZStd::string str = AZStd::string::format("%s/Slices/Camera.slice", gEnv->pFileIO->GetAlias("@assets@"));
// CryLog("dynamicSlice Path: %s", str.c_str());
// EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), dynamicSliceAssetType, true);
// if (assetId.IsValid()) {
// CryLog("Loading dynamicSlice");
// AZ::Data::Asset<AZ::DynamicPrefabAsset> dynamicSliceAsset(assetId, dynamicSliceAssetType);
// AzFramework::SliceInstantiationTicket ticket;
// AZ::Transform transform;
// transform.SetFromEulerDegrees(AZ::Vector3(305, 0, 0));
// transform.SetPosition(500, 500, 50);
// EBUS_EVENT_RESULT(ticket, AzFramework::GameEntityContextRequestBus, InstantiateDynamicSlice, dynamicSliceAsset, transform, nullptr);
// }
// else
// {
// AZ_Error(0, false, "cannot instantiate camera slice");
// }
//}
m_tickCounter = 300;
AZ::SystemTickBus::Handler::BusConnect();
}
void GameManagerSystemComponent::CreateGameManager()
{
bool gameManagerAlreadyExists = false;
EBUS_EVENT_RESULT(gameManagerAlreadyExists, GameManagerRequestBus, GameManagerAlreadyExists);
if (gameManagerAlreadyExists)
{
AZ_Printf(0, "GameManager already exists");
}
else
{
AZ_Printf(0, "GameManager is missing : creating the default one");
rapidjson::Value &info = m_gameDocument["gamemode"];
//create game manager
AZ::Entity *gameManager = aznew AZ::Entity("GameManager");
if (gameManager) {
GameManagerComponent* gm = gameManager->CreateComponent<GameManagerComponent>();
gameManager->CreateComponent<ProjectileManagerSystemComponent>();
gameManager->CreateComponent<GameNetSyncComponent>();
gameManager->CreateComponent<AzFramework::NetBindingComponent>();
const AZ::Data::AssetType& scriptAssetType = azrtti_typeid<AZ::ScriptAsset>();
////script for showing cursor
//AzFramework::ScriptComponent *cursor = gameManager->CreateComponent<AzFramework::ScriptComponent>();
//{
// AZ::Data::AssetId assetId;
// AZStd::string str = AZStd::string::format("%s/scripts/ShowCursor.lua", gEnv->pFileIO->GetAlias("@assets@"));
// CryLog("Script Path: %s", str.c_str());
// EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true);
// //EBUS_EVENT( AZ::Data::AssetCatalogRequestBus, UnregisterAsset, assetId);
// //EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true);
// if (assetId.IsValid()) {
// CryLog("Setting Script.");
// AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType);
// cursor->SetScript(scriptAsset);
// }
//}
//script for handling modifiers
AzFramework::ScriptComponent *modifiers = gameManager->CreateComponent<AzFramework::ScriptComponent>();
{
AZ::Data::AssetId assetId;
AZStd::string str = AZStd::string::format("%s/scripts/modifier.lua", gEnv->pFileIO->GetAlias("@assets@"));
CryLog("Script Path: %s", str.c_str());
EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true);
if (assetId.IsValid()) {
CryLog("Setting Script.");
AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType);
modifiers->SetScript(scriptAsset);
}
}
//script for handling game mode
if (info.HasMember("lua-file")) {
AzFramework::ScriptComponent *scriptComponent = gameManager->CreateComponent<AzFramework::ScriptComponent>();
AZ::Data::AssetId assetId;
AZStd::string str = AZStd::string::format("%s/scripts/%s", gEnv->pFileIO->GetAlias("@assets@"), info["lua-file"].GetString());
CryLog("Script Path: %s", str.c_str());
EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true);
if (assetId.IsValid()) {
CryLog("Setting Script.");
AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType);
scriptComponent->SetScript(scriptAsset);
}
}
////script for loading the HUD canvas
//AzFramework::ScriptComponent *canvas = gameManager->CreateComponent<AzFramework::ScriptComponent>();
//{
// AZ::Data::AssetId assetId;
// AZStd::string str = AZStd::string::format("%s/scripts/LoadHUD.lua", gEnv->pFileIO->GetAlias("@assets@"));
// CryLog("Script Path: %s", str.c_str());
// EBUS_EVENT_RESULT(assetId, AZ::Data::AssetCatalogRequestBus, GetAssetIdByPath, str.c_str(), scriptAssetType, true);
// if (assetId.IsValid()) {
// CryLog("Setting Script.");
// AZ::Data::Asset<AZ::ScriptAsset> scriptAsset(assetId, scriptAssetType);
// canvas->SetScript(scriptAsset);
// }
//}
//gm->m_gameDocument.Swap(m_gameDocument);
gameManager->Init();
gameManager->Activate();
}
}
}
void GameManagerSystemComponent::OnSystemTick()
{
--m_tickCounter;
if (m_tickCounter <= 0)
{
CreateGameManager();
AZ::SystemTickBus::Handler::BusDisconnect();
}
}
void GameManagerSystemComponent::ExecuteConsoleCommand(AZStd::string cmd)
{
//todo check for injection attack
gEnv->pConsole->ExecuteString(cmd.c_str(), false, true);
}
struct DependeciesGraphNode
{
AZStd::vector<ItemTypeId> dependencies;
AZStd::vector<ItemTypeId> required_for;
};
void CalculateItemsDependencies(rapidjson::Document &document)
{
sLOG("CalculateItemsDependencies called");
if (!document.IsObject() || !document.HasMember("items"))return;
auto &allocator = document.GetAllocator();
auto &items = document["items"];
AZStd::unordered_map<ItemTypeId, DependeciesGraphNode> graph;
//get all node
for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item)
{
graph[item->name.GetString()] = DependeciesGraphNode();
}
//check and set dependencies and "required_for"( if the items in the dependency list exist )
for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item)
{
if (!item->value.IsObject() || !item->value.HasMember("dependencies"))continue;
auto &dependencies = item->value["dependencies"];
if (!dependencies.IsArray())continue;
AZStd::vector<ItemTypeId> dependencies_vector;
for (auto itr = dependencies.Begin(); itr != dependencies.End(); ++itr)
{
if (itr->IsString() && graph.find(itr->GetString()) != graph.end())
{
dependencies_vector.push_back(itr->GetString());
graph[itr->GetString()].required_for.push_back(item->name.GetString());
}
}
graph[item->name.GetString()].dependencies = dependencies_vector;
}
//update the json
for (auto item = items.MemberBegin(); item != items.MemberEnd(); ++item)
{
//sLOG(item->name.GetString()+" is "+JsonUtils::ToString(item->value));
if (!item->value.IsObject())continue;
rapidjson::Value dep(rapidjson::kArrayType);
for (auto d : graph[item->name.GetString()].dependencies)
{
rapidjson::Value str;
str.SetString(d.c_str(),allocator);
dep.PushBack(str,allocator);
}
rapidjson::Value req(rapidjson::kArrayType);
for (auto d : graph[item->name.GetString()].required_for)
{
rapidjson::Value str;
str.SetString(d.c_str(),allocator);
req.PushBack(str,allocator);
}
item->value.RemoveMember("dependencies");
item->value.RemoveMember("required_for");
item->value.AddMember("dependencies", dep, allocator);
item->value.AddMember("required_for", req, allocator);
}
}
void CalculateExtends(rapidjson::Value &object, rapidjson::Value &parent, rapidjson::Document &document)
{
if (!object.IsObject())return;
AZStd::vector<AZStd::string> extends;
auto extendsJson = object.FindMember("extends");
if (extendsJson != object.MemberEnd())
{
if (extendsJson->value.IsArray())
{
for (auto it = extendsJson->value.Begin(); it != extendsJson->value.End(); ++it)
{
if (it->IsString())
{
extends.push_back(it->GetString());
}
}
}
else if (extendsJson->value.IsString())
{
extends.push_back(extendsJson->value.GetString());
}
}
if (extendsJson != object.MemberEnd())
{
object.EraseMember(extendsJson); //so we don't create extend loops
}
for (auto e : extends)
{
auto path = StringUtils::SplitString(e, "/");
rapidjson::Value* root = &parent;
rapidjson::Value* value = JsonUtils::FindValue(path, *root); //try the relative path
root = &document;
if (!value)value = JsonUtils::FindValue(path, *root); //try the absolute path
if (value)
{
path.pop_back();
auto value_parent = JsonUtils::FindValue(path, *root);
CalculateExtends(*value, *value_parent, document);
JsonUtils::MergeObjects(object, *value, document.GetAllocator());
}
}
};
void CalculateExtends(rapidjson::Document &document)
{
sLOG("CalculateExtends called");
/* syntax is
"something_else":{
...
},
"something" : {
"extends" : "something_else",
...
}
*/
JsonUtils::ForeachMemberWithParent(document, [&document](rapidjson::Value &member, rapidjson::Value &parent)
{
CalculateExtends(member, parent, document);
});
}
void GameManagerSystemComponent::OnGameManagerActivated(AZ::Entity* gameManager)
{
AZ_Printf(0,"GameManagerSystemComponent:OnGameManagerActivated called");
AZ_Error("GameManagerSystemComponent", gameManager, " OnGameManagerActivated with null entity pointer");
GameManagerComponent* gm = gameManager->FindComponent<GameManagerComponent>();
AZ_Error("GameManagerSystemComponent", gm, " OnGameManagerActivated called, but the entity is without a GameManagerComponent");
AZ::SystemTickBus::Handler::BusDisconnect();
if (!m_gameDocument.IsObject() || m_gameDocument.MemberCount()==0)// !gm->m_gameDocument.IsObject() || gm->m_gameDocument.ObjectEmpty())
{
LoadGameMode(gm->GetGamemode());
}
CalculateExtends(m_gameDocument);
CalculateItemsDependencies(m_gameDocument);
AZStd::reverse(s_directories.begin(), s_directories.end());//imported gamemodes are inserted before, so we need to reverse the vector to have the priorities right
sLOG("final gamemode json is : "+JsonUtils::ToString(m_gameDocument));
gm->SetGameJson(m_gameDocument, s_directories);
m_gameDocument.SetObject();//clear the document and all for the next gamemode
s_filenames.clear();
s_directories.clear();
gm->StartGame();
}
| 30.443831 | 163 | 0.721432 | chrisinajar |
030f051b9c430e2f2dd8095b2a5b04b7dfb1beb8 | 10,593 | cc | C++ | mysql-server/storage/myisam/ft_update.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/myisam/ft_update.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/myisam/ft_update.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Written by Sergei A. Golubchik, who has a shared copyright to this code */
/* functions to work with full-text indices */
#include <math.h>
#include <sys/types.h>
#include <algorithm>
#include "my_byteorder.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_macros.h"
#include "storage/myisam/ftdefs.h"
#include "storage/myisam/myisamdef.h"
void _mi_ft_segiterator_init(MI_INFO *info, uint keynr, const uchar *record,
FT_SEG_ITERATOR *ftsi) {
DBUG_TRACE;
ftsi->num = info->s->keyinfo[keynr].keysegs;
ftsi->seg = info->s->keyinfo[keynr].seg;
ftsi->rec = record;
}
void _mi_ft_segiterator_dummy_init(const uchar *record, uint len,
FT_SEG_ITERATOR *ftsi) {
DBUG_TRACE;
ftsi->num = 1;
ftsi->seg = nullptr;
ftsi->pos = record;
ftsi->len = len;
}
/*
This function breaks convention "return 0 in success"
but it's easier to use like this
while(_mi_ft_segiterator())
so "1" means "OK", "0" means "EOF"
*/
uint _mi_ft_segiterator(FT_SEG_ITERATOR *ftsi) {
DBUG_TRACE;
if (!ftsi->num) return 0;
ftsi->num--;
if (!ftsi->seg) return 1;
ftsi->seg--;
if (ftsi->seg->null_bit &&
(ftsi->rec[ftsi->seg->null_pos] & ftsi->seg->null_bit)) {
ftsi->pos = nullptr;
return 1;
}
ftsi->pos = ftsi->rec + ftsi->seg->start;
if (ftsi->seg->flag & HA_VAR_LENGTH_PART) {
uint pack_length = (ftsi->seg->bit_start);
ftsi->len = (pack_length == 1 ? (uint)*ftsi->pos : uint2korr(ftsi->pos));
ftsi->pos += pack_length; /* Skip VARCHAR length */
return 1;
}
if (ftsi->seg->flag & HA_BLOB_PART) {
ftsi->len = _mi_calc_blob_length(ftsi->seg->bit_start, ftsi->pos);
memcpy((uchar *)&ftsi->pos, ftsi->pos + ftsi->seg->bit_start,
sizeof(char *));
return 1;
}
ftsi->len = ftsi->seg->length;
return 1;
}
/* parses a document i.e. calls ft_parse for every keyseg */
uint _mi_ft_parse(TREE *parsed, MI_INFO *info, uint keynr, const uchar *record,
MYSQL_FTPARSER_PARAM *param, MEM_ROOT *mem_root) {
FT_SEG_ITERATOR ftsi = {0, 0, nullptr, nullptr, nullptr};
struct st_mysql_ftparser *parser;
DBUG_TRACE;
_mi_ft_segiterator_init(info, keynr, record, &ftsi);
ft_parse_init(parsed, info->s->keyinfo[keynr].seg->charset);
parser = info->s->keyinfo[keynr].parser;
while (_mi_ft_segiterator(&ftsi)) {
if (ftsi.pos)
if (ft_parse(parsed, const_cast<uchar *>(ftsi.pos), ftsi.len, parser,
param, mem_root))
return 1;
}
return 0;
}
FT_WORD *_mi_ft_parserecord(MI_INFO *info, uint keynr, const uchar *record,
MEM_ROOT *mem_root) {
TREE ptree;
MYSQL_FTPARSER_PARAM *param;
DBUG_TRACE;
if (!(param = ftparser_call_initializer(info, keynr, 0))) return nullptr;
memset(&ptree, 0, sizeof(ptree));
param->flags = 0;
if (_mi_ft_parse(&ptree, info, keynr, record, param, mem_root))
return nullptr;
return ft_linearize(&ptree, mem_root);
}
static int _mi_ft_store(MI_INFO *info, uint keynr, uchar *keybuf,
FT_WORD *wlist, my_off_t filepos) {
uint key_length;
DBUG_TRACE;
for (; wlist->pos; wlist++) {
key_length = _ft_make_key(info, keynr, keybuf, wlist, filepos);
if (_mi_ck_write(info, keynr, (uchar *)keybuf, key_length)) return 1;
}
return 0;
}
static int _mi_ft_erase(MI_INFO *info, uint keynr, uchar *keybuf,
FT_WORD *wlist, my_off_t filepos) {
uint key_length, err = 0;
DBUG_TRACE;
for (; wlist->pos; wlist++) {
key_length = _ft_make_key(info, keynr, keybuf, wlist, filepos);
if (_mi_ck_delete(info, keynr, (uchar *)keybuf, key_length)) err = 1;
}
return err;
}
/*
Compares an appropriate parts of two WORD_KEY keys directly out of records
returns 1 if they are different
*/
#define THOSE_TWO_DAMN_KEYS_ARE_REALLY_DIFFERENT 1
#define GEE_THEY_ARE_ABSOLUTELY_IDENTICAL 0
int _mi_ft_cmp(MI_INFO *info, uint keynr, const uchar *rec1,
const uchar *rec2) {
FT_SEG_ITERATOR ftsi1 = {0, 0, nullptr, nullptr, nullptr};
FT_SEG_ITERATOR ftsi2 = {0, 0, nullptr, nullptr, nullptr};
const CHARSET_INFO *cs = info->s->keyinfo[keynr].seg->charset;
DBUG_TRACE;
_mi_ft_segiterator_init(info, keynr, rec1, &ftsi1);
_mi_ft_segiterator_init(info, keynr, rec2, &ftsi2);
while (_mi_ft_segiterator(&ftsi1) && _mi_ft_segiterator(&ftsi2)) {
if ((ftsi1.pos != ftsi2.pos) &&
(!ftsi1.pos || !ftsi2.pos ||
ha_compare_text(cs, ftsi1.pos, ftsi1.len, ftsi2.pos, ftsi2.len,
false)))
return THOSE_TWO_DAMN_KEYS_ARE_REALLY_DIFFERENT;
}
return GEE_THEY_ARE_ABSOLUTELY_IDENTICAL;
}
/* update a document entry */
int _mi_ft_update(MI_INFO *info, uint keynr, uchar *keybuf, const uchar *oldrec,
const uchar *newrec, my_off_t pos) {
int error = -1;
FT_WORD *oldlist, *newlist, *old_word, *new_word;
const CHARSET_INFO *cs = info->s->keyinfo[keynr].seg->charset;
uint key_length;
int cmp, cmp2;
DBUG_TRACE;
if (!(old_word = oldlist =
_mi_ft_parserecord(info, keynr, oldrec, &info->ft_memroot)) ||
!(new_word = newlist =
_mi_ft_parserecord(info, keynr, newrec, &info->ft_memroot)))
goto err;
error = 0;
while (old_word->pos && new_word->pos) {
cmp = ha_compare_text(cs, (uchar *)old_word->pos, old_word->len,
(uchar *)new_word->pos, new_word->len, false);
cmp2 = cmp ? 0 : (fabs(old_word->weight - new_word->weight) > 1.e-5);
if (cmp < 0 || cmp2) {
key_length = _ft_make_key(info, keynr, keybuf, old_word, pos);
if ((error = _mi_ck_delete(info, keynr, (uchar *)keybuf, key_length)))
goto err;
}
if (cmp > 0 || cmp2) {
key_length = _ft_make_key(info, keynr, keybuf, new_word, pos);
if ((error = _mi_ck_write(info, keynr, (uchar *)keybuf, key_length)))
goto err;
}
if (cmp <= 0) old_word++;
if (cmp >= 0) new_word++;
}
if (old_word->pos)
error = _mi_ft_erase(info, keynr, keybuf, old_word, pos);
else if (new_word->pos)
error = _mi_ft_store(info, keynr, keybuf, new_word, pos);
err:
free_root(&info->ft_memroot, MYF(MY_MARK_BLOCKS_FREE));
return error;
}
/* adds a document to the collection */
int _mi_ft_add(MI_INFO *info, uint keynr, uchar *keybuf, const uchar *record,
my_off_t pos) {
int error = -1;
FT_WORD *wlist;
DBUG_TRACE;
DBUG_PRINT("enter", ("keynr: %d", keynr));
if ((wlist = _mi_ft_parserecord(info, keynr, record, &info->ft_memroot)))
error = _mi_ft_store(info, keynr, keybuf, wlist, pos);
free_root(&info->ft_memroot, MYF(MY_MARK_BLOCKS_FREE));
DBUG_PRINT("exit", ("Return: %d", error));
return error;
}
/* removes a document from the collection */
int _mi_ft_del(MI_INFO *info, uint keynr, uchar *keybuf, const uchar *record,
my_off_t pos) {
int error = -1;
FT_WORD *wlist;
DBUG_TRACE;
DBUG_PRINT("enter", ("keynr: %d", keynr));
if ((wlist = _mi_ft_parserecord(info, keynr, record, &info->ft_memroot)))
error = _mi_ft_erase(info, keynr, keybuf, wlist, pos);
free_root(&info->ft_memroot, MYF(MY_MARK_BLOCKS_FREE));
DBUG_PRINT("exit", ("Return: %d", error));
return error;
}
uint _ft_make_key(MI_INFO *info, uint keynr, uchar *keybuf, FT_WORD *wptr,
my_off_t filepos) {
uchar buf[HA_FT_MAXBYTELEN + 16];
DBUG_TRACE;
{
float weight = (float)((filepos == HA_OFFSET_ERROR) ? 0 : wptr->weight);
mi_float4store(buf, weight);
}
int2store(buf + HA_FT_WLEN, wptr->len);
memcpy(buf + HA_FT_WLEN + 2, wptr->pos, wptr->len);
return _mi_make_key(info, keynr, (uchar *)keybuf, buf, filepos);
}
/*
convert key value to ft2
*/
uint _mi_ft_convert_to_ft2(MI_INFO *info, uint keynr, uchar *key) {
my_off_t root;
DYNAMIC_ARRAY *da = info->ft1_to_ft2;
MI_KEYDEF *keyinfo = &info->s->ft2_keyinfo;
uchar *key_ptr = da->buffer, *end;
uint length, key_length;
DBUG_TRACE;
/* we'll generate one pageful at once, and insert the rest one-by-one */
/* calculating the length of this page ...*/
length = (keyinfo->block_length - 2) / keyinfo->keylength;
length = std::min(length, da->elements);
length = length * keyinfo->keylength;
get_key_full_length_rdonly(key_length, key);
while (_mi_ck_delete(info, keynr, key, key_length) == 0) {
/*
nothing to do here.
_mi_ck_delete() will populate info->ft1_to_ft2 with deleted keys
*/
}
/* creating pageful of keys */
mi_putint(info->buff, length + 2, 0);
memcpy(info->buff + 2, key_ptr, length);
info->buff_used = info->page_changed = true; /* info->buff is used */
if ((root = _mi_new(info, keyinfo, DFLT_INIT_HITS)) == HA_OFFSET_ERROR ||
_mi_write_keypage(info, keyinfo, root, DFLT_INIT_HITS, info->buff))
return -1;
/* inserting the rest of key values */
end = da->buffer + (da->elements * da->size_of_element);
for (key_ptr += length; key_ptr < end; key_ptr += keyinfo->keylength)
if (_mi_ck_real_write_btree(info, keyinfo, key_ptr, 0, &root, SEARCH_SAME))
return -1;
/* now, writing the word key entry */
ft_intXstore(key + key_length, -(int)da->elements);
_mi_dpointer(info, key + key_length + HA_FT_WLEN, root);
return _mi_ck_real_write_btree(info, info->s->keyinfo + keynr, key, 0,
&info->s->state.key_root[keynr], SEARCH_SAME);
}
| 32.493865 | 80 | 0.663268 | silenc3502 |
030f6cd98e071ed25741e7a0ff17d0cc8e16ff18 | 6,139 | cpp | C++ | ContextCommon2/src/file_logger.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | ContextCommon2/src/file_logger.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | ContextCommon2/src/file_logger.cpp | crutchwalkfactory/jaikuengine-mobile-client | c47100ec009d47a4045b3d98addc9b8ad887b132 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2009 Google Inc.
// Copyright (c) 2006-2007 Jaiku Ltd.
// Copyright (c) 2002-2006 Mika Raento and Renaud Petit
//
// This software is licensed at your choice under either 1 or 2 below.
//
// 1. MIT 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.
//
// 2. Gnu General Public license 2.0
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//
// This file is part of the JaikuEngine mobile client.
#include "file_logger.h"
#include "cl_settings.h"
#include "break.h"
#include "e32std.h"
#include "csd_event.h"
void Cfile_logger::get_value(const MBBData* d)
{
if (!d) return;
iBuf->Des().Zero();
TInt err=KErrOverflow;
while (err==KErrOverflow) {
iBuf->Des().Zero();
TPtr p=iBuf->Des();
CC_TRAP(err, d->IntoStringL(p));
if (err==KErrOverflow) {
CC_TRAP(err, iBuf=iBuf->ReAllocL(iBuf->Des().MaxLength()*2));
if (err==KErrNone) err=KErrOverflow;
}
}
}
void Cfile_logger::get_value(const CBBSensorEvent& aEvent)
{
const MBBData* d=aEvent.iData();
get_value(d);
}
void Cfile_logger::NewSensorEventL(const TTupleName& aTuple, const TDesC& , const CBBSensorEvent& aEvent)
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("NewSensorEventL"));
if (aEvent.iPriority()<priority_limit) return;
if (aEvent.iPriority()==CBBSensorEvent::UNCHANGED_VALUE) return;
if (aTuple==KStatusTuple) return;
get_value(aEvent);
new_value(aEvent.iPriority(), aEvent.iName(), *iBuf, aEvent.iStamp());
}
void Cfile_logger::NewValueL(TUint, const TTupleName& aName, const TDesC& aSubName, const MBBData* aData)
{
const CBBSensorEvent* e=bb_cast<CBBSensorEvent>(aData);
if (e) {
NewSensorEventL(aName, aSubName, *e);
} else {
get_value(aData);
new_value(CBBSensorEvent::ERR, _L("unknown"), *iBuf, GetTime());
}
}
void Cfile_logger::new_value(TInt priority, const TDesC& aSource, const TDesC& aValue, const TTime& time)
{
if (priority<priority_limit) return;
if (priority==CBBSensorEvent::UNCHANGED_VALUE) return;
write_time(time);
write_to_output(aSource);
_LIT(sep, ": ");
write_to_output(sep);
write_to_output(aValue);
write_nl();
}
EXPORT_C void Cfile_logger::write_line(const TDesC& aLine)
{
write_time(GetTime());
write_to_output(aLine);
write_nl();
}
void Cfile_logger::ConstructL(const TDesC& prefix, TInt aMaxLogCount)
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("ConstructL"));
Mlogger::ConstructL(AppContextAccess());
iBuf=HBufC::NewL(512);
TBool logging=ETrue;
Settings().GetSettingL(SETTING_LOGGING_ENABLE, logging);
Settings().NotifyOnChange(SETTING_LOGGING_ENABLE, this);
enabled=logging;
Mfile_output_base::ConstructL(prefix, logging, aMaxLogCount);
}
void Cfile_logger::write_to_output(const TDesC& str)
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("write_to_output"));
if (paused) return;
Mfile_output_base::write_to_output(str);
}
void Cfile_logger::SettingChanged(TInt /*Setting*/)
{
TBool logging;
if (Settings().GetSettingL(SETTING_LOGGING_ENABLE, logging) && ! logging) {
enabled=false;
pause();
} else {
enabled=true;
unpause();
}
}
EXPORT_C void Cfile_logger::pause()
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("pause"));
if (paused) return;
paused=true;
write_time();
_LIT(pausedtxt, "PAUSED");
write_to_output(pausedtxt);
write_nl();
}
EXPORT_C void Cfile_logger::unpause()
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("unpause"));
if (!paused || !enabled) return;
//switch_file();
write_time();
_LIT(unpaused, "CONTINUING");
write_to_output(unpaused);
write_nl();
paused=false;
}
EXPORT_C bool Cfile_logger::is_paused()
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("is_paused"));
return paused;
}
Cfile_logger::Cfile_logger(MApp_context& Context, CBBSensorEvent::TPriority limit): Mfile_output_base(Context),
priority_limit(limit) { }
Cfile_logger::~Cfile_logger()
{
CALLSTACKITEM_N(_CL("Cfile_logger"), _CL("~Cfile_logger"));
Settings().CancelNotifyOnChange(SETTING_LOGGING_ENABLE, this);
if (!paused && enabled) {
TInt err;
_LIT(stopped, "STOPPED");
CC_TRAP(err,
write_time();
write_to_output(stopped);
write_nl();
);
}
delete iBuf;
}
EXPORT_C Cfile_logger* Cfile_logger::NewL(MApp_context& Context,
const TDesC& prefix, CBBSensorEvent::TPriority limit,
TInt aMaxLogCount)
{
CALLSTACKITEMSTATIC_N(_CL("Cfile_logger"), _CL("NewL"));
auto_ptr<Cfile_logger> ret(new (ELeave) Cfile_logger(Context, limit));
ret->ConstructL(prefix, aMaxLogCount);
return ret.release();
}
| 28.16055 | 111 | 0.735136 | crutchwalkfactory |
030fffffe2cce81add201e252639f814437619a3 | 4,237 | cpp | C++ | model/UpdateCallbackSettingsInputObject.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | model/UpdateCallbackSettingsInputObject.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | model/UpdateCallbackSettingsInputObject.cpp | imissyouso/textmagic-rest-cpp | b5810fd41c08dbab320a52e93d524896e2c2200f | [
"MIT"
] | null | null | null | /**
* TextMagic API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 2
*
*
* NOTE: This class is auto generated by the swagger code generator 2.4.8.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "UpdateCallbackSettingsInputObject.h"
namespace com {
namespace textmagic {
namespace client {
namespace model {
UpdateCallbackSettingsInputObject::UpdateCallbackSettingsInputObject()
{
m_OutUrl = utility::conversions::to_string_t("");
m_InUrl = utility::conversions::to_string_t("");
m_Format = utility::conversions::to_string_t("");
}
UpdateCallbackSettingsInputObject::~UpdateCallbackSettingsInputObject()
{
}
void UpdateCallbackSettingsInputObject::validate()
{
// TODO: implement validation
}
web::json::value UpdateCallbackSettingsInputObject::toJson() const
{
web::json::value val = web::json::value::object();
val[utility::conversions::to_string_t("outUrl")] = ModelBase::toJson(m_OutUrl);
val[utility::conversions::to_string_t("inUrl")] = ModelBase::toJson(m_InUrl);
val[utility::conversions::to_string_t("format")] = ModelBase::toJson(m_Format);
return val;
}
void UpdateCallbackSettingsInputObject::fromJson(web::json::value& val)
{
if(val.has_field(utility::conversions::to_string_t("outUrl")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("outUrl")];
if(!fieldValue.is_null())
{
setOutUrl(ModelBase::stringFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("inUrl")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("inUrl")];
if(!fieldValue.is_null())
{
setInUrl(ModelBase::stringFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("format")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("format")];
if(!fieldValue.is_null())
{
setFormat(ModelBase::stringFromJson(fieldValue));
}
}
}
void UpdateCallbackSettingsInputObject::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("outUrl"), m_OutUrl));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("inUrl"), m_InUrl));
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("format"), m_Format));
}
void UpdateCallbackSettingsInputObject::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
setOutUrl(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("outUrl"))));
setInUrl(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("inUrl"))));
setFormat(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("format"))));
}
utility::string_t UpdateCallbackSettingsInputObject::getOutUrl() const
{
return m_OutUrl;
}
void UpdateCallbackSettingsInputObject::setOutUrl(utility::string_t value)
{
m_OutUrl = value;
}
utility::string_t UpdateCallbackSettingsInputObject::getInUrl() const
{
return m_InUrl;
}
void UpdateCallbackSettingsInputObject::setInUrl(utility::string_t value)
{
m_InUrl = value;
}
utility::string_t UpdateCallbackSettingsInputObject::getFormat() const
{
return m_Format;
}
void UpdateCallbackSettingsInputObject::setFormat(utility::string_t value)
{
m_Format = value;
}
}
}
}
}
| 30.049645 | 136 | 0.71206 | imissyouso |
0310133372a8a8f1654321664c21e429d0545c45 | 930 | cpp | C++ | [376] Wiggle Subsequence/376.wiggle-subsequence.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | [376] Wiggle Subsequence/376.wiggle-subsequence.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | [376] Wiggle Subsequence/376.wiggle-subsequence.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=376 lang=cpp
*
* [376] Wiggle Subsequence
*/
// @lc code=start
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
// O(n) dp method
int n = nums.size();
if (n == 1) return 1;
// up[] and down[] record the max wiggle sequence length so far at index i.
// which don't have to end with nums[i]
vector<int> up(n, 0);
vector<int> down(n, 0);
up[0] = 1;
down[0] = 1;
for (int i = 1; i < n; i++) {
if (nums[i] > nums[i-1]) {
up[i] = down[i-1]+1;
down[i] = down[i-1];
} else if (nums[i] < nums[i-1]) {
up[i] = up[i-1];
down[i] = up[i-1]+1;
} else {
up[i] = up[i-1];
down[i] = down[i-1];
}
}
return max(up[n-1], down[n-1]);
}
};
// @lc code=end
| 25.135135 | 83 | 0.416129 | Coolzyh |
0310cab9b39f630f6690e0d7fb042e7772a016b2 | 5,038 | cpp | C++ | Plugin/DateFormat.cpp | matanki-saito/CK2dll | 882d09b44bcd750447b7cf76412ca0e78aeb5818 | [
"MIT"
] | 228 | 2018-07-09T05:20:03.000Z | 2022-03-28T12:35:07.000Z | Plugin/DateFormat.cpp | matanki-saito/CK2dll | 882d09b44bcd750447b7cf76412ca0e78aeb5818 | [
"MIT"
] | 81 | 2018-08-04T21:03:34.000Z | 2021-12-08T03:08:29.000Z | Plugin/DateFormat.cpp | matanki-saito/CK2dll | 882d09b44bcd750447b7cf76412ca0e78aeb5818 | [
"MIT"
] | 40 | 2018-08-27T10:57:37.000Z | 2022-02-08T10:55:17.000Z | #include "stdinc.h"
#include "byte_pattern.h"
// Menu bar date format
// https://github.com/matanki-saito/CK2dll/issues/38
namespace DateFormat {
/*-----------------------------------------------*/
uintptr_t issue_38_copyBufFunc_v28;
/*-----------------------------------------------*/
errno_t copyBufFunc_hook(RunOptions *options) {
std::string desc = "copy buf func";
switch (options->version) {
case v2_8_X:
case v3_0_0:
case v3_0_X:
case v3_1_0:
case v3_1_1:
// issue33と同じもの
// sub esp,20h
byte_pattern::temp_instance().find_pattern("83 EC 20 56 FF 75 0C 8D 45 D8");
if (byte_pattern::temp_instance().has_size(1, desc)) {
issue_38_copyBufFunc_v28 = byte_pattern::temp_instance().get_first().address(-0x18);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
V *year;
V *day;
uintptr_t issue_38_fix1_v28_end;
__declspec(naked) void issue_38_fix1_v28_start() {
__asm {
// edi: year
// [ebp - 0x44] : _,
// [ebp - 0x100] : month
// [ebp - 0x2C] : _
// [ebp - 0xC0] : day
//
mov byte ptr[ebp - 0x4], 8;
push year;
lea ecx, [ebp - 0xA8];
push ecx; // buf
mov ecx, edi;
call issue_38_copyBufFunc_v28;
//
lea ecx,[ebp - 0x100];
mov byte ptr[ebp - 0x4], 9;
push ecx;
lea ecx, [ebp - 0x90];
push ecx; // buf
mov ecx, eax;
call issue_38_copyBufFunc_v28;
//
lea ecx, [ebp - 0xC0];
mov byte ptr[ebp - 0x4], 0xA;
push ecx;
lea ecx, [ebp - 0x78];
push ecx; // buf
mov ecx, eax;
call issue_38_copyBufFunc_v28;
//
push day;
lea ecx, [ebp - 0x60];
mov byte ptr[ebp - 0x4], 0Bh;
push ecx; // buf
mov ecx, eax;
call issue_38_copyBufFunc_v28;
push issue_38_fix1_v28_end;
ret;
}
}
/*-----------------------------------------------*/
errno_t fix1_hook(RunOptions *options) {
std::string desc = "fix 1";
year = new V();
year->t.text[0] = 15;
year->t.text[1] = '\0';
year->len = 1;
year->len2 = 1;
day = new V();
day->t.text[0] = 14;
day->t.text[1] = '\0';
day->len = 1;
day->len2 = 1;
switch (options->version) {
case v2_8_X:
case v3_0_0:
case v3_0_X:
case v3_1_0:
case v3_1_1:
byte_pattern::temp_instance().find_pattern("8D 4D D4 C6 45 FC 08 51 8D 8D 58");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// lea ecx,[ebp+var_2C]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), issue_38_fix1_v28_start);
// mov byte ptr [ebp+var_4],0Ch
issue_38_fix1_v28_end = byte_pattern::temp_instance().get_first().address(0x52);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
errno_t dateOrder_hook(RunOptions *options) {
std::string desc = "date order fix";
switch (options->version) {
case v2_8_X:
case v3_0_0:
case v3_0_X:
case v3_1_0:
case v3_1_1:
byte_pattern::temp_instance().find_pattern("64 20 77 20 6D 77 20 2C");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(0), 0x79, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(1), 0x20, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(2), 0x10, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(3), 0x74, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(4), 0x5E, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(5), 0x20, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(6), 0x6D, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(7), 0x77, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(8), 0x20, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(9), 0x64, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(10), 0x20, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(11), 0x10, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(12), 0xE5, true);
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(13), 0x65, true);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
errno_t init(RunOptions *options) {
errno_t result = NOERROR;
if (options->dateFormat) {
byte_pattern::debug_output2("Date Format");
/* 右上のツールバーの日付表記の修正 */
result |= dateOrder_hook(options);
/* 関数フック */
result |= copyBufFunc_hook(options);
/* issue-38 「DD MON, YYYY」を「YYYY年MONDD日」にしたい */
result |= fix1_hook(options);
}
return result;
}
} | 27.988889 | 102 | 0.627829 | matanki-saito |
031179759ea7cb3f1760bfa730032d403f328af9 | 8,742 | cpp | C++ | LightBase/src/scene.cpp | vsiles/learnopengl | 9e5221128755cd7621a3ae9f2ea8d2f90d84e68c | [
"BSD-3-Clause"
] | null | null | null | LightBase/src/scene.cpp | vsiles/learnopengl | 9e5221128755cd7621a3ae9f2ea8d2f90d84e68c | [
"BSD-3-Clause"
] | null | null | null | LightBase/src/scene.cpp | vsiles/learnopengl | 9e5221128755cd7621a3ae9f2ea8d2f90d84e68c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <SDL.h>
#include <SDL_image.h>
/* #define GLM_FORCE_MESSAGES */
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "cube.hpp"
#include "scene.hpp"
using namespace std;
using namespace vinz;
Scene::Scene(string name, int width, int height) : camera()
{
int ret = SDL_Init(SDL_INIT_VIDEO);
if (ret != 0) {
throw SceneFailure(SceneFailure::Cause::Init, SDL_GetError());
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
this->width = width;
this->height = height;
window = SDL_CreateWindow(name.c_str(),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL |
SDL_WINDOW_RESIZABLE);
if (window == nullptr) {
const char *err = SDL_GetError();
SDL_Quit();
throw SceneFailure(SceneFailure::Cause::Window, err);
}
glcontext = SDL_GL_CreateContext(window);
if (glcontext == nullptr) {
const char *err = SDL_GetError();
SDL_DestroyWindow(window);
SDL_Quit();
throw SceneFailure(SceneFailure::Cause::Context, err);
}
if (gl3wInit()) {
SDL_DestroyWindow(window);
SDL_Quit();
throw SceneFailure(SceneFailure::Cause::Extension, "gl3w");
}
if (!gl3wIsSupported(4, 2)) {
SDL_DestroyWindow(window);
SDL_Quit();
throw SceneFailure(SceneFailure::Cause::Extension, "4.2");
}
ret = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
if ((ret & (IMG_INIT_JPG | IMG_INIT_PNG)) == 0) {
SDL_DestroyWindow(window);
SDL_Quit();
throw SceneFailure(SceneFailure::Cause::Init, "IMG_Init");
}
}
Scene::~Scene()
{
IMG_Quit();
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
}
void Scene::updateProjView()
{
GLfloat w = (GLfloat)width;
GLfloat h = (GLfloat)height;
GLfloat aspect = w / h;
/* TODO: fov, far, near */
projection = glm::perspective(glm::radians(45.0f), aspect, 0.1f, 100.0f);
glViewport(0, 0, width, height);
}
void Scene::run()
{
updateProjView();
Cube cube;
cube.init();
/* uncomment to draw in wireframe mode */
/* glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); */
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glEnable(GL_DEPTH_TEST);
camera.setPosition(glm::vec3(0.0f, 0.0f, 3.0f));
SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_CaptureMouse(SDL_TRUE);
while (true) {
bool done = processEvent();
if (done)
break;
float currentFrame = SDL_GetTicks();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float ldelta = currentFrame / 1000.0f;
glm::vec3 lightPos(1.2f * cos(ldelta), 1.0f, sin(ldelta) * 2.0f);
shader.activate();
shader.setVec3("light.position", lightPos.x, lightPos.y, lightPos.z);
const glm::vec3 &pos = camera.getPosition();
shader.setVec3("viewPos", pos.x, pos.y, pos.z);
shader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
shader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
shader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
shader.setInt("material.diffuse", 0);
shader.setInt("material.specular", 1);
shader.setFloat("material.shininess", 64.0f);
/* Projection matrix is updated when needed */
shader.setMat4("projection", glm::value_ptr(projection));
glm::mat4 view = camera.view();
shader.setMat4("view", glm::value_ptr(view));
glm::mat4 model = glm::mat4(1.0f);
shader.setMat4("model", glm::value_ptr(model));
/* Bind the Texture */
glActiveTexture(GL_TEXTURE0);
crate_diffuse.bind();
glActiveTexture(GL_TEXTURE1);
crate_specular.bind();
/* Draw cube */
cube.render();
lampShader.activate();
lampShader.setMat4("projection", glm::value_ptr(projection));
lampShader.setMat4("view", glm::value_ptr(view));
model = glm::mat4(1.0f);
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f));
lampShader.setMat4("model", glm::value_ptr(model));
cube.render();
SDL_GL_SwapWindow(window);
}
}
bool Scene::init(string &res_path)
{
string vertex_shader = res_path + "shaders/lighttest-4.vert";
string fragment_shader = res_path + "shaders/lighttest-4.frag";
string lamp_fragment_shader = res_path + "shaders/lamp.frag";
try {
cerr << "Vertex shader compiling..." << endl;
Shader vert(vertex_shader, Shader::Type::Vertex);
cerr << "Fragment shader compiling..." << endl;
Shader frag(fragment_shader, Shader::Type::Fragment);
cerr << "Fragment shader (lamp) compiling..." << endl;
Shader lfrag(lamp_fragment_shader, Shader::Type::Fragment);
ShaderFailure cause;
if (!shader.init(vert, frag, cause))
throw cause;
if (!lampShader.init(vert, lfrag, cause))
throw cause;
} catch (ShaderFailure &excp) {
switch (excp.cause) {
case ShaderFailure::Cause::Create:
cerr << "Shader creation failed" << endl;
break;
case ShaderFailure::Cause::Compile:
cerr << "Shader compilation failed:" << endl;
cerr << excp.log << endl;
break;
case ShaderFailure::Cause::IO:
cerr << "Can't access shader file" << endl;
break;
}
return false;
}
cerr << "Loading container.png" << endl;
if (!crate_diffuse.init(res_path + "images/container.png")) {
cerr << "Can't load container.png" << endl;
return false;
}
cerr << "Loading container_specular.png" << endl;
if (!crate_specular.init(res_path + "images/container_specular.png")) {
cerr << "Can't load container_specular.png" << endl;
return false;
}
deltaTime = 0.0f;
lastFrame = 0.0f;
return true;
}
bool Scene::processEvent()
{
bool done = false;
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
switch (event.type) {
case SDL_QUIT:
done = true;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
done = true;
break;
case SDLK_z:
camera.processKeys(Camera::Movement::FORWARD,
deltaTime);
break;
case SDLK_s:
camera.processKeys(Camera::Movement::BACKWARD,
deltaTime);
break;
case SDLK_q:
camera.processKeys(Camera::Movement::LEFT,
deltaTime);
break;
case SDLK_d:
camera.processKeys(Camera::Movement::RIGHT,
deltaTime);
break;
case SDLK_SPACE:
camera.processKeys(Camera::Movement::UP,
deltaTime);
break;
case SDLK_LCTRL:
camera.processKeys(Camera::Movement::DOWN,
deltaTime);
break;
}
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_RESIZED:
case SDL_WINDOWEVENT_SIZE_CHANGED:
width = event.window.data1;
height = event.window.data2;
updateProjView();
break;
}
break;
case SDL_MOUSEMOTION:
camera.processMotion(event.motion.xrel, event.motion.yrel);
break;
}
if (done)
break;
}
return done;
}
| 31.559567 | 77 | 0.544498 | vsiles |
03123a6d86ea7e87e1afe345039412b79c1ff84b | 12,852 | cpp | C++ | src/gpu/gl/GrGLNameAllocator.cpp | Perspex/skia | e25fe5a294e9cee8f23207eef63fad6cffa9ced4 | [
"Apache-2.0"
] | 7 | 2016-01-12T23:32:32.000Z | 2021-12-03T11:21:26.000Z | src/gpu/gl/GrGLNameAllocator.cpp | AvaloniaUI/skia | e25fe5a294e9cee8f23207eef63fad6cffa9ced4 | [
"Apache-2.0"
] | null | null | null | src/gpu/gl/GrGLNameAllocator.cpp | AvaloniaUI/skia | e25fe5a294e9cee8f23207eef63fad6cffa9ced4 | [
"Apache-2.0"
] | 6 | 2015-12-09T14:00:19.000Z | 2021-12-06T03:08:43.000Z |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLNameAllocator.h"
/**
* This is the abstract base class for a nonempty AVL tree that tracks allocated
* names within the half-open range [fFirst, fEnd). The inner nodes can be
* sparse (meaning not every name within the range is necessarily allocated),
* but the bounds are tight, so fFirst *is* guaranteed to be allocated, and so
* is fEnd - 1.
*/
class GrGLNameAllocator::SparseNameRange : public SkRefCnt {
public:
virtual ~SparseNameRange() {}
/**
* Return the beginning of the range. first() is guaranteed to be allocated.
*
* @return The first name in the range.
*/
GrGLuint first() const { return fFirst; }
/**
* Return the end of the range. end() - 1 is guaranteed to be allocated.
*
* @return One plus the final name in the range.
*/
GrGLuint end() const { return fEnd; }
/**
* Return the height of the tree. This can only be nonzero at an inner node.
*
* @return 0 if the implementation is a leaf node,
* The nonzero height of the tree otherwise.
*/
GrGLuint height() const { return fHeight; }
/**
* Allocate a name from strictly inside this range. The call will fail if
* there is not a free name within.
*
* @param outName A pointer that receives the allocated name. outName will
* be set to zero if there were no free names within the
* range [fFirst, fEnd).
* @return The resulting SparseNameRange after the allocation. Note that
* this call is destructive, so the original SparseNameRange will no
* longer be valid afterward. The caller must always update its
* pointer with the new SparseNameRange.
*/
virtual SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) = 0;
/**
* Remove the leftmost leaf node from this range (or the entire thing if it
* *is* a leaf node). This is an internal helper method that is used after
* an allocation if one contiguous range became adjacent to another. (The
* range gets removed so the one immediately before can be extended,
* collapsing the two into one.)
*
* @param removedCount A pointer that receives the size of the contiguous
range that was removed.
* @return The resulting SparseNameRange after the removal (or nullptr if it
* became empty). Note that this call is destructive, so the
* original SparseNameRange will no longer be valid afterward. The
* caller must always update its pointer with the new
* SparseNameRange.
*/
virtual SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) = 0;
/**
* Append adjacent allocated names to the end of this range. This operation
* does not affect the structure of the tree. The caller is responsible for
* ensuring the new names won't overlap sibling ranges, if any.
*
* @param count The number of adjacent names to append.
* @return The first name appended.
*/
virtual GrGLuint appendNames(GrGLuint count) = 0;
/**
* Prepend adjacent allocated names behind the beginning of this range. This
* operation does not affect the structure of the tree. The caller is
* responsible for ensuring the new names won't overlap sibling ranges, if
* any.
*
* @param count The number of adjacent names to prepend.
* @return The final name prepended (the one with the lowest value).
*/
virtual GrGLuint prependNames(GrGLuint count) = 0;
/**
* Free a name so it is no longer tracked as allocated. If the name is at
* the very beginning or very end of the range, the boundaries [fFirst, fEnd)
* will be tightened.
*
* @param name The name to free. Not-allocated names are silently ignored
* the same way they are in the OpenGL spec.
* @return The resulting SparseNameRange after the free (or nullptr if it
* became empty). Note that this call is destructive, so the
* original SparseNameRange will no longer be valid afterward. The
* caller must always update its pointer with the new
* SparseNameRange.
*/
virtual SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) = 0;
protected:
SparseNameRange* takeRef() {
this->ref();
return this;
}
GrGLuint fFirst;
GrGLuint fEnd;
GrGLuint fHeight;
};
/**
* This class is the SparseNameRange implementation for an inner node. It is an
* AVL tree with non-null, non-adjacent left and right children.
*/
class GrGLNameAllocator::SparseNameTree : public SparseNameRange {
public:
SparseNameTree(SparseNameRange* left, SparseNameRange* right)
: fLeft(left),
fRight(right) {
SkASSERT(fLeft.get());
SkASSERT(fRight.get());
this->updateStats();
}
SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) override {
// Try allocating the range inside fLeft's internal gaps.
fLeft.reset(fLeft->internalAllocate(outName));
if (0 != *outName) {
this->updateStats();
return this->rebalance();
}
if (fLeft->end() + 1 == fRight->first()) {
// It closed the gap between fLeft and fRight; merge.
GrGLuint removedCount;
fRight.reset(fRight->removeLeftmostContiguousRange(&removedCount));
*outName = fLeft->appendNames(1 + removedCount);
if (nullptr == fRight.get()) {
return fLeft.detach();
}
this->updateStats();
return this->rebalance();
}
// There is guaranteed to be a gap between fLeft and fRight, and the
// "size 1" case has already been covered.
SkASSERT(fLeft->end() + 1 < fRight->first());
*outName = fLeft->appendNames(1);
return this->takeRef();
}
SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) override {
fLeft.reset(fLeft->removeLeftmostContiguousRange(removedCount));
if (nullptr == fLeft) {
return fRight.detach();
}
this->updateStats();
return this->rebalance();
}
GrGLuint appendNames(GrGLuint count) override {
SkASSERT(fEnd + count > fEnd); // Check for integer wrap.
GrGLuint name = fRight->appendNames(count);
SkASSERT(fRight->end() == fEnd + count);
this->updateStats();
return name;
}
GrGLuint prependNames(GrGLuint count) override {
SkASSERT(fFirst > count); // We can't allocate at or below 0.
GrGLuint name = fLeft->prependNames(count);
SkASSERT(fLeft->first() == fFirst - count);
this->updateStats();
return name;
}
SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) override {
if (name < fLeft->end()) {
fLeft.reset(fLeft->free(name));
if (nullptr == fLeft) {
// fLeft became empty after the free.
return fRight.detach();
}
this->updateStats();
return this->rebalance();
} else {
fRight.reset(fRight->free(name));
if (nullptr == fRight) {
// fRight became empty after the free.
return fLeft.detach();
}
this->updateStats();
return this->rebalance();
}
}
private:
typedef SkAutoTUnref<SparseNameRange> SparseNameTree::* ChildRange;
SparseNameRange* SK_WARN_UNUSED_RESULT rebalance() {
if (fLeft->height() > fRight->height() + 1) {
return this->rebalanceImpl<&SparseNameTree::fLeft, &SparseNameTree::fRight>();
}
if (fRight->height() > fLeft->height() + 1) {
return this->rebalanceImpl<&SparseNameTree::fRight, &SparseNameTree::fLeft>();
}
return this->takeRef();
}
/**
* Rebalance the tree using rotations, as described in the AVL algorithm:
* http://en.wikipedia.org/wiki/AVL_tree#Insertion
*/
template<ChildRange Tall, ChildRange Short>
SparseNameRange* SK_WARN_UNUSED_RESULT rebalanceImpl() {
// We should be calling rebalance() enough that the tree never gets more
// than one rotation off balance.
SkASSERT(2 == (this->*Tall)->height() - (this->*Short)->height());
// Ensure we are in the 'Left Left' or 'Right Right' case:
// http://en.wikipedia.org/wiki/AVL_tree#Insertion
SparseNameTree* tallChild = static_cast<SparseNameTree*>((this->*Tall).get());
if ((tallChild->*Tall)->height() < (tallChild->*Short)->height()) {
(this->*Tall).reset(tallChild->rotate<Short, Tall>());
}
// Perform a rotation to balance the tree.
return this->rotate<Tall, Short>();
}
/**
* Perform a node rotation, as described in the AVL algorithm:
* http://en.wikipedia.org/wiki/AVL_tree#Insertion
*/
template<ChildRange Tall, ChildRange Short>
SparseNameRange* SK_WARN_UNUSED_RESULT rotate() {
SparseNameTree* newRoot = static_cast<SparseNameTree*>((this->*Tall).detach());
(this->*Tall).reset((newRoot->*Short).detach());
this->updateStats();
(newRoot->*Short).reset(this->takeRef());
newRoot->updateStats();
return newRoot;
}
void updateStats() {
SkASSERT(fLeft->end() < fRight->first()); // There must be a gap between left and right.
fFirst = fLeft->first();
fEnd = fRight->end();
fHeight = 1 + SkMax32(fLeft->height(), fRight->height());
}
SkAutoTUnref<SparseNameRange> fLeft;
SkAutoTUnref<SparseNameRange> fRight;
};
/**
* This class is the SparseNameRange implementation for a leaf node. It just a
* contiguous range of allocated names.
*/
class GrGLNameAllocator::ContiguousNameRange : public SparseNameRange {
public:
ContiguousNameRange(GrGLuint first, GrGLuint end) {
SkASSERT(first < end);
fFirst = first;
fEnd = end;
fHeight = 0;
}
SparseNameRange* SK_WARN_UNUSED_RESULT internalAllocate(GrGLuint* outName) override {
*outName = 0; // No internal gaps, we are contiguous.
return this->takeRef();
}
SparseNameRange* SK_WARN_UNUSED_RESULT removeLeftmostContiguousRange(GrGLuint* removedCount) override {
*removedCount = fEnd - fFirst;
return nullptr;
}
GrGLuint appendNames(GrGLuint count) override {
SkASSERT(fEnd + count > fEnd); // Check for integer wrap.
GrGLuint name = fEnd;
fEnd += count;
return name;
}
GrGLuint prependNames(GrGLuint count) override {
SkASSERT(fFirst > count); // We can't allocate at or below 0.
fFirst -= count;
return fFirst;
}
SparseNameRange* SK_WARN_UNUSED_RESULT free(GrGLuint name) override {
if (name < fFirst || name >= fEnd) {
// Not-allocated names are silently ignored.
return this->takeRef();
}
if (fFirst == name) {
++fFirst;
return (fEnd == fFirst) ? nullptr : this->takeRef();
}
if (fEnd == name + 1) {
--fEnd;
return this->takeRef();
}
SparseNameRange* left = new ContiguousNameRange(fFirst, name);
SparseNameRange* right = this->takeRef();
fFirst = name + 1;
return new SparseNameTree(left, right);
}
};
GrGLNameAllocator::GrGLNameAllocator(GrGLuint firstName, GrGLuint endName)
: fFirstName(firstName),
fEndName(endName) {
SkASSERT(firstName > 0);
SkASSERT(endName > firstName);
}
GrGLNameAllocator::~GrGLNameAllocator() {
}
GrGLuint GrGLNameAllocator::allocateName() {
if (nullptr == fAllocatedNames.get()) {
fAllocatedNames.reset(new ContiguousNameRange(fFirstName, fFirstName + 1));
return fFirstName;
}
if (fAllocatedNames->first() > fFirstName) {
return fAllocatedNames->prependNames(1);
}
GrGLuint name;
fAllocatedNames.reset(fAllocatedNames->internalAllocate(&name));
if (0 != name) {
return name;
}
if (fAllocatedNames->end() < fEndName) {
return fAllocatedNames->appendNames(1);
}
// Out of names.
return 0;
}
void GrGLNameAllocator::free(GrGLuint name) {
if (!fAllocatedNames.get()) {
// Not-allocated names are silently ignored.
return;
}
fAllocatedNames.reset(fAllocatedNames->free(name));
}
| 34.641509 | 109 | 0.625506 | Perspex |
0312f6af041724cd83fe29671b1210937fdb98e0 | 40,147 | cpp | C++ | ompi/contrib/vt/vt/extlib/otf/tools/otfaux/State.cpp | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2016-05-01T09:37:07.000Z | 2016-05-01T09:37:07.000Z | ompi/contrib/vt/vt/extlib/otf/tools/otfaux/State.cpp | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/contrib/vt/vt/extlib/otf/tools/otfaux/State.cpp | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
This is part of the OTF library. Copyright by ZIH, TU Dresden 2005-2011.
Authors: Andreas Knuepfer, Holger Brunst, Ronny Brendel, Thomas Kriebitzsch
*/
#include "OTF_Platform.h"
#include "State.h"
#include <iostream>
#include <cassert>
using namespace std;
FunctionCall::FunctionCall( uint64_t _time, uint32_t _token, OTF_KeyValueList *_kvlist ) {
time = _time;
token = _token;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, _kvlist );
}
FunctionCall::FunctionCall( const FunctionCall& fc ) {
time = fc.time;
token = fc.token;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, fc.kvlist );
}
FunctionCall::~FunctionCall() {
OTF_KeyValueList_close( kvlist );
}
FunctionCall FunctionCall::operator=( const FunctionCall& fc ) {
if( this == &fc )
return *this;
time = fc.time;
token = fc.token;
OTF_KeyValueList_reset( kvlist );
OTF_KeyValueList_appendKeyValueList( kvlist, fc.kvlist );
return *this;
}
Send::Send( uint64_t _originaltime, uint32_t _receiver, uint32_t _procGroup,
uint32_t _tag, uint32_t _length, uint32_t _source, OTF_KeyValueList *_kvlist ) {
originaltime = _originaltime;
receiver = _receiver;
procGroup = _procGroup;
tag = _tag;
length = _length;
source = _source;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, _kvlist );
}
Send::Send( const Send& s ) {
originaltime = s.originaltime;
receiver = s.receiver;
procGroup = s.procGroup;
tag = s.tag;
length = s.length;
source = s.source;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, s.kvlist );
}
Send::~Send() {
OTF_KeyValueList_close( kvlist );
}
Send Send::operator=( const Send& s ) {
if( this == &s )
return *this;
originaltime = s.originaltime;
receiver = s.receiver;
procGroup = s.procGroup;
tag = s.tag;
length = s.length;
source = s.source;
OTF_KeyValueList_reset( kvlist );
OTF_KeyValueList_appendKeyValueList( kvlist, s.kvlist );
return *this;
}
BeginCollOperation::BeginCollOperation( uint64_t _time, uint32_t _root, uint32_t _procGroup,
uint32_t _col, uint32_t _type, uint64_t _invoc_sent, uint64_t _invoc_recv, uint64_t _bytesSent,
uint64_t _bytesRecv, uint32_t _scltoken, OTF_KeyValueList *_kvlist ) {
time = _time;
root = _root;
procGroup = _procGroup;
col = _col;
type = _type;
invoc_sent = _invoc_sent;
invoc_recv = _invoc_recv;
bytesSent = _bytesSent;
bytesRecv = _bytesRecv;
scltoken = _scltoken;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, _kvlist );
}
BeginCollOperation::BeginCollOperation( const BeginCollOperation& cop ) {
time = cop.time;
root = cop.root;
procGroup = cop.procGroup;
col = cop.col;
type = cop.type;
invoc_sent = cop.invoc_sent;
invoc_recv = cop.invoc_recv;
bytesSent = cop.bytesSent;
bytesRecv = cop.bytesRecv;
scltoken = cop.scltoken;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, cop.kvlist );
}
BeginCollOperation::~BeginCollOperation() {
OTF_KeyValueList_close( kvlist );
}
BeginCollOperation BeginCollOperation::operator=( const BeginCollOperation& cop ) {
if( this == &cop )
return *this;
time = cop.time;
root = cop.root;
procGroup = cop.procGroup;
col = cop.col;
type = cop.type;
invoc_sent = cop.invoc_sent;
invoc_recv = cop.invoc_recv;
bytesSent = cop.bytesSent;
bytesRecv = cop.bytesRecv;
scltoken = cop.scltoken;
OTF_KeyValueList_reset( kvlist );
OTF_KeyValueList_appendKeyValueList( kvlist, cop.kvlist );
return *this;
}
BeginFileOperation::BeginFileOperation( uint64_t _time, uint32_t _scltoken, OTF_KeyValueList *_kvlist ) {
time = _time;
scltoken = _scltoken;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, _kvlist );
}
BeginFileOperation::BeginFileOperation( const BeginFileOperation& fop ) {
time = fop.time;
scltoken = fop.scltoken;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, fop.kvlist );
}
BeginFileOperation::~BeginFileOperation() {
OTF_KeyValueList_close( kvlist );
}
BeginFileOperation BeginFileOperation::operator=( const BeginFileOperation& fop ) {
if( this == &fop )
return *this;
time = fop.time;
scltoken = fop.scltoken;
OTF_KeyValueList_reset( kvlist );
OTF_KeyValueList_appendKeyValueList( kvlist, fop.kvlist );
return *this;
}
FileOpen::FileOpen( uint64_t _time, uint32_t _fileid, uint32_t _source, OTF_KeyValueList *_kvlist ) {
time = _time;
fileid = _fileid;
source = _source;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, _kvlist );
}
FileOpen::FileOpen( const FileOpen& fo ) {
time = fo.time;
fileid = fo.fileid;
source = fo.source;
kvlist = OTF_KeyValueList_new();
OTF_KeyValueList_appendKeyValueList( kvlist, fo.kvlist );
}
FileOpen::~FileOpen() {
OTF_KeyValueList_close( kvlist );
}
FileOpen FileOpen::operator=( const FileOpen& fo ) {
if( this == &fo )
return *this;
time = fo.time;
fileid = fo.fileid;
source = fo.source;
OTF_KeyValueList_reset( kvlist );
OTF_KeyValueList_appendKeyValueList( kvlist, fo.kvlist );
return *this;
}
/* *** ProcessState *** ********************************* */
void ProcessState::enterFunction( uint64_t time, uint32_t token, OTF_KeyValueList *kvlist ) {
fstack.push_back( FunctionCall( time, token, kvlist ) );
FunctionStatistics& stat= fstatistics[ token ];
stat.occurrences++;
}
void ProcessState::leaveFunction( uint64_t time, uint32_t token ) {
assert( ! fstack.empty() );
const FunctionCall& call= fstack.back();
/* if not special token 0 tokens must match */
if ( ( 0 != token ) && ( call.token != token ) ) {
cerr << " leave at " << time << " with corrupt stack " <<
call.token << " != " << token << endl;
}
/* update stack */
fstack.pop_back();
/* update statistics */
FunctionStatistics& stat= fstatistics[ call.token ];
stat.exclusiveTime += time - call.time;
stat.inclusiveTime += time - call.time;
/* subtract time from parents 'exclusiveTime' */
if ( ! fstack.empty() ) {
const FunctionCall& parent= fstack.back();
FunctionStatistics& parentstat= fstatistics[ parent.token ];
parentstat.exclusiveTime -= time - call.time;
}
}
void ProcessState::collOperation( uint64_t time, uint32_t col, uint32_t type, uint32_t numSent,
uint32_t numRecv, uint32_t bytesSent, uint32_t bytesRecv ) {
CollOps.numSent[type] += numSent;
CollOps.numRecv[type] += numRecv;
CollOps.bytesSent[type] += bytesSent;
CollOps.bytesRecv[type] += bytesRecv;
CollOps.Type2Col[type] = col;
}
int ProcessState::beginCollOperation( uint64_t time, uint32_t root, uint32_t procGroup,
uint32_t col, uint32_t type, uint64_t matchingId, uint64_t invoc_sent,
uint64_t invoc_recv, uint64_t bytesSent, uint64_t bytesRecv, uint32_t scltoken,
OTF_KeyValueList *kvlist ) {
std::map<uint64_t, BeginCollOperation>::iterator it;
it = beginCollOps.find( matchingId );
if( it != beginCollOps.end() ) {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"MatchingId %llu has already been used. aborting\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) matchingId );
# endif
return OTF_RETURN_ABORT;
}
/* insert the record into the list of begun collective operations */
beginCollOps.insert( pair<uint64_t,BeginCollOperation>( matchingId,
BeginCollOperation( time, root, procGroup, col, type, invoc_sent,
invoc_recv, bytesSent, bytesRecv, scltoken, kvlist ) ) );
return OTF_RETURN_OK;
}
int ProcessState::endCollOperation( uint64_t time, uint32_t matchingId ) {
std::map<uint64_t, BeginCollOperation>::iterator it;
it = beginCollOps.find( matchingId );
if( it == beginCollOps.end() ) {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"MatchingId %llu was not found. aborting\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) matchingId );
# endif
return OTF_RETURN_ABORT;
}
collOperation( time /*?*/, it->second.col, it->second.type, it->second.invoc_sent,
it->second.invoc_recv, it->second.bytesSent, it->second.bytesRecv );
beginCollOps.erase( it );
return OTF_RETURN_OK;
}
int ProcessState::beginFileOperation( uint64_t time, uint64_t matchingId, uint32_t scltoken, OTF_KeyValueList *kvlist ) {
std::map<uint64_t, BeginFileOperation>::iterator it;
it = beginFileOps.find( matchingId );
if( it != beginFileOps.end() ) {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"Handleid %llu has already been used. aborting\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) matchingId );
# endif
return OTF_RETURN_ABORT;
}
/* insert the record into the list of unfinished file operations */
beginFileOps.insert( pair<uint64_t, BeginFileOperation>( matchingId, BeginFileOperation( time, scltoken, kvlist ) ) );
return OTF_RETURN_OK;
}
int ProcessState::endFileOperation( uint64_t matchingId ) {
std::map<uint64_t, BeginFileOperation>::iterator it;
it = beginFileOps.find( matchingId );
if( it == beginFileOps.end() ) {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"Handleid %llu was not found. aborting\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) matchingId );
# endif
return OTF_RETURN_ABORT;
}
beginFileOps.erase( it );
return OTF_RETURN_OK;
}
void ProcessState::sendMessage( uint64_t time, uint32_t receiver,
uint32_t procGroup, uint32_t tag, uint32_t msglength, uint32_t source,
OTF_KeyValueList *kvlist ) {
sstatistics.bytes_sent+= msglength;
sstatistics.number_sent++;
sstack.push_back( Send( time, receiver, procGroup, tag, msglength, source, kvlist ) );
}
void ProcessState::recvMessage( uint32_t msglength ) {
sstatistics.bytes_recvd+= (uint64_t) msglength;
sstatistics.number_recvd++;
}
void ProcessState::matchMessage( uint32_t receiver, uint32_t procGroup, uint32_t tag ) {
deque<Send>::iterator jt= sstack.begin();
deque<Send>::iterator jtend= sstack.end();
for ( ; jt != jtend; ++jt ) {
if (jt->receiver == receiver
&& procGroup == jt->procGroup
&& tag == jt->tag ) {
sstack.erase( jt );
break;
}
}
}
int ProcessState::openFile( uint64_t time, uint32_t fileid, uint64_t handleid,
uint32_t source, OTF_KeyValueList *kvlist ) {
std::map<uint64_t, FileOpen>::iterator it;
it= openfiles.find( handleid );
if( it == openfiles.end() ) {
/* insert the file into the list of opened files */
openfiles.insert( pair<uint64_t,FileOpen>( handleid,
FileOpen( time, fileid, source, kvlist ) ) );
/* make the statistics */
map<uint32_t,FileOperationStatistics>::iterator it2;
it2= fostatistics.find( fileid );
if( it2 != fostatistics.end() ) {
FileOperationStatistics& fos= it2->second;
++fos.nopen;
} else {
fostatistics.insert( pair<uint32_t, FileOperationStatistics> ( fileid,
FileOperationStatistics( 1, 0, 0, 0, 0, 0, 0 ) ) );
}
return OTF_RETURN_OK;
} else {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"Handleid %llu has already been used. aborting\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) handleid );
# endif
return OTF_RETURN_ABORT;
}
}
int ProcessState::closeFile( uint64_t handleid ) {
uint32_t ret;
map<uint64_t/*handleid*/, FileOpen>::iterator it;
it= openfiles.find( handleid );
if( it == openfiles.end() ) {
# ifdef OTF_VERBOSE
fprintf( stderr, "WARNING in function %s, file: %s, line: %i:\n "
"Trying to close a file that is not open with handle %llu. "
"This might be caused by a VT error, please check! Ignore this for now.\n",
__FUNCTION__, __FILE__, __LINE__, (long long unsigned) handleid );
# endif
/* make it a warning that cannot be disabled because I suspect an error in VT ! */
/* return OTF_RETURN_ABORT; */
return OTF_RETURN_OK;
}
/* make the statistics */
map<uint32_t,FileOperationStatistics>::iterator it2;
it2= fostatistics.find( it->second.fileid );
if( it2 != fostatistics.end() ) {
FileOperationStatistics& fos= it2->second;
++fos.nclose;
ret= OTF_RETURN_OK;
} else {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"Trying to close not yet opened file. aborting\n",
__FUNCTION__, __FILE__, __LINE__ );
# endif
ret= OTF_RETURN_ABORT;
}
/* erase the file from the opened files list */
openfiles.erase( it );
return ret;
}
int ProcessState::writeFile( uint32_t fileid, uint64_t bytes ) {
map<uint32_t,FileOperationStatistics>::iterator it;
it= fostatistics.find( fileid );
if( it != fostatistics.end() ) {
FileOperationStatistics& fos= it->second;
++fos.nwrite;
fos.byteswrite+= bytes;
} else {
fostatistics.insert( pair<uint32_t, FileOperationStatistics> ( fileid,
FileOperationStatistics( 0, 0, 0, 1, 0, 0, bytes ) ) );
}
return OTF_RETURN_OK;
}
int ProcessState::readFile( uint32_t fileid, uint64_t bytes ) {
map<uint32_t,FileOperationStatistics>::iterator it;
it= fostatistics.find( fileid );
if( it != fostatistics.end() ) {
FileOperationStatistics& fos= it->second;
++fos.nread;
fos.bytesread+= bytes;
} else {
fostatistics.insert( pair<uint32_t, FileOperationStatistics> ( fileid,
FileOperationStatistics( 0, 0, 1, 0, 0, bytes, 0 ) ) );
}
return OTF_RETURN_OK;
}
int ProcessState::seekFile( uint32_t fileid, uint64_t bytes ) {
map<uint32_t,FileOperationStatistics>::iterator it;
it= fostatistics.find( fileid );
if( it != fostatistics.end() ) {
FileOperationStatistics& fos= it->second;
++fos.nseek;
return OTF_RETURN_OK;
} else {
# ifdef OTF_VERBOSE
fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
"Trying to seek in a not yet opened file. aborting\n",
__FUNCTION__, __FILE__, __LINE__ );
# endif
return OTF_RETURN_ABORT;
}
}
void ProcessState::printStack( uint32_t processid ) const {
cerr << " stack of process " << processid << endl;
deque<FunctionCall>::const_iterator it= fstack.begin();
deque<FunctionCall>::const_iterator itend= fstack.end();
for ( ; it != itend; ++it ) {
cerr << " " << it->time << ": " << it->token << endl;
}
}
void ProcessState::printSends( uint32_t processid ) const {
cerr << " pending sends on process " << processid << endl;
deque<Send>::const_iterator it= sstack.begin();
deque<Send>::const_iterator itend= sstack.end();
for ( ; it != itend; ++it ) {
cerr << " " << "otime: " << it->originaltime << " recver: " << it->receiver <<
" group: " << it->procGroup << " tag: " << it->tag << " source: " <<
it->source << endl;
}
}
void ProcessState::printOpenFiles( uint32_t processid ) const {
cerr << " opened files on process " << processid << endl;
map<uint64_t/*handleid*/, FileOpen>::const_iterator it;
map<uint64_t/*handleid*/, FileOpen>::const_iterator itend= openfiles.end();
for( it= openfiles.begin(); it != itend; ++it ) {
cerr << " " << "time " << it->second.time << " handleid " << it->first << " fileid "
<< it->second.fileid << " source " << it->second.source << endl;
}
}
void ProcessState::printStatistics( uint32_t processid, uint64_t time,
map< uint32_t, uint32_t> *functiongroups,
map< uint32_t, uint32_t> *filegroups ) const {
map<uint32_t,FunctionStatistics> localStatistics;
map<uint32_t,FunctionStatistics> groupStatistics;
uint64_t lasttime= time;
deque<FunctionCall>::const_reverse_iterator it= fstack.rbegin();
deque<FunctionCall>::const_reverse_iterator itend= fstack.rend();
for ( ; it != itend; ++it ) {
FunctionStatistics& lstats= localStatistics[ it->token ];
/* lstats.occurrences++; */
lstats.exclusiveTime += lasttime - it->time;
lstats.inclusiveTime += time - it->time;
assert( lasttime >= it->time );
lasttime= it->time;
}
/* actually write statistics */
cerr << " statistics of process " << processid << endl;
map<uint32_t,FunctionStatistics>::const_iterator jt= fstatistics.begin();
map<uint32_t,FunctionStatistics>::const_iterator jtend= fstatistics.end();
for ( ; jt != jtend; ++jt ) {
uint64_t oc= jt->second.occurrences;
uint64_t ex= jt->second.exclusiveTime;
uint64_t in= jt->second.inclusiveTime;
map<uint32_t,FunctionStatistics>::const_iterator kt= localStatistics.find( jt->first );
map<uint32_t,FunctionStatistics>::const_iterator ktend= localStatistics.end();
if ( kt != ktend ) {
oc += kt->second.occurrences;
ex += kt->second.exclusiveTime;
in += kt->second.inclusiveTime;
}
if ( NULL == functiongroups ) {
cerr << " func " << jt->first << ": " <<
oc << ", " <<
ex << ", " <<
in << ", " << endl;
} else {
groupStatistics[(*functiongroups)[jt->first]].occurrences+= oc;
groupStatistics[(*functiongroups)[jt->first]].exclusiveTime+= ex;
groupStatistics[(*functiongroups)[jt->first]].inclusiveTime+= in;
}
}
/* write functiongroup summary */
if ( NULL != functiongroups ) {
map<uint32_t,FunctionStatistics>::const_iterator kt= groupStatistics.begin();
map<uint32_t,FunctionStatistics>::const_iterator ktend= groupStatistics.end();
for( ; kt != ktend; kt++ ) {
uint64_t oc= kt->second.occurrences;
uint64_t ex= kt->second.exclusiveTime;
uint64_t in= kt->second.inclusiveTime;
cerr << " funcgroup" << kt->first << ": " <<
oc << ", " <<
ex << ", " <<
in << ", " << endl;
}
}
/* write the message summary if any message was sent */
cerr << " " << sstatistics.number_sent << " messages sent, " << sstatistics.number_recvd
<< " messages received, " << sstatistics.bytes_sent <<
" sent bytes, " << sstatistics.bytes_recvd << " bytes received" << endl;
/* write file operation statistics */
map<uint32_t,FileOperationStatistics>::const_iterator itfo;
map<uint32_t,FileOperationStatistics>::const_iterator itendfo= fostatistics.end();
if( NULL == filegroups ) {
/* print out alle statistics */
for( itfo= fostatistics.begin(); itfo != itendfo; ++itfo ) {
const FileOperationStatistics& fost= itfo->second;
cerr << " file " << itfo->first << ": " << fost.nopen << " opened files, "
<< fost.nclose << " closed files, " << fost.nread << " read events, "
<< fost.nwrite << " write events, " << fost.nseek << " seek events, "
<< fost.bytesread << " read bytes, " << fost.byteswrite << " written bytes "
<< endl;
}
} else {
map<uint32_t/*groupid*/,FileOperationStatistics> groupstats;
map<uint32_t/*groupid*/,FileOperationStatistics>::iterator itgr;
map<uint32_t/*groupid*/,FileOperationStatistics>::iterator itendgr;
/* calculate group statistics */
for( itfo= fostatistics.begin(); itfo != itendfo; ++itfo ) {
itgr= groupstats.find( (*filegroups)[itfo->first] );
if( itgr != groupstats.end() ) {
FileOperationStatistics& fost= itgr->second;
fost.nopen+= itfo->second.nopen;
fost.nclose+= itfo->second.nclose;
fost.nread+= itfo->second.nread;
fost.nwrite+= itfo->second.nwrite;
fost.nseek+= itfo->second.nseek;
fost.bytesread+= itfo->second.bytesread;
fost.byteswrite+= itfo->second.byteswrite;
} else {
groupstats.insert( pair<uint32_t,FileOperationStatistics>(
(*filegroups)[itfo->first],
FileOperationStatistics( itfo->second.nopen, itfo->second.nclose,
itfo->second.nread, itfo->second.nwrite, itfo->second.nseek,
itfo->second.bytesread, itfo->second.byteswrite ) ) );
}
}
/* print out all group statistics */
for( itgr= groupstats.begin(), itendgr= groupstats.end(); itgr != itendgr; ++itgr ) {
const FileOperationStatistics& fost= itgr->second;
cerr << " filegroup " << itgr->first << ": " << fost.nopen << " opened files, "
<< fost.nclose << " closed files, " << fost.nread << " read events, "
<< fost.nwrite << " write events, " << fost.nseek << " seek events, "
<< fost.bytesread << " read bytes, " << fost.byteswrite << " written bytes "
<< endl;
}
}
}
void ProcessState::writeStack( OTF_Writer* writer, uint64_t time, uint32_t processid ) const {
if ( fstack.empty() ) {
OTF_Writer_writeSnapshotComment( writer,
time, processid, "empty stack" );
return;
}
OTF_KeyValueList *kvlist = OTF_KeyValueList_new();
deque<FunctionCall>::const_iterator jt= fstack.begin();
deque<FunctionCall>::const_iterator jtend= fstack.end();
for ( ; jt != jtend; ++jt ) {
/* make a copy of the key-value list to keep the data */
OTF_KeyValueList_appendKeyValueList( kvlist, jt->kvlist );
/* this will reset the key-value list */
OTF_Writer_writeEnterSnapshotKV( writer, time,
jt->time /* uint64_t originaltime */,
jt->token /* uint32_t function */,
processid /* uint32_t process */,
0 /* uint32_t source */,
kvlist /* key-value list */ );
}
OTF_KeyValueList_close( kvlist );
}
void ProcessState::writeStatistics( OTF_Writer* writer, uint64_t time,
uint32_t processid, map< uint32_t,uint32_t> *functiongroups,
map< uint32_t,uint32_t> *filegroups ) const {
/* all past function calls are considered in 'fstatistics' already,
now the time and occurrences of all active functions need to be added.
one could modify & restore the 'fstatistics' but this seems unsafe.
furthermore, this is a 'const' method. therfore we use a temporary
data structure even though it is kind of overkill :( */
map<uint32_t,FunctionStatistics> localStatistics;
map<uint32_t,FunctionStatistics> groupStatistics;
uint64_t lasttime= time;
/* cerr << "writeStatistics p" << processid << ", t" << time << endl; */
deque<FunctionCall>::const_reverse_iterator it= fstack.rbegin();
deque<FunctionCall>::const_reverse_iterator itend= fstack.rend();
for ( ; it != itend; ++it ) {
FunctionStatistics& lstats= localStatistics[ it->token ];
/* lstats.occurrences++; */
lstats.exclusiveTime += lasttime - it->time;
lstats.inclusiveTime += time - it->time;
assert( lasttime >= it->time );
lasttime= it->time;
}
/* actually write statistics */
map<uint32_t,FunctionStatistics>::const_iterator jt= fstatistics.begin();
map<uint32_t,FunctionStatistics>::const_iterator jtend= fstatistics.end();
for ( ; jt != jtend; ++jt ) {
uint64_t oc= jt->second.occurrences;
uint64_t ex= jt->second.exclusiveTime;
uint64_t in= jt->second.inclusiveTime;
map<uint32_t,FunctionStatistics>::const_iterator kt= localStatistics.find( jt->first );
map<uint32_t,FunctionStatistics>::const_iterator ktend= localStatistics.end();
if ( kt != ktend ) {
oc += kt->second.occurrences;
ex += kt->second.exclusiveTime;
in += kt->second.inclusiveTime;
}
if ( NULL == functiongroups ) {
OTF_Writer_writeFunctionSummary( writer,
time /* uint64_t time */,
jt->first /* uint32_t function */,
processid /* uint32_t process */,
oc /* uint64_t count */,
ex /* uint64_t excltime */,
in /* uint64_t incltime */ );
} else {
groupStatistics[(*functiongroups)[jt->first]].occurrences+= oc;
groupStatistics[(*functiongroups)[jt->first]].exclusiveTime+= ex;
groupStatistics[(*functiongroups)[jt->first]].inclusiveTime+= in;
}
}
/* write functiongroup summary */
if ( NULL != functiongroups ) {
map<uint32_t,FunctionStatistics>::const_iterator kt= groupStatistics.begin();
map<uint32_t,FunctionStatistics>::const_iterator ktend= groupStatistics.end();
for( ; kt != ktend; kt++ ) {
uint64_t oc= kt->second.occurrences;
uint64_t ex= kt->second.exclusiveTime;
uint64_t in= kt->second.inclusiveTime;
OTF_Writer_writeFunctionGroupSummary( writer,
time /* uint64_t time */,
kt->first /* uint32_t functiongroup */,
processid /* uint32_t process */,
oc /* uint64_t count */,
ex /* uint64_t excltime */,
in /* uint64_t incltime */ );
}
}
/* write the message summary if any message was sent */
if ( sstatistics.number_sent > 0 || sstatistics.number_recvd > 0) {
OTF_Writer_writeMessageSummary( writer, time /* current time */,
processid /* id of the process */, 0 /* peer */, 0 /* communicator */,
0 /* message tag */, sstatistics.number_sent, sstatistics.number_recvd,
sstatistics.bytes_sent, sstatistics.bytes_recvd );
}
/* write the collop summary */
map<uint32_t,uint32_t>::iterator Iter;
for(Iter=CollOps.Type2Col.begin(); Iter!=CollOps.Type2Col.end(); ++Iter) {
OTF_Writer_writeCollopSummary(writer,time,processid,0,Iter->second,CollOps.numSent[Iter->first],
CollOps.numRecv[Iter->first],CollOps.bytesSent[Iter->first],CollOps.bytesRecv[Iter->first]);
}
/* write file operation statistics */
map<uint32_t,FileOperationStatistics>::const_iterator itfo;
map<uint32_t,FileOperationStatistics>::const_iterator itendfo= fostatistics.end();
if( NULL == filegroups ) {
/* print out alle statistics */
for( itfo= fostatistics.begin(); itfo != itendfo; ++itfo ) {
const FileOperationStatistics& fost= itfo->second;
OTF_Writer_writeFileOperationSummary( writer, time, itfo->first,
processid, fost.nopen, fost.nclose, fost.nread, fost.nwrite,
fost.nseek, fost.bytesread, fost.byteswrite );
}
} else {
map<uint32_t/*groupid*/,FileOperationStatistics> groupstats;
map<uint32_t/*groupid*/,FileOperationStatistics>::iterator itgr;
map<uint32_t/*groupid*/,FileOperationStatistics>::iterator itendgr;
/* calculate group statistics */
for( itfo= fostatistics.begin(); itfo != itendfo; ++itfo ) {
itgr= groupstats.find( (*filegroups)[itfo->first] );
if( itgr != groupstats.end() ) {
FileOperationStatistics& fost= itgr->second;
fost.nopen+= itfo->second.nopen;
fost.nclose+= itfo->second.nclose;
fost.nread+= itfo->second.nread;
fost.nwrite+= itfo->second.nwrite;
fost.nseek+= itfo->second.nseek;
fost.bytesread+= itfo->second.bytesread;
fost.byteswrite+= itfo->second.byteswrite;
} else {
groupstats.insert( pair<uint32_t,FileOperationStatistics>(
(*filegroups)[itfo->first],
FileOperationStatistics( itfo->second.nopen, itfo->second.nclose,
itfo->second.nread, itfo->second.nwrite, itfo->second.nseek,
itfo->second.bytesread, itfo->second.byteswrite ) ) );
}
}
/* print out all group statistics */
for( itgr= groupstats.begin(), itendgr= groupstats.end(); itgr != itendgr; ++itgr ) {
const FileOperationStatistics& fost= itgr->second;
OTF_Writer_writeFileGroupOperationSummary( writer, time,
itgr->first, processid, fost.nopen, fost.nclose, fost.nread,
fost.nwrite, fost.nseek, fost.bytesread, fost.byteswrite );
}
}
}
void ProcessState::writeSends( OTF_Writer* writer, uint64_t time,
uint32_t processid ) const {
/*
if ( sstack.empty() ) {
OTF_Writer_writeSnapshotComment( writer,
time, processid, "no msgs" );
return;
}
*/
OTF_KeyValueList *kvlist = OTF_KeyValueList_new();
deque<Send>::const_iterator jt= sstack.begin();
deque<Send>::const_iterator jtend= sstack.end();
for ( ; jt != jtend; ++jt ) {
/* make a copy of the key-value list to keep the data */
OTF_KeyValueList_appendKeyValueList( kvlist, jt->kvlist );
/* this will reset the key-value list */
OTF_Writer_writeSendSnapshotKV( writer,
time, /* current time */
jt->originaltime /* uint64_t originaltime */,
processid /* sender */,
jt->receiver /* receiver */,
jt->procGroup /* proc group */,
jt->tag /* message tag */,
jt->length /* message length */,
jt->source /* source code location */,
kvlist /* key-value list */ );
}
OTF_KeyValueList_close( kvlist );
}
void ProcessState::writeOpenFiles( OTF_Writer* writer, uint64_t time,
uint32_t processid ) const {
/*
if( openfiles.empty() ) {
OTF_Writer_writeSnapshotComment( writer,
time, processid, "no openfiles" );
return;
}
*/
OTF_KeyValueList *kvlist = OTF_KeyValueList_new();
map<uint64_t, FileOpen>::const_iterator it;
map<uint64_t, FileOpen>::const_iterator itend= openfiles.end();
for( it= openfiles.begin(); it != itend; ++it ) {
/* make a copy of the key-value list to keep the data */
OTF_KeyValueList_appendKeyValueList( kvlist, it->second.kvlist );
/* this will reset the key-value list */
OTF_Writer_writeOpenFileSnapshotKV( writer,
time,
it->second.time,
it->second.fileid,
processid,
it->first,
it->second.source,
kvlist );
}
OTF_KeyValueList_close( kvlist );
}
void ProcessState::writeCollOps( OTF_Writer* writer, uint64_t time,
uint32_t processid ) const {
OTF_KeyValueList *kvlist = OTF_KeyValueList_new();
map<uint64_t, BeginCollOperation>::const_iterator it;
for ( it = beginCollOps.begin(); it != beginCollOps.end(); ++it ) {
/* make a copy of the key-value list to keep the data */
OTF_KeyValueList_appendKeyValueList( kvlist, it->second.kvlist );
/* this will reset the key-value list */
OTF_Writer_writeBeginCollopSnapshotKV( writer,
time, /* current time */
it->second.time, /* originaltime */
processid, /* process */
it->second.col,
it->first, /* matchingId */
it->second.procGroup,
it->second.root,
it->second.bytesSent,
it->second.bytesRecv,
it->second.scltoken,
kvlist );
}
OTF_KeyValueList_close( kvlist );
}
void ProcessState::writeFileOps( OTF_Writer* writer, uint64_t time,
uint32_t processid ) const {
OTF_KeyValueList *kvlist = OTF_KeyValueList_new();
map<uint64_t, BeginFileOperation>::const_iterator it;
for ( it = beginFileOps.begin(); it != beginFileOps.end(); ++it ) {
/* make a copy of the key-value list to keep the data */
OTF_KeyValueList_appendKeyValueList( kvlist, it->second.kvlist );
/* this will reset the key-value list */
OTF_Writer_writeBeginFileOpSnapshotKV( writer,
time,
it->second.time,
processid,
it->first,
it->second.scltoken,
kvlist );
}
OTF_KeyValueList_close( kvlist );
}
void State::defProcess( uint32_t processid ) {
/* explicit creation is not necessary.
it would furthermore disturbs selective creation of statistics
processes[ processid ];
*/
}
void State::defFunction( uint32_t function, uint32_t group ) {
functiongroups[function]= group;
}
void State::defFile( uint32_t fileid, uint32_t group ) {
filegroups[fileid]= group;
}
void State::defCollOp( uint32_t col, uint32_t type) {
Col2Type[col] = type;
}
void State::enterFunction( uint64_t time, uint32_t processid, uint32_t token, OTF_KeyValueList *kvlist ) {
/* cerr << " " << time << " enter " << token << " on " << processid << endl; */
processes[ processid ].enterFunction( time, token, kvlist );
}
void State::leaveFunction( uint64_t time, uint32_t processid, uint32_t token ) {
/* cerr << " " << time << " leave " << token << " on " << processid << endl; */
processes[ processid ].leaveFunction( time, token );
}
void State::sendMessage( uint64_t time, uint32_t sender, uint32_t receiver,
uint32_t procGroup, uint32_t tag, uint32_t length, uint32_t source,
OTF_KeyValueList *kvlist ) {
processes[ sender ].sendMessage( time, receiver, procGroup, tag, length, source, kvlist );
}
void State::recvMessage( uint32_t sender, uint32_t receiver, uint32_t procGroup,
uint32_t tag, uint32_t msglength ) {
processes[ receiver ].recvMessage( msglength );
/* only touch other process if 'doSnapshots' is set to true */
if ( doSnapshots ) {
processes[ sender ].matchMessage( receiver, procGroup, tag );
}
}
void State::collOperation( uint64_t time, uint32_t proc, uint32_t root, uint32_t col,
uint32_t bytesSent, uint32_t bytesRecv ) {
uint32_t invoc_sent = 0;
uint32_t invoc_recv = 0;
switch (Col2Type[col])
{
case OTF_COLLECTIVE_TYPE_ALL2ONE:
if(proc == root) {
invoc_sent = 1;
invoc_recv = 1;
} else {
invoc_sent = 1;
}
break;
case OTF_COLLECTIVE_TYPE_ONE2ALL:
if(proc == root) {
invoc_sent = 1;
invoc_recv = 1;
} else {
invoc_recv = 1;
}
break;
case OTF_COLLECTIVE_TYPE_ALL2ALL:
invoc_sent = 1;
invoc_recv = 1;
break;
case OTF_COLLECTIVE_TYPE_BARRIER:
invoc_sent = 1;
break;
}
processes[proc].collOperation( time, col, Col2Type[col], invoc_sent, invoc_recv, bytesSent, bytesRecv );
}
int State::fileOperation( uint64_t time, uint32_t fileid, uint32_t process,
uint64_t handleid, uint32_t operation, uint64_t bytes, uint64_t duration,
uint32_t source, OTF_KeyValueList *kvlist ) {
switch( operation & OTF_FILEOP_BITS ) {
case OTF_FILEOP_OPEN:
return processes[ process ].openFile( time, fileid, handleid, source, kvlist );
case OTF_FILEOP_CLOSE:
return processes[ process ].closeFile( handleid );
case OTF_FILEOP_READ:
return processes[ process ].readFile( fileid, bytes );
case OTF_FILEOP_WRITE:
return processes[ process ].writeFile( fileid, bytes );
case OTF_FILEOP_SEEK:
return processes[ process ].seekFile( fileid, bytes );
}
return OTF_RETURN_OK;
}
int State::beginCollOperation( uint64_t time, uint32_t proc, uint32_t root, uint32_t procGroup,
uint32_t col, uint64_t matchingId, uint64_t bytesSent, uint64_t bytesRecv, uint32_t scltoken,
OTF_KeyValueList *kvlist ) {
uint64_t invoc_sent = 0;
uint64_t invoc_recv = 0;
switch (Col2Type[col])
{
case OTF_COLLECTIVE_TYPE_ALL2ONE:
if(proc == root) {
invoc_sent = 1;
invoc_recv = 1;
} else {
invoc_sent = 1;
}
break;
case OTF_COLLECTIVE_TYPE_ONE2ALL:
if(proc == root) {
invoc_sent = 1;
invoc_recv = 1;
} else {
invoc_recv = 1;
}
break;
case OTF_COLLECTIVE_TYPE_ALL2ALL:
invoc_sent = 1;
invoc_recv = 1;
break;
case OTF_COLLECTIVE_TYPE_BARRIER:
invoc_sent = 1;
break;
}
return processes[proc].beginCollOperation( time, root, procGroup, col, Col2Type[col], matchingId, invoc_sent,
invoc_recv, bytesSent, bytesRecv, scltoken, kvlist );
}
int State::endCollOperation( uint64_t time, uint32_t proc, uint64_t matchingId ) {
return processes[proc].endCollOperation( time, matchingId );
}
int State::beginFileOperation( uint64_t time, uint32_t process, uint64_t matchingId,
uint32_t scltoken, OTF_KeyValueList *kvlist ) {
return processes[process].beginFileOperation( time, matchingId, scltoken, kvlist );
}
int State::endFileOperation( uint64_t time, uint32_t process, uint32_t fileid,
uint64_t matchingId, uint64_t handleId, uint32_t operation, uint64_t bytes,
uint32_t scltoken, OTF_KeyValueList *kvlist ) {
int ret;
ret = processes[process].endFileOperation( matchingId );
if( ret == OTF_RETURN_ABORT ) {
return ret;
}
switch( operation & OTF_FILEOP_BITS ) {
case OTF_FILEOP_OPEN:
return processes[ process ].openFile( time, fileid, handleId, scltoken, kvlist );
case OTF_FILEOP_CLOSE:
return processes[ process ].closeFile( handleId );
case OTF_FILEOP_READ:
return processes[ process ].readFile( fileid, bytes );
case OTF_FILEOP_WRITE:
return processes[ process ].writeFile( fileid, bytes );
case OTF_FILEOP_SEEK:
return processes[ process ].seekFile( fileid, bytes );
}
return OTF_RETURN_OK;
}
void State::printStack() const {
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.printStack( it->first );
}
}
void State::printSends() const {
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.printSends( it->first );
}
}
void State::printOpenFiles() const {
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.printOpenFiles( it->first );
}
}
void State::printStatistics( uint64_t time ) {
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.printStatistics( it->first, time, false == usefunctiongroups ?
NULL : &functiongroups, false == usefilegroups ? NULL : &filegroups );
}
}
void State::writeSnapshot( OTF_Writer* writer,
uint64_t time ) {
if ( ! doSnapshots ) return;
assert( NULL != writer );
/* cout << " SNAPSHOT " << time << endl; */
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.writeStack( writer, time, it->first /* processid */ );
it->second.writeSends( writer, time, it->first /* processid */ );
it->second.writeOpenFiles( writer, time, it->first /* processid */ );
it->second.writeCollOps( writer, time, it->first /* processid */ );
it->second.writeFileOps( writer, time, it->first /* processid */ );
}
}
void State::writeStatistics( OTF_Writer* writer,
uint64_t time ) {
if ( ! doStatistics ) return;
assert( NULL != writer );
/* cout << " STATISTICS " << time << endl; */
map<uint32_t,ProcessState>::const_iterator it= processes.begin();
map<uint32_t,ProcessState>::const_iterator itend= processes.end();
for ( ; it != itend; ++it ) {
it->second.writeStatistics( writer, time,
it->first /* processid */, false == usefunctiongroups ?
NULL : &functiongroups, false == usefilegroups ? NULL : &filegroups );
}
}
| 25.951519 | 122 | 0.645353 | bringhurst |
0315b9a79c66e94e3b82f15fc90e4e3758bfaefd | 2,112 | cpp | C++ | C++17TemplateFeatures/folding_basics.cpp | rostislav-nikitin/edu.cpp | 3cbb87b32042cc24ebfc9937927ba86ca24a92aa | [
"MIT"
] | null | null | null | C++17TemplateFeatures/folding_basics.cpp | rostislav-nikitin/edu.cpp | 3cbb87b32042cc24ebfc9937927ba86ca24a92aa | [
"MIT"
] | null | null | null | C++17TemplateFeatures/folding_basics.cpp | rostislav-nikitin/edu.cpp | 3cbb87b32042cc24ebfc9937927ba86ca24a92aa | [
"MIT"
] | null | null | null | // Single-line comment
/*
* Multiple line comment
*/
#include <iostream>
#include <sstream>
using namespace std;
// Variadic tempalte
auto sum()
{
return 0;
}
template<typename T, typename...Args>
auto sum(T current, Args ...args)
{
return current + sum(args...);
}
//C++17 fold expressions
//Unary
template <typename...Args>
auto sum_unary_right(Args ...args)
{
return (args + ...);
}
template <typename...Args>
auto sum_unary_left(Args ...args)
{
return (... + args);
}
template <typename...Args>
auto sum_binary_right(Args ...args)
{
return (args + ... + 0);
}
template <typename...Args>
auto sum_binary_left(Args ...args)
{
return (0 + ... + args);
}
/*
* Fold expressions operators:
* + - * / % ^ & | = < > << >> += -
* = *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->*
*/
/* If empty args pack list f():
* && - true
* || - false
* , - void
* Other ill-formed
*/
// Unary:
template<typename...Args>
bool EvenAnyOf(Args ...args)
{
return (... || (args % 2 == 0));
}
template<typename...Args>
bool EvenAllOf(Args ...args)
{
return (... && (args % 2 == 0));
}
template<typename Predicate, typename ...Args>
bool AnyOf(Predicate p, Args ...args)
{
return (... || p(args));
}
template<typename ...Args>
cpp_printf(Args...args)
{
return (... << (out << args));
}
int main()
{
cout << sum(1, 2, 3, 4, 5) << endl;
cout << sum_unary_right(1, 2, 3, 4, 5) << endl;
cout << sum_unary_left(1, 2, 3, 4, 5) << endl;
// Error:
//cout << sum_unary_left() << endl;
cout << sum_binary_right() << endl;
cout << sum_binary_left(1, 2, 3, 4) << endl;
// Even:
cout << "Event any of: " << boolalpha << EvenAnyOf(1, 5, 7) << endl;
cout << "Event any of: " << boolalpha << EvenAnyOf(1, 5, 8) << endl;
cout << "Event all of: " << boolalpha << EvenAllOf(1, 5, 8) << endl;
cout << "Event all of: " << boolalpha << EvenAllOf(2, 4, 8) << endl;
// Predicate:
cout << "Any of: " << AnyOf([](int x){ return x % 2 == 0; }, 1, 1, 3) << endl;
std::ostringstream out {};
cpp_printf(out, "Hello {0} {1}\n", "Rostislav", "Nikitin");
return 0;
}
| 18.526316 | 79 | 0.552557 | rostislav-nikitin |
031b13288a44c73b9bb85d08c2c8372ed60e2bc4 | 2,259 | cpp | C++ | database/moviemodel.cpp | softmarch/learnqml | 9aded6804e74f8f5383ab577437bc5c9dc4a0d56 | [
"MIT"
] | 3 | 2020-09-25T09:32:01.000Z | 2021-07-10T05:17:39.000Z | database/moviemodel.cpp | heafox/learnqml | 37f9d7a22dad03c0bb4b7bb036a4638a9a9e4354 | [
"MIT"
] | null | null | null | database/moviemodel.cpp | heafox/learnqml | 37f9d7a22dad03c0bb4b7bb036a4638a9a9e4354 | [
"MIT"
] | 5 | 2020-09-24T05:27:12.000Z | 2022-02-22T17:44:29.000Z | #include "moviemodel.h"
#include <QSqlQuery>
#include <QVariant>
MovieModel::MovieModel(QObject *parent)
: QObject(parent)
{
}
void MovieModel::create()
{
QSqlQuery q;
q.exec("drop table Movies");
q.exec("drop table Names");
q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)");
insert(0, "Metropolis", "Fritz Lang", 8.4);
insert(1, "Nosferatu, eine Symphonie des Grauens", "F.W. Murnau", 8.1);
insert(2, "Bis ans Ende der Welt", "Wim Wenders", 6.5);
insert(3, "Hardware", "Richard Stanley", 5.2);
insert(4, "Mitchell", "Andrew V. McLaglen", 2.1);
}
bool MovieModel::insert(int id, const QString &title, const QString &director, double rating)
{
QSqlQuery q;
q.prepare("insert into Movies values (?, ?, ?, ?)");
q.bindValue(0, id);
q.bindValue(1, title);
q.bindValue(2, director);
q.bindValue(3, rating);
return q.exec();
}
QJsonArray MovieModel::get()
{
QSqlQuery q;
// SELECT 列名称 FROM 表名称
q.prepare("select * from Movies");
QJsonArray array;
if (!q.exec())
return array;
while (q.next()) {
QJsonObject o;
o["id"] = q.value(0).toInt();
o["title"] = q.value(1).toString();
o["director"] = q.value(2).toString();
o["rating"] = q.value(3).toDouble();
array.append(o);
}
return array;
}
QJsonObject MovieModel::get(int id)
{
QSqlQuery q;
q.prepare("select * from Movies where id = ?");
q.bindValue(0, id);
QJsonObject o;
if (!q.exec())
return o;
while (q.next()) {
o["id"] = q.value(0).toInt();
o["title"] = q.value(1).toString();
o["director"] = q.value(2).toString();
o["rating"] = q.value(3).toDouble();
}
return o;
}
bool MovieModel::remove(int id)
{
QSqlQuery q;
// DELETE FROM 表名称 WHERE 列名称 = 值
q.prepare("delete from Movies where id = ?");
q.bindValue(0, id);
return q.exec();
}
bool MovieModel::updateTitle(int id, const QString &title)
{
QSqlQuery q;
// UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
q.prepare("UPDATE Movies SET Title = ? where id = ?");
q.bindValue(0, title);
q.bindValue(1, id);
return q.exec();
}
| 22.147059 | 107 | 0.585215 | softmarch |
0320601242ad93efda44e5ebcbaee0ab884cf04e | 1,447 | cc | C++ | Sandbox/src/MakeTestInputFile_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | Sandbox/src/MakeTestInputFile_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | Sandbox/src/MakeTestInputFile_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | //
// Write a text file that can be used as input for the Source00 module.
//
// Original author Rob Kutschke
//
// The format of the file is one event per line:
// runNumber subRunNumber eventNumber dataProduct
//
// where dataProduct is a trivial data product: it is a single
// integer whose value is:
//
// 10000*runNumber + 100*subRunNumber + eventNumber
//
// Framework includes.
#include "art/Framework/Core/EDAnalyzer.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/SubRun.h"
#include <iostream>
#include <fstream>
using namespace std;
namespace mu2e {
class MakeTestInputFile : public art::EDAnalyzer {
public:
explicit MakeTestInputFile(fhicl::ParameterSet const& pset);
void analyze ( art::Event const& event) override;
private:
ofstream ofile_;
};
MakeTestInputFile::MakeTestInputFile(fhicl::ParameterSet const& pset):
EDAnalyzer(pset),
ofile_( pset.get<std::string>("filename")){
}
void MakeTestInputFile::analyze(art::Event const& event) {
double dataProduct = 10000*event.id().run() + 100*event.id().subRun() + event.id().event();
ofile_ << event.id().run() << " "
<< event.id().subRun() << " "
<< event.id().event() << " "
<< dataProduct << endl;
}
} // end namespace mu2e
using mu2e::MakeTestInputFile;
DEFINE_ART_MODULE(MakeTestInputFile)
| 24.525424 | 95 | 0.67519 | bonventre |
03227cc465d6db467bdfe80cb1188d727e76839c | 17,870 | cpp | C++ | Src/MainLib/InterceptLog.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 468 | 2015-04-13T19:03:57.000Z | 2022-03-23T00:11:24.000Z | Src/MainLib/InterceptLog.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 12 | 2015-05-25T11:15:21.000Z | 2020-10-26T02:46:50.000Z | Src/MainLib/InterceptLog.cpp | vinjn/glintercept | f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f | [
"MIT"
] | 67 | 2015-04-22T13:22:48.000Z | 2022-03-05T01:11:02.000Z | /*=============================================================================
GLIntercept - OpenGL intercept/debugging tool
Copyright (C) 2004 Damian Trebilco
Licensed under the MIT license - See Docs\license.txt for details.
=============================================================================*/
#include "InterceptLog.h"
#include "ErrorLog.h"
#include "GLDriver.h"
#include <time.h>
#include <iostream>
#include <sstream>
#include <string.h>
USING_ERRORLOG
extern GLDriver glDriver;
///////////////////////////////////////////////////////////////////////////////
//
InterceptLog::InterceptLog(FunctionTable * functionTable):
functionTable(functionTable),
glGetErrorFuncIndex(-1)
{
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptLog::Init()
{
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
InterceptLog::~InterceptLog()
{
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptLog::GetFunctionString(const FunctionData *funcData,uint index, const FunctionArgs & args, string &retString)
{
//Append the function name first
retString = funcData->GetName() + "(";
//Get a copy of the arguments
FunctionArgs newArgs(args);
//Loop for all the parameters
for(uint i=0;i<funcData->parameterArray.size();i++)
{
//Get the parameter
const ParameterData * paramData = &funcData->parameterArray[i];
//Determine if we are processing pointers
bool isPointer=false;
if(paramData->pointerCount > 0 || paramData->length != -1)
{
isPointer=true;
}
//Get the value
ParamValue value;
if(!GetNextValue(paramData->GetGLType(),newArgs,isPointer, value))
{
break;
}
//Test if this is an array value
if(paramData->length != -1)
{
bool isArrayOfPointers = false;
//Test for an array of pointers
if(paramData->pointerCount > 0)
{
isArrayOfPointers = true;
}
//Assign the array
void * array = value.pointerValue;
//Loop and print the array
retString += "[";
for(uint i2=0;i2<(uint)paramData->length;i2++)
{
//Get the value from the array
if(!GetNextArrayValue(paramData->GetGLType(),&array,isArrayOfPointers, value))
{
break;
}
//Convert and print the value
retString += ConvertParam(value,isArrayOfPointers,paramData);
//Add a comma
if(i2 != (uint)(paramData->length - 1))
{
retString += ",";
}
}
retString += "]";
}
else
{
//Just get the single value
retString += ConvertParam(value,isPointer,paramData);
}
//Add a comma if there are more parameters
if(i != funcData->parameterArray.size() - 1)
{
retString += ",";
}
}
//If there are no parameters (unknown function)
if(funcData->parameterArray.size() == 0)
{
retString += " ??? ";
}
//Close the bracket
retString += ")";
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptLog::GetReturnString(const FunctionData *funcData,uint index, const FunctionRetValue & retVal, string &retString)
{
//Empty the return string
retString = "";
//Check the function data
if(!funcData)
{
LOGERR(("InterceptLog::GetReturnString - Function data for index %u is NULL",index));
return;
}
//Get the return parameter
const ParameterData * returnData = &funcData->returnType;
//Determine if we are processing pointers
bool isPointer=false;
if(returnData->pointerCount > 0 || returnData->length != -1)
{
isPointer=true;
}
//Check the return value
if(isPointer ||
returnData->type != PT_void)
{
//Look up the data
ParamValue value;
if(GetReturnValue(returnData->type, retVal, isPointer, value))
{
retString = ConvertParam(value, isPointer, returnData);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void InterceptLog::GetErrorStringValue(uint errorCode, string &retString)
{
//If we do no have the index of glGetError yet, get it
if(glGetErrorFuncIndex < 0)
{
//Get the index of the function
glGetErrorFuncIndex = functionTable->FindFunction("glGetError");
}
//If there is a valid index
const FunctionData * glGetErrorFuncData = NULL;
if(glGetErrorFuncIndex != -1)
{
//Get the function data
// (Note: The returned pointer is not permanent (as future calls may add to the table)
// so we can only store the function index)
glGetErrorFuncData = functionTable->GetFunctionData(glGetErrorFuncIndex);
}
//If the function is still not found, just log the number
if(glGetErrorFuncData == NULL || glGetErrorFuncData->returnType.type != PT_enum)
{
StringPrintF(retString,"0x%04x",errorCode);
}
else
{
//Get the return parameter
const ParameterData * returnData = &glGetErrorFuncData->returnType;
//Get the string version
ParamValue value;
value.enumValue = errorCode;
retString = ConvertParam(value, false, returnData);
}
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptLog::GetNextValue(ParameterType pType, FunctionArgs &args, bool isPointer, ParamValue &value)
{
//Test if we are getting a pointer
if(isPointer)
{
//Get the pointer value
args.Get(value.pointerValue);
//Return true
return true;
}
//Determine the type to return
switch(pType)
{
case(PT_enum):
args.Get(value.enumValue);
break;
case(PT_bitfield):
args.Get(value.bitfieldValue);
break;
case(PT_void):
break;
case(PT_byte):
args.Get(value.byteValue);
break;
case(PT_short):
args.Get(value.shortValue);
break;
case(PT_int):
args.Get(value.intValue);
break;
case(PT_sizei):
args.Get(value.sizeiValue);
break;
case(PT_ubyte):
args.Get(value.ubyteValue);
break;
case(PT_char):
args.Get(value.charValue);
break;
case(PT_boolean):
args.Get(value.booleanValue);
break;
case(PT_ushort):
args.Get(value.ushortValue);
break;
case(PT_uint):
args.Get(value.uintValue);
break;
case(PT_handle):
args.Get(value.uintValue);
break;
case(PT_float):
args.Get(value.floatValue);
break;
case(PT_double):
args.Get(value.doubleValue);
break;
case(PT_intptr):
args.Get(value.intptrValue);
break;
case(PT_sizeiptr):
args.Get(value.sizeiptrValue);
break;
case(PT_int64):
args.Get(value.int64Value);
break;
case(PT_uint64):
args.Get(value.uint64Value);
break;
case(PT_sync):
args.Get(value.syncValue);
break;
default:
LOGERR(("InterceptLog::GetNextValue - Unhandled parameter in function of type %d",(int)pType));
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptLog::GetNextArrayValue(ParameterType pType, void **array, bool isPointer, ParamValue &value)
{
//The value to increment the array by
uint arrayInc;
//Check for NULL arrays
if(*array == NULL)
{
LOGERR(("InterceptLog::GetNextArrayValue - Passing NULL as array parameter?"));
return false;
}
//Test if we are getting a pointer (is an array of pointers)
if(isPointer)
{
arrayInc = sizeof(void *);
value.pointerValue = *((void**)(*array));
}
else
{
//Determine the type to return
switch(pType)
{
case(PT_enum):
value.enumValue = *((GLenum*)(*array));
arrayInc = sizeof(GLenum);
break;
case(PT_bitfield):
value.bitfieldValue = *((GLbitfield*)(*array));
arrayInc = sizeof(GLbitfield);
break;
case(PT_void):
arrayInc = 0;
break;
case(PT_byte):
value.byteValue = *((GLbyte*)(*array));
arrayInc = sizeof(GLbyte);
break;
case(PT_short):
value.shortValue = *((GLshort*)(*array));
arrayInc = sizeof(GLshort);
break;
case(PT_int):
value.intValue = *((GLint*)(*array));
arrayInc = sizeof(GLint);
break;
case(PT_sizei):
value.sizeiValue = *((GLsizei*)(*array));
arrayInc = sizeof(GLsizei);
break;
case(PT_ubyte):
value.ubyteValue = *((GLubyte*)(*array));
arrayInc = sizeof(GLubyte);
break;
case(PT_char):
value.charValue = *((GLchar*)(*array));
arrayInc = sizeof(GLchar);
break;
case(PT_boolean):
value.booleanValue = *((GLboolean*)(*array));
arrayInc = sizeof(GLboolean);
break;
case(PT_ushort):
value.ushortValue = *((GLushort*)(*array));
arrayInc = sizeof(GLushort);
break;
case(PT_uint):
case(PT_handle):
value.uintValue = *((GLuint*)(*array));
arrayInc = sizeof(GLuint);
break;
case(PT_intptr):
value.intptrValue = *((GLintptr*)(*array));
arrayInc = sizeof(GLintptr);
break;
case(PT_sizeiptr):
value.sizeiptrValue = *((GLsizeiptr*)(*array));
arrayInc = sizeof(GLsizeiptr);
break;
case(PT_int64):
value.int64Value = *((GLint64*)(*array));
arrayInc = sizeof(GLint64);
break;
case(PT_uint64):
value.uint64Value = *((GLuint64*)(*array));
arrayInc = sizeof(GLuint64);
break;
case(PT_sync):
value.syncValue = *((GLsync*)(*array));
arrayInc = sizeof(GLsync);
break;
case(PT_float):
value.floatValue = *((GLfloat*)(*array));
arrayInc = sizeof(GLfloat);
break;
case(PT_double):
value.doubleValue = *((GLdouble*)(*array));
arrayInc = sizeof(GLdouble);
break;
default:
LOGERR(("InterceptLog::GetNextArrayValue - Unhandled parameter in function of type %d",(int)pType));
return false;
}
}
//Increment the array
*array = ((char *)(*array) + arrayInc);
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptLog::GetReturnValue(ParameterType pType, const FunctionRetValue & retVal, bool isPointer, ParamValue &value)
{
//Test if we are getting a pointer
if(isPointer)
{
//Get the pointer value
retVal.Get(value.pointerValue);
//Return true
return true;
}
//Determine the type to return
switch(pType)
{
case(PT_enum):
retVal.Get(value.enumValue);
break;
case(PT_bitfield):
retVal.Get(value.bitfieldValue);
break;
case(PT_void):
break;
case(PT_byte):
retVal.Get(value.byteValue);
break;
case(PT_short):
retVal.Get(value.shortValue);
break;
case(PT_int):
retVal.Get(value.intValue);
break;
case(PT_sizei):
retVal.Get(value.sizeiValue);
break;
case(PT_ubyte):
retVal.Get(value.ubyteValue);
break;
case(PT_boolean):
retVal.Get(value.booleanValue);
break;
case(PT_ushort):
retVal.Get(value.ushortValue);
break;
case(PT_uint):
retVal.Get(value.uintValue);
break;
case(PT_handle):
retVal.Get(value.uintValue);
break;
case(PT_char):
retVal.Get(value.charValue);
break;
case(PT_intptr):
retVal.Get(value.intptrValue);
break;
case(PT_sizeiptr):
retVal.Get(value.sizeiptrValue);
break;
case(PT_sync):
retVal.Get(value.syncValue);
break;
// Float types and int64 types are not really allowed via the assembly wrappers currently - but there are some hard coded exceptions
case(PT_float):
retVal.Get(value.floatValue);
break;
case(PT_int64):
retVal.Get(value.int64Value);
break;
case(PT_uint64):
retVal.Get(value.uint64Value);
break;
/* If these types are ever return types, will need to update the wrapper asm (esp. float types on x64)
case(PT_double):
retVal.Get(value.doubleValue);
break;
*/
default:
LOGERR(("InterceptLog::GetReturnValue - Unhandled return value in function of type %d",(int)pType));
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
string InterceptLog::ConvertParam(const ParamValue &data, bool isPointer,const ParameterData *paramData)
{
string retString;
//If the data is a custom type, attempt to handle it
if(paramData->IsCustomType() &&
ConvertCustomParam(data,isPointer,paramData,retString))
{
return retString;
}
//If this is a pointer, out-put the address
if(isPointer)
{
//Just get the pointer's address
StringPrintF(retString,"%p",data.pointerValue);
}
else
{
//Do a big switch statement
ParameterType pType=paramData->GetGLType();
switch(pType)
{
case(PT_enum):
{
//Get the enum data
const EnumData * enumData=functionTable->GetEnumData(paramData->index);
//If the index is invalid, Just print the hex values
if(enumData ==NULL)
{
StringPrintF(retString,"0x%04x", data.enumValue);
}
else
{
retString = enumData->GetDisplayString(data.enumValue);
}
}
break;
case(PT_bitfield):
{
//Get the enum data
const EnumData * enumData=functionTable->GetEnumData(paramData->index);
//If the index is invalid, Just print the hex values
if(enumData ==NULL)
{
StringPrintF(retString,"0x%04x", data.bitfieldValue);
}
else
{
retString = enumData->GetDisplayString(data.bitfieldValue);
}
}
break;
case(PT_boolean):
{
int num = data.booleanValue;
//Check the value
if(num == 0)
{
retString = "false";
}
else if(num == 1)
{
retString = "true";
}
else
{
StringPrintF(retString,"Invalid boolean %u",num);
}
break;
}
case(PT_void):
break;
case(PT_byte):
{
StringPrintF(retString,"%d",data.byteValue);
break;
}
case(PT_short):
{
StringPrintF(retString,"%d",data.shortValue);
break;
}
case(PT_int):
{
StringPrintF(retString,"%d",data.intValue);
break;
}
case(PT_sizei):
{
CASSERT(sizeof(data.sizeiValue) == sizeof(int), __Update_type_printf__);
StringPrintF(retString,"%d",data.sizeiValue);
break;
}
case(PT_ubyte):
{
StringPrintF(retString,"%u",data.ubyteValue);
break;
}
case(PT_char):
{
StringPrintF(retString,"%c",data.charValue);
break;
}
case(PT_ushort):
{
StringPrintF(retString,"%u",data.ushortValue);
break;
}
case(PT_uint):
case(PT_handle):
{
StringPrintF(retString,"%u",data.uintValue);
break;
}
case(PT_intptr):
{
ostringstream s1;
s1 << data.intptrValue;
retString = s1.str();
break;
}
case(PT_sizeiptr):
{
ostringstream s1;
s1 << data.sizeiptrValue;
retString = s1.str();
break;
}
case(PT_int64):
{
ostringstream s1;
s1 << data.int64Value;
retString = s1.str();
break;
}
case(PT_uint64):
{
ostringstream s1;
s1 << data.uint64Value;
retString = s1.str();
break;
}
case(PT_sync):
{
ostringstream s1;
s1 << data.syncValue;
retString = s1.str();
break;
}
case(PT_float):
{
StringPrintF(retString,"%f",data.floatValue);
break;
}
case(PT_double):
{
StringPrintF(retString,"%f",data.doubleValue);
break;
}
default:
LOGERR(("InterceptLog::ConvertParam - Unhandled parameter in function of type %d",(int)pType));
}
}
return retString;
}
///////////////////////////////////////////////////////////////////////////////
//
bool InterceptLog::ConvertCustomParam(const ParamValue &data, bool isPointer,const ParameterData *paramData,string &retString)
{
//Handle pointer types first
if(isPointer)
{
//If the pointer is to an array of characters, get the characters
if(paramData->type == PT_ascii_string && paramData->pointerCount == 1)
{
char * charArray = (char *)data.pointerValue;
//If it is a NULL string, the user has an error
if (charArray == NULL)
{
retString = "NULL";
}
//If the string length is greater than 25 charcters, append it
else if(strlen(charArray) > 25)
{
//Assign the buffer data
retString.assign(charArray,25);
retString = "\"" + retString + "...\"";
}
else
{
//Assign the entire character array
retString = charArray;
retString = "\"" + retString + "\"";
}
return true;
}
}
/*
//Determine the type
switch(paramData->type)
{
}
*/
return false;
}
| 22.70648 | 136 | 0.548853 | vinjn |
032be2b0115cffea95fc220954cdd2f0b383a2ca | 11,175 | cpp | C++ | src/Recording.cpp | JanitzaElectronics/umg801-recordings | 39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a | [
"MIT"
] | null | null | null | src/Recording.cpp | JanitzaElectronics/umg801-recordings | 39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a | [
"MIT"
] | null | null | null | src/Recording.cpp | JanitzaElectronics/umg801-recordings | 39b39bcbe9dfcf1e7c5b31726951e5d00f2ba63a | [
"MIT"
] | null | null | null | /*
* Recording.cpp
*
* Created on: 06.09.2021
* Copyright: 2021 by Janitza electronics GmbH
*/
#include "Recording.hpp"
#include "Umg801.hpp"
#include <iostream>
#include <iomanip>
#include <chrono>
#include <ctime>
Recording::Recording(Umg801& client, const uint32_t& id, const NodeId& nodeId) :
m_client(client),
m_id(id),
m_nodeId(nodeId),
m_dataId(),
m_getRangeId(),
m_countByRangeId(),
m_readByStartAndCountIdId(),
m_configIds() {}
UA_StatusCode Recording::getNodeIds() {
auto recordChilds = m_client.getHierarichalNodes(m_nodeId);
m_dataId = recordChilds["Data"];
if(m_dataId.isNull()) {
std::cerr << "NodeId of Node 'Data' of Recording"<<m_id<<" not found!" << std::endl;
return UA_STATUSCODE_BADINTERNALERROR;
}
for(const auto c : recordChilds) {
if(OpcUaUtil::isPrefix(c.first,"RecordingConfiguration")) {
m_configIds.emplace(OpcUaUtil::getIdSuffix(c.first),c.second);
}
}
m_getRangeId = m_client.browsePathToNodeId(NodeId(0,UA_NS0ID_BASEOBJECTTYPE),
{{2,"RecordingType", UA_NS0ID_HASSUBTYPE},
{2,"Data", UA_NS0ID_HASCOMPONENT},
{2,"GetRange", UA_NS0ID_HASCOMPONENT}});
if(m_getRangeId.isNull()) {
std::cerr << "Node BaseObjectType/RecordingType/Data/GetRange not found!" << std::endl;
return UA_STATUSCODE_BADINTERNALERROR;
}
m_countByRangeId = m_client.browsePathToNodeId(NodeId(0,UA_NS0ID_BASEOBJECTTYPE),
{{2,"RecordingType", UA_NS0ID_HASSUBTYPE},
{2,"Data", UA_NS0ID_HASCOMPONENT},
{2,"CountByRange", UA_NS0ID_HASCOMPONENT}});
if(m_countByRangeId.isNull()) {
std::cerr << "Node BaseObjectType/RecordingType/Data/CountByRange not found!" << std::endl;
return UA_STATUSCODE_BADINTERNALERROR;
}
m_readByStartAndCountIdId = m_client.browsePathToNodeId(NodeId(0, UA_NS0ID_BASEOBJECTTYPE),
{{2,"RecordingType", UA_NS0ID_HASSUBTYPE},
{2,"Data", UA_NS0ID_HASCOMPONENT},
{2,"ReadByStartAndCount", UA_NS0ID_HASCOMPONENT}});
if(m_readByStartAndCountIdId.isNull()) {
std::cerr << "Node BaseObjectType/RecordingType/Data/ReadByStartAndCount not found!" << std::endl;
return UA_STATUSCODE_BADINTERNALERROR;
}
return UA_STATUSCODE_GOOD;
}
uint32_t Recording::getId() const {
return m_id;
}
UA_StatusCode Recording::getRange(UA_DateTime& startTime, UA_DateTime& endTime) const {
UA_StatusCode retval = UA_STATUSCODE_GOOD;
size_t outputSize;
UA_Variant *output;
retval = m_client.clientCall(m_dataId, m_getRangeId, 0, nullptr, &outputSize, &output);
if(retval != UA_STATUSCODE_GOOD) {
std::cerr << "Method call to GetRange of Recording"<<m_id<<" was unsuccessful: " << UA_StatusCode_name(retval) << std::endl;
} else {
startTime = *(UA_DateTime*)output[0].data;
endTime = *(UA_DateTime*)output[1].data;
UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]);
}
return retval;
}
int Recording::countByRange(const UA_DateTime& startTime, const UA_DateTime& endTime) const {
int retval = 0;
UA_StatusCode status = UA_STATUSCODE_GOOD;
UA_Variant input[2] = {0};
size_t outputSize;
UA_Variant *output;
UA_Variant_setScalarCopy(&input[0], &startTime, &UA_TYPES[UA_TYPES_DATETIME]);
UA_Variant_setScalarCopy(&input[1], &endTime, &UA_TYPES[UA_TYPES_DATETIME]);
status = m_client.clientCall(m_dataId, m_countByRangeId, 2, input, &outputSize, &output);
if(status != UA_STATUSCODE_GOOD) {
std::cerr << "Method call to CountByRange of Recording"<<m_id<<" was unsuccessful: " << UA_StatusCode_name(status) << std::endl;
retval = -1;
} else {
retval = *(UA_UInt32*)output[0].data;
UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]);
}
return retval;
}
UA_StatusCode Recording::readByStartAndCount(const UA_DateTime& startTime, const uint32_t& count) const {
UA_StatusCode retval = UA_STATUSCODE_GOOD;
int remian = count;
UA_DateTime nextStartTime = startTime;
std::list<std::pair<uint32_t, records::RecordedData>> data;
while(remian > 0) {
UA_Variant input[2] = {0};
size_t outputSize;
UA_Variant *output;
UA_Variant_setScalarCopy(&input[0], &nextStartTime, &UA_TYPES[UA_TYPES_DATETIME]);
UA_Variant_setScalarCopy(&input[1], &count, &UA_TYPES[UA_TYPES_UINT32]);
retval = m_client.clientCall(m_dataId, m_readByStartAndCountIdId, 2, input, &outputSize, &output);
for(auto& inp : input) {
UA_Variant_clear(&inp);
}
if(retval != UA_STATUSCODE_GOOD) {
std::cerr << "Method call 'ReadByStartAndCount' was unsuccessful " << UA_StatusCode_name(retval) << std::endl;
break;
} else {
if(nextStartTime >= *(UA_DateTime*)output[1].data) {
std::cerr << "Warning: Read LastDateTime is not bigger than start-time from last read! Stopping here!";
remian = 0;
}
nextStartTime = *(UA_DateTime*)output[1].data;
const size_t recordingPoints = output[2].arrayDimensions[0];
UA_RecordingPoint* p = (UA_RecordingPoint*)output[2].data;
for(size_t i=0; i<recordingPoints; i++) {
UA_ByteString* b = &(p[i].data);
/* The received Data is stored in a google protobuf structure.
* Parse the received Byte-String as protobuf here!
*/
records::RecordedData protobuf;
if(!protobuf.ParseFromArray(b->data, b->length)) {
std::cerr << "Failed to decode protobuffer of Recording-Point " << i << "(Recording" << m_id << ")" << std::endl;
} else {
data.emplace_back(p[i].configId, protobuf);
}
}
UA_Array_delete(output, outputSize, &UA_TYPES[UA_TYPES_VARIANT]);
if(recordingPoints == 0) {
std::cerr << "Warning: no recording points returned while expecting " << remian << " more points! Stopping here!" << std::endl;
remian = 0;
}
remian -= recordingPoints;
}
}
retval = decodeData(data);
return retval;
}
template<typename T>
void Recording::printProtobuf(RecordingConfiguration& cfg, const T& protobuf, size_t& index, const std::string& browsename) const {
std::cout << "\"" << browsename << "\" : { ";
if(cfg.algorithm == UA_RECORDINGALGORITHM_AVERAGE) {
std::cout << "\"avg\" : " << protobuf.avgvalue(index) << " ";
} else {
std::cout << "\"sample\" : " << protobuf.sample(index) << " ";
}
if(cfg.extremals.minimum) {
std::cout << ", \"min\" : " << protobuf.minvalue(index) << " ";
if(cfg.extremals.timestamps) {
std::cout << ", \"min_time\" : " << protobuf.mintimestamp(index) << " ";
}
}
if(cfg.extremals.maximum) {
std::cout << ", \"max\" : " << protobuf.maxvalue(index) << " ";
if(cfg.extremals.timestamps) {
std::cout << ", \"max_time\" : " << protobuf.maxtimestamp(index) << " ";
}
}
std::cout << " }, " << std::endl;
/* Here we increment the index of the specific type-array in the protobuffer,
* so the next call will fetch the next element.
*/
index++;
}
UA_StatusCode Recording::decodeData(std::list<std::pair<uint32_t, records::RecordedData>>& data) const {
UA_StatusCode retval = UA_STATUSCODE_GOOD;
std::map<uint32_t, RecordingConfiguration> configs;
for(const auto& d : data) {
// Get RecordingConfiguration from configs. Read from device if not known yet.
auto it = configs.find(d.first);
if(it == configs.end()) {
RecordingConfiguration cfg;
retval = readRecordingConfiguration(d.first, cfg);
if(retval != UA_STATUSCODE_GOOD) {
return retval;
}
it = configs.emplace(d.first, cfg).first;
}
RecordingConfiguration& cfg = it->second;
// Convert and print timestamp. Protobuffer holds time in Seconds UTC (POSIX time)
std::time_t time = d.second.starttimeutc();
std::cout << "{ \"time\" : \"" << std::put_time(std::localtime(&time), "%Y-%m-%d %X") << "\"" << std::endl;
size_t counts[8] = {0};
/* The protobuffer holds arrays for each possible datatype that can be stored.
* Depending of the configuration, the values are stored to the type-belonging arrays
* in the same order as in configuration. To match values, we iterate throught the values in
* configuration and fetch the next value from the array of the protobuffer.
*/
for(const auto& var : cfg.values) {
if(var.info.status != UA_REFERENCESTATUS_AVAILABLE) {
// ignore values that are not available.
counts[var.info.typeInfo.dataType]++;
continue;
}
std::string name = var.browsePath;
if(var.info.typeInfo.array) {
name += "[" + std::to_string(var.info.value.arrayIndex) + "]";
}
switch(var.info.typeInfo.dataType) {
case UA_RecordingDataType::UA_RECORDINGDATATYPE_BOOLEAN:
printProtobuf(cfg, d.second.bool_(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_INT32:
printProtobuf(cfg, d.second.sint32(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_UINT32:
printProtobuf(cfg, d.second.uint32(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_INT64:
printProtobuf(cfg, d.second.sint64(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_UINT64:
printProtobuf(cfg, d.second.uint64(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_FLOAT:
printProtobuf(cfg, d.second.float_(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_DOUBLE:
printProtobuf(cfg, d.second.double_(), counts[var.info.typeInfo.dataType], name); break;
case UA_RecordingDataType::UA_RECORDINGDATATYPE_UNDEFINED:
default:
std::cerr << "Found UNDEFINED datatype; this should _not_ happen!";
}
}
std::cout << "}," << std::endl;
}
return retval;
}
UA_StatusCode Recording::readRecordingConfiguration(const uint32_t& id, RecordingConfiguration& cfg) const {
UA_StatusCode retval = UA_STATUSCODE_GOOD;
const auto cfgIter = m_configIds.find(id);
if(cfgIter == m_configIds.end()) {
std::cerr << "Failed to get " << "RecordingConfiguration"+std::to_string(id) << " from node " << m_nodeId.toString() <<": NodeId not found!"<< std::endl;
return UA_STATUSCODE_BADNOTFOUND;
}
auto nodes = m_client.getHierarichalNodes(cfgIter->second);
cfg.id = id;
cfg.algorithm = m_client.getVariantValue<UA_RecordingAlgorithm>(nodes["Algorithm"]);
cfg.extremals = m_client.getVariantValue<UA_RecordingExtremals>(nodes["Extremals"]);
cfg.interval_seconds = m_client.getVariantValue<UA_UInt32>(nodes["Interval"]);
for(const auto& v : m_client.getVariantArrayValue<UA_RecordingValueInfo>(nodes["Values"])) {
std::string browsepath = "";
if(v.status == UA_REFERENCESTATUS_AVAILABLE) {
auto p = m_client.lookup(NodeId(v.value.node), UA_TAG_RECORDABLE);
if(p) {
browsepath = *p;
}
}
cfg.values.emplace_back(RecordingValueInfo(v, browsepath));
}
// Print configuration information
std::cout << "RecordingConfig" << cfg.id << ": Algorithm=";
if(cfg.algorithm == UA_RECORDINGALGORITHM_SAMPLE) std::cout << "Sample; Extremals:";
else std::cout << "Average; Extremals:";
if(cfg.extremals.maximum) std::cout << "max,";
if(cfg.extremals.minimum) std::cout << "min,";
if(cfg.extremals.timestamps) std::cout << "timestmaps";
std::cout << "; Interval=" << cfg.interval_seconds << "sec ";
std::cout << "; Value-Count=" << cfg.values.size() << std::endl;
return retval;
}
| 38.270548 | 155 | 0.708993 | JanitzaElectronics |
032c358fc56460a3c22230f24741725a9c05edcb | 3,346 | cpp | C++ | src/engine/entity/src/diagnostics/world_stats.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 3,262 | 2016-04-10T15:24:10.000Z | 2022-03-31T17:47:08.000Z | src/engine/entity/src/diagnostics/world_stats.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 53 | 2016-10-09T16:25:04.000Z | 2022-01-10T13:52:37.000Z | src/engine/entity/src/diagnostics/world_stats.cpp | code-disaster/halley | 5c85c889b76c69c6bdef6f4801c6aba282b7af80 | [
"Apache-2.0"
] | 193 | 2017-10-23T06:08:41.000Z | 2022-03-22T12:59:58.000Z | #include "diagnostics/world_stats.h"
#include "halley/core/graphics/render_context.h"
#include "halley/core/graphics/text/font.h"
#include "halley/core/resources/resources.h"
#include "halley/core/api/core_api.h"
#include "world.h"
#include "system.h"
#include "halley/core/api/halley_api.h"
#include "halley/text/string_converter.h"
using namespace Halley;
WorldStatsView::WorldStatsView(Resources& resources, const HalleyAPI& api)
: StatsView(resources, api)
, text(resources.get<Font>("Ubuntu Bold"), "", 16, Colour(1, 1, 1), 1.0f, Colour(0.1f, 0.1f, 0.1f))
{
}
void WorldStatsView::paint(Painter& painter)
{
int64_t grandTotal = 0;
TimeLine timelines[] = { TimeLine::FixedUpdate, TimeLine::VariableUpdate, TimeLine::Render };
String timelineLabels[] = { "Fixed", "Variable", "Render" };
int i = 0;
float width = (1280.0f - 40.0f) / 3.0f;
auto drawStats = [&] (String name, int nEntities, int64_t time, Vector2f& basePos)
{
text.setText(name).setAlignment(0).setPosition(basePos + Vector2f(10, 0)).draw(painter);
text.setAlignment(1);
if (nEntities > 0) {
text.setText(toString(nEntities)).setPosition(basePos + Vector2f(width - 120, 0)).draw(painter);
}
text.setText(formatTime(time)).setPosition(basePos + Vector2f(width - 50, 0)).draw(painter);
text.setAlignment(0);
basePos.y += 20;
};
auto& coreAPI = *api.core;
for (auto timeline : timelines) {
int64_t engineTime = coreAPI.getTime(CoreAPITimer::Engine, timeline, StopwatchRollingAveraging::Mode::Average);
int64_t gameTime = coreAPI.getTime(CoreAPITimer::Game, timeline, StopwatchRollingAveraging::Mode::Average);
if (timeline == TimeLine::Render) {
const auto selfTime = timer.averageElapsedNanoSeconds();
gameTime -= selfTime;
}
grandTotal += engineTime + gameTime;
Vector2f pos = Vector2f(20 + (i++) * width, 60);
text.setColour(Colour(0.2f, 1.0f, 0.3f)).setText(String(timelineLabels[int(timeline)]) + ": ").setPosition(pos).draw(painter);
text.setColour(Colour(1, 1, 1));
pos.y += 20;
int64_t worldTotal = world ? world->getAverageTime(timeline) : 0;
int64_t sysTotal = 0;
if (world) {
for (auto& system : world->getSystems(timeline)) {
String name = system->getName();
int64_t ns = system->getNanoSecondsTakenAvg();
sysTotal += ns;
drawStats(name, int(system->getEntityCount()), ns, pos);
}
text.setColour(Colour(0.8f, 0.8f, 0.8f));
drawStats("[World]", 0, worldTotal - sysTotal, pos);
}
drawStats("[Game]", 0, gameTime - worldTotal, pos);
int64_t vsyncTime = 0;
if (timeline == TimeLine::Render) {
vsyncTime = coreAPI.getTime(CoreAPITimer::Vsync, TimeLine::Render, StopwatchRollingAveraging::Mode::Average);
drawStats("[VSync]", 0, vsyncTime, pos);
}
drawStats("[Engine]", 0, engineTime, pos);
text.setColour(Colour(0.8f, 1.0f, 0.8f));
drawStats("Total", world ? int(world->numEntities()) : 0, engineTime + gameTime + vsyncTime, pos);
}
int maxFPS = int(lround(1'000'000'000.0 / grandTotal));
text
.setColour(Colour(1, 1, 1))
.setText("Total elapsed: " + formatTime(grandTotal) + " ms [" + toString(maxFPS) + " FPS maximum].\n" + toString(painter.getPrevDrawCalls()) + " draw calls, " + toString(painter.getPrevTriangles()) + " triangles, " + toString(painter.getPrevVertices()) + " vertices.")
.setPosition(Vector2f(20, 20))
.draw(painter);
}
| 36.769231 | 270 | 0.69217 | code-disaster |
032f82f4bb639fc066a787a8c605c634685a8aa4 | 1,616 | cpp | C++ | webrtc-jni/src/main/cpp/src/media/audio/AudioProcessingStats.cpp | preciate/webrtc-java | 9073e12b57a74e8c89ed0950d41d29ab7f5cc691 | [
"Apache-2.0"
] | 1 | 2022-02-11T16:26:08.000Z | 2022-02-11T16:26:08.000Z | webrtc-jni/src/main/cpp/src/media/audio/AudioProcessingStats.cpp | preciate/webrtc-java | 9073e12b57a74e8c89ed0950d41d29ab7f5cc691 | [
"Apache-2.0"
] | 1 | 2022-02-11T16:30:13.000Z | 2022-02-11T16:30:13.000Z | webrtc-jni/src/main/cpp/src/media/audio/AudioProcessingStats.cpp | internet-of-presence/webrtc-java | 26ab2091f962533288e2267a16980008d7008528 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "media/audio/AudioProcessingStats.h"
#include "JavaClasses.h"
#include "JavaObject.h"
#include "JavaUtils.h"
#include "JNI_WebRTC.h"
namespace jni
{
namespace AudioProcessingStats
{
JavaAudioProcessingStatsClass::JavaAudioProcessingStatsClass(JNIEnv * env)
{
cls = FindClass(env, PKG_AUDIO"AudioProcessingStats");
voiceDetected = GetFieldID(env, cls, "voiceDetected", "Z");
echoReturnLoss = GetFieldID(env, cls, "echoReturnLoss", "D");
echoReturnLossEnhancement = GetFieldID(env, cls, "echoReturnLossEnhancement", "D");
divergentFilterFraction = GetFieldID(env, cls, "divergentFilterFraction", "D");
delayMs = GetFieldID(env, cls, "delayMs", "I");
delayMedianMs = GetFieldID(env, cls, "delayMedianMs", "I");
delayStandardDeviationMs = GetFieldID(env, cls, "delayStandardDeviationMs", "I");
residualEchoLikelihood = GetFieldID(env, cls, "residualEchoLikelihood", "D");
residualEchoLikelihoodRecentMax = GetFieldID(env, cls, "residualEchoLikelihoodRecentMax", "D");
}
}
} | 37.581395 | 98 | 0.741337 | preciate |
033491cc97254a0ce5e5e614a7138c018d9fd099 | 12,229 | cpp | C++ | src/db/db_bookshelf.cpp | cuhk-eda/ripple-fpga | 059646fcaa0c8d77e4283f55be2bd5692862a039 | [
"Unlicense"
] | 60 | 2019-05-15T13:21:40.000Z | 2021-12-11T14:38:56.000Z | src/db/db_bookshelf.cpp | jordanpui/ripplefpga | 059646fcaa0c8d77e4283f55be2bd5692862a039 | [
"Unlicense"
] | 3 | 2020-05-31T13:14:05.000Z | 2021-12-11T14:27:59.000Z | src/db/db_bookshelf.cpp | cuhk-eda/ripple-fpga | 059646fcaa0c8d77e4283f55be2bd5692862a039 | [
"Unlicense"
] | 16 | 2019-06-07T14:56:34.000Z | 2022-03-29T20:22:38.000Z | #include "db.h"
using namespace db;
bool read_line_as_tokens(istream &is, vector<string> &tokens) {
tokens.clear();
string line;
getline(is, line);
while (is && tokens.empty()) {
string token = "";
for (unsigned i=0; i<line.size(); ++i) {
char currChar = line[i];
if (isspace(currChar)) {
if (!token.empty()) {
// Add the current token to the list of tokens
tokens.push_back(token);
token.clear();
}
}else{
// Add the char to the current token
token.push_back(currChar);
}
}
if(!token.empty()){
tokens.push_back(token);
}
if(tokens.empty()){
// Previous line read was empty. Read the next one.
getline(is, line);
}
}
return !tokens.empty();
}
bool Database::readAux(string file){
string directory;
size_t found=file.find_last_of("/\\");
if (found==file.npos) {
directory="./";
}else{
directory=file.substr(0,found);
directory+="/";
}
ifstream fs(file);
if (!fs.good()){
printlog(LOG_ERROR, "Cannot open %s to read", file.c_str());
return false;
}
string buffer;
while (fs>>buffer) {
if (buffer=="#") {
//ignore comments
fs.ignore(std::numeric_limits<streamsize>::max(), '\n');
continue;
}
size_t dot_pos = buffer.find_last_of(".");
if ( dot_pos == string::npos) {
//ignore words without "dot"
continue;
}
string ext=buffer.substr(dot_pos);
if (ext==".nodes") {
setting.io_nodes = directory+buffer;
}else if (ext==".nets") {
setting.io_nets = directory+buffer;
}else if (ext==".pl") {
setting.io_pl = directory+buffer;
}else if (ext==".wts") {
setting.io_wts = directory+buffer;
}else if (ext==".scl") {
setting.io_scl = directory+buffer;
}else if(ext==".lib"){
setting.io_lib = directory+buffer;
}else {
continue;
}
}
printlog(LOG_VERBOSE, "nodes = %s", setting.io_nodes.c_str());
printlog(LOG_VERBOSE, "nets = %s", setting.io_nets.c_str());
printlog(LOG_VERBOSE, "pl = %s", setting.io_pl.c_str());
printlog(LOG_VERBOSE, "wts = %s", setting.io_wts.c_str());
printlog(LOG_VERBOSE, "scl = %s", setting.io_scl.c_str());
printlog(LOG_VERBOSE, "lib = %s", setting.io_lib.c_str());
fs.close();
return true;
}
bool Database::readNodes(string file){
ifstream fs(file);
if (!fs.good()) {
cerr<<"Read nodes file: "<<file<<" fail"<<endl;
return false;
}
vector<string> tokens;
while(read_line_as_tokens(fs, tokens)){
Instance *instance = database.getInstance(tokens[0]);
if(instance != NULL){
printlog(LOG_ERROR, "Instance duplicated: %s", tokens[0].c_str());
}else{
Master *master = database.getMaster(Master::NameString2Enum(tokens[1]));
if(master == NULL){
printlog(LOG_ERROR, "Master not found: %s", tokens[1].c_str());
}else{
Instance newinstance(tokens[0], master);
instance = database.addInstance(newinstance);
}
}
}
fs.close();
return true;
}
bool Database::readNets(string file){
ifstream fs(file);
if (!fs.good()) {
cerr<<"Read net file: "<<file<<" fail"<<endl;
return false;
}
vector<string> tokens;
Net *net = NULL;
while(read_line_as_tokens(fs, tokens)){
if(tokens[0][0] == '#'){
continue;
}
if(tokens[0] == "net"){
net = database.getNet(tokens[1]);
if(net != NULL){
printlog(LOG_ERROR, "Net duplicated: %s", tokens[1].c_str());
}else{
Net newnet(tokens[1]);
net = database.addNet(newnet);
}
}else if(tokens[0] == "endnet"){
net = NULL;
}else{
Instance *instance = database.getInstance(tokens[0].c_str());
Pin *pin = NULL;
if(instance != NULL){
pin = instance->getPin(tokens[1]);
}else{
printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str());
}
if(pin == NULL){
printlog(LOG_ERROR, "Pin not found: %s", tokens[1].c_str());
}else{
net->addPin(pin);
if (pin->type->type=='o' && pin->instance->master->name==Master::BUFGCE){
net->isClk=true;
}
}
}
}
fs.close();
return false;
}
bool Database::readPl(string file){
ifstream fs(file);
if (!fs.good()) {
cerr<<"Read pl file: "<<file<<" fail"<<endl;
return false;
}
vector<string> tokens;
while(read_line_as_tokens(fs, tokens)){
Instance *instance = database.getInstance(tokens[0]);
if(instance == NULL){
printlog(LOG_ERROR, "Instance not found: %s", tokens[0].c_str());
continue;
}
int x = atoi(tokens[1].c_str());
int y = atoi(tokens[2].c_str());
int slot = atoi(tokens[3].c_str());
instance->inputFixed = (tokens.size() >= 5 && tokens[4] == "FIXED");
instance->fixed = instance->inputFixed;
if(instance->IsFF()) slot += 16;
else if(instance->IsCARRY()) slot += 32;
place(instance, x, y, slot);
}
fs.close();
return true;
}
bool Database::readScl(string file){
ifstream fs(file);
if (!fs.good()) {
printlog(LOG_ERROR, "Cannot open %s to read", file.c_str());
return false;
}
vector<string> tokens;
while(read_line_as_tokens(fs, tokens)){
if(tokens[0] == "SITE"){
SiteType *sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[1]));
if(sitetype == NULL){
SiteType newsitetype(SiteType::NameString2Enum(tokens[1]));
sitetype = database.addSiteType(newsitetype);
}else{
printlog(LOG_WARN, "Duplicated site type: %s", sitetype->name);
}
while(read_line_as_tokens(fs, tokens)){
if(tokens[0] == "END" && tokens[1] == "SITE"){
break;
}
Resource *resource = database.getResource(Resource::NameString2Enum(tokens[0]));
if(resource == NULL){
Resource newresource(Resource::NameString2Enum(tokens[0]));
resource = database.addResource(newresource);
}
sitetype->addResource(resource, atoi(tokens[1].c_str()));
}
}
if(tokens[0] == "RESOURCES"){
while(read_line_as_tokens(fs, tokens)){
if(tokens[0] == "END" && tokens[1] == "RESOURCES"){
break;
}
Resource *resource = database.getResource(Resource::NameString2Enum(tokens[0]));
if(resource == NULL){
Resource newresource(Resource::NameString2Enum(tokens[0]));
resource = database.addResource(newresource);
}
for(int i=1; i<(int)tokens.size(); i++){
Master *master = database.getMaster(Master::NameString2Enum(tokens[i]));
if(master == NULL){
printlog(LOG_ERROR, "Master not found: %s", tokens[i].c_str());
}else{
resource->addMaster(master);
}
}
}
}
if(tokens[0] == "SITEMAP"){
int nx = atoi(tokens[1].c_str());
int ny = atoi(tokens[2].c_str());
database.setSiteMap(nx, ny);
database.setSwitchBoxes(nx/2-1, ny);
while(read_line_as_tokens(fs, tokens)){
if(tokens[0] == "END" && tokens[1] == "SITEMAP"){
break;
}
int x = atoi(tokens[0].c_str());
int y = atoi(tokens[1].c_str());
SiteType *sitetype = database.getSiteType(SiteType::NameString2Enum(tokens[2]));
if(sitetype == NULL){
printlog(LOG_ERROR, "Site type not found: %s", tokens[2].c_str());
}else{
database.addSite(x, y, sitetype);
}
}
}
if(tokens[0] == "CLOCKREGIONS"){
int nx = atoi(tokens[1].c_str());
int ny = atoi(tokens[2].c_str());
crmap_nx = nx;
crmap_ny = ny;
clkrgns.assign(nx, vector<ClkRgn*>(ny, NULL));
hfcols.assign(sitemap_nx,vector<HfCol*>(2*ny,NULL));
for (int x=0; x<nx; x++){
for (int y=0; y<ny; y++){
read_line_as_tokens(fs, tokens);
string name = tokens[0]+tokens[1];
int lx = atoi(tokens[3].c_str());
int ly = atoi(tokens[4].c_str());
int hx = atoi(tokens[5].c_str());
int hy = atoi(tokens[6].c_str());
clkrgns[x][y]=new ClkRgn(name, lx, ly, hx, hy, x, y);
}
}
}
}
fs.close();
return true;
}
bool Database::readLib(string file){
ifstream fs(file);
if (!fs.good()) {
printlog(LOG_ERROR, "Cannot open %s to read", file.c_str());
return false;
}
vector<string> tokens;
Master *master = NULL;
while(read_line_as_tokens(fs, tokens)){
if (tokens[0]=="CELL") {
master = database.getMaster(Master::NameString2Enum(tokens[1]));
if(master == NULL){
Master newmaster(Master::NameString2Enum(tokens[1]));
master = database.addMaster(newmaster);
}else{
printlog(LOG_WARN, "Duplicated master: %s", tokens[1].c_str());
}
} else if (tokens[0]=="PIN") {
char type = 'x';
if(tokens.size() >= 4){
if(tokens[3] == "CLOCK"){
type = 'c';
}else if(tokens[3] == "CTRL"){
type = 'e';
}
}else if(tokens.size() >= 3){
if(tokens[2] == "OUTPUT"){
type = 'o';
}else if(tokens[2] == "INPUT"){
type = 'i';
}
}
PinType pintype(tokens[1], type);
if(master != NULL){
master->addPin(pintype);
}
} else if (tokens[0]=="END") {
}
}
fs.close();
return true;
}
bool Database::readWts(string file){
return false;
}
bool Database::writePl(string file){
ofstream fs(file);
if(!fs.good()){
printlog(LOG_ERROR, "Cannot open %s to write", file.c_str());
return false;
}
vector<Instance*>::iterator ii = database.instances.begin();
vector<Instance*>::iterator ie = database.instances.end();
int nErrorLimit = 10;
for(; ii!=ie; ++ii){
Instance *instance = *ii;
if(instance->pack == NULL || instance->pack->site == NULL){
if(nErrorLimit > 0){
printlog(LOG_ERROR, "Instance not placed: %s", instance->name.c_str());
nErrorLimit--;
}else if(nErrorLimit == 0){
printlog(LOG_ERROR, "(Remaining same errors are not shown)");
nErrorLimit--;
}
continue;
}
Site *site = instance->pack->site;
int slot = instance->slot;
if(instance->IsFF()) slot -= 16;
else if(instance->IsCARRY()) slot -= 32;
fs<<instance->name<<" "<<site->x<<" "<<site->y<<" "<<slot;
if(instance->inputFixed) fs<<" FIXED";
fs<<endl;
}
return true;
}
| 32.962264 | 96 | 0.485567 | cuhk-eda |
0335ed4041cad29100751e37044a798e3b592f78 | 8,910 | cpp | C++ | Beta 3 casi final/gestionarowner.cpp | roiso/unisys | f23f66ccb426a8127ebe79479953c7b4367121d8 | [
"MIT"
] | null | null | null | Beta 3 casi final/gestionarowner.cpp | roiso/unisys | f23f66ccb426a8127ebe79479953c7b4367121d8 | [
"MIT"
] | null | null | null | Beta 3 casi final/gestionarowner.cpp | roiso/unisys | f23f66ccb426a8127ebe79479953c7b4367121d8 | [
"MIT"
] | null | null | null | #include "gestionarowner.h"
#include "ui_gestionarowner.h"
#include <qmessagebox.h>
#include <QDebug>
//Guillermo
gestionarOwner::gestionarOwner(QWidget *parent) :
QDialog(parent),
ui(new Ui::gestionarOwner){
ui->setupUi(this);
}
gestionarOwner::~gestionarOwner()
{
compania v2;
v2.setController(*controller_);
v2.exec();
delete ui;
}
void gestionarOwner::setController (MainController &controller){
controller_=&controller;
this->inicial();
}
void gestionarOwner::inicial(){
this->showOwner();
ui->editOwner->setEnabled(false);
ui->btnAcpetar->setEnabled(false);
ui->btnCancelar->setEnabled(false);
ui->btnModificar->setEnabled(false);
ui->btnBorrar->setEnabled(false);
ui->btnNuevo->setEnabled(true);
ui->tableOwner->setEnabled(true);
}
void gestionarOwner::limpiarLabel(){
ui->txtOwner->clear();
ui->txtRazon->clear();
ui->txtTlfn->clear();
ui->txtNIF->clear();
ui->txtPoblacion->clear();
ui->txtProvincia->clear();
ui->txtCP->clear();
ui->txtPais->clear();
ui->txtDireccion->clear();
ui->plaintxtObservaciones->clear();
}
void gestionarOwner::showOwner(){
rellenarTabla(controller_->getOwners(), ui->tableOwner, &criterio);
}
void gestionarOwner::showLabel(){
QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text();
int seleccionado = ID.toInt();
encontrarID(controller_->getOwners(), &seleccionado);
ui->txtOwner->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).owner()));
ui->txtRazon->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).razon()));
ui->txtTlfn->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).tlfn()));
ui->txtNIF->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).NIF()));
ui->txtPoblacion->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).poblacion()));
ui->txtProvincia->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).provincia()));
ui->txtCP->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).CP()));
ui->txtPais->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).pais()));
ui->txtDireccion->setText(QString::fromStdString(controller_->getOwners().at(seleccionado).direccion()));
ui->plaintxtObservaciones->setPlainText(QString::fromStdString(controller_->getOwners().at(seleccionado).observaciones()));
ui->btnModificar->setEnabled(true);
ui->btnBorrar->setEnabled(true);
}
void gestionarOwner::nuevo(){
opcion=1;
ui->editOwner->setEnabled(true);
ui->tableOwner->clearSelection();
ui->tableOwner->setEnabled(false);
ui->btnModificar->setEnabled(false);
ui->btnBorrar->setEnabled(false);
ui->btnAcpetar->setEnabled(true);
ui->btnCancelar->setEnabled(true);
ui->btnNuevo->setEnabled(false);
this->limpiarLabel();
ui->txtOwner->setFocus();
}
void gestionarOwner::modificar(){
QModelIndexList selectedList = ui->tableOwner->selectionModel()->selectedRows();
if (!selectedList.empty()){
opcion=2;
ui->editOwner->setEnabled(true);
ui->tableOwner->setEnabled(false);
ui->txtOwner->setFocus();
ui->btnAcpetar->setEnabled(true);
ui->btnCancelar->setEnabled(true);
ui->btnModificar->setEnabled(false);
ui->btnBorrar->setEnabled(false);
ui->btnNuevo->setEnabled(false);
}
}
void gestionarOwner::borrar(){
QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text();
int seleccionado = ID.toInt();
encontrarID(controller_->getNegos(), &seleccionado);
ui->editOwner->setEnabled(false);
ui->tableOwner->setEnabled(false);
ui->btnAcpetar->setEnabled(false);
ui->btnCancelar->setEnabled(false);
ui->btnModificar->setEnabled(false);
ui->btnBorrar->setEnabled(false);
ui->btnNuevo->setEnabled(false);
QMessageBox::StandardButton btnBorrar;
btnBorrar = QMessageBox::question(this, "", "Está seguro que desea eliminar el Owner: " + QString::fromStdString(controller_->getOwners().at(seleccionado).owner()), QMessageBox::Yes | QMessageBox:: No);
if(btnBorrar == QMessageBox::Yes){
c_owner copyBorrar = controller_->getOwners().at(seleccionado);
copyBorrar.setBorrado(true);
controller_->modificarOwner(seleccionado, copyBorrar);
for (size_t i=0; i<controller_->getUsers().count(); i++){
if(controller_->getUsers().at(i).ID_owner()==ID.toInt()){
c_user copyUser = controller_->getUsers().at(i);
copyUser.setBorrado(true);
controller_->modificarUser(i,copyUser);
}
}
for(size_t i=0; i<controller_->getOficinas().count(); i++){
if(controller_->getOficinas().at(i).ID_owner()==ID.toInt()){
c_oficina copyOficina = controller_->getOficinas().at(i);
copyOficina.setBorrado(true);
controller_->modificarOficina(i, copyOficina);
}
}
for(size_t i=0; i<controller_->getNegos().count(); i++){
if(controller_->getNegos().at(i).ID_owner()==ID.toInt()){
c_nego copyNego = controller_->getNegos().at(i);
copyNego.setBorrado(true);
controller_->modificarNego(i, copyNego);
}
}
this->inicial();
this->limpiarLabel();
}else if(btnBorrar == QMessageBox::No){
this->inicial();
this->limpiarLabel();
}
}
void gestionarOwner::aceptar(){
switch (opcion) {
case 1:{
if(ui->txtOwner->text().isEmpty() || ui->txtRazon->text().isEmpty() || ui->txtCP->text().isEmpty() || ui->txtDireccion->text().isEmpty() || ui->txtNIF->text().isEmpty() || ui->txtPais->text().isEmpty() || ui->txtPoblacion->text().isEmpty() || ui->txtProvincia->text().isEmpty() || ui->txtTlfn->text().isEmpty()){
QMessageBox::information(this, "", "Debe rellenar todos los campos");
}else{
c_owner nuevo;
controller_->setUltimoIDowners();
nuevo.setID(controller_->getUltimoIDowners());
nuevo.setBorrado(false);
nuevo.setOwner(ui->txtOwner->text().toStdString());
nuevo.setRazon(ui->txtRazon->text().toStdString());
nuevo.setNIF(ui->txtNIF->text().toStdString());
nuevo.setTlfn(ui->txtTlfn->text().toStdString());
nuevo.setDireccion(ui->txtDireccion->text().toStdString());
nuevo.setCP(ui->txtCP->text().toStdString());
nuevo.setPoblacion(ui->txtPoblacion->text().toStdString());
nuevo.setProvincia(ui->txtProvincia->text().toStdString());
nuevo.setPais(ui->txtPais->text().toStdString());
nuevo.setObservaciones(ui->plaintxtObservaciones->toPlainText().toStdString());
controller_->setOwner(nuevo);
this->inicial();
ui->tableOwner->selectRow(ui->tableOwner->rowCount()-1);
}
break;
}
case 2:{
QString ID = ui->tableOwner->item(ui->tableOwner->currentRow(),4)->text();
int seleccionado = ID.toInt();
encontrarID(controller_->getOwners(), &seleccionado);
int fila = ui->tableOwner->currentRow();
if(ui->txtOwner->text().isEmpty() || ui->txtRazon->text().isEmpty() || ui->txtCP->text().isEmpty() || ui->txtDireccion->text().isEmpty() || ui->txtNIF->text().isEmpty() || ui->txtPais->text().isEmpty() || ui->txtPoblacion->text().isEmpty() || ui->txtProvincia->text().isEmpty() || ui->txtTlfn->text().isEmpty()){
QMessageBox::information(this, "", "Todos los campos deben estár rellenos");
}else{
c_owner modificado;
modificado=controller_->getOwners().at(seleccionado);
modificado.setOwner(ui->txtOwner->text().toStdString());
modificado.setRazon(ui->txtRazon->text().toStdString());
modificado.setNIF(ui->txtNIF->text().toStdString());
modificado.setTlfn(ui->txtTlfn->text().toStdString());
modificado.setDireccion(ui->txtDireccion->text().toStdString());
modificado.setCP(ui->txtCP->text().toStdString());
modificado.setPoblacion(ui->txtPoblacion->text().toStdString());
modificado.setProvincia(ui->txtProvincia->text().toStdString());
modificado.setPais(ui->txtPais->text().toStdString());
modificado.setObservaciones(ui->plaintxtObservaciones->toPlainText().toStdString());
controller_->modificarOwner(seleccionado, modificado);
this->inicial();
ui->tableOwner->selectRow(fila);
}
break;
}
default:
break;
}
}
void gestionarOwner::cancelar(){
this->inicial();
this->limpiarLabel();
}
| 39.955157 | 320 | 0.63771 | roiso |
033f3439742b4c8100746e943d5ff7fcd865af51 | 339 | hpp | C++ | Server/include/Pages/ControlPannel.hpp | siisgoo/siisty | 66103c54e0d1b35b88177c290e2bf60012607309 | [
"MIT"
] | null | null | null | Server/include/Pages/ControlPannel.hpp | siisgoo/siisty | 66103c54e0d1b35b88177c290e2bf60012607309 | [
"MIT"
] | null | null | null | Server/include/Pages/ControlPannel.hpp | siisgoo/siisty | 66103c54e0d1b35b88177c290e2bf60012607309 | [
"MIT"
] | null | null | null | #ifndef CONTROLPANNEL_HPP
#define CONTROLPANNEL_HPP
#include <QWidget>
namespace Ui {
class ControlPannel;
}
class ControlPannel : public QWidget {
Q_OBJECT
public:
explicit ControlPannel(QWidget *parent = nullptr);
~ControlPannel();
private:
Ui::ControlPannel *ui;
};
#endif // CONTROLPANNEL_HPP
| 15.409091 | 58 | 0.690265 | siisgoo |
034018a24168009ea6ac2846053c600e898da0fa | 1,321 | cpp | C++ | Source/FactoryGame/FGTargetPointLinkedList.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGTargetPointLinkedList.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGTargetPointLinkedList.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | // This file has been automatically generated by the Unreal Header Implementation tool
#include "FGTargetPointLinkedList.h"
UFGTargetPointLinkedList::UFGTargetPointLinkedList(){ }
void UFGTargetPointLinkedList::PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void UFGTargetPointLinkedList::PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void UFGTargetPointLinkedList::PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void UFGTargetPointLinkedList::PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void UFGTargetPointLinkedList::GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects){ }
bool UFGTargetPointLinkedList::NeedTransform_Implementation(){ return bool(); }
bool UFGTargetPointLinkedList::ShouldSave_Implementation() const{ return bool(); }
void UFGTargetPointLinkedList::InsertItem( AFGTargetPoint* newTarget){ }
void UFGTargetPointLinkedList::RemoveItem( AFGTargetPoint* targetToRemove){ }
void UFGTargetPointLinkedList::SetCurrentTarget( AFGTargetPoint* newTarget){ }
void UFGTargetPointLinkedList::SetPathVisibility( bool inVisible){ }
void UFGTargetPointLinkedList::SetNextTarget(){ }
void UFGTargetPointLinkedList::SetClosestPointAsTarget(){ }
void UFGTargetPointLinkedList::ClearRecording(){ }
| 66.05 | 110 | 0.84103 | iam-Legend |
03409f67932eecc7dff926f199e2c962a793cf50 | 3,052 | inl | C++ | include/eagine/memory/alloc_arena.inl | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | 1 | 2022-01-25T10:31:51.000Z | 2022-01-25T10:31:51.000Z | include/eagine/memory/alloc_arena.inl | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | include/eagine/memory/alloc_arena.inl | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | /// @file
///
/// Copyright Matus Chochlik.
/// 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 <eagine/assert.hpp>
#include <cstdlib>
namespace eagine::memory {
//------------------------------------------------------------------------------
template <typename Alloc>
inline auto basic_allocation_arena<Alloc>::_do_allocate(
const span_size_t size,
const span_size_t align) -> block {
owned_block b = _alloc.allocate(size, align);
if(b.empty()) {
return {};
}
EAGINE_ASSERT(is_aligned_to(b.addr(), align));
EAGINE_ASSERT(b.size() >= size);
_blks.push_back(std::move(b));
_alns.push_back(align);
return _blks.back();
}
//------------------------------------------------------------------------------
template <typename Alloc>
inline void basic_allocation_arena<Alloc>::clear() {
EAGINE_ASSERT(_blks.size() == _alns.size());
for(std_size_t i = 0; i < _blks.size(); ++i) {
_alloc.deallocate(std::move(_blks[i]), _alns[i]);
}
_blks.clear();
_alns.clear();
}
//------------------------------------------------------------------------------
template <typename Alloc>
template <typename T>
inline auto basic_allocation_arena<Alloc>::_allocate(
const span_size_t count,
const span_size_t align) -> block {
return _do_allocate(
span_size_of<T>(count), std::max(align, span_align_of<T>()));
}
//------------------------------------------------------------------------------
template <typename Alloc>
template <typename T>
inline auto basic_allocation_arena<Alloc>::_make_n(
const span_size_t count,
const span_size_t align) -> T* {
return new(_allocate<T>(count, align).data()) T[std_size(count)]{};
}
//------------------------------------------------------------------------------
template <typename Alloc>
template <typename T, typename... Args>
inline auto basic_allocation_arena<Alloc>::_make_1(
const span_size_t align,
Args&&... a) -> T* {
return new(_allocate<T>(1, align).data()) T(std::forward<Args>(a)...);
}
//------------------------------------------------------------------------------
template <typename Alloc>
template <typename T>
inline auto basic_allocation_arena<Alloc>::make_aligned_array(
const span_size_t count,
const span_size_t align) -> span<T> {
if(count < 1) {
return {};
}
T* p = _make_n<T>(count, align);
if(!p) {
throw std::bad_alloc();
}
return {p, count};
}
//------------------------------------------------------------------------------
template <typename Alloc>
template <typename T, typename... Args>
inline auto basic_allocation_arena<Alloc>::make_aligned(
const span_size_t align,
Args&&... args) -> T& {
T* p = _make_1<T>(align, std::forward<Args>(args)...);
if(!p) {
throw std::bad_alloc();
}
return *p;
}
//------------------------------------------------------------------------------
} // namespace eagine::memory
| 31.142857 | 80 | 0.524574 | matus-chochlik |
034422cdc98a49c025a3585cef8bfe146bc259bf | 1,383 | cpp | C++ | source/Cell.cpp | LgHS/GameOfLife-3DS-ClubMatrix | f3c73be09cb9ebeda7334679aa3b83df7dbb428e | [
"MIT"
] | null | null | null | source/Cell.cpp | LgHS/GameOfLife-3DS-ClubMatrix | f3c73be09cb9ebeda7334679aa3b83df7dbb428e | [
"MIT"
] | null | null | null | source/Cell.cpp | LgHS/GameOfLife-3DS-ClubMatrix | f3c73be09cb9ebeda7334679aa3b83df7dbb428e | [
"MIT"
] | null | null | null | #include <3ds.h>
#include <stdio.h>
#include <string.h>
#include "Cell.h"
#include <stdlib.h>
Cell::Cell(Vector2* position, int isAlive, Vector2* worldSize)
{
this->IsAlive = isAlive;
this->Position = position;
this->newState = IsAlive;
this->worldSize = worldSize;
memset(neighbours, 0, (8 * sizeof(Cell*)));
}
void Cell::AddNeighbourgs(Cell* cell)
{
neighbours[currentNeighbors] = cell;
currentNeighbors++;
}
void Cell::ComputeState()
{
// Compute alive cells
int aliveCellCount = 0;
for (int x = 0; x < currentNeighbors; x++)
if (neighbours[x]->IsAlive)
aliveCellCount++;
// Apply Conways lay
if(this->IsAlive)
{
if (aliveCellCount < 2) newState = 0;
else if (aliveCellCount <= 3) newState = 1;
else newState = 0;
}
else if (aliveCellCount == 3) newState = 1;
}
Vector2* Cell::AdjustCoordonates(Vector2* vector)
{
if (vector->X >= worldSize->X) vector->X = 0;
else if (vector->X < 0) vector->X = worldSize->X - 1;
if (vector->Y >= worldSize->Y) vector->Y = 0;
else if (vector->Y < 0) vector->Y = worldSize->Y - 1;
return vector;
}
void Cell::SetNewstate(int state)
{
this->IsAlive = state;
this->newState = state;
}
void Cell::ApplyNewState()
{
this->IsAlive = this->newState;
} | 23.440678 | 63 | 0.587852 | LgHS |
0345f5a370de078b505293ad5169e5656305f4cf | 2,378 | cpp | C++ | modules/ti.UI/url/URLUtils.cpp | Gussy/titanium_desktop | 37dbaab5664e595115e2fcdc348ed125cd50b48d | [
"Apache-2.0"
] | 3 | 2020-01-31T03:40:26.000Z | 2022-02-06T12:20:52.000Z | modules/ti.UI/url/URLUtils.cpp | appcelerator-archive/titanium_desktop | 37dbaab5664e595115e2fcdc348ed125cd50b48d | [
"Apache-2.0"
] | null | null | null | modules/ti.UI/url/URLUtils.cpp | appcelerator-archive/titanium_desktop | 37dbaab5664e595115e2fcdc348ed125cd50b48d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2008-2010 Appcelerator, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "URLUtils.h"
#include <kroll/kroll.h>
#include <Poco/Environment.h>
#include <Poco/URI.h>
using namespace Poco;
using namespace std;
namespace Titanium {
void NormalizeURLCallback(const char* url, char* buffer, int bufferLength)
{
strncpy(buffer, url, bufferLength);
buffer[bufferLength - 1] = '\0';
string urlString = url;
string normalized = URLUtils::NormalizeURL(urlString);
if (normalized != urlString)
{
strncpy(buffer, normalized.c_str(), bufferLength);
buffer[bufferLength - 1] = '\0';
}
}
void URLToFileURLCallback(const char* url, char* buffer, int bufferLength)
{
strncpy(buffer, url, bufferLength);
buffer[bufferLength - 1] = '\0';
try
{
string newURL = url;
string path = URLUtils::URLToPath(newURL);
if (path != newURL)
newURL = URLUtils::PathToFileURL(path);
strncpy(buffer, newURL.c_str(), bufferLength);
buffer[bufferLength - 1] = '\0';
}
catch (ValueException& e)
{
SharedString ss = e.DisplayString();
kroll::Logger* log = kroll::Logger::Get("UI.URL");
log->Error("Could not convert %s to a path: %s", url, ss->c_str());
}
catch (...)
{
kroll::Logger* log = kroll::Logger::Get("UI.URL");
log->Error("Could not convert %s to a path", url);
}
}
void ProxyForURLCallback(const char* url, char* buffer, int bufferLength)
{
buffer[bufferLength - 1] = '\0';
std::string urlString(url);
SharedProxy proxy(ProxyConfig::GetProxyForURL(urlString));
if (proxy.isNull())
strncpy(buffer, "direct://", bufferLength);
else
strncpy(buffer, proxy->ToString().c_str(), bufferLength);
}
} // namespace Titanium
| 28.650602 | 75 | 0.654331 | Gussy |
034a73e43802c08ce8cdb045177e3d679765d325 | 302 | hpp | C++ | sources/CastlesStrategy/Server/Managers/Manager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | sources/CastlesStrategy/Server/Managers/Manager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | sources/CastlesStrategy/Server/Managers/Manager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | #pragma once
namespace CastlesStrategy
{
class ManagersHub;
class Manager
{
public:
explicit Manager (ManagersHub *managersHub);
virtual ~Manager ();
ManagersHub * GetManagersHub () const;
virtual void HandleUpdate (float timeStep) = 0;
private:
ManagersHub *managersHub_;
};
}
| 15.1 | 51 | 0.715232 | KonstantinTomashevich |
034ac56e05fcf45cc11692058e406937fb7ca319 | 6,513 | cpp | C++ | xfa/fwl/core/ifwl_tooltip.cpp | isabella232/pdfium-1 | d8f710cedd62c1d28beee15d7dc3d31ddd148437 | [
"BSD-3-Clause"
] | 38 | 2015-11-25T02:25:25.000Z | 2022-01-04T01:11:15.000Z | xfa/fwl/core/ifwl_tooltip.cpp | isabella232/pdfium-1 | d8f710cedd62c1d28beee15d7dc3d31ddd148437 | [
"BSD-3-Clause"
] | 1 | 2021-02-23T22:36:54.000Z | 2021-02-23T22:36:54.000Z | xfa/fwl/core/ifwl_tooltip.cpp | isabella232/pdfium-1 | d8f710cedd62c1d28beee15d7dc3d31ddd148437 | [
"BSD-3-Clause"
] | 13 | 2016-08-03T02:35:18.000Z | 2020-12-17T10:14:04.000Z | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fwl/core/ifwl_tooltip.h"
#include "third_party/base/ptr_util.h"
#include "xfa/fde/tto/fde_textout.h"
#include "xfa/fwl/core/cfwl_themebackground.h"
#include "xfa/fwl/core/cfwl_themepart.h"
#include "xfa/fwl/core/cfwl_themetext.h"
#include "xfa/fwl/core/fwl_noteimp.h"
#include "xfa/fwl/core/ifwl_themeprovider.h"
#include "xfa/fwl/core/ifwl_tooltip.h"
#include "xfa/fwl/theme/cfwl_widgettp.h"
IFWL_ToolTip::IFWL_ToolTip(const IFWL_App* app,
std::unique_ptr<CFWL_WidgetProperties> properties,
IFWL_Widget* pOuter)
: IFWL_Form(app, std::move(properties), pOuter),
m_dwTTOStyles(FDE_TTOSTYLE_SingleLine),
m_iTTOAlign(FDE_TTOALIGNMENT_Center),
m_pTimerInfoShow(nullptr),
m_pTimerInfoHide(nullptr),
m_TimerShow(this),
m_TimerHide(this) {
m_rtClient.Set(0, 0, 0, 0);
m_rtCaption.Set(0, 0, 0, 0);
m_rtAnchor.Set(0, 0, 0, 0);
m_pProperties->m_dwStyles &= ~FWL_WGTSTYLE_Child;
m_pProperties->m_dwStyles |= FWL_WGTSTYLE_Popup;
}
IFWL_ToolTip::~IFWL_ToolTip() {}
FWL_Type IFWL_ToolTip::GetClassID() const {
return FWL_Type::ToolTip;
}
void IFWL_ToolTip::GetWidgetRect(CFX_RectF& rect, bool bAutoSize) {
if (!bAutoSize) {
rect = m_pProperties->m_rtWidget;
return;
}
rect.Set(0, 0, 0, 0);
if (!m_pProperties->m_pThemeProvider)
m_pProperties->m_pThemeProvider = GetAvailableTheme();
CFX_WideString wsCaption;
if (m_pProperties->m_pDataProvider)
m_pProperties->m_pDataProvider->GetCaption(this, wsCaption);
int32_t iLen = wsCaption.GetLength();
if (iLen > 0) {
CFX_SizeF sz = CalcTextSize(wsCaption, m_pProperties->m_pThemeProvider);
rect.Set(0, 0, sz.x, sz.y);
rect.width += 25;
rect.height += 16;
}
IFWL_Widget::GetWidgetRect(rect, true);
}
void IFWL_ToolTip::Update() {
if (IsLocked())
return;
if (!m_pProperties->m_pThemeProvider)
m_pProperties->m_pThemeProvider = GetAvailableTheme();
UpdateTextOutStyles();
GetClientRect(m_rtClient);
m_rtCaption = m_rtClient;
}
void IFWL_ToolTip::GetClientRect(CFX_RectF& rect) {
FX_FLOAT x = 0;
FX_FLOAT y = 0;
FX_FLOAT t = 0;
IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider;
if (pTheme) {
CFWL_ThemePart part;
part.m_pWidget = this;
x = *static_cast<FX_FLOAT*>(
pTheme->GetCapacity(&part, CFWL_WidgetCapacity::CXBorder));
y = *static_cast<FX_FLOAT*>(
pTheme->GetCapacity(&part, CFWL_WidgetCapacity::CYBorder));
}
rect = m_pProperties->m_rtWidget;
rect.Offset(-rect.left, -rect.top);
rect.Deflate(x, t, x, y);
}
void IFWL_ToolTip::DrawWidget(CFX_Graphics* pGraphics,
const CFX_Matrix* pMatrix) {
if (!pGraphics || !m_pProperties->m_pThemeProvider)
return;
IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider;
DrawBkground(pGraphics, pTheme, pMatrix);
DrawText(pGraphics, pTheme, pMatrix);
}
void IFWL_ToolTip::DrawBkground(CFX_Graphics* pGraphics,
IFWL_ThemeProvider* pTheme,
const CFX_Matrix* pMatrix) {
CFWL_ThemeBackground param;
param.m_pWidget = this;
param.m_iPart = CFWL_Part::Background;
param.m_dwStates = m_pProperties->m_dwStates;
param.m_pGraphics = pGraphics;
if (pMatrix)
param.m_matrix.Concat(*pMatrix);
param.m_rtPart = m_rtClient;
if (m_pProperties->m_dwStates & FWL_WGTSTATE_Focused)
param.m_pData = &m_rtCaption;
pTheme->DrawBackground(¶m);
}
void IFWL_ToolTip::DrawText(CFX_Graphics* pGraphics,
IFWL_ThemeProvider* pTheme,
const CFX_Matrix* pMatrix) {
if (!m_pProperties->m_pDataProvider)
return;
CFX_WideString wsCaption;
m_pProperties->m_pDataProvider->GetCaption(this, wsCaption);
if (wsCaption.IsEmpty())
return;
CFWL_ThemeText param;
param.m_pWidget = this;
param.m_iPart = CFWL_Part::Caption;
param.m_dwStates = m_pProperties->m_dwStates;
param.m_pGraphics = pGraphics;
if (pMatrix)
param.m_matrix.Concat(*pMatrix);
param.m_rtPart = m_rtCaption;
param.m_wsText = wsCaption;
param.m_dwTTOStyles = m_dwTTOStyles;
param.m_iTTOAlign = m_iTTOAlign;
pTheme->DrawText(¶m);
}
void IFWL_ToolTip::UpdateTextOutStyles() {
m_iTTOAlign = FDE_TTOALIGNMENT_Center;
m_dwTTOStyles = FDE_TTOSTYLE_SingleLine;
if (m_pProperties->m_dwStyleExes & FWL_WGTSTYLE_RTLReading)
m_dwTTOStyles |= FDE_TTOSTYLE_RTL;
if (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_Multiline)
m_dwTTOStyles &= ~FDE_TTOSTYLE_SingleLine;
}
void IFWL_ToolTip::RefreshToolTipPos() {
if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_NoAnchor) == 0) {
CFX_RectF rtPopup;
CFX_RectF rtWidget(m_pProperties->m_rtWidget);
CFX_RectF rtAnchor(m_rtAnchor);
rtPopup.Set(0, 0, 0, 0);
FX_FLOAT fx = rtAnchor.Center().x + 20;
FX_FLOAT fy = rtAnchor.Center().y + 20;
rtPopup.Set(fx, fy, rtWidget.Width(), rtWidget.Height());
if (rtPopup.bottom() > 0.0f)
rtPopup.Offset(0, 0.0f - rtPopup.bottom());
if (rtPopup.right() > 0.0f)
rtPopup.Offset(0.0f - rtPopup.right(), 0);
if (rtPopup.left < 0)
rtPopup.Offset(0 - rtPopup.left, 0);
if (rtPopup.top < 0)
rtPopup.Offset(0, 0 - rtPopup.top);
SetWidgetRect(rtPopup);
Update();
}
}
void IFWL_ToolTip::OnDrawWidget(CFX_Graphics* pGraphics,
const CFX_Matrix* pMatrix) {
DrawWidget(pGraphics, pMatrix);
}
IFWL_ToolTip::Timer::Timer(IFWL_ToolTip* pToolTip) : IFWL_Timer(pToolTip) {}
void IFWL_ToolTip::Timer::Run(IFWL_TimerInfo* pTimerInfo) {
IFWL_ToolTip* pToolTip = static_cast<IFWL_ToolTip*>(m_pWidget);
if (pToolTip->m_pTimerInfoShow == pTimerInfo && pToolTip->m_pTimerInfoShow) {
if (pToolTip->GetStates() & FWL_WGTSTATE_Invisible) {
pToolTip->SetStates(FWL_WGTSTATE_Invisible, false);
pToolTip->RefreshToolTipPos();
pToolTip->m_pTimerInfoShow->StopTimer();
pToolTip->m_pTimerInfoShow = nullptr;
return;
}
}
if (pToolTip->m_pTimerInfoHide == pTimerInfo && pToolTip->m_pTimerInfoHide) {
pToolTip->SetStates(FWL_WGTSTATE_Invisible, true);
pToolTip->m_pTimerInfoHide->StopTimer();
pToolTip->m_pTimerInfoHide = nullptr;
}
}
| 31.926471 | 80 | 0.698142 | isabella232 |
034ae43994310df4301f805397fb442d10c7f6ff | 12,728 | cpp | C++ | Homework/boilerplate/main.cpp | lflame/Router-Lab | 58cbcf72fd8e86babbdb3abbe03b4eb23826b79b | [
"Linux-OpenIB"
] | 1 | 2021-09-13T02:38:19.000Z | 2021-09-13T02:38:19.000Z | Homework/boilerplate/main.cpp | lflame/Router-Lab | 58cbcf72fd8e86babbdb3abbe03b4eb23826b79b | [
"Linux-OpenIB"
] | null | null | null | Homework/boilerplate/main.cpp | lflame/Router-Lab | 58cbcf72fd8e86babbdb3abbe03b4eb23826b79b | [
"Linux-OpenIB"
] | 1 | 2021-05-22T08:09:28.000Z | 2021-05-22T08:09:28.000Z | #include "router_hal.h"
#include "rip.h"
#include "router.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <vector>
#define RIP_MAX_ENTRY 25
#define TICKS_PER_SEC 1000
#define TIMEOUT 60
// TODO 暂定为 60s 超时
// 注意1s有1000个TICKS
extern bool validateIPChecksum(uint8_t *packet, size_t len);
extern bool update(RoutingTableEntry entry);
extern bool query(uint32_t addr, uint32_t *nexthop, uint32_t *if_index);
extern bool forward(uint8_t *packet, size_t len);
extern bool disassemble(const uint8_t *packet, uint32_t len, RipPacket *output);
extern uint32_t assemble(const RipPacket *rip, uint8_t *buffer);
extern uint32_t getFourByte(uint8_t *packet);
extern void putFourByte(uint8_t *packet, uint32_t num);
extern uint32_t convertBigSmallEndian32(uint32_t num);
extern uint16_t calcIPChecksum(uint8_t *packet, size_t len);
extern uint16_t calcUDPChecksum(uint8_t *packet, size_t len, in_addr_t srcAddr, in_addr_t dstAddr);
extern uint32_t getMaskFromLen(uint32_t len);
extern uint32_t getLenFromMask(uint32_t mask);
extern bool isInSameNetworkSegment(in_addr_t addr1, in_addr_t addr2, uint32_t len);
extern std::vector<RoutingTableEntry> table;
extern void printAddr(const in_addr_t &addr, FILE *file);
extern void printRouteEntry(const RoutingTableEntry &entry, FILE *file);
extern void printRouteTable(uint64_t time, FILE *file);
bool DEBUG = false; // 是否输出调试信息(总开关),不能关闭路由表打印
uint8_t packet[2048];
uint8_t output[2048];
uint16_t ipTag; // ip头中的16位标识
// 0: 10.0.0.1
// 1: 10.0.1.1
// 2: 10.0.2.1
// 3: 10.0.3.1
// 你可以按需进行修改,注意端序
// in_addr_t addrs[N_IFACE_ON_BOARD] = {0x0100000a, 0x0101000a, 0x0102000a, 0x0103000a};
// TODO: 记得更改正确的 IP 地址,以及对应的接口名称(在standard.h中修改)
// 0: 192.168.3.2
// 1: 192.168.4.1
// 2: 10.0.2.1
// 3: 10.0.3.1
in_addr_t addrs[N_IFACE_ON_BOARD] = {0x0101A8C0, 0x0103A8C0, 0x0102A8C0};
const in_addr_t multicastAddr = 0x090000E0; // ripv2 的组播地址 224.0.0.9
macaddr_t multicastMac;
void sendRipPacketByHAL(const uint32_t &if_index, const RipPacket &rip, in_addr_t dstAddr, macaddr_t dstMac) {
// 将 rip 封装 UDP 和 IP 头,并从索引为 if_index 的网络接口发送出去,发送的目的 ip 地址为dstAddr。注意 rip 报文封装之后长度不会超过以太网的 MTU
// assemble
// 为了获得 rip_len, 先填入 rip 部分:
uint32_t rip_len = assemble(&rip, &output[20 + 8]);
in_addr_t srcAddr = addrs[if_index];
// IP
++ipTag;
output[0] = 0x45;
output[1] = 0xC0; // 此处设置为同抓包得到的相同,表示网间控制的一般服务
output[2] = ((rip_len + 20 + 8) >> 8) & 0xFF;
output[3] = (rip_len + 20 + 8) & 0xFF;
output[4] = (ipTag >> 8) & 0xFF; // IP 长度
output[5] = ipTag & 0xFF;
output[6] = 0x00; // 不用考虑分片
output[7] = 0x00;
output[8] = 0x01; // TTL为1,因为只向邻居发送rip报文
output[9] = 0x11; // 表示携带UDP协议
output[10] = 0x00;
output[11] = 0x00; // 头部校验和留至填充头部完毕之后计算
putFourByte(output + 12, srcAddr);
putFourByte(output + 16, dstAddr);
uint16_t cksum = calcIPChecksum(output, rip_len + 20 + 8); // IP 头部校验和
output[10] = (cksum >> 8) & 0xFF;
output[11] = cksum & 0xFF;
// UDP
// port = 520
output[20] = 0x02;
output[21] = 0x08; // 源端口为 520
output[22] = 0x02;
output[23] = 0x08; // 目的端口为 520
output[24] = ((rip_len + 8) >> 8) & 0xFF;
output[25] = (rip_len + 8) & 0xFF; // UDP长度
output[26] = 0x00;
output[27] = 0x00; // 待会计算校验和
cksum = calcUDPChecksum(output + 20, rip_len + 8, srcAddr, dstAddr);
output[26] = (cksum >> 8) & 0xFF;
output[27] = cksum & 0xFF;
// RIP 在上面已经填过了
// checksum calculation for ip and udp
// if you don't want to calculate udp checksum, set it to zero
// send it back
HAL_SendIPPacket(if_index, output, rip_len + 20 + 8, dstMac);
}
void sendRipUpdate(const RipPacket &upd) {
// 向各个网口发送 rip 更新报文,更新报文从 upd 计算得到
// 注意计算时滤掉 addr 与出接口在同一网段的,并且对于
// nexthop 与出接口在同一网段的,发送的 metric 设为 16(毒逆)
// NOTE: 这样的毒逆默认了路由器不会在同一接口上进行转发
// 也就是说默认同一网段可互达
if (DEBUG) printf("sendRipUpdate\n");
RipPacket resp;
for (int i = 0; i < N_IFACE_ON_BOARD; ++i) {
macaddr_t mac;
resp.numEntries = 0;
resp.command = 2;
for (int j = 0; j < upd.numEntries; ++j) {
// 毒性逆转
uint32_t len = getLenFromMask(convertBigSmallEndian32(upd.entries[j].mask));
if (!isInSameNetworkSegment(upd.entries[j].addr, addrs[i], len)) {
uint32_t id = resp.numEntries++;
resp.entries[id] = upd.entries[j];
// if (isInSameNetworkSegment(table[resp.entries[id].localTableInd].nexthop, addrs[i], len)) {
if (i == table[resp.entries[id].localTableInd].if_index) {
resp.entries[id].metric = convertBigSmallEndian32(16);
}
}
}
if (resp.numEntries) {
sendRipPacketByHAL(i, resp, multicastAddr, multicastMac);
}
}
}
void sendRipRequest() {
// 向各网口发送 rip 请求报文
RipPacket rip;
rip.numEntries = 1;
rip.command = 1;
rip.entries[0].addr = 0;
rip.entries[0].mask = 0;
rip.entries[0].nexthop = 0;
rip.entries[0].metric = convertBigSmallEndian32(16);
for (int i = 0; i < RIP_MAX_ENTRY; ++i) {
sendRipPacketByHAL(i, rip, multicastAddr, multicastMac);
}
}
int main(int argc, char *argv[]) {
freopen("nul", "w", stdout); // 用于不输出琐碎的信息
// freopen("nul", "w", stderr); // 用于不输出关键的信息
srand(time(NULL));
ipTag = (uint32_t)rand();
int res = HAL_Init(DEBUG, addrs);
int messageId = 0; // for debug
if (res < 0) {
return res;
}
HAL_ArpGetMacAddress(0, multicastAddr, multicastMac); // 组播 ip 对应的组播 mac 地址,一定存在
// Add direct routes
// For example:
// 10.0.0.0/24 if 0
// 10.0.1.0/24 if 1
// 10.0.2.0/24 if 2
// 10.0.3.0/24 if 3
for (uint32_t i = 0; i < N_IFACE_ON_BOARD;i++) {
RoutingTableEntry entry = {
.addr = addrs[i], // big endian
.len = 24, // small endian
.if_index = i, // small endian
.metric = 0, // small endian
.timestamp = 0, // small endian 直连网络不需要timestamp
.nexthop = 0 // big endian, means direct
};
update(entry);
}
// 加入时向各网口发出请求报文
sendRipRequest();
uint64_t last_time = 0;
int updCnt = 0; // 每计6次(5*6 = 30s)进行一次更新
bool first_send = false;
while (1) {
uint64_t time = HAL_GetTicks();
if (!first_send || time > last_time + 5 * TICKS_PER_SEC) {
// 例行更新
// 发出响应报文之前记得确认timestamp
if (!first_send || ++updCnt == 1) {
fprintf(stderr, "Timer Fired: Send update\n");
first_send = true;
updCnt = 0;
RipPacket upd;
upd.command = 2;
upd.numEntries = 0;
for (int i = 0; i < table.size(); ++i) {
uint32_t id = upd.numEntries++;
upd.entries[id].addr = table[i].addr;
upd.entries[id].mask = convertBigSmallEndian32(getMaskFromLen(table[i].len));
upd.entries[id].nexthop = 0;
upd.entries[id].metric = convertBigSmallEndian32(table[i].metric);
upd.entries[id].localTableInd = i;
if (table[i].nexthop != 0 && (double)(time - table[i].timestamp) / TICKS_PER_SEC > TIMEOUT) {
// 非直连,且路由表项超时,这里采取简单的做法,直接发出报文——一个更好的做法是等待一段时间之后未被更新再发出报文
upd.entries[id].metric = convertBigSmallEndian32(16);
table.erase(table.begin() + i);
}
if (upd.numEntries == RIP_MAX_ENTRY) {
sendRipUpdate(upd);
upd.numEntries = 0;
}
}
if (upd.numEntries) {
sendRipUpdate(upd);
}
}
last_time = time;
printRouteTable(time, stderr);
}
int mask = (1 << N_IFACE_ON_BOARD) - 1;
macaddr_t srcMac;
macaddr_t dstMac;
int if_index;
res = HAL_ReceiveIPPacket(mask, packet, sizeof(packet), srcMac,
dstMac, 1000, &if_index);
if (res == HAL_ERR_EOF) {
break;
} else if (res < 0) {
return res;
} else if (res == 0) {
// Timeout
continue;
} else if (res > sizeof(packet)) {
// packet is truncated, ignore it
continue;
}
++messageId;
if (DEBUG) printf("%d:: Valid Message. res: %d\n", messageId, res);
if (!validateIPChecksum(packet, res)) {
if (DEBUG) printf("%d:: Invalid IP Checksum\n", messageId);
continue;
}
in_addr_t srcAddr, dstAddr;
// extract srcAddr and dstAddr from packet
// big endian
srcAddr = getFourByte(packet + 12);
dstAddr = getFourByte(packet + 16);
bool dst_is_me = false;
for (int i = 0; i < N_IFACE_ON_BOARD;i++) {
if (memcmp(&dstAddr, &addrs[i], sizeof(in_addr_t)) == 0) {
dst_is_me = true;
break;
}
}
bool isMulti = (dstAddr == multicastAddr);
if (isMulti || dst_is_me) {
// 224.0.0.9 or me,进行接收处理
if (DEBUG) printf("%d:: Dst is me or multicast.\n", messageId);
RipPacket rip;
if (disassemble(packet, res, &rip)) {
// 为 rip 数据报
if (rip.command == 1) {
// request
// 请求报文必须满足 metric 为 16,注意 metric 为大端序
// 注意若表项数目大于 25,则需要分开发送
if (DEBUG) printf("%d:: Received rip request.\n", messageId);
uint32_t metricSmall = convertBigSmallEndian32(rip.entries[0].metric);
if (metricSmall != 16) continue;
RipPacket resp;
// 封装响应报文,注意选择路由条目
resp.command = 2; // response
resp.numEntries = 0;
for (int j = 0; j < table.size(); ++j) {
if (!isInSameNetworkSegment(table[j].addr, srcAddr, table[j].len)) {
// 与来源ip的网段不同
uint32_t id = resp.numEntries++;
resp.entries[id].addr = table[j].addr;
resp.entries[id].mask = convertBigSmallEndian32(getMaskFromLen(table[j].len));
resp.entries[id].nexthop = 0;
resp.entries[id].metric = convertBigSmallEndian32(table[j].metric);
if (isInSameNetworkSegment(table[j].nexthop, addrs[if_index], table[j].len)) {
// 毒性逆转
resp.entries[id].metric = convertBigSmallEndian32(16);
}
if (resp.numEntries == RIP_MAX_ENTRY) {
// 满 25 条,进行一次发送
sendRipPacketByHAL(if_index, resp, srcAddr, srcMac);
resp.numEntries = 0;
}
}
}
if (resp.numEntries) {
sendRipPacketByHAL(if_index, resp, srcAddr, srcMac);
}
} else {
// response
if (DEBUG) printf("%d:: Received rip response.\n", messageId);
RipPacket upd;
upd.numEntries = 0;
upd.command = 2;
for (int i = 0; i < rip.numEntries; ++i) {
RoutingTableEntry entry;
entry.addr = rip.entries[i].addr;
entry.len = getLenFromMask(convertBigSmallEndian32(rip.entries[i].mask));
entry.if_index = if_index;
entry.metric = convertBigSmallEndian32(rip.entries[i].metric);
entry.timestamp = HAL_GetTicks();
entry.nexthop = srcAddr;
bool suc = update(entry);
if (suc) {
// 若更新路由表成功,触发更新
printf("%d:: Update router successfully.", messageId);
printRouteEntry(entry, stdout);
uint32_t id = upd.numEntries++;
upd.entries[id] = rip.entries[i];
upd.entries[id].nexthop = 0;
upd.entries[id].metric = convertBigSmallEndian32(entry.metric);
upd.entries[id].localTableInd = i;
}
}
if (upd.numEntries) {
sendRipUpdate(upd);
}
}
} else {
// Target is me but not rip.
}
} else {
// forward
// beware of endianness
if (DEBUG) printf("%d:: Forward.\n", messageId);
uint32_t nexthop, dest_if;
if (query(dstAddr, &nexthop, &dest_if)) {
// found
macaddr_t dest_mac;
// direct routing
if (nexthop == 0) {
nexthop = dstAddr;
}
if (HAL_ArpGetMacAddress(dest_if, nexthop, dest_mac) == 0) {
// found
// update ttl and checksum
forward(packet, res);
// check ttl!=0
if (packet[8] != 0) {
HAL_SendIPPacket(dest_if, packet, res, dest_mac);
if (DEBUG) printf("%d:: Forward successfully. dest_if: %d Nexthop:", messageId, dest_if);
if (DEBUG) printAddr(nexthop, stdout);
if (DEBUG) printf("\n");
} else {
// ttl == 0
if (DEBUG) printf("%d:: TTL is 0.\n", messageId);
}
} else {
// not found
if (DEBUG) printf("%d:: Failed to get mac address. dest_if: %d Nexthop:", messageId, dest_if);
if (DEBUG) printAddr(nexthop, stdout);
if (DEBUG) printf("\n");
}
} else {
// not found
if (DEBUG) printf("%d:: No matching item in table.\n", messageId);
}
}
}
return 0;
}
| 34.032086 | 110 | 0.594987 | lflame |
034d3551c0d88596c40765d5a675830546e30a42 | 6,421 | cpp | C++ | source/thewizardplusplus/anna/sound/OpenALSource.cpp | thewizardplusplus/anna-sound | 317cb26b9d968e2813a45cc7579b0dbe3451c282 | [
"MIT"
] | null | null | null | source/thewizardplusplus/anna/sound/OpenALSource.cpp | thewizardplusplus/anna-sound | 317cb26b9d968e2813a45cc7579b0dbe3451c282 | [
"MIT"
] | null | null | null | source/thewizardplusplus/anna/sound/OpenALSource.cpp | thewizardplusplus/anna-sound | 317cb26b9d968e2813a45cc7579b0dbe3451c282 | [
"MIT"
] | null | null | null | #include "OpenALSource.h"
#include "OpenALAudioDevice.h"
#include <AL/al.h>
#include <cfloat>
using namespace thewizardplusplus::anna::sound;
using namespace thewizardplusplus::anna::maths;
OpenALSource::OpenALSource(OpenALAudioDevice* audio_device, unsigned int
openal_source)
:
audio_device(audio_device),
openal_source(openal_source),
cone_inner_angle(360.0f),
cone_outer_angle(360.0f),
gain(1.0f),
cone_outer_gain(0.0f),
minimal_gain(0.0f),
maximal_gain(1.0f),
reference_distance(1.0f),
rolloff_factor(1.0f),
maximal_distance(FLT_MAX),
pitch(1.0f),
looping(false)
{
alGetListener3f(AL_POSITION, &position.x, &position.z, &position.y);
position.y = -position.y;
alGetListener3f(AL_POSITION, &velocity.x, &velocity.z, &velocity.y);
velocity.y = -velocity.y;
alGetListener3f(AL_POSITION, &direction.x, &direction.z, &direction.y);
direction.y = -direction.y;
alGetSourcef(openal_source, AL_CONE_INNER_ANGLE, &cone_inner_angle);
alGetSourcef(openal_source, AL_CONE_OUTER_ANGLE, &cone_outer_angle);
alGetSourcef(openal_source, AL_GAIN, &gain);
alGetSourcef(openal_source, AL_CONE_OUTER_GAIN, &cone_outer_gain);
alGetSourcef(openal_source, AL_MIN_GAIN, &minimal_gain);
alGetSourcef(openal_source, AL_MAX_GAIN, &maximal_gain);
alGetSourcef(openal_source, AL_REFERENCE_DISTANCE, &reference_distance);
alGetSourcef(openal_source, AL_ROLLOFF_FACTOR, &rolloff_factor);
alGetSourcef(openal_source, AL_MAX_DISTANCE, &maximal_distance);
alGetSourcef(openal_source, AL_PITCH, &pitch);
int looping = 0;
alGetSourcei(openal_source, AL_LOOPING, &looping);
this->looping = looping;
}
OpenALSource::~OpenALSource(void) {
alDeleteSources(1, &openal_source);
}
Vector3D<float> OpenALSource::getPosition(void) const {
return position;
}
void OpenALSource::setPosition(const maths::Vector3D<float>& position) {
this->position = position;
alSource3f(openal_source, AL_POSITION, position.x, position.z, -position.y);
}
Vector3D<float> OpenALSource::getVelocity(void) const {
return velocity;
}
void OpenALSource::setVelocity(const maths::Vector3D<float>& velocity) {
this->velocity = velocity;
alSource3f(openal_source, AL_VELOCITY, velocity.x, velocity.z, -velocity.y);
}
Vector3D<float> OpenALSource::getDirection(void) const {
return direction;
}
void OpenALSource::setDirection(const maths::Vector3D<float>& direction) {
this->direction = direction;
alSource3f(openal_source, AL_DIRECTION, direction.x, direction.z,
-direction.y);
}
float OpenALSource::getConeInnerAngle(void) const {
return cone_inner_angle;
}
void OpenALSource::setConeInnerAngle(float angle_in_degrees) {
cone_inner_angle = angle_in_degrees;
alSourcef(openal_source, AL_CONE_INNER_ANGLE, angle_in_degrees);
}
float OpenALSource::getConeOuterAngle(void) const {
return cone_outer_angle;
}
void OpenALSource::setConeOuterAngle(float angle_in_degrees) {
cone_outer_angle = angle_in_degrees;
alSourcef(openal_source, AL_CONE_OUTER_ANGLE, angle_in_degrees);
}
float OpenALSource::getGain(void) const {
return gain;
}
void OpenALSource::setGain(float gain) {
this->gain = gain;
alSourcei(openal_source, AL_GAIN, gain);
}
float OpenALSource::getConeOuterGain(void) const {
return cone_outer_gain;
}
void OpenALSource::setConeOuterGain(float gain) {
cone_outer_gain = gain;
alSourcef(openal_source, AL_CONE_OUTER_GAIN, gain);
}
float OpenALSource::getMinimalGain(void) const {
return minimal_gain;
}
void OpenALSource::setMinimalGain(float minimal_gain) {
this->minimal_gain = minimal_gain;
alSourcef(openal_source, AL_MIN_GAIN, minimal_gain);
}
float OpenALSource::getMaximalGain(void) const {
return maximal_gain;
}
void OpenALSource::setMaximalGain(float maximal_gain) {
this->maximal_gain = maximal_gain;
alSourcef(openal_source, AL_MAX_GAIN, maximal_gain);
}
float OpenALSource::getReferenceDistance(void) const {
return reference_distance;
}
void OpenALSource::setReferenceDistance(float reference_distance) {
this->reference_distance = reference_distance;
alSourcef(openal_source, AL_REFERENCE_DISTANCE, reference_distance);
}
float OpenALSource::getRolloffFactor(void) const {
return rolloff_factor;
}
void OpenALSource::setRolloffFactor(float rolloff_factor) {
this->rolloff_factor = rolloff_factor;
alSourcef(openal_source, AL_ROLLOFF_FACTOR, rolloff_factor);
}
float OpenALSource::getMaximalDistance(void) const {
return maximal_distance;
}
void OpenALSource::setMaximalDistance(float maximal_distance) {
this->maximal_distance = maximal_distance;
alSourcef(openal_source, AL_MAX_DISTANCE, maximal_distance);
}
float OpenALSource::getPitch(void) const {
return pitch;
}
void OpenALSource::setPitch(float pitch) {
this->pitch = pitch;
alSourcei(openal_source, AL_PITCH, pitch);
}
bool OpenALSource::getLooping(void) const {
return looping;
}
void OpenALSource::setLooping(bool looping) {
this->looping = looping;
alSourcei(openal_source, AL_LOOPING, looping);
}
SourceState::Types OpenALSource::getState(void) const {
int state = 0;
alGetSourcei(openal_source, AL_SOURCE_STATE, &state);
switch (state) {
case AL_INITIAL:
return SourceState::INITIAL;
case AL_PLAYING:
return SourceState::PLAYING;
case AL_PAUSED:
return SourceState::PAUSED;
case AL_STOPPED:
return SourceState::STOPPED;
default:
return SourceState::UNKNOWN;
}
}
float OpenALSource::getOffset(SourceOffsetUnits::Types units) const {
float offset = 0.0f;
switch (units) {
case SourceOffsetUnits::SECONDS:
alGetSourcef(openal_source, AL_SEC_OFFSET, &offset);
break;
case SourceOffsetUnits::SAMPLES:
alGetSourcef(openal_source, AL_SAMPLE_OFFSET, &offset);
break;
case SourceOffsetUnits::BYTES:
alGetSourcef(openal_source, AL_BYTE_OFFSET, &offset);
break;
}
return offset;
}
void OpenALSource::setOffset(float offset, SourceOffsetUnits::Types units) {
switch (units) {
case SourceOffsetUnits::SECONDS:
alSourcef(openal_source, AL_SEC_OFFSET, offset);
break;
case SourceOffsetUnits::SAMPLES:
alSourcef(openal_source, AL_SAMPLE_OFFSET, offset);
break;
case SourceOffsetUnits::BYTES:
alSourcef(openal_source, AL_BYTE_OFFSET, offset);
break;
}
}
void OpenALSource::play(void) {
alSourcePlay(openal_source);
}
void OpenALSource::pause(void) {
alSourcePause(openal_source);
}
void OpenALSource::stop(void) {
alSourceStop(openal_source);
}
void OpenALSource::rewind(void) {
alSourceRewind(openal_source);
}
| 26.423868 | 77 | 0.781031 | thewizardplusplus |
034fcc273045ccc0e78d1ab866f9407015901004 | 7,244 | cpp | C++ | src/Util/VRMLWriter.cpp | snozawa/choreonoid | 12ab42ccbf287d68216637e55ddae8412771c752 | [
"MIT"
] | null | null | null | src/Util/VRMLWriter.cpp | snozawa/choreonoid | 12ab42ccbf287d68216637e55ddae8412771c752 | [
"MIT"
] | null | null | null | src/Util/VRMLWriter.cpp | snozawa/choreonoid | 12ab42ccbf287d68216637e55ddae8412771c752 | [
"MIT"
] | null | null | null | /*!
@file
@author Shin'ichiro Nakaoka
*/
#include "VRMLWriter.h"
using namespace std;
using namespace boost;
using namespace cnoid;
namespace {
typedef void (VRMLWriter::*VRMLWriterNodeMethod)(VRMLNodePtr node);
typedef std::map<std::string, VRMLWriterNodeMethod> TNodeMethodMap;
typedef std::pair<std::string, VRMLWriterNodeMethod> TNodeMethodPair;
TNodeMethodMap nodeMethodMap;
inline void registerNodeMethod(const std::type_info& t, VRMLWriterNodeMethod method) {
nodeMethodMap.insert(TNodeMethodPair(t.name(), method));
}
VRMLWriterNodeMethod getNodeMethod(VRMLNodePtr node) {
TNodeMethodMap::iterator p = nodeMethodMap.find(typeid(*node).name());
return (p != nodeMethodMap.end()) ? p->second : 0;
}
inline std::ostream& operator<<(std::ostream& out, VRMLWriter::TIndent& indent)
{
return out << indent.spaces;
}
inline const char* boolstr(bool v)
{
if(v){
return "TRUE";
} else {
return "FALSE";
}
}
ostream& operator<<(std::ostream& out, const SFVec2f& v)
{
return out << v[0] << " " << v[1];
}
ostream& operator<<(std::ostream& out, const SFVec3f& v)
{
return out << v[0] << " " << v[1] << " " << v[2];
}
ostream& operator<<(std::ostream& out, const SFColor& v)
{
return out << v[0] << " " << v[1] << " " << v[2];
}
ostream& operator<<(std::ostream& out, const SFRotation& v)
{
const SFRotation::Vector3& a = v.axis();
return out << a[0] << " " << a[1] << " " << a[2] << " " << v.angle();
}
}
template <class MFValues> void VRMLWriter::writeMFValues(MFValues values, int numColumn)
{
out << ++indent << "[\n";
++indent;
out << indent;
int col = 0;
int n = values.size();
for(int i=0; i < n; i++){
out << values[i] << " ";
col++;
if(col == numColumn){
col = 0;
out << "\n";
if(i < n-1){
out << indent;
}
}
}
out << --indent << "]\n";
--indent;
}
void VRMLWriter::writeMFInt32SeparatedByMinusValue(MFInt32& values)
{
out << ++indent << "[\n";
++indent;
out << indent;
int n = values.size();
for(int i=0; i < n; i++){
out << values[i] << " ";
if(values[i] < 0){
out << "\n";
if(i < n-1){
out << indent;
}
}
}
out << --indent << "]\n";
--indent;
}
VRMLWriter::VRMLWriter(std::ostream& out) : out(out)
{
if(nodeMethodMap.empty()){
registerNodeMethodMap();
}
}
void VRMLWriter::registerNodeMethodMap()
{
registerNodeMethod(typeid(VRMLGroup), &VRMLWriter::writeGroupNode);
registerNodeMethod(typeid(VRMLTransform), &VRMLWriter::writeTransformNode);
registerNodeMethod(typeid(VRMLShape), &VRMLWriter::writeShapeNode);
registerNodeMethod(typeid(VRMLIndexedFaceSet), &VRMLWriter::writeIndexedFaceSetNode);
}
void VRMLWriter::writeHeader()
{
out << "#VRML V2.0 utf8\n";
}
bool VRMLWriter::writeNode(VRMLNodePtr node)
{
indent.clear();
out << "\n";
writeNodeIter(node);
return true;
}
void VRMLWriter::writeNodeIter(VRMLNodePtr node)
{
VRMLWriterNodeMethod method = getNodeMethod(node);
if(method){
(this->*method)(node);
}
}
void VRMLWriter::beginNode(const char* nodename, VRMLNodePtr node)
{
out << indent;
if(node->defName.empty()){
out << nodename << " {\n";
} else {
out << "DEF " << node->defName << " " << nodename << " {\n";
}
++indent;
}
void VRMLWriter::endNode()
{
out << --indent << "}\n";
}
void VRMLWriter::writeGroupNode(VRMLNodePtr node)
{
VRMLGroupPtr group = static_pointer_cast<VRMLGroup>(node);
beginNode("Group", group);
writeGroupFields(group);
endNode();
}
void VRMLWriter::writeGroupFields(VRMLGroupPtr group)
{
if(group->bboxSize[0] >= 0){
out << indent << "bboxCenter " << group->bboxCenter << "\n";
out << indent << "bboxSize " << group->bboxSize << "\n";
}
if(!group->children.empty()){
out << indent << "children [\n";
++indent;
for(size_t i=0; i < group->children.size(); i++){
writeNodeIter(group->children[i]);
}
out << --indent << "]\n";
}
}
void VRMLWriter::writeTransformNode(VRMLNodePtr node)
{
VRMLTransformPtr trans = static_pointer_cast<VRMLTransform>(node);
beginNode("Transform", trans);
out << indent << "center " << trans->center << "\n";
out << indent << "rotation " << trans->rotation << "\n";
out << indent << "scale " << trans->scale << "\n";
out << indent << "scaleOrientation " << trans->scaleOrientation << "\n";
out << indent << "translation " << trans->translation << "\n";
writeGroupFields(trans);
endNode();
}
void VRMLWriter::writeShapeNode(VRMLNodePtr node)
{
VRMLShapePtr shape = static_pointer_cast<VRMLShape>(node);
beginNode("Shape", shape);
if(shape->appearance){
out << indent << "appearance\n";
++indent;
writeAppearanceNode(shape->appearance);
--indent;
}
if(shape->geometry){
out << indent << "geometry\n";
VRMLWriterNodeMethod method = getNodeMethod(shape->geometry);
if(method){
++indent;
(this->*method)(shape->geometry);
--indent;
}
}
endNode();
}
void VRMLWriter::writeAppearanceNode(VRMLAppearancePtr appearance)
{
beginNode("Appearance", appearance);
if(appearance->material){
out << indent << "material\n";
++indent;
writeMaterialNode(appearance->material);
--indent;
}
endNode();
}
void VRMLWriter::writeMaterialNode(VRMLMaterialPtr material)
{
beginNode("Material", material);
out << indent << "ambientIntensity " << material->ambientIntensity << "\n";
out << indent << "diffuseColor " << material->diffuseColor << "\n";
out << indent << "emissiveColor " << material->emissiveColor << "\n";
out << indent << "shininess " << material->shininess << "\n";
out << indent << "specularColor " << material->specularColor << "\n";
out << indent << "transparency " << material->transparency << "\n";
endNode();
}
void VRMLWriter::writeIndexedFaceSetNode(VRMLNodePtr node)
{
VRMLIndexedFaceSetPtr faceset = static_pointer_cast<VRMLIndexedFaceSet>(node);
beginNode("IndexedFaceSet", faceset);
if(faceset->coord){
out << indent << "coord\n";
++indent;
writeCoordinateNode(faceset->coord);
--indent;
}
if(!faceset->coordIndex.empty()){
out << indent << "coordIndex\n";
writeMFInt32SeparatedByMinusValue(faceset->coordIndex);
}
out << indent << "ccw " << boolstr(faceset->ccw) << "\n";
out << indent << "convex " << boolstr(faceset->convex) << "\n";
out << indent << "creaseAngle " << faceset->creaseAngle << "\n";
out << indent << "solid " << boolstr(faceset->solid) << "\n";
endNode();
}
void VRMLWriter::writeCoordinateNode(VRMLCoordinatePtr coord)
{
beginNode("Coordinate", coord);
if(!coord->point.empty()){
out << indent << "point\n";
writeMFValues(coord->point, 1);
}
endNode();
}
| 23.367742 | 89 | 0.583793 | snozawa |
0350f1705a77c68a74f42c0d54992730d42b45c3 | 1,580 | hpp | C++ | caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp | gustavla/autocolorizer | 79d4ce1054d35c06bdfcc93236b71e161e082ebb | [
"BSD-3-Clause"
] | 234 | 2016-04-04T15:12:24.000Z | 2022-03-14T12:55:09.000Z | caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp | TrinhQuocNguyen/autocolorize | 79d4ce1054d35c06bdfcc93236b71e161e082ebb | [
"BSD-3-Clause"
] | 20 | 2016-04-05T12:44:04.000Z | 2022-02-22T06:02:17.000Z | caffe/include/caffe/layers/sparse_histogram_extractor_layer.hpp | TrinhQuocNguyen/autocolorize | 79d4ce1054d35c06bdfcc93236b71e161e082ebb | [
"BSD-3-Clause"
] | 71 | 2016-07-12T15:28:16.000Z | 2021-12-16T12:22:57.000Z | #ifndef CAFFE_SPARSE_PATCH_LAYER_HPP
#define CAFFE_SPARSE_PATCH_LAYER_HPP
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
namespace caffe {
/**
* Takes locations and extracts a stack of histograms.
*/
template <typename Dtype>
class SparseHistogramExtractorLayer : public Layer<Dtype> {
public:
explicit SparseHistogramExtractorLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "SparseHistogramExtractor"; }
virtual inline int ExactNumBottomBlobs() const { return 2; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
int num_layers_;
int num_channels_;
int num_locations_;
std::vector<int> sizes_;
// Temporary storage for the summed area table
Blob<Dtype> integral_histogram_;
};
} // namespace caffe
#endif // CAFFE_SPARSE_PATCH_LAYER_HPP
| 29.259259 | 80 | 0.729747 | gustavla |
03568559c8068436b36aa4d72dab560a5e174e05 | 2,939 | cpp | C++ | opcodes.cpp | stavros-avramidis/Assembler | 5c061cfd7c98e1b607f024f30e2545a19d0a70ea | [
"MIT"
] | null | null | null | opcodes.cpp | stavros-avramidis/Assembler | 5c061cfd7c98e1b607f024f30e2545a19d0a70ea | [
"MIT"
] | null | null | null | opcodes.cpp | stavros-avramidis/Assembler | 5c061cfd7c98e1b607f024f30e2545a19d0a70ea | [
"MIT"
] | null | null | null | /* opcodes.cpp
*
* Created by purpl3f0x on 9/12/18.
* Stavros Avramidis
*/
#include "opcodes.hpp"
/*-------------------------------------------*/
/*-------------- OpCodes ---------------*/
unsigned int OpCodes::getBinary(std::string name) const {
for (auto op: *this)
if (op.name==name)
return op.binary;
return 0; // returns NOP
}
unsigned int OpCodes::numOfArgs(std::string name) const {
for (auto op: *this)
if (op.name==name)
return op.numOfArgs;
return 0;
}
std::string OpCodes::getName(unsigned short bin) const {
for (auto op: *this)
if (op.binary==bin)
return op.name;
return "";
}
bool OpCodes::isOpCode(std::string name) const {
for (auto op: *this)
if (op.name==name)
return true;
return false;
}
opCode *OpCodes::find(std::string name) {
for (auto &&op: *this)
if (op.name==name)
return &op;
return nullptr;
}
std::string OpCodes::operator[](int bin) {
return this->getName(bin);
}
int OpCodes::operator[](std::string name) {
return this->getBinary(name);
}
/* Declare opCodes*/
OpCodes opCodes = {
//Basic operations
opCode("NOP", 0b0000000, 0),
opCode("RI", 0b0000001, 0),
opCode("LDA", 0b0000010, 1),
opCode("LDI", 0b0000011, 1),
opCode("STA", 0b0000100, 1),
opCode("JMP", 0b0000101, 1),
opCode("MI", 0b0000110, 2),
opCode("MO", 0b0000111, 2),
//Conditional Jumps
opCode("JC", 0b0001000, 2),
opCode("JO", 0b0001001, 2),
opCode("JG", 0b0001010, 2),
opCode("JGE", 0b0001011, 2),
opCode("JE", 0b0001100, 2),
opCode("JLE", 0b0001101, 2),
opCode("JL", 0b0001110, 2),
opCode("JNO", 0b0001111, 2),
opCode("JZ", 0b0010000, 2),
opCode("JNZ", 0b0010001, 2),
opCode("JS", 0b0010010, 2),
opCode("JNS", 0b0010011, 2),
// ALU
opCode("ADD", 0b1000000, 3),
opCode("SUB", 0b1000001, 3),
opCode("MUL", 0b1000010, 3),
opCode("DIV", 0b1000011, 3),
opCode("ADDI", 0b1000100, 3),
opCode("SUBI", 0b1000101, 3),
opCode("MULI", 0b1000110, 3),
opCode("DIVI", 0b1000111, 3),
//Complex ALU operations
opCode("SQRT", 0b1001000, 2),
opCode("MOD", 0b1001001, 3),
// Bitwise operationns
opCode("AND", 0b1100000, 3),
opCode("OR", 0b11000001, 3),
opCode("NAND", 0b1100010, 3),
opCode("NOR", 0b1100011, 3),
opCode("NOT", 0b1100100, 3),
opCode("XOR", 0b1100101, 3),
opCode("XOR", 0b1100110, 3),
opCode("SHL", 0b1100111, 3),
opCode("SHR", 0b1101000, 3),
opCode("ROT", 0b1101001, 3),
opCode("CMP", 0b1101010, 3),
//FPU
opCode("FADD", 0b1110000, 3),
opCode("FSUB", 0b1110001, 3),
opCode("FMUL", 0b1110010, 3),
opCode("FDIV", 0b1110011, 3),
opCode("FSQRT", 0b1110100, 3),
opCode("ITOF", 0b1110101, 3),
opCode("FTOI", 0b1110111, 3),
opCode("FMOD", 0b1111000, 3),
//HACF -- HALT AND CATCH FIRE
opCode("HLT", 0b1111111, 0),
};
| 22.265152 | 57 | 0.578088 | stavros-avramidis |
03576a32c36935551439518249e7a4f5e922bae5 | 982 | hpp | C++ | src/main/include/Interfaces/IStateSupplier.hpp | Koldar/pathfinding-utils | e1c67bbb9eb0dca9f9f748f2f929310a7ab319f8 | [
"MIT"
] | 2 | 2020-10-04T00:52:20.000Z | 2020-10-19T06:46:04.000Z | src/main/include/Interfaces/IStateSupplier.hpp | Koldar/pathfinding-utils | e1c67bbb9eb0dca9f9f748f2f929310a7ab319f8 | [
"MIT"
] | null | null | null | src/main/include/Interfaces/IStateSupplier.hpp | Koldar/pathfinding-utils | e1c67bbb9eb0dca9f9f748f2f929310a7ab319f8 | [
"MIT"
] | null | null | null | #ifndef _ISTATESUPPLIER_HEADER__
#define _ISTATESUPPLIER_HEADER__
#include "ISearchState.hpp"
#include <cpp-utils/pool.hpp>
#include <cpp-utils/imemory.hpp>
#include <cpp-utils/ICleanable.hpp>
#include <memory>
namespace pathfinding::search {
template <typename STATE, typename... STATE_IMPORTANT_TYPES>
class IStateSupplier;
/**
* @brief a class whose job is to generate a new search state
*
* @tparam STATE the IState implementation we will yield
* @tparam STATE_IMPORTANT_TYPES additional parameters required to generate a state
*/
template <typename STATE, typename... STATE_IMPORTANT_TYPES>
class IStateSupplier: public ICleanable, IMemorable {
public:
/**
* @brief get a search state without providing an id
*
* This will likely to generate a new state almost always
*
* @param args additional information required to generate states
* @return STATE& the new state
*/
virtual STATE& getState(const STATE_IMPORTANT_TYPES&... args) = 0;
};
}
#endif | 26.540541 | 83 | 0.758656 | Koldar |
035d9bb4998f07127523f0ec169ac61e67a2b910 | 508 | cpp | C++ | UnitTest/IntentTest.cpp | omarekik/EmbeddedIntentRecognizer | dc3104702e1d3c572f62d9deb763a9b60f97e14e | [
"MIT"
] | null | null | null | UnitTest/IntentTest.cpp | omarekik/EmbeddedIntentRecognizer | dc3104702e1d3c572f62d9deb763a9b60f97e14e | [
"MIT"
] | null | null | null | UnitTest/IntentTest.cpp | omarekik/EmbeddedIntentRecognizer | dc3104702e1d3c572f62d9deb763a9b60f97e14e | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "Intent.h"
TEST(Intent, canFindContextInSentence)
{
Intent intent({"HELLO", "HI", "MORNING"}, "GREETING");
EXPECT_FALSE(intent.find("IT WILL BE THE BEST DAY."));
EXPECT_TRUE(intent.find("GOOD MORNING MY CAR."));
}
TEST(Intent, canFindExpressionContextInSentence)
{
Intent intent({"HELLO", "HI", "GOOD MORNING"}, "GREETING");
EXPECT_FALSE(intent.find("IT WILL BE THE BEST DAY."));
EXPECT_TRUE(intent.find("GOOD MORNING MY CAR."));
}
| 29.882353 | 64 | 0.661417 | omarekik |
035db36438e670f15e3f72d03de21b4be307d031 | 434 | cpp | C++ | src_compressible/conservedPrimitiveConversions.cpp | ckim103/FHDeX | 9182d7589db7e7ee318ca2a0f343c378d9c120a0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src_compressible/conservedPrimitiveConversions.cpp | ckim103/FHDeX | 9182d7589db7e7ee318ca2a0f343c378d9c120a0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src_compressible/conservedPrimitiveConversions.cpp | ckim103/FHDeX | 9182d7589db7e7ee318ca2a0f343c378d9c120a0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "compressible_functions.H"
#include "compressible_functions_F.H"
void conservedToPrimitive(MultiFab& prim, const MultiFab& cons)
{
// Loop over boxes
for ( MFIter mfi(prim); mfi.isValid(); ++mfi) {
const Box& bx = mfi.validbox();
cons_to_prim(ARLIM_3D(bx.loVect()), ARLIM_3D(bx.hiVect()),
cons[mfi].dataPtr(),
prim[mfi].dataPtr());
}
}
| 27.125 | 68 | 0.576037 | ckim103 |
035e3f6d11f0a2b7634651309c930cfacac9808e | 2,953 | cpp | C++ | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim | f4e5c4959a4d8848823c1eccf85c53251962df3b | [
"MIT"
] | null | null | null | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim | f4e5c4959a4d8848823c1eccf85c53251962df3b | [
"MIT"
] | null | null | null | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-if-tim | f4e5c4959a4d8848823c1eccf85c53251962df3b | [
"MIT"
] | null | null | null | #include <iostream> // cout
#include <algorithm> // copy, fill
#include "tasks.hpp"
// ИСПОЛЬЗОВАНИЕ ЛЮБЫХ ДРУГИХ БИБЛИОТЕК НЕ СОВЕТУЕТСЯ И МОЖЕТ ПОВЛИЯТЬ НА ВАШИ БАЛЛЫ
using std::cout;
using std::fill;
using std::copy;
// Задание 1
void swap_args(int *lhs, int *rhs) {
if (lhs == nullptr || rhs == nullptr) {
return;
}
int tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
// Задание 2
int **allocate_2d_array(int num_rows, int num_cols, int init_value) {
if (num_rows < 1 || num_cols < 1) {
return nullptr;
}
int **two_dimension_array = new int*[num_rows];
for (int row_index = 0; row_index < num_rows; row_index++) {
two_dimension_array[row_index] = new int[num_cols];
}
for (int row_index = 0; row_index < num_rows; row_index++) {
for (int column_index = 0; column_index < num_cols; column_index++) {
two_dimension_array[row_index][column_index] = init_value;
}
}
return two_dimension_array;
}
// Задание 3
bool copy_2d_array(int **arr_2d_source, int **arr_2d_target, int num_rows, int num_cols) {
if (arr_2d_source == nullptr || arr_2d_target == nullptr || num_rows < 1 || num_cols < 1) {
return false;
}
for (int row_index = 0; row_index < num_rows; row_index++) {
for (int column_index = 0; column_index < num_cols;column_index++) {
int tmp = arr_2d_source[row_index][column_index];
arr_2d_target[row_index][column_index] = tmp;
}
}
return true;
}
// Задание 4
void reverse_1d_array(vector<int> &arr) {
for (int left = 0, right = arr.size() - 1; left < right; left++, right--) {
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}
}
// Задание 5
void reverse_1d_array(int *arr_begin, int *arr_end) {
if (arr_begin == nullptr || arr_end == nullptr) {
return;
}
for (int *left = arr_begin, *right = arr_end; left < right; left++, right--) {
int tmp = * left;
*left = *right;
*right = tmp;
}
}
// Задание 6
int *find_max_element(int *arr, int size) {
if (arr == nullptr || size < 1) {
return nullptr;
}
int *max = arr;
for (int *iterator = arr; iterator <= arr + size - 1; iterator++) {
if (*max < *iterator) {
max = iterator;
}
}
return max;
}
// Задание 7
vector<int> find_odd_numbers(vector<int> &arr) {
vector<int> result;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] % 2 != 0) {
result.push_back(arr[i]);
}
}
return result;
}
// Задание 8
vector<int> find_common_elements(vector<int> &arr_a, vector<int> &arr_b) {
vector<int> result;
for (int i = 0; i < arr_a.size(); i++) {
for (int j = 0; j < arr_b.size(); j++) {
if (arr_a[i] == arr_b[j]) {
result.push_back(arr_a[i]);
}
}
}
return result;
}
| 26.603604 | 95 | 0.568574 | Algorithms-and-Data-Structures-2021 |
03639be17057299e455cb996a2b7e61f1d06d155 | 19,827 | cc | C++ | chrome/browser/gtk/browser_toolbar_gtk.cc | zachlatta/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2021-09-24T22:49:10.000Z | 2021-09-24T22:49:10.000Z | chrome/browser/gtk/browser_toolbar_gtk.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/gtk/browser_toolbar_gtk.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/browser_toolbar_gtk.h"
#include <gdk/gdkkeysyms.h>
#include <X11/XF86keysym.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/base_paths_linux.h"
#include "base/path_service.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/gtk/back_forward_button_gtk.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/go_button_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_dnd_util.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/location_bar_view_gtk.h"
#include "chrome/browser/gtk/nine_box.h"
#include "chrome/browser/gtk/standard_menus.h"
#include "chrome/browser/gtk/tabs/tab_strip_gtk.h"
#include "chrome/browser/gtk/toolbar_star_toggle_gtk.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/url_constants.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace {
// Height of the toolbar in pixels.
const int kToolbarHeight = 37;
// Interior spacing between toolbar widgets.
const int kToolbarWidgetSpacing = 4;
// The amount of space between the bottom of the star and the top of the
// Omnibox results popup window. We want a two pixel space between the bottom
// and the results, but have some extra space below the buttons already.
const int kPopupTopMargin = 0;
// Space between the edge of the star/go button and the popup frame. We want
// to leave 1 pixel on both side here so that the borders line up.
const int kPopupLeftRightMargin = 1;
} // namespace
// BrowserToolbarGtk, public ---------------------------------------------------
BrowserToolbarGtk::BrowserToolbarGtk(Browser* browser, BrowserWindowGtk* window)
: toolbar_(NULL),
location_bar_(new LocationBarViewGtk(browser->command_updater(),
browser->toolbar_model(),
this)),
model_(browser->toolbar_model()),
browser_(browser),
window_(window),
profile_(NULL),
last_release_event_flags_(0) {
browser_->command_updater()->AddCommandObserver(IDC_BACK, this);
browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this);
browser_->command_updater()->AddCommandObserver(IDC_RELOAD, this);
browser_->command_updater()->AddCommandObserver(IDC_HOME, this);
browser_->command_updater()->AddCommandObserver(IDC_STAR, this);
InitNineBox();
}
BrowserToolbarGtk::~BrowserToolbarGtk() {
// When we created our MenuGtk objects, we pass them a pointer to our accel
// group. Make sure to tear them down before |accel_group_|.
page_menu_.reset();
app_menu_.reset();
page_menu_button_.Destroy();
app_menu_button_.Destroy();
g_object_unref(accel_group_);
}
void BrowserToolbarGtk::Init(Profile* profile,
GtkWindow* top_level_window) {
// Make sure to tell the location bar the profile before calling its Init.
SetProfile(profile);
show_home_button_.Init(prefs::kShowHomeButton, profile->GetPrefs(), this);
event_box_ = gtk_event_box_new();
toolbar_ = gtk_hbox_new(FALSE, kToolbarWidgetSpacing);
gtk_container_add(GTK_CONTAINER(event_box_), toolbar_);
gtk_container_set_border_width(GTK_CONTAINER(toolbar_), 4);
// Demand we're always at least kToolbarHeight tall.
// -1 for width means "let GTK do its normal sizing".
gtk_widget_set_size_request(toolbar_, -1, kToolbarHeight);
g_signal_connect(toolbar_, "expose-event",
G_CALLBACK(&OnToolbarExpose), this);
// A GtkAccelGroup is not InitiallyUnowned, meaning we get a real reference
// count starting at one. We don't want the lifetime to be managed by the
// top level window, since the lifetime should be tied to the C++ object.
// When we add the accelerator group, the window will take a reference, but
// we still hold on to the original, and thus own a reference to the group.
accel_group_ = gtk_accel_group_new();
gtk_window_add_accel_group(top_level_window, accel_group_);
// Group back and forward into an hbox so there's no spacing between them.
GtkWidget* back_forward_hbox_ = gtk_hbox_new(FALSE, 0);
back_.reset(new BackForwardButtonGtk(browser_, false));
gtk_box_pack_start(GTK_BOX(back_forward_hbox_), back_->widget(), FALSE,
FALSE, 0);
forward_.reset(new BackForwardButtonGtk(browser_, true));
gtk_box_pack_start(GTK_BOX(back_forward_hbox_), forward_->widget(), FALSE,
FALSE, 0);
gtk_box_pack_start(GTK_BOX(toolbar_), back_forward_hbox_, FALSE, FALSE, 0);
reload_.reset(BuildToolbarButton(IDR_RELOAD, IDR_RELOAD_P, IDR_RELOAD_H, 0,
l10n_util::GetStringUTF8(IDS_TOOLTIP_RELOAD),
GTK_STOCK_REFRESH));
home_.reset(BuildToolbarButton(IDR_HOME, IDR_HOME_P, IDR_HOME_H, 0,
l10n_util::GetStringUTF8(IDS_TOOLTIP_HOME),
GTK_STOCK_HOME));
gtk_util::SetButtonTriggersNavigation(home_->widget());
SetUpDragForHomeButton();
// Group the start, omnibox, and go button into an hbox.
GtkWidget* omnibox_hbox_ = gtk_hbox_new(FALSE, 0);
star_.reset(BuildStarButton(l10n_util::GetStringUTF8(IDS_TOOLTIP_STAR)));
gtk_box_pack_start(GTK_BOX(omnibox_hbox_), star_->widget(), FALSE, FALSE, 0);
location_bar_->Init();
gtk_box_pack_start(GTK_BOX(omnibox_hbox_), location_bar_->widget(), TRUE,
TRUE, 0);
go_.reset(new GoButtonGtk(location_bar_.get(), browser_));
gtk_box_pack_start(GTK_BOX(omnibox_hbox_), go_->widget(), FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(toolbar_), omnibox_hbox_, TRUE, TRUE, 0);
// Group the menu buttons together in an hbox.
GtkWidget* menus_hbox_ = gtk_hbox_new(FALSE, 0);
GtkWidget* page_menu = BuildToolbarMenuButton(IDR_MENU_PAGE,
l10n_util::GetStringUTF8(IDS_PAGEMENU_TOOLTIP),
&page_menu_button_);
page_menu_.reset(new MenuGtk(this, GetStandardPageMenu(), accel_group_));
g_signal_connect(page_menu_->widget(), "motion-notify-event",
G_CALLBACK(OnPageAppMenuMouseMotion), this);
g_signal_connect(page_menu_->widget(), "move-current",
G_CALLBACK(OnPageAppMenuMoveCurrent), this);
gtk_box_pack_start(GTK_BOX(menus_hbox_), page_menu, FALSE, FALSE, 0);
GtkWidget* chrome_menu = BuildToolbarMenuButton(IDR_MENU_CHROME,
l10n_util::GetStringFUTF8(IDS_APPMENU_TOOLTIP,
WideToUTF16(l10n_util::GetString(IDS_PRODUCT_NAME))),
&app_menu_button_);
app_menu_.reset(new MenuGtk(this, GetStandardAppMenu(), accel_group_));
g_signal_connect(app_menu_->widget(), "motion-notify-event",
G_CALLBACK(OnPageAppMenuMouseMotion), this);
g_signal_connect(app_menu_->widget(), "move-current",
G_CALLBACK(OnPageAppMenuMoveCurrent), this);
gtk_box_pack_start(GTK_BOX(menus_hbox_), chrome_menu, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(toolbar_), menus_hbox_, FALSE, FALSE, 0);
// Force all the CustomDrawButtons to load the correct rendering style.
UserChangedTheme();
gtk_widget_show_all(event_box_);
if (show_home_button_.GetValue()) {
gtk_widget_show(home_->widget());
} else {
gtk_widget_hide(home_->widget());
}
}
void BrowserToolbarGtk::AddToolbarToBox(GtkWidget* box) {
gtk_box_pack_start(GTK_BOX(box), event_box_, FALSE, FALSE, 0);
}
void BrowserToolbarGtk::Show() {
gtk_widget_show(toolbar_);
}
void BrowserToolbarGtk::Hide() {
gtk_widget_hide(toolbar_);
}
LocationBar* BrowserToolbarGtk::GetLocationBar() const {
return location_bar_.get();
}
// CommandUpdater::CommandObserver ---------------------------------------------
void BrowserToolbarGtk::EnabledStateChangedForCommand(int id, bool enabled) {
GtkWidget* widget = NULL;
switch (id) {
case IDC_BACK:
widget = back_->widget();
break;
case IDC_FORWARD:
widget = forward_->widget();
break;
case IDC_RELOAD:
widget = reload_->widget();
break;
case IDC_GO:
widget = go_->widget();
break;
case IDC_HOME:
if (home_.get())
widget = home_->widget();
break;
case IDC_STAR:
widget = star_->widget();
break;
}
if (widget)
gtk_widget_set_sensitive(widget, enabled);
}
// MenuGtk::Delegate -----------------------------------------------------------
bool BrowserToolbarGtk::IsCommandEnabled(int command_id) const {
return browser_->command_updater()->IsCommandEnabled(command_id);
}
bool BrowserToolbarGtk::IsItemChecked(int id) const {
if (!profile_)
return false;
if (id == IDC_SHOW_BOOKMARK_BAR)
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
// TODO(port): Fix this when we get some items that want checking!
return false;
}
void BrowserToolbarGtk::ExecuteCommand(int id) {
browser_->ExecuteCommand(id);
}
void BrowserToolbarGtk::StoppedShowing() {
gtk_chrome_button_unset_paint_state(
GTK_CHROME_BUTTON(page_menu_button_.get()));
gtk_chrome_button_unset_paint_state(
GTK_CHROME_BUTTON(app_menu_button_.get()));
}
// NotificationObserver --------------------------------------------------------
void BrowserToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::wstring* pref_name = Details<std::wstring>(details).ptr();
if (*pref_name == prefs::kShowHomeButton) {
if (show_home_button_.GetValue()) {
gtk_widget_show(home_->widget());
} else {
gtk_widget_hide(home_->widget());
}
}
}
}
// BrowserToolbarGtk, public ---------------------------------------------------
void BrowserToolbarGtk::SetProfile(Profile* profile) {
if (profile == profile_)
return;
profile_ = profile;
location_bar_->SetProfile(profile);
}
void BrowserToolbarGtk::UpdateTabContents(TabContents* contents,
bool should_restore_state) {
location_bar_->Update(should_restore_state ? contents : NULL);
}
void BrowserToolbarGtk::UserChangedTheme() {
bool use_gtk = GtkThemeProvider::UseSystemThemeGraphics(profile_);
back_->SetUseSystemTheme(use_gtk);
forward_->SetUseSystemTheme(use_gtk);
reload_->SetUseSystemTheme(use_gtk);
home_->SetUseSystemTheme(use_gtk);
gtk_chrome_button_set_use_gtk_rendering(
GTK_CHROME_BUTTON(page_menu_button_.get()), use_gtk);
gtk_chrome_button_set_use_gtk_rendering(
GTK_CHROME_BUTTON(app_menu_button_.get()), use_gtk);
}
gfx::Rect BrowserToolbarGtk::GetPopupBounds() const {
GtkWidget* star = star_->widget();
GtkWidget* go = go_->widget();
// TODO(deanm): The go and star buttons probably share the same window,
// so this could be optimized to only one origin request.
gint go_x, go_y;
gdk_window_get_origin(go->window, &go_x, &go_y);
go_x += go->allocation.x + go->allocation.width; // Right edge.
gint star_x, star_y;
gdk_window_get_origin(star->window, &star_x, &star_y);
star_x += star->allocation.x; // Left edge.
star_y += star->allocation.y + star->allocation.height; // Bottom edge.
return gfx::Rect(star_x + kPopupLeftRightMargin, star_y + kPopupTopMargin,
go_x - star_x - (2 * kPopupLeftRightMargin), 0);
}
// BrowserToolbarGtk, private --------------------------------------------------
CustomDrawButton* BrowserToolbarGtk::BuildToolbarButton(
int normal_id, int active_id, int highlight_id, int depressed_id,
const std::string& localized_tooltip, const char* stock_id) {
CustomDrawButton* button = new CustomDrawButton(profile_->GetThemeProvider(),
normal_id, active_id, highlight_id, depressed_id, stock_id);
gtk_widget_set_tooltip_text(button->widget(),
localized_tooltip.c_str());
g_signal_connect(button->widget(), "clicked",
G_CALLBACK(OnButtonClick), this);
g_signal_connect(button->widget(), "button-release-event",
G_CALLBACK(OnButtonRelease), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
return button;
}
ToolbarStarToggleGtk* BrowserToolbarGtk::BuildStarButton(
const std::string& localized_tooltip) {
ToolbarStarToggleGtk* button = new ToolbarStarToggleGtk(this);
gtk_widget_set_tooltip_text(button->widget(),
localized_tooltip.c_str());
g_signal_connect(button->widget(), "clicked",
G_CALLBACK(OnButtonClick), this);
return button;
}
GtkWidget* BrowserToolbarGtk::BuildToolbarMenuButton(
int icon_id,
const std::string& localized_tooltip,
OwnedWidgetGtk* owner) {
GtkWidget* button = gtk_chrome_button_new();
owner->Own(button);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
if (!GtkThemeProvider::UseSystemThemeGraphics(profile_))
gtk_container_set_border_width(GTK_CONTAINER(button), 2);
gtk_container_add(GTK_CONTAINER(button),
gtk_image_new_from_pixbuf(rb.GetPixbufNamed(icon_id)));
gtk_widget_set_tooltip_text(button, localized_tooltip.c_str());
g_signal_connect(button, "button-press-event",
G_CALLBACK(OnMenuButtonPressEvent), this);
GTK_WIDGET_UNSET_FLAGS(button, GTK_CAN_FOCUS);
return button;
}
void BrowserToolbarGtk::SetUpDragForHomeButton() {
// TODO(estade): we should use a custom drag-drop handler so that we can
// prefer URIs over plain text when both are available.
gtk_drag_dest_set(home_->widget(), GTK_DEST_DEFAULT_ALL,
NULL, 0, GDK_ACTION_COPY);
GtkDndUtil::SetDestTargetListFromCodeMask(home_->widget(),
GtkDndUtil::X_CHROME_TEXT_PLAIN |
GtkDndUtil::X_CHROME_TEXT_URI_LIST);
g_signal_connect(home_->widget(), "drag-data-received",
G_CALLBACK(OnDragDataReceived), this);
}
void BrowserToolbarGtk::ChangeActiveMenu(GtkWidget* active_menu,
guint timestamp) {
MenuGtk* old_menu;
MenuGtk* new_menu;
GtkWidget* relevant_button;
if (active_menu == app_menu_->widget()) {
old_menu = app_menu_.get();
new_menu = page_menu_.get();
relevant_button = page_menu_button_.get();
} else {
old_menu = page_menu_.get();
new_menu = app_menu_.get();
relevant_button = app_menu_button_.get();
}
old_menu->Cancel();
gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(relevant_button),
GTK_STATE_ACTIVE);
new_menu->Popup(relevant_button, 0, timestamp);
}
// static
gboolean BrowserToolbarGtk::OnToolbarExpose(GtkWidget* widget,
GdkEventExpose* e,
BrowserToolbarGtk* toolbar) {
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
cairo_rectangle(cr, e->area.x, e->area.y, e->area.width, e->area.height);
cairo_clip(cr);
// The toolbar is supposed to blend in with the active tab, so we have to pass
// coordinates for the IDR_THEME_TOOLBAR bitmap relative to the top of the
// tab strip.
gfx::Point tabstrip_origin =
toolbar->window_->tabstrip()->GetTabStripOriginForWidget(widget);
toolbar->background_ninebox_->RenderTopCenterStrip(
cr, tabstrip_origin.x(), tabstrip_origin.y(),
e->area.x + e->area.width - tabstrip_origin.x());
cairo_destroy(cr);
return FALSE; // Allow subwidgets to paint.
}
// static
void BrowserToolbarGtk::OnButtonClick(GtkWidget* button,
BrowserToolbarGtk* toolbar) {
int tag = -1;
if (button == toolbar->reload_->widget())
tag = IDC_RELOAD;
else if (toolbar->home_.get() && button == toolbar->home_->widget())
tag = IDC_HOME;
else if (button == toolbar->star_->widget())
tag = IDC_STAR;
DCHECK_NE(tag, -1) << "Unexpected button click callback";
toolbar->browser_->ExecuteCommandWithDisposition(tag,
event_utils::DispositionFromEventFlags(
toolbar->last_release_event_flags_));
}
// static
gboolean BrowserToolbarGtk::OnButtonRelease(GtkWidget* button,
GdkEventButton* event,
BrowserToolbarGtk* toolbar) {
toolbar->last_release_event_flags_ = event->state;
return FALSE;
}
// static
gboolean BrowserToolbarGtk::OnMenuButtonPressEvent(GtkWidget* button,
GdkEventButton* event,
BrowserToolbarGtk* toolbar) {
if (event->button != 1)
return FALSE;
gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(button),
GTK_STATE_ACTIVE);
MenuGtk* menu = button == toolbar->page_menu_button_.get() ?
toolbar->page_menu_.get() : toolbar->app_menu_.get();
menu->Popup(button, reinterpret_cast<GdkEvent*>(event));
return TRUE;
}
// static
void BrowserToolbarGtk::OnDragDataReceived(GtkWidget* widget,
GdkDragContext* drag_context, gint x, gint y,
GtkSelectionData* data, guint info, guint time,
BrowserToolbarGtk* toolbar) {
if (info != GtkDndUtil::X_CHROME_TEXT_PLAIN) {
NOTIMPLEMENTED() << "Only support plain text drops for now, sorry!";
return;
}
GURL url(reinterpret_cast<char*>(data->data));
if (!url.is_valid())
return;
bool url_is_newtab = url.spec() == chrome::kChromeUINewTabURL;
toolbar->profile_->GetPrefs()->SetBoolean(prefs::kHomePageIsNewTabPage,
url_is_newtab);
if (!url_is_newtab) {
toolbar->profile_->GetPrefs()->SetString(prefs::kHomePage,
UTF8ToWide(url.spec()));
}
}
// static
gboolean BrowserToolbarGtk::OnPageAppMenuMouseMotion(GtkWidget* menu,
GdkEventMotion* event, BrowserToolbarGtk* toolbar) {
if (gtk_util::WidgetContainsCursor(menu == toolbar->app_menu_->widget() ?
toolbar->page_menu_button_.get() :
toolbar->app_menu_button_.get())) {
toolbar->ChangeActiveMenu(menu, event->time);
return TRUE;
}
return FALSE;
}
// static
void BrowserToolbarGtk::OnPageAppMenuMoveCurrent(GtkWidget* menu,
GtkMenuDirectionType dir, BrowserToolbarGtk* toolbar) {
GtkWidget* active_item = GTK_MENU_SHELL(menu)->active_menu_item;
switch (dir) {
case GTK_MENU_DIR_CHILD:
// The move is going to open a submenu; don't override default behavior.
if (active_item && gtk_menu_item_get_submenu(GTK_MENU_ITEM(active_item)))
break;
// Fall through.
case GTK_MENU_DIR_PARENT:
toolbar->ChangeActiveMenu(menu, gtk_get_current_event_time());
// This signal doesn't have a return value; we have to manually stop its
// propagation.
g_signal_stop_emission_by_name(menu, "move-current");
default:
break;
}
}
void BrowserToolbarGtk::InitNineBox() {
// TODO(estade): use |profile_|?
background_ninebox_.reset(new NineBox(
browser_->profile()->GetThemeProvider(),
0, IDR_THEME_TOOLBAR, 0, 0, 0, 0, 0, 0, 0));
}
| 36.990672 | 80 | 0.685832 | zachlatta |
0363c7505ed00c6aa0609f4dbe1da1174a8f301e | 3,510 | cpp | C++ | samples/stencil/matrix_mult/main.cpp | Jerry-Ma/grppi | d6e5435a2c146605fc53eed899d1777ac0b35699 | [
"ECL-2.0",
"Apache-2.0"
] | 75 | 2017-05-05T08:22:47.000Z | 2022-02-18T23:48:13.000Z | samples/stencil/matrix_mult/main.cpp | Jerry-Ma/grppi | d6e5435a2c146605fc53eed899d1777ac0b35699 | [
"ECL-2.0",
"Apache-2.0"
] | 317 | 2017-03-29T15:26:18.000Z | 2021-10-02T04:18:27.000Z | samples/stencil/matrix_mult/main.cpp | Yagoloco2210/grppi | 03f3712f282298a64b37dc560b28f6109437b774 | [
"ECL-2.0",
"Apache-2.0"
] | 21 | 2017-08-02T14:35:19.000Z | 2022-02-17T22:19:06.000Z | /*
* Copyright 2018 Universidad Carlos III de Madrid
*
* 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.
*/
// Standard library
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <string>
#include <numeric>
#include <stdexcept>
#include <random>
// grppi
#include "grppi/grppi.h"
// Samples shared utilities
#include "../../util/util.h"
template <typename T>
class row_span {
public:
row_span(std::vector<T> & v, int cols, int r) : vec_{v}, cols_{cols}, row_{r} {}
T operator[](int i) const { return vec_[row_*cols_+i]; }
private:
std::vector<T> & vec_;
int cols_;
int row_;
};
template <typename T>
class col_span {
public:
col_span(std::vector<T> & v, int cols, int c) : vec_{v}, cols_{cols}, col_{c} {}
T operator[](int i) const { return vec_[i*cols_+col_]; }
private:
std::vector<T> & vec_;
int cols_;
int col_;
};
template <typename C, typename I>
int row_index(I it, C & cont, int ncols) {
return std::distance(cont.begin(), it) / ncols;
}
template <typename C, typename I>
int col_index(I it, C & cont, int ncols) {
return std::distance(cont.begin(), it) % ncols;
}
void matrix_mult(grppi::dynamic_execution & e, int n) {
using namespace std;
random_device rdev;
uniform_real_distribution<double> gen{1.0, 100.00};
std::vector<double> a;
generate_n(back_inserter(a), n*n,
[&]() { return gen(rdev); });
std::vector<double> b;
generate_n(back_inserter(b), n*n,
[&]() { return gen(rdev); });
std::vector<double> c(n*n);
grppi::stencil(e, make_tuple(begin(a),begin(b)), end(a), begin(c),
[=](auto, auto nh) {
double r = 0;
for (int k=0;k<n;++k) { r+= nh.first[k] * nh.second[k]; }
return r;
},
[&](auto it1, auto it2) {
return make_pair(
row_span<double>{a, n, row_index(it1,a,n)},
col_span<double>{b, n, col_index(it2,b,n)}
);
}
);
cout << "size(a)" << a.size() << endl;
copy(begin(a), end(a), ostream_iterator<double>(cout, " "));
cout << endl << endl;
cout << "size(b)" << b.size() << endl;
copy(begin(b), end(b), ostream_iterator<double>(cout, " "));
cout << endl << endl;
cout << "size(c)" << c.size() << endl;
copy(begin(c), end(c), ostream_iterator<double>(cout, " "));
cout << endl << endl;
}
void print_message(const std::string & prog, const std::string & msg) {
using namespace std;
cerr << msg << endl;
cerr << "Usage: " << prog << " size mode" << endl;
cerr << " size: Integer value with problem size" << endl;
cerr << " mode:" << endl;
print_available_modes(cerr);
}
int main(int argc, char **argv) {
using namespace std;
if(argc < 3){
print_message(argv[0], "Invalid number of arguments.");
return -1;
}
int n = stoi(argv[1]);
if(n <= 0){
print_message(argv[0], "Invalid problem size. Use a positive number.");
return -1;
}
if (!run_test(argv[2], matrix_mult, n)) {
print_message(argv[0], "Invalid policy.");
return -1;
}
return 0;
}
| 25.434783 | 82 | 0.628205 | Jerry-Ma |
24e9859e191191bb2ea014dc368064b20bf174f9 | 1,113 | cc | C++ | python/jittor/src/opt/tuner/reorder_tuner.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 2,571 | 2020-03-20T03:38:35.000Z | 2022-03-31T08:20:05.000Z | python/jittor/src/opt/tuner/reorder_tuner.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 197 | 2020-03-20T04:11:47.000Z | 2022-03-31T10:14:24.000Z | python/jittor/src/opt/tuner/reorder_tuner.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 284 | 2020-03-20T03:53:15.000Z | 2022-03-28T07:20:32.000Z | // ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include "common.h"
#include "opt/tuner/reorder_tuner.h"
#include "opt/pass_manager.h"
#include "opt/pass/loop_var_analyze_pass.h"
#include "opt/pass/split_loop_pass.h"
namespace jittor {
void ReorderTuner::run(PassManager* pm, TunerManager* tm) {
auto* lva_pass = pm->get_pass<LoopVarAnalyzePass>("loop_var_analyze");
auto* sl_pass = pm->get_pass<SplitLoopPass>("split_loop");
if (!sl_pass || !lva_pass) return;
auto number_of_ranges = lva_pass->number_of_ranges;
auto number_of_ranges_after_split = sl_pass->number_of_ranges_after_split;
for (int i=0; i<number_of_ranges_after_split; i++)
for (int j=0; j<std::min(i+1, number_of_ranges); j++)
add_candidate("order"+S(i), j);
confidence = 1;
}
} | 41.222222 | 78 | 0.630728 | Exusial |
24e9d1f3329528c4b173fab20fa8988fea791da1 | 652 | cpp | C++ | windows/wrapper/impl_org_webRtc.cpp | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 9 | 2019-03-27T12:19:29.000Z | 2022-01-25T05:13:55.000Z | windows/wrapper/impl_org_webRtc.cpp | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 8 | 2018-11-07T19:09:19.000Z | 2019-11-27T15:20:08.000Z | windows/wrapper/impl_org_webRtc.cpp | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 12 | 2019-06-06T14:15:26.000Z | 2022-01-24T13:35:30.000Z |
#include <zsLib/Log.h>
#include "Org.WebRtc.Glue.events.h"
#include "Org.WebRtc.Glue.events.jman.h"
namespace wrapper { namespace impl { namespace org { namespace webRtc { ZS_IMPLEMENT_SUBSYSTEM(wrapper_org_webRtc); } } } }
ZS_EVENTING_SUBSYSTEM_DEFAULT_LEVEL(wrapper_org_webRtc, Debug)
namespace wrapper {
namespace impl {
namespace org {
namespace webRtc {
void initSubsystems() noexcept
{
ZS_GET_SUBSYSTEM_LOG_LEVEL(ZS_GET_OTHER_SUBSYSTEM(wrapper::impl::org::webRtc, wrapper_org_webRtc));
ZS_EVENTING_REGISTER(Org_WebRtc_Glue);
}
} // namespace webRtc
} // namespace impl
} // namespace org
} // namespace webRtc
| 25.076923 | 124 | 0.745399 | webrtc-uwp |
24eb934681d78000ad65cb9e4a4409f1e88088d8 | 4,340 | cpp | C++ | tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 476 | 2018-09-07T01:27:11.000Z | 2022-03-21T05:16:50.000Z | tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 594 | 2018-09-06T02:03:01.000Z | 2022-03-23T19:18:26.000Z | tools/jsoncons/tests/src/jsonpath/jsonpath_error_tests.cpp | SheldonHH/eosio.cdt | 64448283307b2daebb7db4df947fafd3fc56a83c | [
"MIT"
] | 349 | 2018-09-06T05:02:09.000Z | 2022-03-12T11:07:17.000Z | // Copyright 2013 Daniel Parker
// Distributed under Boost license
#ifdef __linux__
#define BOOST_TEST_DYN_LINK
#endif
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <vector>
#include <utility>
#include <ctime>
#include <new>
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpath/json_query.hpp>
using namespace jsoncons;
using namespace jsoncons::jsonpath;
BOOST_AUTO_TEST_SUITE(jsonpath_error_tests)
struct jsonpath_fixture
{
static const char* store_text()
{
static const char* text = "{ \"store\": {\"book\": [ { \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95},{ \"category\": \"fiction\",\"author\": \"Evelyn Waugh\",\"title\": \"Sword of Honour\",\"price\": 12.99},{ \"category\": \"fiction\",\"author\": \"Herman Melville\",\"title\": \"Moby Dick\",\"isbn\": \"0-553-21311-3\",\"price\": 8.99},{ \"category\": \"fiction\",\"author\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"0-395-19395-8\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}}}";
return text;
}
static const char* store_text_empty_isbn()
{
static const char* text = "{ \"store\": {\"book\": [ { \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95},{ \"category\": \"fiction\",\"author\": \"Evelyn Waugh\",\"title\": \"Sword of Honour\",\"price\": 12.99},{ \"category\": \"fiction\",\"author\": \"Herman Melville\",\"title\": \"Moby Dick\",\"isbn\": \"0-553-21311-3\",\"price\": 8.99},{ \"category\": \"fiction\",\"author\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}}}";
return text;
}
static const char* book_text()
{
static const char* text = "{ \"category\": \"reference\",\"author\": \"Nigel Rees\",\"title\": \"Sayings of the Century\",\"price\": 8.95}";
return text;
}
json book()
{
json root = json::parse(jsonpath_fixture::store_text());
json book = root["store"]["book"];
return book;
}
json bicycle()
{
json root = json::parse(jsonpath_fixture::store_text());
json bicycle = root["store"]["bicycle"];
return bicycle;
}
};
void test_error_code(const json& root, const std::string& path, int value, const std::error_category& category, size_t line, size_t column)
{
try
{
json result = json_query(root,path);
BOOST_FAIL(path);
}
catch (const parse_error& e)
{
BOOST_CHECK_MESSAGE(e.code().value() == value && e.code().category() == category, e.what());
BOOST_CHECK_MESSAGE(e.line_number() == line, e.what());
BOOST_CHECK_MESSAGE(e.column_number() == column, e.what());
}
}
void test_error_code(const json& root, const std::string& path, std::error_code value, size_t line, size_t column)
{
try
{
json result = json_query(root,path);
BOOST_FAIL(path);
}
catch (const parse_error& e)
{
BOOST_CHECK_MESSAGE(e.code() == value, e.what());
BOOST_CHECK_MESSAGE(e.line_number() == line, e.what());
BOOST_CHECK_MESSAGE(e.column_number() == column, e.what());
}
}
BOOST_AUTO_TEST_CASE(test_root_error)
{
json root = json::parse(jsonpath_fixture::store_text());
test_error_code(root, "..*", jsonpath_parser_errc::expected_root,1,1);
}
BOOST_AUTO_TEST_CASE(test_right_bracket_error)
{
json root = json::parse(jsonpath_fixture::store_text());
test_error_code(root, "$['store']['book'[*]", jsonpath_parser_errc::expected_right_bracket,1,18);
}
BOOST_AUTO_TEST_CASE(test_dot_dot_dot)
{
json root = json::parse(jsonpath_fixture::store_text());
test_error_code(root, "$.store...price", jsonpath_parser_errc::expected_name,1,10);
}
BOOST_AUTO_TEST_CASE(test_dot_star_name)
{
json root = json::parse(jsonpath_fixture::store_text());
test_error_code(root, "$.store.*price", jsonpath_parser_errc::expected_separator,1,10);
}
BOOST_AUTO_TEST_CASE(test_filter_error)
{
json root = json::parse(jsonpath_fixture::store_text());
test_error_code(root, "$..book[?(.price<10)]", json_parse_errc::invalid_json_text,1,17);
}
BOOST_AUTO_TEST_SUITE_END()
| 35.284553 | 608 | 0.62765 | SheldonHH |
24edf49e181944da98af31a868f2d29d7553e08a | 1,387 | cpp | C++ | general/occa.cpp | benzwick/mfem | 4d5fdfd553b24ff37716f736f83df2d238d9a696 | [
"BSD-3-Clause"
] | 1 | 2020-08-15T07:00:22.000Z | 2020-08-15T07:00:22.000Z | general/occa.cpp | benzwick/mfem | 4d5fdfd553b24ff37716f736f83df2d238d9a696 | [
"BSD-3-Clause"
] | 1 | 2019-04-24T21:18:24.000Z | 2019-04-25T18:00:45.000Z | general/occa.cpp | benzwick/mfem | 4d5fdfd553b24ff37716f736f83df2d238d9a696 | [
"BSD-3-Clause"
] | 1 | 2021-09-15T14:14:29.000Z | 2021-09-15T14:14:29.000Z | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "occa.hpp"
#ifdef MFEM_USE_OCCA
#include "device.hpp"
#if defined(MFEM_USE_CUDA) && OCCA_CUDA_ENABLED
#include <occa/modes/cuda/utils.hpp>
#endif
namespace mfem
{
// This variable is defined in device.cpp:
namespace internal { extern occa::device occaDevice; }
occa::device &OccaDev() { return internal::occaDevice; }
occa::memory OccaMemoryWrap(void *ptr, std::size_t bytes)
{
#if defined(MFEM_USE_CUDA) && OCCA_CUDA_ENABLED
// If OCCA_CUDA is allowed, it will be used since it has the highest priority
if (Device::Allows(Backend::OCCA_CUDA))
{
return occa::cuda::wrapMemory(internal::occaDevice, ptr, bytes);
}
#endif // MFEM_USE_CUDA && OCCA_CUDA_ENABLED
// otherwise, fallback to occa::cpu address space
return occa::cpu::wrapMemory(internal::occaDevice, ptr, bytes);
}
} // namespace mfem
#endif // MFEM_USE_OCCA
| 30.822222 | 80 | 0.740447 | benzwick |
24f2abc15752f49ebf22d4295f33d62b280dd16a | 432 | hpp | C++ | src/gs/gsTundraTextureGenerator.hpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | 2 | 2016-12-06T17:51:30.000Z | 2018-06-21T08:52:58.000Z | src/gs/gsTundraTextureGenerator.hpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | null | null | null | src/gs/gsTundraTextureGenerator.hpp | frmr/gs | b9721ad27f59ca2e19f637bccd9eba32b663b6a3 | [
"MIT"
] | null | null | null | #pragma once
#include "gsLandTile.hpp"
#include "gsColor.hpp"
#include <vector>
#include "../FastNoise/FastNoise.h"
namespace gs
{
class TundraTextureGenerator
{
private:
static const std::vector<gs::Vec3d> colors;
static const std::vector<float> limits;
FastNoise noiseA;
FastNoise noiseB;
public:
gs::Color Sample(const gs::Vec3d& coord, const gs::LandTile::Terrain terrain);
TundraTextureGenerator();
};
} | 17.28 | 80 | 0.722222 | frmr |
24f4d724ede6f8e8482fe1bab8097ce7277e0eb2 | 3,237 | hh | C++ | ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh | shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 216 | 2018-09-09T11:53:56.000Z | 2022-03-19T13:41:35.000Z | ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh | gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 13 | 2018-10-23T08:29:09.000Z | 2021-09-08T06:45:34.000Z | ACAP_linux/3rd/CoMISo/NSolver/FiniteElementLogBarrier.hh | shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer | 8c9afe017769f9554706bcd267b6861c4c144999 | [
"MIT"
] | 41 | 2018-09-13T08:50:41.000Z | 2022-02-23T00:33:54.000Z | //=============================================================================
//
// CLASS FiniteElementLogBarrier
//
//=============================================================================
#ifndef COMISO_FINITEELEMENTLOGBARRIER_HH
#define COMISO_FINITEELEMENTLOGBARRIER_HH
//== INCLUDES =================================================================
#include <CoMISo/Config/CoMISoDefines.hh>
#include "NProblemInterface.hh"
//== FORWARDDECLARATIONS ======================================================
//== NAMESPACES ===============================================================
namespace COMISO {
//== CLASS DEFINITION =========================================================
/** \class FiniteElementLogBarrierLowerBound
Implements function of the type f(x) = -c1*log(x-c0) with constants (c0,c1)
A more elaborate description follows.
*/
class FiniteElementLogBarrierLowerBound
{
public:
// define dimensions
const static int NV = 1;
const static int NC = 2;
typedef Eigen::Matrix<size_t,NV,1> VecI;
typedef Eigen::Matrix<double,NV,1> VecV;
typedef Eigen::Matrix<double,NC,1> VecC;
typedef Eigen::Triplet<double> Triplet;
inline double eval_f (const VecV& _x, const VecC& _c) const
{
return -_c[1]*std::log(_x[0]-_c[0]);
}
inline void eval_gradient(const VecV& _x, const VecC& _c, VecV& _g) const
{
_g[0] = -_c[1]/(_x[0]-_c[0]);
}
inline void eval_hessian (const VecV& _x, const VecC& _c, std::vector<Triplet>& _triplets) const
{
_triplets.clear();
_triplets.push_back(Triplet(0,0,_c[1]/std::pow(_x[0]-_c[0],2)));
}
inline double max_feasible_step(const VecV& _x, const VecV& _v, const VecC& _c)
{
if(_v[0] >=0.0)
return DBL_MAX;
else
return 0.999*(_c[0]-_x[0])/_v[0];
}
};
/** \class FiniteElementLogBarrierUpperBound
Implements function of the type f(x) = -c1*log(c0-x) with constants (c0,c1)
A more elaborate description follows.
*/
class FiniteElementLogBarrierUpperBound
{
public:
// define dimensions
const static int NV = 1;
const static int NC = 2;
typedef Eigen::Matrix<size_t,NV,1> VecI;
typedef Eigen::Matrix<double,NV,1> VecV;
typedef Eigen::Matrix<double,NC,1> VecC;
typedef Eigen::Triplet<double> Triplet;
inline double eval_f (const VecV& _x, const VecC& _c) const
{
return -_c[1]*std::log(_c[0]-_x[0]);
}
inline void eval_gradient(const VecV& _x, const VecC& _c, VecV& _g) const
{
_g[0] = _c[1]/(_c[0]-_x[0]);
}
inline void eval_hessian (const VecV& _x, const VecC& _c, std::vector<Triplet>& _triplets) const
{
_triplets.clear();
_triplets.push_back(Triplet(0,0,_c[1]/std::pow(_c[0]-_x[0],2)));
}
inline double max_feasible_step(const VecV& _x, const VecV& _v, const VecC& _c)
{
if(_v[0] <=0.0)
return DBL_MAX;
else
return 0.999*(_c[0]-_x[0])/_v[0];
}
};
//=============================================================================
} // namespace COMISO
//=============================================================================
#endif // COMISO_FINITEELEMENTLOGBARRIER_HH defined
//=============================================================================
| 25.488189 | 100 | 0.531047 | shubhMaheshwari |
24f4e64bc56fa15c9f344524594aacc9f448f597 | 2,464 | cpp | C++ | devices/GNSS/NMEA/src/GGAProcessor.cpp | gboyraz/macchina.io | 3e26fea95e87512459693831242b297f0780cc21 | [
"Apache-2.0"
] | 2 | 2020-11-23T23:37:00.000Z | 2020-12-22T04:02:41.000Z | devices/GNSS/NMEA/src/GGAProcessor.cpp | gboyraz/macchina.io | 3e26fea95e87512459693831242b297f0780cc21 | [
"Apache-2.0"
] | null | null | null | devices/GNSS/NMEA/src/GGAProcessor.cpp | gboyraz/macchina.io | 3e26fea95e87512459693831242b297f0780cc21 | [
"Apache-2.0"
] | 1 | 2020-11-23T23:37:09.000Z | 2020-11-23T23:37:09.000Z | //
// GGAProcessor.cpp
//
// Library: IoT/GNSS/NMEA
// Package: Sentences
// Module: GGAProcessor
//
// Copyright (c) 2010-2015, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "IoT/GNSS/NMEA/GGAProcessor.h"
#include "Poco/DateTimeParser.h"
#include "Poco/DateTime.h"
#include "Poco/NumberParser.h"
#include <cmath>
namespace IoT {
namespace GNSS {
namespace NMEA {
GGAProcessor::GGAProcessor()
{
}
GGAProcessor::~GGAProcessor()
{
}
void GGAProcessor::processSentence(const Sentence& sentence)
{
if (sentence.type() == "GGA" && sentence.size() > 9)
{
bool valid = true;
GGA gga;
try
{
if (!sentence[0].empty())
{
std::string timeStr = sentence[0];
int tzd;
Poco::DateTime dt = Poco::DateTimeParser::parse("%H%M%s", timeStr, tzd);
Poco::DateTime now;
gga.utc = Poco::DateTime(now.year(), now.month(), now.day(), dt.hour(), dt.minute(), dt.second()).timestamp();
}
else
{
gga.utc.update();
}
if (!sentence[1].empty() && !sentence[3].empty())
{
double lat = Poco::NumberParser::parseFloat(sentence[1]);
double latDeg = std::floor(lat/100);
double latMin = lat - 100*latDeg;
latDeg += latMin/60;
if (sentence[2] == "S") latDeg = -latDeg;
double lon = Poco::NumberParser::parseFloat(sentence[3]);
double lonDeg = std::floor(lon/100);
double lonMin = lon - 100*lonDeg;
lonDeg += lonMin/60;
if (sentence[4] == "W") lonDeg = -lonDeg;
gga.position.assign(Poco::Geo::Angle::fromDegreesLatitude(latDeg), Poco::Geo::Angle::fromDegreesLongitude(lonDeg));
}
else
{
valid = false;
}
if (!sentence[5].empty())
{
gga.quality = static_cast<FixQuality>(Poco::NumberParser::parseFloat(sentence[5]));
}
else
{
gga.quality = FIX_UNKNOWN;
}
if (!sentence[6].empty())
{
gga.satellitesInView = Poco::NumberParser::parseFloat(sentence[6]);
}
else
{
gga.satellitesInView = 0;
}
if (!sentence[7].empty())
{
gga.hdop = Poco::NumberParser::parseFloat(sentence[7]);
}
else
{
gga.hdop = -9999;
}
if (!sentence[8].empty())
{
gga.altitude = Poco::NumberParser::parseFloat(sentence[8]);
}
else
{
gga.altitude = -9999;
}
}
catch (Poco::Exception&)
{
valid = false;
}
if (valid)
{
ggaReceived(this, gga);
}
}
}
} } } // namespace IoT::GNSS::NMEA
| 19.25 | 119 | 0.609172 | gboyraz |
24f81a976aadb3e9f2db1da58b7f25ccc91f344e | 8,104 | cpp | C++ | src/OptimalContactFinder.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/OptimalContactFinder.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/OptimalContactFinder.cpp | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | #include "CommonHeader.h"
#include "NonlinearOptimizerInfo.h"
#include <queue>
extern std::vector<LinkInfo> LinkInfoObj;
extern SDFInfo SDFInfoObj;
extern ReachabilityMap ReachabilityMapObj;
extern AnyCollisionGeometry3D TerrColGeomObj;
typedef std::pair<double, Vector3> qEle;
static std::vector<std::pair<Vector3, double>> ContactFreeInfoFn(const Robot & SimRobot, const std::vector<ContactStatusInfo> & RobotContactInfo){
std::vector<std::pair<Vector3, double>> ContactFreeInfo;
for (int i = 0; i < RobotContactInfo.size(); i++){
if(RobotContactInfo[i].LocalContactStatus[0]){
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(LinkInfoObj[i].AvgLocalContact, LinkInfoObj[i].LinkIndex, LinkiPjPos);
double Radius = ReachabilityMapObj.EndEffectorGeometryRadius[i];
auto ContactFreeInfo_i = std::make_pair (LinkiPjPos, Radius);
ContactFreeInfo.push_back(ContactFreeInfo_i);
}
}
return ContactFreeInfo;
}
static std::vector<Vector3> SupportContactFinder(const PIPInfo & PIPObj, const std::vector<Vector3> & ContactFreeContact){
Vector3 EdgeA = PIPObj.edge_a;
Vector3 EdgeB = PIPObj.edge_b;
Vector3 EdgeDir = EdgeB - EdgeA;
std::vector<Vector3> SupportContact;
SupportContact.reserve(ContactFreeContact.size());
for (int i = 0; i < ContactFreeContact.size(); i++){
Vector3 ContactFreePoint = ContactFreeContact[i];
Vector3 PointNormDir = SDFInfoObj.SignedDistanceNormal(ContactFreePoint);
Vector3 rPos2COMPos = ContactFreePoint - EdgeA;
Vector3 InducedMomentum = cross(rPos2COMPos, PointNormDir);
double ProjMomentumVal = InducedMomentum.dot(EdgeDir);
if(ProjMomentumVal<0.0) SupportContact.push_back(ContactFreePoint);
}
return SupportContact;
}
static std::vector<Vector3> OptimalContactFinder(const std::vector<Vector3> & SupportContact, const std::vector<Vector3> & FixedContacts, const Vector3 & COMPos, const Vector3 & COMVel, int CutOffNo, SimPara & SimParaObj){
// This function selects the optimal contact given support contact.
std::priority_queue<qEle, std::vector<qEle>, less<qEle> > OptimalContactQueue;
std::vector<Vector3> CandidateContacts;
std::vector<Vector3> CandidateContactWeights;
std::vector<double> ContactFailureMetric(SupportContact.size());
Vector3 CurContact = SimParaObj.getInitContactPos();
LinkInfo SwingLinkInfo = LinkInfoObj[SimParaObj.getSwingLinkInfoIndex()];
int RobotLinkIndex = SwingLinkInfo.LinkIndex;
double ContactSelectionCoeff = SimParaObj.getContactSelectionCoeff();
for (int i = 0; i < SupportContact.size(); i++){
std::vector<Vector3> ActContacts = FixedContacts;
ActContacts.push_back(SupportContact[i]);
switch (RobotLinkIndex){ // Attach four vertices
case 11:{
for (int j = 0; j < SwingLinkInfo.LocalContacts.size(); j++){
Vector3 Vertex = SupportContact[i] + SwingLinkInfo.LocalContacts[j] - SwingLinkInfo.AvgLocalContact;
ActContacts.push_back(Vertex);
}
}
break;
case 17:{
for (int j = 0; j < SwingLinkInfo.LocalContacts.size(); j++){
Vector3 Vertex = SupportContact[i] + SwingLinkInfo.LocalContacts[j] - SwingLinkInfo.AvgLocalContact;
ActContacts.push_back(Vertex);
}
}
break;
default:
break;
}
std::vector<PIPInfo> PIPTotal = PIPGenerator(COMPos, COMVel, ActContacts);
ContactFailureMetric[i] = FailureMetricEval(PIPTotal);
if(ContactFailureMetric[i]>0.0){
Vector3 ContactDiff = CurContact - SupportContact[i];
double ContactDiffDist = ContactDiff.normSquared();
double ContactDistCost = 1.0 * exp(-ContactSelectionCoeff * ContactDiffDist);
ContactFailureMetric[i]*= ContactDistCost;
OptimalContactQueue.push(std::make_pair(ContactFailureMetric[i], SupportContact[i]));
CandidateContacts.push_back(SupportContact[i]);
CandidateContactWeights.push_back(ContactFailureMetric[i] * SDFInfoObj.SignedDistanceNormal(SupportContact[i]));
}
}
std::vector<Vector3> SelectedContacts;
if(!CandidateContacts.size()){
int OptiIndex = std::distance(ContactFailureMetric.begin(), std::max_element(ContactFailureMetric.begin(), ContactFailureMetric.end()));
CandidateContacts.push_back(SupportContact[OptiIndex]);
CandidateContactWeights.push_back(0.0);
SelectedContacts.push_back(SupportContact[OptiIndex]);
} else {
int OptimalContactNumber = CandidateContacts.size();
int OptEleNo = std::min(OptimalContactNumber, CutOffNo);
for (int i = 0; i < OptEleNo; i++) {
SelectedContacts.push_back(OptimalContactQueue.top().second);
OptimalContactQueue.pop();
}
}
Vector3Writer(CandidateContacts, "OptimalContact");
Vector3Writer(CandidateContactWeights, "OptimalContactWeights");
SimParaObj.DataRecorderObj.setCCSData(CandidateContacts, CandidateContactWeights, SelectedContacts);
return SelectedContacts;
}
std::vector<Vector3> OptimalContactSearcher(const Robot & SimRobotInner, const PIPInfo & PIPObj, const ContactForm & ContactFormObj, SimPara & SimParaObj, Config & UpdatedConfig, double ForwardTime){
std::vector<Vector3> OptimalContact;
Vector3 COMPos, COMVel;
getCentroidalState(SimRobotInner, COMPos, COMVel);
InvertedPendulumInfo InvertedPendulumObj(PIPObj.L, PIPObj.g, PIPObj.theta, PIPObj.thetadot, COMPos, COMVel);
InvertedPendulumObj.setEdges(PIPObj.edge_a, PIPObj.edge_b);
bool TouchDownFlag, PenetrationFlag;
Robot SimRobot = SimRobotInner;
UpdatedConfig = WholeBodyDynamicsIntegrator(SimRobot, SimParaObj.getSwingLinkInfoIndex(),
InvertedPendulumObj, ForwardTime,
TouchDownFlag, PenetrationFlag);
SimRobot.UpdateConfig(UpdatedConfig);
COMPos = InvertedPendulumObj.COMPos;
COMVel = InvertedPendulumObj.COMVel;
// std::string ConfigPath = "./";
// std::string OptConfigFile = "UpdatedConfigContactSearch.config";
// RobotConfigWriter(UpdatedConfig, ConfigPath, OptConfigFile);
// 0. Reachable with respect to the pivotal joint
std::vector<Vector3> ReachableContacts = ReachabilityMapObj.ReachablePointsFinder(SimRobot, ContactFormObj.SwingLinkInfoIndex, SDFInfoObj);
if(!ReachableContacts.size()){
std::printf("ReachableContacts Size Zero!\n");
return OptimalContact;
}
// 1. Self-collision from other end effectors
std::vector<std::pair<Vector3, double>> ContactFreeInfoVec = ContactFreeInfoFn(SimRobot, ContactFormObj.FixedContactStatusInfo);
std::vector<Vector3> CollisionFreeContacts = ReachabilityMapObj.ContactFreePointsFinder(ReachabilityMapObj.EndEffectorGeometryRadius[ContactFormObj.SwingLinkInfoIndex], ReachableContacts, ContactFreeInfoVec);
if(!CollisionFreeContacts.size()){
std::printf("CollisionFreeContacts Size Zero!\n");
return OptimalContact;
}
// 2. Supportive
std::vector<Vector3> SupportiveContacts = SupportContactFinder(PIPObj, CollisionFreeContacts);
if(!SupportiveContacts.size()){
std::printf("SupportiveContacts Size Zero!\n");
return OptimalContact;
}
SimParaObj.DataRecorderObj.setRCSData(ReachableContacts, CollisionFreeContacts, SupportiveContacts);
Vector3Writer(ReachableContacts, "ReachableContacts");
Vector3Writer(CollisionFreeContacts, "CollisionFreeContacts");
Vector3Writer(SupportiveContacts, "SupportiveContacts");
std::vector<Vector3> FixedContactPos;
for (int i = 0; i < LinkInfoObj.size(); i++){
for (int j = 0; j < LinkInfoObj[i].LocalContacts.size(); j++){
if(ContactFormObj.FixedContactStatusInfo[i].LocalContactStatus[j]){
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(LinkInfoObj[i].LocalContacts[j], LinkInfoObj[i].LinkIndex, LinkiPjPos);
FixedContactPos.push_back(LinkiPjPos);
}
}
}
// 3. Optimal Contact
int CutOffNo = 5;
OptimalContact = OptimalContactFinder(SupportiveContacts, FixedContactPos, COMPos, COMVel, CutOffNo, SimParaObj);
if(!OptimalContact.size()){
std::printf("OptimalContact Size Zero!\n");
return OptimalContact;
}
return OptimalContact;
} | 45.785311 | 222 | 0.74272 | ShihaoWang |
24faa860c54e73e6cfb94c387fb5968c6e320630 | 878 | cpp | C++ | algorithms/cpp/134.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/134.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/134.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int len = gas.size();
int tank = 0, start = 0;
for ( int cur = 0; cur < start+len; cur++ )
{
tank += gas[cur%len]-cost[cur%len];
while ( start < len && tank < 0 )
{
tank -= gas[start]-cost[start];
start++;
}
if ( start == len )
return -1;
}
return start;
}
};
int main()
{
int gasarr[] = {2,4}, costarr[] = {3,4};
vector<int> gas(gasarr, gasarr+sizeof(gasarr)/sizeof(gasarr[0]));
vector<int> cost(costarr, costarr+sizeof(costarr)/sizeof(costarr[0]));
Solution solution;
cout << solution.canCompleteCircuit(gas, cost) << endl;
return 0;
}
| 24.388889 | 74 | 0.512528 | viing937 |
24faecdf69e9cb2a9a9a76567079c752184286af | 27,128 | cpp | C++ | src/Kiln.cpp | 0xc0dec/kiln | 4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5 | [
"MIT"
] | null | null | null | src/Kiln.cpp | 0xc0dec/kiln | 4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5 | [
"MIT"
] | null | null | null | src/Kiln.cpp | 0xc0dec/kiln | 4fbaf31a2f9e07f1dca7af2bed86f479e0079fa5 | [
"MIT"
] | null | null | null | // TODO Refactor ImageData/Font using pointers avoiding pimpl
// TODO Font geometry and rendering
// TODO Use shaderc (see Granite project on Github)
/*
Copyright (c) Aleksey Fedotov
MIT license
*/
#include "Input.h"
#include "FileSystem.h"
#include "Spectator.h"
#include "Camera.h"
#include "Window.h"
#include "ImageData.h"
#include "MeshData.h"
#include "Font.h"
#include "Vulkan/Vulkan.h"
#include "Vulkan/VulkanDevice.h"
#include "Vulkan/VulkanRenderPass.h"
#include "Vulkan/VulkanSwapchain.h"
#include "Vulkan/VulkanDescriptorPool.h"
#include "Vulkan/VulkanBuffer.h"
#include "Vulkan/VulkanPipeline.h"
#include "Vulkan/VulkanDescriptorSetLayoutBuilder.h"
#include "Vulkan/VulkanImage.h"
#include "Vulkan/VulkanDescriptorSetUpdater.h"
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.inl>
#include <glm/gtc/matrix_transform.inl>
#include <vector>
static const std::vector<float> xAxisVertexData =
{
0, 0, 0,
1, 0, 0
};
static const std::vector<float> yAxisVertexData =
{
0, 0, 0,
0, 1, 0
};
static const std::vector<float> zAxisVertexData =
{
0, 0, 0,
0, 0, 1
};
static const std::vector<float> quadVertexData =
{
1, 1, 0, 1, 0,
-1, 1, 0, 0, 0,
-1, -1, 0, 0, 1,
1, 1, 0, 1, 0,
-1, -1, 0, 0, 1,
1, -1, 0, 1, 1
};
class Scene
{
public:
Scene(const vk::Device &device)
{
viewMatricesBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(viewMatrices));
descPool = vk::DescriptorPool(device, 20, vk::DescriptorPoolConfig()
.forDescriptors(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 20)
.forDescriptors(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 20));
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.build();
descSet = descPool.allocateSet(descSetLayout);
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, descSet, viewMatricesBuffer, 0, sizeof(viewMatrices))
.updateSets();
}
void update(const Camera &cam)
{
viewMatrices.proj = cam.getProjectionMatrix();
viewMatrices.view = cam.getViewMatrix();
viewMatricesBuffer.update(&viewMatrices);
}
auto getDescPool() -> vk::DescriptorPool& { return descPool; }
auto getDescSetLayout() const -> VkDescriptorSetLayout { return descSetLayout; }
auto getDescSet() const -> VkDescriptorSet { return descSet; }
private:
vk::DescriptorPool descPool;
vk::Resource<VkDescriptorSetLayout> descSetLayout;
VkDescriptorSet descSet;
struct
{
glm::mat4 proj;
glm::mat4 view;
} viewMatrices;
vk::Buffer viewMatricesBuffer;
};
class Offscreen
{
public:
Offscreen(const vk::Device &device, uint32_t canvasWidth, uint32_t canvasHeight)
{
colorAttachment = vk::Image(device, canvasWidth, canvasHeight, 1, 1,
VK_FORMAT_R8G8B8A8_UNORM,
0,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_ASPECT_COLOR_BIT);
depthAttachment = vk::Image(device, canvasWidth, canvasHeight, 1, 1,
device.getDepthFormat(),
0,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
renderPass = vk::RenderPass(device, vk::RenderPassConfig()
.withColorAttachment(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, true, {0, 1, 1, 0})
.withDepthAttachment(device.getDepthFormat(), true, {1, 0}));
frameBuffer = createFrameBuffer(device, colorAttachment.getView(),
depthAttachment.getView(), renderPass, canvasWidth, canvasHeight);
semaphore = createSemaphore(device);
commandBuffer = createCommandBuffer(device, device.getCommandPool());
}
auto getColorAttachment() -> vk::Image& { return colorAttachment; }
auto getRenderPass() -> vk::RenderPass& { return renderPass; }
auto getSemaphore() -> vk::Resource<VkSemaphore>& { return semaphore; }
auto getCommandBuffer() -> vk::Resource<VkCommandBuffer>& { return commandBuffer; }
auto getFrameBuffer() const -> VkFramebuffer { return frameBuffer; }
private:
vk::Image colorAttachment;
vk::Image depthAttachment;
vk::Resource<VkFramebuffer> frameBuffer;
vk::RenderPass renderPass;
vk::Resource<VkSemaphore> semaphore;
vk::Resource<VkCommandBuffer> commandBuffer;
};
class Mesh
{
public:
Mesh(const vk::Device &device, VkRenderPass renderPass, Scene &scene):
globalDescSet(scene.getDescSet())
{
auto vsSrc = fs::readBytes("../../assets/shaders/Mesh.vert.spv");
auto fsSrc = fs::readBytes("../../assets/shaders/Mesh.frag.spv");
auto vs = createShader(device, vsSrc.data(), vsSrc.size());
auto fs = createShader(device, fsSrc.data(), fsSrc.size());
glm::mat4 modelMatrix{};
modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4));
modelMatrixBuffer.update(&modelMatrix);
auto data = MeshData::load("../../assets/meshes/Teapot.obj");
vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * data.getVertexData().size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, data.getVertexData().data());
indexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(uint32_t) * data.getIndexData().size(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT, data.getIndexData().data());
indexCount = data.getIndexData().size();
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT)
.build();
pipeline = vk::Pipeline(device, renderPass, vk::PipelineConfig(vs, fs)
.withDescriptorSetLayout(scene.getDescSetLayout())
.withDescriptorSetLayout(descSetLayout)
.withFrontFace(VK_FRONT_FACE_CLOCKWISE)
.withCullMode(VK_CULL_MODE_NONE)
.withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)
.withVertexFormat(data.getFormat()));
descSet = scene.getDescPool().allocateSet(descSetLayout);
const auto textureData = ImageData::load2D("../../assets/textures/Cobblestone.png");
texture = vk::Image::create2D(device, textureData);
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forTexture(1, descSet, texture.getView(), texture.getSampler(), texture.getLayout())
.updateSets();
}
void render(VkCommandBuffer buf)
{
VkBuffer vertexBuffer = this->vertexBuffer;
VkDeviceSize vertexBufferOffset = 0;
std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet};
vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, &vertexBuffer, &vertexBufferOffset);
vkCmdBindIndexBuffer(buf, indexBuffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(buf, indexCount, 1, 0, 0, 0);
}
private:
vk::Resource<VkDescriptorSetLayout> descSetLayout;
vk::Pipeline pipeline;
vk::Image texture;
vk::Buffer modelMatrixBuffer;
vk::Buffer vertexBuffer;
vk::Buffer indexBuffer;
uint32_t indexCount;
VkDescriptorSet descSet;
VkDescriptorSet globalDescSet;
};
class PostProcessor
{
public:
PostProcessor(const vk::Device &device, Offscreen &offscreen, Scene &scene)
{
auto vsSrc = fs::readBytes("../../assets/shaders/PostProcess.vert.spv");
auto fsSrc = fs::readBytes("../../assets/shaders/PostProcess.frag.spv");
const auto vs = createShader(device, vsSrc.data(), vsSrc.size());
const auto fs = createShader(device, fsSrc.data(), fsSrc.size());
vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * quadVertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, quadVertexData.data());
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT)
.build();
pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs)
.withDepthTest(false, false)
.withDescriptorSetLayout(descSetLayout)
.withFrontFace(VK_FRONT_FACE_CLOCKWISE)
.withCullMode(VK_CULL_MODE_NONE)
.withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)
.withVertexFormat(VertexFormat{{3, 2}}));
descSet = scene.getDescPool().allocateSet(descSetLayout);
auto &colorAttachment = offscreen.getColorAttachment();
vk::DescriptorSetUpdater(device)
.forTexture(0, descSet, colorAttachment.getView(), colorAttachment.getSampler(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
.updateSets();
}
void render(VkCommandBuffer buf)
{
std::vector<VkBuffer> vertexBuffers = {vertexBuffer};
std::vector<VkDeviceSize> vertexBufferOffsets = {0};
std::vector<VkDescriptorSet> descSets = {descSet};
vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 1, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data());
vkCmdDraw(buf, 6, 1, 0, 0);
}
private:
vk::Resource<VkDescriptorSetLayout> descSetLayout;
vk::Pipeline pipeline;
vk::Image texture;
vk::Buffer modelMatrixBuffer;
vk::Buffer vertexBuffer;
VkDescriptorSet descSet;
};
class Skybox
{
public:
Skybox(const vk::Device &device, Offscreen &offscreen, Scene &scene):
globalDescSet(scene.getDescSet())
{
auto vsSrc = fs::readBytes("../../assets/shaders/Skybox.vert.spv");
auto fsSrc = fs::readBytes("../../assets/shaders/Skybox.frag.spv");
const auto vs = createShader(device, vsSrc.data(), vsSrc.size());
const auto fs = createShader(device, fsSrc.data(), fsSrc.size());
glm::mat4 modelMatrix{};
modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4));
modelMatrixBuffer.update(&modelMatrix);
vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * quadVertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, quadVertexData.data());
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT)
.build();
pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs)
.withDepthTest(false, false)
.withDescriptorSetLayout(scene.getDescSetLayout())
.withDescriptorSetLayout(descSetLayout)
.withFrontFace(VK_FRONT_FACE_CLOCKWISE)
.withCullMode(VK_CULL_MODE_NONE)
.withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)
.withVertexBinding(0, sizeof(float) * 5, VK_VERTEX_INPUT_RATE_VERTEX)
.withVertexAttribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0)
.withVertexAttribute(1, 0, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3));
descSet = scene.getDescPool().allocateSet(descSetLayout);
const auto data = ImageData::loadCube("../../assets/textures/Cubemap_space.ktx");
texture = vk::Image::createCube(device, data);
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forTexture(1, descSet, texture.getView(), texture.getSampler(), texture.getLayout())
.updateSets();
}
void render(VkCommandBuffer buf)
{
std::vector<VkBuffer> vertexBuffers = {vertexBuffer};
std::vector<VkDeviceSize> vertexBufferOffsets = {0};
std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet};
vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data());
vkCmdDraw(buf, 6, 1, 0, 0);
}
private:
vk::Resource<VkDescriptorSetLayout> descSetLayout;
vk::Pipeline pipeline;
vk::Image texture;
vk::Buffer modelMatrixBuffer;
vk::Buffer vertexBuffer;
VkDescriptorSet descSet;
VkDescriptorSet globalDescSet;
};
class Axes
{
public:
Axes(const vk::Device &device, Offscreen &offscreen, Scene &scene):
globalDescSet(scene.getDescSet())
{
Transform t;
t.setLocalPosition({3, 0, 3});
auto modelMatrix = t.getWorldMatrix();
modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4));
modelMatrixBuffer.update(&modelMatrix);
glm::vec3 red{1.0f, 0, 0};
redColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3));
redColorUniformBuffer.update(&red);
glm::vec3 green{0, 1.0f, 0};
greenColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3));
greenColorUniformBuffer.update(&green);
glm::vec3 blue{0, 0, 1.0f};
blueColorUniformBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::vec3));
blueColorUniformBuffer.update(&blue);
auto vsSrc = fs::readBytes("../../assets/shaders/Axis.vert.spv");
auto fsSrc = fs::readBytes("../../assets/shaders/Axis.frag.spv");
const auto vs = createShader(device, vsSrc.data(), vsSrc.size());
const auto fs = createShader(device, fsSrc.data(), fsSrc.size());
xAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * xAxisVertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, xAxisVertexData.data());
yAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * yAxisVertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, yAxisVertexData.data());
zAxisVertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * zAxisVertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, zAxisVertexData.data());
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.withBinding(1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.build();
pipeline = vk::Pipeline(device, offscreen.getRenderPass(), vk::PipelineConfig(vs, fs)
.withDescriptorSetLayout(scene.getDescSetLayout())
.withDescriptorSetLayout(descSetLayout)
.withFrontFace(VK_FRONT_FACE_CLOCKWISE)
.withCullMode(VK_CULL_MODE_NONE)
.withTopology(VK_PRIMITIVE_TOPOLOGY_LINE_LIST)
.withVertexBinding(0, sizeof(float) * 3, VK_VERTEX_INPUT_RATE_VERTEX)
.withVertexAttribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0));
redDescSet = scene.getDescPool().allocateSet(descSetLayout);
greenDescSet = scene.getDescPool().allocateSet(descSetLayout);
blueDescSet = scene.getDescPool().allocateSet(descSetLayout);
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, redDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forUniformBuffer(1, redDescSet, redColorUniformBuffer, 0, sizeof(glm::vec3))
.updateSets();
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, greenDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forUniformBuffer(1, greenDescSet, greenColorUniformBuffer, 0, sizeof(glm::vec3))
.updateSets();
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, blueDescSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forUniformBuffer(1, blueDescSet, blueColorUniformBuffer, 0, sizeof(glm::vec3))
.updateSets();
}
void render(VkCommandBuffer buf)
{
vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
std::vector<VkDescriptorSet> descSets = {globalDescSet, redDescSet};
std::vector<VkDeviceSize> vertexBufferOffsets = {0};
// TODO bind all at once
std::vector<VkBuffer> vertexBuffers = {xAxisVertexBuffer};
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data());
vkCmdDraw(buf, 4, 1, 0, 0);
vertexBuffers[0] = yAxisVertexBuffer;
descSets[1] = greenDescSet;
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data());
vkCmdDraw(buf, 4, 1, 0, 0);
vertexBuffers[0] = zAxisVertexBuffer;
descSets[1] = blueDescSet;
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, vertexBuffers.data(), vertexBufferOffsets.data());
vkCmdDraw(buf, 4, 1, 0, 0);
}
private:
vk::Resource<VkDescriptorSetLayout> descSetLayout;
vk::Pipeline pipeline;
vk::Buffer redColorUniformBuffer;
vk::Buffer greenColorUniformBuffer;
vk::Buffer blueColorUniformBuffer;
vk::Buffer xAxisVertexBuffer;
vk::Buffer yAxisVertexBuffer;
vk::Buffer zAxisVertexBuffer;
vk::Buffer modelMatrixBuffer;
VkDescriptorSet redDescSet;
VkDescriptorSet greenDescSet;
VkDescriptorSet blueDescSet;
VkDescriptorSet globalDescSet;
};
class Label
{
public:
Label(const vk::Device &device, const std::string &text, VkRenderPass renderPass, Scene &scene):
globalDescSet(scene.getDescSet())
{
const auto fontData = fs::readBytes("../../assets/Aller.ttf");
font = Font::createTrueType(device, fontData, 100, 2048, 2048, ' ', '~' - ' ', 2, 2);
std::vector<float> vertexData;
std::vector<uint32_t> indexData;
uint16_t lastIndex = 0;
float offsetX = 0, offsetY = 0;
for (auto c : text)
{
const auto glyphInfo = font.getGlyphInfo(c, offsetX, offsetY);
offsetX = glyphInfo.offsetX;
offsetY = glyphInfo.offsetY;
vertexData.push_back(glyphInfo.positions[0].x);
vertexData.push_back(glyphInfo.positions[0].y);
vertexData.push_back(glyphInfo.positions[0].z);
vertexData.push_back(glyphInfo.uvs[0].x);
vertexData.push_back(glyphInfo.uvs[0].y);
vertexData.push_back(glyphInfo.positions[1].x);
vertexData.push_back(glyphInfo.positions[1].y);
vertexData.push_back(glyphInfo.positions[1].z);
vertexData.push_back(glyphInfo.uvs[1].x);
vertexData.push_back(glyphInfo.uvs[1].y);
vertexData.push_back(glyphInfo.positions[2].x);
vertexData.push_back(glyphInfo.positions[2].y);
vertexData.push_back(glyphInfo.positions[2].z);
vertexData.push_back(glyphInfo.uvs[2].x);
vertexData.push_back(glyphInfo.uvs[2].y);
vertexData.push_back(glyphInfo.positions[3].x);
vertexData.push_back(glyphInfo.positions[3].y);
vertexData.push_back(glyphInfo.positions[3].z);
vertexData.push_back(glyphInfo.uvs[3].x);
vertexData.push_back(glyphInfo.uvs[3].y);
indexData.push_back(lastIndex);
indexData.push_back(lastIndex + 1);
indexData.push_back(lastIndex + 2);
indexData.push_back(lastIndex);
indexData.push_back(lastIndex + 2);
indexData.push_back(lastIndex + 3);
lastIndex += 4;
}
auto vsSrc = fs::readBytes("../../assets/shaders/Font.vert.spv");
auto fsSrc = fs::readBytes("../../assets/shaders/Font.frag.spv");
const auto vs = createShader(device, vsSrc.data(), vsSrc.size());
const auto fs = createShader(device, fsSrc.data(), fsSrc.size());
Transform t;
t.setLocalScale({0.05f, 0.05f, 0.05f});
t.setLocalPosition({0, 0, 4});
auto modelMatrix = t.getWorldMatrix();
modelMatrixBuffer = vk::Buffer::createUniformHostVisible(device, sizeof(glm::mat4));
modelMatrixBuffer.update(&modelMatrix);
vertexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(float) * vertexData.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexData.data());
indexBuffer = vk::Buffer::createDeviceLocal(device, sizeof(uint32_t) * indexData.size(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT, indexData.data());
indexCount = indexData.size();
descSetLayout = vk::DescriptorSetLayoutBuilder(device)
.withBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL_GRAPHICS)
.withBinding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT)
.build();
const auto vf = VertexFormat({3, 2});
pipeline = vk::Pipeline(device, renderPass, vk::PipelineConfig(vs, fs)
.withDescriptorSetLayout(scene.getDescSetLayout())
.withDescriptorSetLayout(descSetLayout)
.withFrontFace(VK_FRONT_FACE_CLOCKWISE)
.withCullMode(VK_CULL_MODE_NONE)
.withBlend(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE)
.withTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)
.withVertexFormat(vf));
descSet = scene.getDescPool().allocateSet(descSetLayout);
vk::DescriptorSetUpdater(device)
.forUniformBuffer(0, descSet, modelMatrixBuffer, 0, sizeof(modelMatrix))
.forTexture(1, descSet, font.getAtlas().getView(), font.getAtlas().getSampler(), font.getAtlas().getLayout())
.updateSets();
}
void render(VkCommandBuffer buf)
{
VkBuffer vertexBuffer = this->vertexBuffer;
VkDeviceSize vertexBufferOffset = 0;
std::vector<VkDescriptorSet> descSets = {globalDescSet, descSet};
vkCmdBindPipeline(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
vkCmdBindDescriptorSets(buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.getLayout(), 0, 2, descSets.data(), 0, nullptr);
vkCmdBindVertexBuffers(buf, 0, 1, &vertexBuffer, &vertexBufferOffset);
vkCmdBindIndexBuffer(buf, indexBuffer, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(buf, indexCount, 1, 0, 0, 0);
}
private:
Font font;
vk::Resource<VkDescriptorSetLayout> descSetLayout;
vk::Pipeline pipeline;
vk::Image texture;
vk::Buffer modelMatrixBuffer;
vk::Buffer vertexBuffer;
vk::Buffer indexBuffer;
uint32_t indexCount;
VkDescriptorSet descSet;
VkDescriptorSet globalDescSet;
};
int main()
{
const uint32_t canvasWidth = 1366;
const uint32_t canvasHeight = 768;
Window window{canvasWidth, canvasHeight, "Demo"};
auto device = vk::Device::create(window.getPlatformHandle());
auto swapchain = vk::Swapchain(device, canvasWidth, canvasHeight, false);
Camera cam;
cam.setPerspective(glm::radians(45.0f), canvasWidth / (canvasHeight * 1.0f), 0.01f, 100);
cam.getTransform().setLocalPosition({10, -5, 10});
cam.getTransform().lookAt({0, 0, 0}, {0, 1, 0});
Scene scene{device};
Offscreen offscreen{device, canvasWidth, canvasHeight};
Mesh mesh{device, offscreen.getRenderPass(), scene};
PostProcessor postProcessor{device, offscreen, scene};
Skybox skybox{device, offscreen, scene};
Axes axes{device, offscreen, scene};
Label label{device, "Test", offscreen.getRenderPass(), scene};
// Record command buffers
{
const VkCommandBuffer buf = offscreen.getCommandBuffer();
vk::beginCommandBuffer(buf, false);
offscreen.getRenderPass().begin(buf, offscreen.getFrameBuffer(), canvasWidth, canvasHeight);
auto vp = VkViewport{0, 0, canvasWidth, canvasHeight, 0, 1};
vkCmdSetViewport(buf, 0, 1, &vp);
VkRect2D scissor{{0, 0}, {vp.width, vp.height}};
vkCmdSetScissor(buf, 0, 1, &scissor);
skybox.render(buf);
axes.render(buf);
mesh.render(buf);
label.render(buf);
offscreen.getRenderPass().end(buf);
KL_VK_CHECK_RESULT(vkEndCommandBuffer(buf));
}
swapchain.recordCommandBuffers([&](VkFramebuffer fb, VkCommandBuffer buf)
{
swapchain.getRenderPass().begin(buf, fb, canvasWidth, canvasHeight);
auto vp = VkViewport{0, 0, static_cast<float>(canvasWidth), static_cast<float>(canvasHeight), 0, 1};
vkCmdSetViewport(buf, 0, 1, &vp);
VkRect2D scissor{{0, 0}, {vp.width, vp.height}};
vkCmdSetScissor(buf, 0, 1, &scissor);
postProcessor.render(buf);
swapchain.getRenderPass().end(buf);
});
// Main loop
Input input;
while (!window.closeRequested() && !input.isKeyPressed(SDLK_ESCAPE, true))
{
window.beginUpdate(input);
const auto dt = window.getTimeDelta();
applySpectator(cam.getTransform(), input, dt, 1, 5);
scene.update(cam);
auto presentCompleteSemaphore = swapchain.acquireNext();
vk::queueSubmit(device.getQueue(), 1, &presentCompleteSemaphore, 1, &offscreen.getSemaphore(), 1, &offscreen.getCommandBuffer());
swapchain.presentNext(device.getQueue(), 1, &offscreen.getSemaphore());
KL_VK_CHECK_RESULT(vkQueueWaitIdle(device.getQueue()));
window.endUpdate();
}
return 0;
}
| 40.855422 | 138 | 0.656812 | 0xc0dec |
7000baede852b6a9e293ddfe18e4980ef432280e | 7,458 | cpp | C++ | src/colin_main.cpp | ferhatgec/colin | d0502da986198869765e3d98b5c6928292095658 | [
"MIT"
] | 4 | 2021-03-30T00:33:39.000Z | 2021-04-08T20:56:33.000Z | src/colin_main.cpp | ferhatgec/colin | d0502da986198869765e3d98b5c6928292095658 | [
"MIT"
] | null | null | null | src/colin_main.cpp | ferhatgec/colin | d0502da986198869765e3d98b5c6928292095658 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
// Distributed under the terms of the MIT License.
//
//
#include "../include/colin_main.hpp"
#define TABLE_LIGHT_GRAY() \
std::cout << \
this->light_gray << \
this->table_item << \
this->white << \
this->table_item << \
this->reset;
#define TABLE_WHITE() \
std::cout << \
this->white << \
this->table_item << \
this->light_gray << \
this->table_item << \
this->reset;
#define TABLE_COLOR() \
std::cout << \
this->color_data << \
this->table_item << \
this->reset;
void Colin::InitColorName() noexcept {
auto iter = this->color_names.find(
std::to_string(this->r) +
"," +
std::to_string(this->g) +
"," +
std::to_string(this->b));
if(iter != this->color_names.end()) {
this->color_name = iter->second;
}
else {
this->color_name = "hmmm?";
}
}
std::string Colin::SetColor(u32 r, u32 g, u32 b) noexcept {
return this->color +
std::to_string(r) +
";" +
std::to_string(g) +
";" +
std::to_string(b) +
"m";
}
std::string Colin::SetFgColor(u32 r, u32 g, u32 b) noexcept {
return "\033[38;2;" +
std::to_string(r) +
";" +
std::to_string(g) +
";" +
std::to_string(b) +
"m";
}
void Colin::Newline() {
if(this->line < this->infos.size()) {
std::cout << " " << this->infos[this->line];
switch(this->line) {
case InfoType::Name: {
std::cout << this->color_name;
break;
}
case InfoType::Rgb: {
std::cout <<
this->pink +
"rgb" +
this->reset +
"("
"\033[0;31m" <<
this->r <<
", \033[0;32m" <<
this->g <<
", \033[0;34m" <<
this->b <<
this->reset +
")";
break;
}
case InfoType::Hex: {
std::cout << this->hex;
break;
}
case InfoType::Cmyk: {
std::cout <<
"("
"\033[0;31m" +
std::get<0>(this->cmyk)+
this->reset +
", \033[0;32m" +
std::get<1>(this->cmyk)+
", \033[0;34m" +
std::get<2>(this->cmyk)+
", " +
this->pink +
std::get<3>(this->cmyk)+
")";
break;
}
case InfoType::Hsl: {
std::cout <<
"("
"\033[0;31m" +
std::get<0>(this->hsl)+
this->reset +
", \033[0;32m" +
std::get<1>(this->hsl)+
", \033[0;34m" +
std::get<2>(this->hsl)+
")";
break;
}
case InfoType::Hsv: {
std::cout <<
"("
"\033[0;31m" +
std::get<0>(this->hsv) +
this->reset +
", \033[0;32m" +
std::get<1>(this->hsv) +
", \033[0;34m" +
std::get<2>(this->hsv) +
")";
break;
}
case InfoType::Ascii: {
std::cout << "\\033" + this->color_data.erase(0, 1);
break;
}
case InfoType::Esc: {
std::cout << "\\033";
break;
}
}
++this->line;
}
std::cout << '\n';
}
void Colin::Init(Color color) noexcept {
this->r = color.r;
this->g = color.g;
this->b = color.b;
this->color_data = SetColor(color.r, color.g, color.b);
this->infos[Name] = "\033[38;2;" +
std::to_string(this->r)+
";" +
std::to_string(this->g)+
";" +
std::to_string(this->b)+
"m" +
"color\033[0m: ";
this->infos[Hex] = this->red +
"hex : " +
this->orange +
this->hex;
this->infos[Cmyk] = this->orange +
"cmyk : " +
this->yellow;
this->infos[Hsl] = this->yellow +
"hsl : " +
this->green;
this->infos[Hsv] = this->green +
"hsv : " +
this->blue;
this->infos[Ascii] = this->blue +
"ascii: " +
this->purple;
this->infos[Esc] =this->purple+
"esc : " +
this->pink;
this->hex = this->converter.ToHex (this->r, this->g, this->b);
this->cmyk= this->converter.ToCMYK(this->r, this->g, this->b);
this->hsl = this->converter.ToHSL (this->r, this->g, this->b);
this->hsv = this->converter.ToHSV (this->r, this->g, this->b);
InitColorName();
}
void Colin::PrintColorBox(bool split) noexcept {
if(split) {
TABLE_LIGHT_GRAY()
}
else {
TABLE_WHITE ()
}
for(unsigned i = 0; i <= 7; i++) {
TABLE_COLOR()
}
if(!split) {
TABLE_LIGHT_GRAY()
}
else {
TABLE_WHITE ()
}
this->Newline();
}
void Colin::PrintBox() noexcept {
unsigned i;
bool split;
for(i = 0; i <= 5; i++) {
TABLE_LIGHT_GRAY()
}
this->Newline();
for(i = 0; i <= 5; i++) {
TABLE_WHITE ()
}
this->Newline();
for(i = 0, split = false; i < 6; i++) {
PrintColorBox(split);
split = !split;
}
for(unsigned i = 0; i <= 5; i++) {
TABLE_LIGHT_GRAY()
}
this->Newline();
for(unsigned i = 0; i <= 5; i++) {
TABLE_WHITE()
}
this->Newline();
}
int main(int argc, char** argv) {
if(argc < 4) {
std::cout <<
"Fegeya Colin : CLI color info tool"
"\n"
"--"
"\n" <<
argv[0]<<
" {r} {g} {b}"
"\n"
"-------"
"\n" <<
argv[0]<<
" 255 255 255"
"\n";
return 1;
}
Colin test;
std::vector<u32> color;
for(unsigned i = 1; i < argc; i++) {
color.push_back(std::stoi(argv[i]));
}
test.Init(Color{color[0], color[1], color[2]});
// ^^^^^^^^ ^^^^^^^^ ^^^^^^^^
// r g b
test.PrintBox();
return 0;
} | 24.058065 | 68 | 0.345267 | ferhatgec |
70053f070cef049d40b9d50d3bd58b4823cafb54 | 1,978 | cpp | C++ | test/main_gtest.cpp | Ali2500/nao_whole_body_ik | 5955415c6a248eda2343098407ef0c080b7d60ec | [
"BSD-2-Clause"
] | null | null | null | test/main_gtest.cpp | Ali2500/nao_whole_body_ik | 5955415c6a248eda2343098407ef0c080b7d60ec | [
"BSD-2-Clause"
] | null | null | null | test/main_gtest.cpp | Ali2500/nao_whole_body_ik | 5955415c6a248eda2343098407ef0c080b7d60ec | [
"BSD-2-Clause"
] | null | null | null | #include "database_reader_test.h"
#include "whole_body_ik_solver_test.h"
nao_whole_body_ik::DatabaseReader2Ptr database_reader;
TEST_F(DatabaseReaderTest, databaseLoadingTest)
{
ASSERT_TRUE(databaseLoadTest());
}
TEST_F(DatabaseReaderTest, DefaultValuesRightArmKNNTest)
{
ASSERT_TRUE(knnDifferenceDefaultPositionRightArm());
}
TEST_F(DatabaseReaderTest, DefaultValuesLeftArmKNNTest)
{
ASSERT_TRUE(knnDifferenceDefaultPositionLeftArm());
}
TEST_F(DatabaseReaderTest, RandomValuesRightArmKNNTest)
{
ASSERT_TRUE(knnDifferenceRandomPositionRightArm());
}
TEST_F(DatabaseReaderTest, RandomValuesLeftArmKNNTest)
{
ASSERT_TRUE(knnDifferenceRandomPositionLeftArm());
}
TEST_F(WholeBodyIKSolverTest, RightArmIKFromDatabaseTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::RIGHT_ARM_ONLY);
ASSERT_TRUE(rightArmIKFromDatabaseTest());
}
TEST_F(WholeBodyIKSolverTest, RightArmIKFromSeedTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::RIGHT_ARM_ONLY);
ASSERT_TRUE(rightArmIKSeedTest());
}
TEST_F(WholeBodyIKSolverTest, LeftArmIKFromDatabaseTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::LEFT_ARM_ONLY);
ASSERT_TRUE(leftArmIKFromDatabaseTest());
}
TEST_F(WholeBodyIKSolverTest, LeftArmIKFromSeedTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::LEFT_ARM_ONLY);
ASSERT_TRUE(leftArmIKSeedTest());
}
TEST_F(WholeBodyIKSolverTest, BothArmsIKFromDatabaseTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::BOTH_ARMS);
ASSERT_TRUE(bothArmsIKFromDatabaseTest());
}
TEST_F(WholeBodyIKSolverTest, BothArmsIKFromSeedTest)
{
SetUp(database_reader, nao_whole_body_ik::NaoWholeBodyKinematics::BOTH_ARMS);
ASSERT_TRUE(bothArmsIKSeedTest());
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "gtest_node");
int return_code RUN_ALL_TESTS();
ros::shutdown();
return return_code;
}
| 26.026316 | 84 | 0.822042 | Ali2500 |
7006c26b1c4d19162f5f98022c7e12137e9a43ab | 4,872 | hpp | C++ | capo/sequence.hpp | mutouyun/capo | d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13 | [
"MIT"
] | 58 | 2015-03-22T03:26:07.000Z | 2022-03-30T05:15:22.000Z | capo/sequence.hpp | mutouyun/capo | d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13 | [
"MIT"
] | 1 | 2019-03-07T12:32:41.000Z | 2019-03-16T15:01:55.000Z | capo/sequence.hpp | mutouyun/capo | d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13 | [
"MIT"
] | 21 | 2015-02-27T06:44:56.000Z | 2022-03-05T15:53:30.000Z | /*
The Capo Library
Code covered by the MIT License
Author: mutouyun (http://orzz.org)
*/
#pragma once
#include "capo/assert.hpp"
#include "capo/iterator.hpp"
#include <type_traits> // std::add_const, std::add_lvalue_reference
#include <tuple> // std::tuple, std::tie
#include <stdexcept> // std::logic_error
#include <utility> // std::forward, std::move, std::swap
#include <cstddef> // size_t
namespace capo {
namespace use {
////////////////////////////////////////////////////////////////
/// Sequence policies
////////////////////////////////////////////////////////////////
/*
Arithmetic sequence
*/
template <int D = 1>
struct arithmetic
{
enum { StateSize = 1 };
template <typename T> static void next(T& a) { a += D; }
template <typename T> static void prev(T& a) { a -= D; }
template <typename T> static void at(T& a1, size_t n)
{
CAPO_ASSERT_(n);
a1 += D * static_cast<T>(n - 1);
}
};
/*
Geometric sequence
*/
template <int Q = 2>
struct geometric
{
static_assert(Q != 0, "Q cannot be equal to 0!");
enum { StateSize = 1 };
template <typename T> static void next(T& a) { a *= Q; }
template <typename T> static void prev(T& a) { a /= Q; }
template <typename T> static void at(T& a1, size_t n)
{
CAPO_ASSERT_(n);
a1 *= power<T>(Q, n - 1);
}
private:
template <typename T> static T power(int x, size_t n)
{
if (n == 0) return 1;
if (x == 0 || x == 1) return x;
T k = 1;
while (n > 1)
{
if (n & 0x01) k *= x;
x *= x;
n >>= 1;
}
return k *= x;
}
};
/*
Fibonacci sequence
*/
struct fibonacci
{
enum { StateSize = 2 };
template <typename T> static void next(T& a1, T& a2)
{
std::swap(a1, a2);
a2 += a1;
}
template <typename T> static void prev(T& a1, T& a2)
{
std::swap(a1, a2);
a1 -= a2;
}
template <typename T> static void at(T& a0, T& a1, size_t n)
{
std::tie(a0, a1) = fib_two(a0, a1, n);
}
private:
template <typename T> static std::tuple<T, T>
fib_two(const T& a0, const T& a1, size_t n)
{
if (n == 1) return std::tuple<T, T>{ a1, a1 + a0 };
if (n == 0) return std::tuple<T, T>{ a0, a1 };
T i, j;
if (n & 0x01) /* F(2n + 1) */
{
std::tie(i, j) = fib_two(a0, a1, (n - 1) >> 1); // {F(n), F(n + 1)}
return std::tuple<T, T>
{
i * i + j * j, // F(2n + 1) = F(n) ^ 2 + F(n + 1) ^ 2
j * (i * 2 + j) // F(2n + 2) = F(n + 1) * (F(n) * 2 + F(n + 1))
};
}
else /* F(2n) */
{
std::tie(i, j) = fib_two(a0, a1, n >> 1); // {F(n), F(n + 1)}
return std::tuple<T, T>
{
i * (j * 2 - i), // F(2n) = F(n) * (F(n + 1) * 2 - F(n))
i * i + j * j // F(2n + 1) = F(n) ^ 2 + F(n + 1) ^ 2
};
}
}
};
} // namespace use
namespace detail_sequence {
////////////////////////////////////////////////////////////////
/// The impl class
////////////////////////////////////////////////////////////////
template <class PolicyT, typename T, class IterT = capo::iterator<PolicyT, T>>
class impl
{
public:
using iterator = IterT;
using const_iterator = const iterator;
using value_type = T;
using reference = typename std::add_lvalue_reference<T>::type;
using const_reference = typename std::add_lvalue_reference<typename std::add_const<T>::type>::type;
using size_type = typename iterator::size_type;
private:
size_type cur_begin_, cur_end_;
typename iterator::tp_t state_;
public:
template <typename... U>
impl(size_type begin, size_type end, U&&... args)
: cur_begin_(begin)
, cur_end_ (end)
, state_ (std::forward<U>(args)...)
{
CAPO_ENSURE_(cur_begin_ < cur_end_)(cur_begin_)(cur_end_)
.except(std::logic_error("End index must be greater than begin index."));
}
size_type size(void) const { return (cur_end_ - cur_begin_); }
const_iterator begin(void) const
{
return { state_, cur_begin_ };
}
const_iterator end(void) const
{
return { state_, cur_end_ };
}
};
} // namespace detail_sequence
////////////////////////////////////////////////////////////////
/// Make a sequence of [begin-index, end-index)
////////////////////////////////////////////////////////////////
template <class PolicyT, typename T, typename... U>
auto sequence(size_t begin, size_t end, U&&... args)
-> detail_sequence::impl<PolicyT, T>
{
return { begin, end, std::forward<U>(args)... };
}
} // namespace capo
| 24.984615 | 103 | 0.476396 | mutouyun |
701178a3f85e3f48ee623745c6709532f279d4f5 | 766 | cc | C++ | 2021_1004_1010/265.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | 2021_1004_1010/265.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | 2021_1004_1010/265.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
int n = costs.size();
int k = costs.at(0).size();
vector<vector<int>> dp(n, vector<int>(k,2021));
for (int i=0; i<k; ++i){
dp.at(n-1).at(i) = costs.at(n-1).at(i);
}
for (int i=n-2; i>=0; --i){
for (int j=0; j<k; ++j){
for (int t=0; t<k; ++t){
if (j!=t){
dp.at(i).at(j) = min(dp.at(i+1).at(t)+costs.at(i).at(j), dp.at(i).at(j));
}
}
}
}
int ans = INT_MAX;
for (int i=0; i<k; ++i){
ans = min(ans,dp.at(0).at(i));
}
return ans;
}
};
| 26.413793 | 97 | 0.353786 | guohaoqiang |
7011b277bf89acabd297d37e10d5f82c30fe0216 | 2,494 | cpp | C++ | tests/data/ModelProperty_Tests.cpp | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 71 | 2018-04-15T13:02:43.000Z | 2022-03-26T11:19:18.000Z | tests/data/ModelProperty_Tests.cpp | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 309 | 2018-04-15T12:10:59.000Z | 2022-01-22T20:13:04.000Z | tests/data/ModelProperty_Tests.cpp | Jamiras/RAIntegration | ccf3dea24d81aefdcf51535f073889d03272b259 | [
"MIT"
] | 17 | 2018-04-17T16:09:31.000Z | 2022-03-04T08:49:03.000Z | #include "data\ModelProperty.hh"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ra {
namespace data {
namespace tests {
TEST_CLASS(ModelProperty_Tests)
{
void AssertProperty(int nKey, const ModelPropertyBase* pExpected)
{
const ModelPropertyBase* pLookup = ModelPropertyBase::GetPropertyForKey(nKey);
if (pLookup != pExpected)
{
if (pExpected)
Assert::Fail(L"Found property when one wasn't expected");
else
Assert::Fail(L"Did not find expected property");
}
}
public:
TEST_METHOD(TestStringModelProperty)
{
int nKey;
{
StringModelProperty pProperty("Test", "Property", L"Default");
Assert::AreEqual("Test", pProperty.GetTypeName());
Assert::AreEqual("Property", pProperty.GetPropertyName());
Assert::AreEqual(std::wstring(L"Default"), pProperty.GetDefaultValue());
nKey = pProperty.GetKey();
AssertProperty(nKey, &pProperty);
pProperty.SetDefaultValue(L"New Default");
Assert::AreEqual(std::wstring(L"New Default"), pProperty.GetDefaultValue());
}
AssertProperty(nKey, nullptr);
}
TEST_METHOD(TestIntModelProperty)
{
int nKey;
{
IntModelProperty pProperty("Test", "Property", 8);
Assert::AreEqual("Test", pProperty.GetTypeName());
Assert::AreEqual("Property", pProperty.GetPropertyName());
Assert::AreEqual(8, pProperty.GetDefaultValue());
nKey = pProperty.GetKey();
AssertProperty(nKey, &pProperty);
pProperty.SetDefaultValue(13);
Assert::AreEqual(13, pProperty.GetDefaultValue());
}
AssertProperty(nKey, nullptr);
}
TEST_METHOD(TestBoolModelProperty)
{
int nKey;
{
BoolModelProperty pProperty("Test", "Property", true);
Assert::AreEqual("Test", pProperty.GetTypeName());
Assert::AreEqual("Property", pProperty.GetPropertyName());
Assert::AreEqual(true, pProperty.GetDefaultValue());
nKey = pProperty.GetKey();
AssertProperty(nKey, &pProperty);
pProperty.SetDefaultValue(false);
Assert::AreEqual(false, pProperty.GetDefaultValue());
}
AssertProperty(nKey, nullptr);
}
};
} // namespace tests
} // namespace ui
} // namespace ra
| 28.340909 | 88 | 0.60425 | Jamiras |
70150516962287d6c6cb22d764f61a1dbc4e9ec5 | 2,623 | hpp | C++ | include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/RootMotion/FinalIK/InteractionSystem_InteractionDelegate.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
// Including type: RootMotion.FinalIK.InteractionSystem
#include "RootMotion/FinalIK/InteractionSystem.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Skipping declaration: IntPtr because it is already included!
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
// Forward declaring type: FullBodyBipedEffector
struct FullBodyBipedEffector;
// Forward declaring type: InteractionObject
class InteractionObject;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Autogenerated type: RootMotion.FinalIK.InteractionSystem/InteractionDelegate
class InteractionSystem::InteractionDelegate : public System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x14391CC
static InteractionSystem::InteractionDelegate* New_ctor(::Il2CppObject* object, System::IntPtr method);
// public System.Void Invoke(RootMotion.FinalIK.FullBodyBipedEffector effectorType, RootMotion.FinalIK.InteractionObject interactionObject)
// Offset: 0x1432B90
void Invoke(RootMotion::FinalIK::FullBodyBipedEffector effectorType, RootMotion::FinalIK::InteractionObject* interactionObject);
// public System.IAsyncResult BeginInvoke(RootMotion.FinalIK.FullBodyBipedEffector effectorType, RootMotion.FinalIK.InteractionObject interactionObject, System.AsyncCallback callback, System.Object object)
// Offset: 0x143A810
System::IAsyncResult* BeginInvoke(RootMotion::FinalIK::FullBodyBipedEffector effectorType, RootMotion::FinalIK::InteractionObject* interactionObject, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Void EndInvoke(System.IAsyncResult result)
// Offset: 0x143A8A8
void EndInvoke(System::IAsyncResult* result);
}; // RootMotion.FinalIK.InteractionSystem/InteractionDelegate
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::InteractionSystem::InteractionDelegate*, "RootMotion.FinalIK", "InteractionSystem/InteractionDelegate");
#pragma pack(pop)
| 50.442308 | 211 | 0.775829 | Futuremappermydud |
7015b97992eab9f30fd34acf4fbf3c2761711766 | 3,743 | cpp | C++ | CIM_Framework/CIMFramework/CPPClasses/Src/AMT_AgentPresenceWatchdogAction.cpp | rgl/lms | cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb | [
"Apache-2.0"
] | 18 | 2019-04-17T10:43:35.000Z | 2022-03-22T22:30:39.000Z | CIM_Framework/CIMFramework/CPPClasses/Src/AMT_AgentPresenceWatchdogAction.cpp | rgl/lms | cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb | [
"Apache-2.0"
] | 9 | 2019-10-03T15:29:51.000Z | 2021-12-27T14:03:33.000Z | CIM_Framework/CIMFramework/CPPClasses/Src/AMT_AgentPresenceWatchdogAction.cpp | isabella232/lms | 50d16f81b49aba6007388c001e8137352c5eb42e | [
"Apache-2.0"
] | 8 | 2019-06-13T23:30:50.000Z | 2021-06-25T15:51:59.000Z | //----------------------------------------------------------------------------
//
// Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved.
//
// File: AMT_AgentPresenceWatchdogAction.cpp
//
// Contents: Represents an action which is triggered on an application watchdog state transition.
//
// This file was automatically generated from AMT_AgentPresenceWatchdogAction.mof, version: 4.0.0
//
//----------------------------------------------------------------------------
#include "AMT_AgentPresenceWatchdogAction.h"
namespace Intel
{
namespace Manageability
{
namespace Cim
{
namespace Typed
{
const CimFieldAttribute AMT_AgentPresenceWatchdogAction::_metadata[] = {
{"EventOnTransition", false, false, false },
{"ActionSd", false, false, false },
};
// class fields
const bool AMT_AgentPresenceWatchdogAction::EventOnTransition() const
{
bool ret = false;
TypeConverter::StringToType(GetField("EventOnTransition"), ret);
return ret;
}
void AMT_AgentPresenceWatchdogAction::EventOnTransition(const bool value)
{
SetOrAddField("EventOnTransition", TypeConverter::TypeToString(value));
}
bool AMT_AgentPresenceWatchdogAction::EventOnTransitionExists() const
{
return ContainsField("EventOnTransition");
}
void AMT_AgentPresenceWatchdogAction::RemoveEventOnTransition()
{
RemoveField("EventOnTransition");
}
const unsigned short AMT_AgentPresenceWatchdogAction::ActionSd() const
{
unsigned short ret = 0;
TypeConverter::StringToType(GetField("ActionSd"), ret);
return ret;
}
void AMT_AgentPresenceWatchdogAction::ActionSd(const unsigned short value)
{
SetOrAddField("ActionSd", TypeConverter::TypeToString(value));
}
bool AMT_AgentPresenceWatchdogAction::ActionSdExists() const
{
return ContainsField("ActionSd");
}
void AMT_AgentPresenceWatchdogAction::RemoveActionSd()
{
RemoveField("ActionSd");
}
CimBase *AMT_AgentPresenceWatchdogAction::CreateFromCimObject(const CimObject &object)
{
AMT_AgentPresenceWatchdogAction *ret = NULL;
if(object.ObjectType() != CLASS_NAME)
{
ret = new CimExtended<AMT_AgentPresenceWatchdogAction>(object);
}
else
{
ret = new AMT_AgentPresenceWatchdogAction(object);
}
return ret;
}
vector<shared_ptr<AMT_AgentPresenceWatchdogAction> > AMT_AgentPresenceWatchdogAction::Enumerate(ICimWsmanClient *client, const CimKeys &keys)
{
return CimBase::Enumerate<AMT_AgentPresenceWatchdogAction>(client, keys);
}
void AMT_AgentPresenceWatchdogAction::Delete(ICimWsmanClient *client, const CimKeys &keys)
{
CimBase::Delete(client, CLASS_URI, keys);
}
const vector<CimFieldAttribute> &AMT_AgentPresenceWatchdogAction::GetMetaData() const
{
return _classMetaData;
}
const bool AMT_AgentPresenceWatchdogAction::GetActionEac_OUTPUT::ActionEac() const
{
bool ret = false;
TypeConverter::StringToType(GetField("ActionEac"), ret);
return ret;
}
bool AMT_AgentPresenceWatchdogAction::GetActionEac_OUTPUT::ActionEacExists() const
{
return ContainsField("ActionEac");
}
unsigned int AMT_AgentPresenceWatchdogAction::GetActionEac(GetActionEac_OUTPUT &output)
{
CimEmptyParam input;
return Invoke("GetActionEac", input, output);
}
const string AMT_AgentPresenceWatchdogAction::CLASS_NAME = "AMT_AgentPresenceWatchdogAction";
const string AMT_AgentPresenceWatchdogAction::CLASS_URI = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AgentPresenceWatchdogAction";
const string AMT_AgentPresenceWatchdogAction::CLASS_NS = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_AgentPresenceWatchdogAction";
const string AMT_AgentPresenceWatchdogAction::CLASS_NS_PREFIX = "AAg892";
CIMFRAMEWORK_API vector <CimFieldAttribute> AMT_AgentPresenceWatchdogAction::_classMetaData;
}
}
}
}
| 32.267241 | 143 | 0.747796 | rgl |
70165506ceb745c49a5e850c651aa9f1618910c8 | 1,459 | cpp | C++ | src/stl_copy_it_insert/main.cpp | MaksimPopp/STL_practice_UNN_381906-3 | 83dedf756b170b4ce89e0c74e615bbfd72c4e0a7 | [
"Apache-2.0"
] | null | null | null | src/stl_copy_it_insert/main.cpp | MaksimPopp/STL_practice_UNN_381906-3 | 83dedf756b170b4ce89e0c74e615bbfd72c4e0a7 | [
"Apache-2.0"
] | 1 | 2020-12-12T09:55:31.000Z | 2020-12-12T11:04:55.000Z | src/stl_copy_it_insert/main.cpp | MaksimPopp/STL_practice_UNN_381906-3 | 83dedf756b170b4ce89e0c74e615bbfd72c4e0a7 | [
"Apache-2.0"
] | 12 | 2020-12-12T09:42:22.000Z | 2020-12-19T11:44:27.000Z | #include <iostream>
#include <vector>
#include <list>
using namespace std;
#define COPY
int main()
{
int a[4] = { 10,20,30,40 };//создаём массив a[] на 4 элемента
//копируем массив a[] в вектор v(указатель на начало участка который нужно скопировать,конец участка копирования)
vector<int> v(a, a + 4);
#ifdef COPY
list<int> L(4); //создаём список L типа int на 4 элемента
list<int>::iterator i;//создаём итератор i для списка L
//копируем вектор v в список L с помощью функции copy(<первый> ,<последний>,<операция>). copy-алгоритм,который позволяет копировать элемнты одного контейнера в другой.
copy(v.begin(), v.end(), L.begin());
#endif // COPY
#ifdef INSERT
list<int> L(5, 123);////создаём список L типа int на 5 элемента и заполняем его значениями 123
list<int>::iterator i = L.begin();//создаём итератор i для списка L и устанавливаем его в начало списка
i++;
i++;//передвигаем итератор на 2
//вствляем в список L вектор v: для этого используем функцию copy,но в аргумент <операция> передаём
//inserter-специальный тип итератора вывода который добавляет элементы из контейнера A в контейнер B. inserter(<имя контейнера>,<итератор>) у нес итератор равен 2
copy(v.begin(), v.end(),inserter(L,i));
//таким образом мы встявляем вектор v в список L между 2-ым и 3-ьим элементами списка
#endif // INSERT
//выврод полученного списка
for (i = L.begin(); i != L.end(); ++i)
{
cout << *i << ' ';
}
cout << endl;
return 0;
}
| 31.717391 | 168 | 0.703221 | MaksimPopp |
701760b91996bb0439dd44c7fbde49cfa6a5a77b | 103 | hpp | C++ | src/agl/opengl/function/sampler/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/sampler/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/sampler/all.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "bind.hpp"
#include "create.hpp"
#include "delete.hpp"
#include "parameter.hpp"
| 14.714286 | 24 | 0.728155 | the-last-willy |
7019415f3760818b6829d9b312ba55aa882cef45 | 128 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/failtest/fullpivqr_int.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:b7c6229e11e2ea021cf66d05b528c35bf8936f5109e7bfb4413548b392e111d9
size 258
| 32 | 75 | 0.882813 | initialz |
701d1cc7548fb12f539c5d23004549ff99e6bcc6 | 22,952 | cpp | C++ | branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/source/ThirdPersonManipulator.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/source/ThirdPersonManipulator.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/source/ThirdPersonManipulator.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | /**
@file GLG3D/ThirdPersonManipulator.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2006-06-09
@edited 2010-01-11
*/
#include "GLG3D/ThirdPersonManipulator.h"
#include "GLG3D/RenderDevice.h"
#include "GLG3D/Draw.h"
#include "GLG3D/OSWindow.h"
#include "GLG3D/UserInput.h"
#include "G3D/Sphere.h"
#include "G3D/AABox.h"
namespace G3D {
namespace _internal {
Vector3 UIGeom::segmentNormal(const LineSegment& seg, const Vector3& eye) {
Vector3 E = eye - seg.point(0);
Vector3 V = seg.point(1) - seg.point(0);
Vector3 U = E.cross(V);
Vector3 N = V.cross(U).direction();
return N;
}
Vector3 UIGeom::computeEye(RenderDevice* rd) {
Vector3 eye = rd->objectToWorldMatrix().pointToObjectSpace(rd->cameraToWorldMatrix().translation);
return eye;
}
bool UIGeom::contains(
const Vector2& p,
float& nearestDepth,
Vector2& tangent2D,
float& projectionW,
float lineRadius) const {
bool result = false;
// Find the nearest containing polygon
for (int i = 0; i < poly2D.size(); ++i) {
bool reverse = m_twoSidedPolys && polyBackfacing[i];
if ((polyDepth[i] < nearestDepth) &&
poly2D[i].contains(p, reverse)) {
nearestDepth = polyDepth[i];
result = true;
}
}
// Find the nearest containing line
for (int i = 0; i < line2D.size(); ++i) {
int segmentIndex = 0;
float d = line2D[i].distance(p, segmentIndex);
if (d <= lineRadius) {
// Find the average depth of this segment
float depth = (lineDepth[i][segmentIndex] + lineDepth[i][segmentIndex + 1]) / 2;
if (depth < nearestDepth) {
tangent2D = (line2D[i].segment(segmentIndex).point(1) - line2D[i].segment(segmentIndex).point(0)) /
line3D[i].segment(segmentIndex).length();
projectionW = (lineW[i][segmentIndex] + lineW[i][segmentIndex]) / 2;
nearestDepth = depth;
result = true;
}
}
}
return result;
}
void UIGeom::computeProjection(RenderDevice* rd) {
Array<Vector2> vertex;
// Polyline segments
line2D.resize(line3D.size());
lineDepth.resize(line2D.size());
lineW.resize(line2D.size());
for (int i = 0; i < line3D.size(); ++i) {
const PolyLine& line = line3D[i];
Array<float>& depth = lineDepth[i];
Array<float>& w = lineW[i];
// Project all vertices
vertex.resize(line.numVertices(), false);
depth.resize(vertex.size());
w.resize(vertex.size());
for (int j = 0; j < line.numVertices(); ++j) {
Vector4 v = rd->project(line.vertex(j));
vertex[j] = v.xy();
depth[j] = v.z;
w[j] = v.w;
}
line2D[i] = PolyLine2D(vertex);
}
// Polygons
poly2D.resize(poly3D.size());
polyDepth.resize(poly2D.size());
if (poly3D.size() > 0) {
polyBackfacing.resize(poly3D.size());
// Used for backface classification
Vector3 objEye = rd->modelViewMatrix().inverse().translation;
float z = 0;
for (int i = 0; i < poly3D.size(); ++i) {
const ConvexPolygon& poly = poly3D[i];
vertex.resize(poly3D[i].numVertices(), false);
for (int j = 0; j < poly.numVertices(); ++j) {
Vector4 v = rd->project(poly.vertex(j));
vertex[j] = v.xy();
z += v.z;
}
polyDepth[i] = z / poly.numVertices();
poly2D[i] = ConvexPolygon2D(vertex);
Vector3 normal = poly.normal();
Vector3 toEye = objEye - poly.vertex(0);
polyBackfacing[i] = normal.dot(toEye) < 0;
}
}
}
#define HIDDEN_LINE_ALPHA (0.1f)
void UIGeom::render(RenderDevice* rd, const Color3& color, float lineScale) const {
if (! visible) {
return;
}
rd->setColor(color);
if (m_twoSidedPolys) {
rd->setCullFace(RenderDevice::CULL_NONE);
rd->enableTwoSidedLighting();
}
for (int i = 0; i < poly3D.size(); ++i) {
const ConvexPolygon& poly = poly3D[i];
rd->beginPrimitive(PrimitiveType::TRIANGLE_FAN);
rd->setNormal(poly.normal());
for (int v = 0; v < poly.numVertices(); ++v) {
rd->sendVertex(poly.vertex(v));
}
rd->endPrimitive();
}
// Per segment normals
Array<Vector3> normal;
const Vector3 eye = computeEye(rd);
for (int i = 0; i < line3D.size(); ++i) {
const PolyLine& line = line3D[i];
// Compute one normal for each segement
normal.resize(line.numSegments(), false);
for (int s = 0; s < line.numSegments(); ++s) {
normal[s] = segmentNormal(line.segment(s), eye);
}
bool closed = line.closed();
// Compute line width
float L = 2;
{
Vector4 v = rd->project(line.vertex(0));
if (v.w > 0) {
L = min(15.0f * v.w, 10.0f);
} else {
L = 10.0f;
}
rd->setLineWidth(L * lineScale);
}
bool colorWrite = rd->colorWrite();
bool depthWrite = rd->depthWrite();
// Draw lines twice. The first time we draw color information
// but do not set the depth buffer. The second time we write
// to the depth buffer; this prevents line strips from
// corrupting their own antialiasing with depth conflicts at
// the line joint points.
if (colorWrite) {
rd->setDepthWrite(false);
// Make two passes; first renders visible lines, the next
// renders hidden ones
for (int i = 0; i < 2; ++i) {
rd->beginPrimitive(PrimitiveType::LINE_STRIP);
{
for (int v = 0; v < line.numVertices(); ++v) {
// Compute the smooth normal. If we have a non-closed
// polyline, the ends are special cases.
Vector3 N;
if (! closed && (v == 0)) {
N = normal[0];
} else if (! closed && (v == line.numVertices())) {
N = normal.last();
} else {
// Average two adjacent normals
N = normal[v % normal.size()] + normal[(v - 1) % normal.size()];
}
if (N.squaredLength() < 0.05) {
// Too small to normalize; revert to the
// nearest segment normal
rd->setNormal(normal[iMin(v, normal.size() - 1)]);
} else {
rd->setNormal(N.direction());
}
rd->sendVertex(line.vertex(v));
}
rd->endPrimitive();
}
// Second pass, render hidden lines
//glEnable(GL_LINE_STIPPLE);
//glLineStipple(1, 15);
rd->setDepthTest(RenderDevice::DEPTH_GREATER);
rd->setColor(Color4(color, HIDDEN_LINE_ALPHA));
}
// Restore depth test
//glDisable(GL_LINE_STIPPLE);
rd->setDepthTest(RenderDevice::DEPTH_LEQUAL);
rd->setColor(color);
}
if (depthWrite) {
rd->setColorWrite(false);
rd->setDepthWrite(true);
rd->beginPrimitive(PrimitiveType::LINE_STRIP);
{
for (int v = 0; v < line.numVertices(); ++v) {
rd->sendVertex(line.vertex(v));
}
}
rd->endPrimitive();
}
rd->setColorWrite(colorWrite);
rd->setDepthWrite(depthWrite);
}
}
} // _internal
ThirdPersonManipulatorRef ThirdPersonManipulator::create() {
return new ThirdPersonManipulator();
}
void ThirdPersonManipulator::render(RenderDevice* rd) const {
rd->pushState();
// Highlight the appropriate axis
// X, Y, Z, XY, YZ, ZX, RX, RY, RZ
Color3 color[] =
{Color3(0.9f, 0, 0),
Color3(0, 0.9f, 0.1f),
Color3(0.0f, 0.4f, 1.0f),
Color3(0.6f, 0.7f, 0.7f),
Color3(0.6f, 0.7f, 0.7f),
Color3(0.6f, 0.7f, 0.7f),
Color3(0.9f, 0, 0),
Color3(0, 0.9f, 0.1f),
Color3(0.0f, 0.4f, 1.0f)};
static const Color3 highlight[] =
{Color3(1.0f, 0.5f, 0.5f),
Color3(0.6f, 1.0f, 0.7f),
Color3(0.5f, 0.7f, 1.0f),
Color3::white(),
Color3::white(),
Color3::white(),
Color3(1.0f, 0.5f, 0.5f),
Color3(0.6f, 1.0f, 0.7f),
Color3(0.5f, 0.7f, 1.0f)};
static const Color3 usingColor = Color3::yellow();
// Highlight whatever we're over
if (m_overAxis != NO_AXIS) {
color[m_overAxis] = highlight[m_overAxis];
}
// Show the selected axes
for (int a = 0; a < NUM_GEOMS; ++a) {
if (m_usingAxis[a]) {
color[a] = usingColor;
}
}
rd->setBlendFunc(RenderDevice::BLEND_SRC_ALPHA,
RenderDevice::BLEND_ONE_MINUS_SRC_ALPHA);
rd->setShadeMode(RenderDevice::SHADE_SMOOTH);
// The Draw::axes command automatically doubles whatever scale we give it
Draw::axes(m_controlFrame, rd, color[0], color[1], color[2], m_axisScale * 0.5f);
// Hidden line
rd->setDepthTest(RenderDevice::DEPTH_GREATER);
Draw::axes(m_controlFrame, rd,
Color4(color[0], HIDDEN_LINE_ALPHA),
Color4(color[1], HIDDEN_LINE_ALPHA),
Color4(color[2], HIDDEN_LINE_ALPHA),
m_axisScale * 0.5f);
rd->setDepthTest(RenderDevice::DEPTH_LEQUAL);
rd->setObjectToWorldMatrix(m_controlFrame);
if (m_translationEnabled) {
for (int g = FIRST_TRANSLATION; g <= LAST_TRANSLATION; ++g) {
m_geomArray[g].render(rd, color[g]);
}
}
if (m_rotationEnabled) {
for (int g = FIRST_ROTATION; g <= LAST_ROTATION; ++g) {
m_geomArray[g].render(rd, color[g], 1.5f);
}
}
computeProjection(rd);
rd->popState();
}
class TPMSurface : public Surface {
friend class ThirdPersonManipulator;
ThirdPersonManipulator* m_manipulator;
TPMSurface(ThirdPersonManipulator* m) : m_manipulator(m) {}
public:
virtual void render(RenderDevice* rd) const {
m_manipulator->render(rd);
}
virtual std::string name() const {
return "ThirdPersonManipulator";
}
virtual void getCoordinateFrame(CoordinateFrame& c) const {
m_manipulator->getControlFrame(c);
}
virtual const MeshAlg::Geometry& objectSpaceGeometry() const {
static MeshAlg::Geometry x;
return x;
}
virtual const Array<Vector3>& objectSpaceFaceNormals
(bool normalize = true) const {
(void)normalize;
static Array<Vector3> x;
return x;
}
virtual const Array<MeshAlg::Face>& faces() const {
static Array<MeshAlg::Face> x;
return x;
}
virtual const Array<MeshAlg::Edge>& edges() const {
static Array<MeshAlg::Edge> x;
return x;
}
virtual const Array<MeshAlg::Vertex>& vertices() const {
static Array<MeshAlg::Vertex> x;
return x;
}
virtual const Array<MeshAlg::Face>& weldedFaces() const {
static Array<MeshAlg::Face> x;
return x;
}
virtual const Array<MeshAlg::Edge>& weldedEdges() const {
static Array<MeshAlg::Edge> x;
return x;
}
virtual const Array<MeshAlg::Vertex>& weldedVertices() const {
static Array<MeshAlg::Vertex> x;
return x;
}
virtual const Array<int>& triangleIndices() const {
static Array<int> x;
return x;
}
virtual void getObjectSpaceBoundingSphere(Sphere& s) const {
s.radius = 2;
s.center = Vector3::zero();
}
virtual void getObjectSpaceBoundingBox(AABox& b) const {
b = AABox(Vector3(-2,-2,-2), Vector3(2,2,2));
}
virtual int numBoundaryEdges() const {
return 0;
}
virtual int numWeldedBoundaryEdges() const {
return 0;
}
};
void ThirdPersonManipulator::onDragBegin(const Vector2& start) {
(void)start;
// Intentionally empty.
}
void ThirdPersonManipulator::onDragEnd(const Vector2& stop) {
(void)stop;
// Intentionally empty.
for (int i = 0; i < NUM_GEOMS; ++i) {
m_usingAxis[i] = false;
}
}
Vector3 ThirdPersonManipulator::singleAxisTranslationDrag(int a, const Vector2& delta) {
// Project the mouse delta onto the drag axis to determine how far to drag
const LineSegment2D& axis = m_geomArray[a].line2D[0].segment(0);
Vector2 vec = axis.point(1) - axis.point(0);
float length2 = max(0.5f, vec.squaredLength());
// Divide by squared length since we not only normalize but need to take into
// account the angular foreshortening.
float distance = vec.dot(delta) / length2;
return m_controlFrame.rotation.column(a) * distance;
}
Vector3 ThirdPersonManipulator::doubleAxisTranslationDrag(int a0, int a1, const Vector2& delta) {
Vector2 axis[2];
int a[2] = {a0, a1};
// The two dot products represent points on a non-orthogonal set of axes.
float dot[2];
for (int i = 0; i < 2; ++i) {
// Project the mouse delta onto the drag axis to determine how far to drag
const LineSegment2D& seg = m_geomArray[a[i]].line2D[0].segment(0);
axis[i] = seg.point(1) - seg.point(0);
float length2 = max(0.5f, axis[i].squaredLength());
axis[i] /= length2;
dot[i] = axis[i].dot(delta);
}
// Distance along both
float common = axis[0].dot(axis[1]) * dot[0] * dot[1];
float distance0 = dot[0] - common;
float distance1 = dot[1] - common;
return m_controlFrame.rotation.column(a0) * distance0 +
m_controlFrame.rotation.column(a1) * distance1;
}
void ThirdPersonManipulator::onDrag(const Vector2& delta) {
if ((m_dragAxis >= XY) && (m_dragAxis <= ZX)) {
// Translation, multiple axes
m_controlFrame.translation += doubleAxisTranslationDrag(m_dragAxis - 3, (m_dragAxis - 2) % 3, delta);
} else if ((m_dragAxis >= X) && (m_dragAxis <= Z)) {
// Translation, single axis
m_controlFrame.translation += singleAxisTranslationDrag(m_dragAxis, delta);
} else {
// Rotation
// Drag distance. We divide by the W coordinate so that
// rotation distance is independent of the size of the widget
// on screen.
float angle = delta.dot(m_dragTangent) * 0.00004f / m_dragW;
// Axis about which to rotate
Vector3 axis = Vector3::zero();
axis[m_dragAxis - RX] = 1.0f;
Matrix3 R = Matrix3::fromAxisAngle(axis, angle);
m_controlFrame.rotation = m_controlFrame.rotation * R;
// Prevent accumulated error
m_controlFrame.rotation.orthonormalize();
}
}
void ThirdPersonManipulator::computeProjection(RenderDevice* rd) const {
// TODO: clip to the near plane; modify LineSegment to go through a projection
for (int g = 0; g < NUM_GEOMS; ++g) {
m_geomArray[g].computeProjection(rd);
}
}
bool ThirdPersonManipulator::enabled() const {
return m_enabled;
}
void ThirdPersonManipulator::setEnabled(bool e) {
if (! e && m_dragging) {
m_dragging = false;
}
m_enabled = e;
}
ThirdPersonManipulator::ThirdPersonManipulator() :
m_axisScale(1),
m_dragging(false),
m_dragKey(GKey::LEFT_MOUSE),
m_doubleAxisDrag(false),
m_overAxis(NO_AXIS),
m_maxAxisDistance2D(15),
m_maxRotationDistance2D(10),
m_rotationEnabled(true),
m_translationEnabled(true),
m_enabled(true) {
for (int i = 0; i < NUM_GEOMS; ++i) {
m_usingAxis[i] = false;
}
// Size of the 2-axis control widget
const float hi = 0.80f, lo = 0.60f;
// Single axis (cut a hole out of the center for grabbing all)
const float cut = 0.20f;
Array<Vector3> vertex;
// Create the translation axes. They will be rendered separately.
vertex.clear();
vertex.append(Vector3(cut, 0, 0), Vector3(1.1f, 0, 0));
m_geomArray[X].line3D.append(_internal::PolyLine(vertex));
m_geomArray[X].visible = false;
vertex.clear();
vertex.append(Vector3(0, cut, 0), Vector3(0, 1.1f, 0));
m_geomArray[Y].line3D.append(_internal::PolyLine(vertex));
m_geomArray[Y].visible = false;
vertex.clear();
vertex.append(Vector3(0, 0, cut), Vector3(0, 0, 1.1f));
m_geomArray[Z].line3D.append(_internal::PolyLine(vertex));
m_geomArray[Z].visible = false;
// Create the translation squares that lie inbetween the axes
if (m_doubleAxisDrag) {
vertex.clear();
vertex.append(Vector3(lo, hi, 0), Vector3(lo, lo, 0), Vector3(hi, lo, 0), Vector3(hi, hi, 0));
m_geomArray[XY].poly3D.append(ConvexPolygon(vertex));
vertex.clear();
vertex.append(Vector3(0, hi, hi), Vector3(0, lo, hi), Vector3(0, lo, lo), Vector3(0, hi, lo));
m_geomArray[YZ].poly3D.append(ConvexPolygon(vertex));
vertex.clear();
vertex.append(Vector3(lo, 0, lo), Vector3(lo, 0, hi), Vector3(hi, 0, hi), Vector3(hi, 0, lo));
m_geomArray[ZX].poly3D.append(ConvexPolygon(vertex));
}
// Create the rotation circles
const int ROT_SEGMENTS = 40;
const float ROT_RADIUS = 0.65f;
vertex.resize(ROT_SEGMENTS + 1);
for (int v = 0; v <= ROT_SEGMENTS; ++v) {
float a = twoPi() * (float)v / ROT_SEGMENTS;
vertex[v].x = 0;
vertex[v].y = cos(a) * ROT_RADIUS;
vertex[v].z = sin(a) * ROT_RADIUS;
}
m_geomArray[RX].line3D.append(_internal::PolyLine(vertex));
for (int v = 0; v <= ROT_SEGMENTS; ++v) {
vertex[v] = vertex[v].zxy();
}
m_geomArray[RY].line3D.append(_internal::PolyLine(vertex));
for (int v = 0; v <= ROT_SEGMENTS; ++v) {
vertex[v] = vertex[v].zxy();
}
m_geomArray[RZ].line3D.append(_internal::PolyLine(vertex));
m_posedModel = new TPMSurface(this);
}
void ThirdPersonManipulator::setRotationEnabled(bool r) {
m_rotationEnabled = r;
}
bool ThirdPersonManipulator::rotationEnabled() const {
return m_rotationEnabled;
}
void ThirdPersonManipulator::setTranslationEnabled(bool r) {
m_translationEnabled = r;
}
bool ThirdPersonManipulator::translationEnabled() const {
return m_translationEnabled;
}
CoordinateFrame ThirdPersonManipulator::computeOffsetFrame(
const CoordinateFrame& controlFrame,
const CoordinateFrame& objectFrame) {
return objectFrame * controlFrame.inverse();
}
CoordinateFrame ThirdPersonManipulator::frame() const {
CoordinateFrame c;
getFrame(c);
return c;
}
void ThirdPersonManipulator::onPose(
Array<Surface::Ref>& posedArray,
Array<Surface2DRef>& posed2DArray) {
if (m_enabled) {
(void)posed2DArray;
posedArray.append(m_posedModel);
}
}
void ThirdPersonManipulator::setControlFrame(const CoordinateFrame& c) {
// Compute the offset for the new control frame, and then
// change the control frame.
m_offsetFrame = c.inverse() * frame();
m_controlFrame = c;
}
void ThirdPersonManipulator::getControlFrame(CoordinateFrame& c) const {
c = m_controlFrame;
}
void ThirdPersonManipulator::setFrame(const CoordinateFrame& c) {
m_controlFrame = m_offsetFrame.inverse() * c;
}
void ThirdPersonManipulator::getFrame(CoordinateFrame& c) const {
c = m_controlFrame * m_offsetFrame;
}
void ThirdPersonManipulator::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) {
(void)rdt;
(void)idt;
(void)sdt;
}
bool ThirdPersonManipulator::onEvent(const GEvent& event) {
if (! m_enabled) {
return false;
}
if (event.type == GEventType::MOUSE_MOTION) {
const Vector2 mouseXY(event.motion.x, event.motion.y);
if (m_dragging) {
// TODO: could use event.motion.xrel/event.motion.yrel if all OSWindows supported it
//onDrag(Vector2(event.motion.xrel, event.motion.yrel));
onDrag(mouseXY - m_oldMouseXY);
} else {
// Highlight the axis closest to the mouse
m_overAxis = NO_AXIS;
float nearestDepth = finf();
if (m_translationEnabled) {
for (int g = FIRST_TRANSLATION; g <= LAST_TRANSLATION; ++g) {
const _internal::UIGeom& geom = m_geomArray[g];
if (geom.contains(mouseXY, nearestDepth, m_dragTangent, m_dragW, m_maxAxisDistance2D)) {
m_overAxis = g;
}
}
}
if (m_rotationEnabled) {
for (int g = FIRST_ROTATION; g <= LAST_ROTATION; ++g) {
const _internal::UIGeom& geom = m_geomArray[g];
if (geom.contains(mouseXY, nearestDepth, m_dragTangent, m_dragW, m_maxRotationDistance2D)) {
m_overAxis = g;
}
}
}
}
m_oldMouseXY = mouseXY;
// Do not consume the motion event
return false;
}
if ((event.type == GEventType::MOUSE_BUTTON_UP) && (event.button.button == 0)) {
// Stop dragging
m_dragging = false;
const Vector2 mouseXY(event.button.x, event.button.y);
onDragEnd(mouseXY);
return true;
} else if ((event.type == GEventType::MOUSE_BUTTON_DOWN) && (event.button.button == 0)) {
// Maybe start a drag
if (m_overAxis != NO_AXIS) {
// The user clicked on an axis
m_dragAxis = m_overAxis;
m_dragging = true;
m_usingAxis[m_overAxis] = true;
// Translation along two axes
if ((m_overAxis >= XY) && (m_overAxis <= ZX)) {
// Slect the two adjacent axes as well as the
// box that was clicked on
m_usingAxis[m_overAxis - 3] = true;
m_usingAxis[(m_overAxis - 3 + 1) % 3] = true;
}
const Vector2 mouseXY(event.button.x, event.button.y);
onDragBegin(mouseXY);
return true;
} // if drag
} // if already dragging
return false;
}
void ThirdPersonManipulator::onUserInput(UserInput* ui) {
(void)ui;
}
void ThirdPersonManipulator::onNetwork() {
}
void ThirdPersonManipulator::onAI() {
}
}
| 29.126904 | 116 | 0.572935 | brown-ccv |
702427a1dd34e78d8a72eb295907bde3d145dd98 | 5,229 | cpp | C++ | tests/spmc_fifo.cpp | drbobbeaty/DKit | b3ae323449a8ad6c93e46dd4d07443f8fcc1a001 | [
"Unlicense"
] | 19 | 2015-01-16T10:11:39.000Z | 2022-02-17T01:48:25.000Z | tests/spmc_fifo.cpp | drbobbeaty/DKit | b3ae323449a8ad6c93e46dd4d07443f8fcc1a001 | [
"Unlicense"
] | null | null | null | tests/spmc_fifo.cpp | drbobbeaty/DKit | b3ae323449a8ad6c93e46dd4d07443f8fcc1a001 | [
"Unlicense"
] | 3 | 2015-06-28T13:20:15.000Z | 2015-12-01T08:35:35.000Z | /**
* This is the tests for the SPMC CircularFIFO
*/
// System Headers
#include <iostream>
#include <string>
// Third-Party Headers
// Other Headers
#include "spmc/CircularFIFO.h"
#include "util/timer.h"
#include "hammer.h"
#include "drain.h"
int main(int argc, char *argv[]) {
bool error = false;
// make a circular FIFO of 1024 int32_t values - max
dkit::spmc::CircularFIFO<int32_t, 10> q;
// put 500 values on the queue - and check the size
if (!error) {
std::cout << "=== Testing speed and correctness of CircularFIFO ===" << std::endl;
// get the starting time
uint64_t goTime = dkit::util::timer::usecStamp();
// do this often enough to rotate through the size of the values
int32_t trips = 100000;
for (int32_t cycle = 0; cycle < trips; ++cycle) {
// put 500 values on the queue - and check the size
for (int32_t i = 0; i < 500; ++i) {
if (!q.push(i)) {
error = true;
std::cout << "ERROR - could not push the value " << i << std::endl;
break;
}
}
// now check the size
if (!error) {
if (q.size() != 500) {
error = true;
std::cout << "ERROR - pushed 500 integers, but size() reports only " << q.size() << std::endl;
} else {
if (cycle == 0) {
std::cout << "Passed - pushed on 500 integers" << std::endl;
}
}
}
// pop off 500 integers and it should be empty
if (!error) {
int32_t v = 0;
for (int32_t i = 0; i < 500; ++i) {
if (!q.pop(v) || (v != i)) {
error = true;
std::cout << "ERROR - could not pop the value " << i << std::endl;
break;
}
}
}
// now check the size
if (!error) {
if (!q.empty()) {
error = true;
std::cout << "ERROR - popped 500 integers, but size() reports " << q.size() << std::endl;
} else {
if (cycle == 0) {
std::cout << "Passed - popped all 500 integers" << std::endl;
}
}
}
// now make sure we can't pop() anything
if (!error) {
int32_t v = 0;
if (!q.pop(v)) {
if (cycle == 0) {
std::cout << "Passed - unable to pop from an empty queue" << std::endl;
}
} else {
error = true;
std::cout << "ERROR - popped " << v << " from an empty queue - shouldn't be possible" << std::endl;
}
}
}
// get the elapsed time
goTime = dkit::util::timer::usecStamp() - goTime;
std::cout << "Passed - did " << (trips * 500) << " push/pop pairs in " << (goTime/1000.0) << "ms = " << ((goTime * 1000.0)/(trips * 500.0)) << "ns/op" << std::endl;
}
// check on how the crash recovery works
if (!error) {
// make sure it's all cleared out for this test
q.clear();
std::cout << "=== Testing crash surviveability CircularFIFO ===" << std::endl;
// push values starting at 0 up until we can't push any more
int32_t v = 0;
int32_t lim = 0;
while (q.push(lim)) {
++lim;
}
std::cout << "Passed - Failed on pushing " << lim << std::endl;
for (int32_t i = 0; i < lim; ++i) {
if (!q.pop(v) || (v != i)) {
error = true;
std::cout << "ERROR - could not pop the value " << i << std::endl;
break;
}
}
if (!error) {
std::cout << "Passed - after crash, still able to recover all values" << std::endl;
}
}
/**
* Make a Hammer and a set of Drains and test threading
*/
if (!error) {
Hammer src(0, &q, 1000);
Drain *dest[] = { NULL, NULL, NULL, NULL };
for (uint32_t i = 0; i < 4; ++i) {
if ((dest[i] = new Drain(i, &q)) == NULL) {
std::cout << "PROBLEM - unable to make Drain #" << i << "!" << std::endl;
break;
}
}
// now start the drains then the hammer
for (uint32_t i = 0; i < 4; ++i) {
if (dest[i] != NULL) {
dest[i]->start();
}
}
src.start();
// now let's wait for the hammer to be done
while (!src.isDone()) {
usleep(250000);
}
// now tell the drains to stop when the queue is empty
for (uint32_t i = 0; i < 4; ++i) {
if (dest[i] != NULL) {
dest[i]->stopOnEmpty();
}
}
// wait for all the drains to be done
bool allDone = false;
uint32_t cnt[] = { 0, 0, 0, 0 };
uint32_t total = 0;
while (!allDone) {
// assume done, but check for the first failure
allDone = true;
// now let's check all the drains to see if they are done
for (uint32_t i = 0; i < 4; ++i) {
if (dest[i] != NULL) {
if (!dest[i]->isDone()) {
allDone = false;
break;
}
// tally up the counts
cnt[i] = dest[i]->getCount();
total += cnt[i];
}
}
// see if we need to wait a bit to try again
if (!allDone) {
usleep(250000);
}
}
// now let's see what we have
if (total == 1000) {
std::cout << "Passed - popped " << total << " integers (" << cnt[0] << "+" << cnt[1] << "+" << cnt[2] << "+" << cnt[3] << "), with four drain threads" << std::endl;
} else {
std::cout << "ERROR - popped " << total << " integers (" << cnt[0] << "+" << cnt[1] << "+" << cnt[2] << "+" << cnt[3] << "), with four drain threads - but should have popped 1000" << std::endl;
}
// finally, clean things up
for (uint32_t i = 0; i < 4; ++i) {
if (dest[i] != NULL) {
delete dest[i];
dest[i] = NULL;
}
}
}
std::cout << (error ? "FAILED!" : "SUCCESS") << std::endl;
return (error ? 1 : 0);
}
| 27.81383 | 196 | 0.536814 | drbobbeaty |
702ac5ddfe1b70c5668a5f3e1250734676e10b0c | 2,054 | cpp | C++ | Source/Engine/Editor/Widgets/PropertyWidget.cpp | muit/FecoEngine | b2f8729c0bf0893b770434645c2a0fa8e7717cb7 | [
"Apache-2.0"
] | 3 | 2019-03-01T19:34:26.000Z | 2021-03-31T09:25:16.000Z | Source/Engine/Editor/Widgets/PropertyWidget.cpp | muit/FecoEngine | b2f8729c0bf0893b770434645c2a0fa8e7717cb7 | [
"Apache-2.0"
] | null | null | null | Source/Engine/Editor/Widgets/PropertyWidget.cpp | muit/FecoEngine | b2f8729c0bf0893b770434645c2a0fa8e7717cb7 | [
"Apache-2.0"
] | 1 | 2019-01-21T21:45:13.000Z | 2019-01-21T21:45:13.000Z | // Copyright 2015-2019 Piperift - All rights reserved
#include "PropertyWidget.h"
#if WITH_EDITOR
#include "Core/Reflection/Runtime/TPropertyHandle.h"
#include "Properties/BoolPropertyWidget.h"
#include "Properties/UInt8PropertyWidget.h"
#include "Properties/Int32PropertyWidget.h"
#include "Properties/FloatPropertyWidget.h"
#include "Properties/NamePropertyWidget.h"
#include "Properties/StringPropertyWidget.h"
#include "Properties/V3PropertyWidget.h"
#include "Properties/V2PropertyWidget.h"
GlobalPtr<PropertyWidget> PropertyWidget::NewPropertyWidget(const Ptr<Widget>& owner, const eastl::shared_ptr<PropertyHandle>& prop)
{
if (prop && owner)
{
Class* customWidgetClass = prop->GetClassDefinedWidgetClass();
if (customWidgetClass)
{
return owner->New<PropertyWidget>(customWidgetClass, prop);
}
// Ordered by estimated usage
// #TODO: Switch to native pointers
if (auto propFloat = eastl::dynamic_pointer_cast<TPropertyHandle<float>>(prop)) {
return owner->New<FloatPropertyWidget>(propFloat);
}
else if (auto propInt32 = eastl::dynamic_pointer_cast<TPropertyHandle<i32>>(prop)) {
return owner->New<Int32PropertyWidget>(propInt32);
}
else if (auto propUInt8 = eastl::dynamic_pointer_cast<TPropertyHandle<u8>>(prop)) {
return owner->New<UInt8PropertyWidget>(propUInt8);
}
else if (auto propBool = eastl::dynamic_pointer_cast<TPropertyHandle<bool>>(prop)) {
return owner->New<BoolPropertyWidget>(propBool);
}
else if (auto propName = eastl::dynamic_pointer_cast<TPropertyHandle<Name>>(prop)) {
return owner->New<NamePropertyWidget>(propName);
}
else if (auto propString = eastl::dynamic_pointer_cast<TPropertyHandle<String>>(prop)) {
return owner->New<StringPropertyWidget>(propString);
}
else if (auto propV3 = eastl::dynamic_pointer_cast<TPropertyHandle<v3>>(prop)) {
return owner->New<V3PropertyWidget>(propV3);
}
else if (auto propV2 = eastl::dynamic_pointer_cast<TPropertyHandle<v2>>(prop)) {
return owner->New<V2PropertyWidget>(propV2);
}
}
return {};
}
#endif
| 34.813559 | 132 | 0.757059 | muit |
702c85fa25150642f93577e4c912e3b0ae9312bb | 2,129 | cpp | C++ | Windows/Controls/DefinitionView.cpp | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 32 | 2017-11-27T03:04:44.000Z | 2022-01-21T17:03:40.000Z | Windows/Controls/DefinitionView.cpp | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 30 | 2017-11-10T09:47:16.000Z | 2018-11-21T22:36:47.000Z | Windows/Controls/DefinitionView.cpp | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 20 | 2018-01-05T17:15:11.000Z | 2021-07-30T14:11:01.000Z | #include "../stdafx.h"
#include "DefinitionView.h"
#include "../Document.h"
#include "../res/resource.h"
#include "ViewUtil.h"
#include "SideSectionDefs.h"
#include "../MainWindow.h"
#include "../MainView.h"
#include "../CPlotApp.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
enum
{
ID_def = 2000
};
IMPLEMENT_DYNAMIC(DefinitionView, CWnd)
BEGIN_MESSAGE_MAP(DefinitionView, CWnd)
ON_WM_CREATE()
ON_WM_SIZE()
ON_BN_CLICKED(ID_def, OnEdit)
END_MESSAGE_MAP()
DefinitionView::DefinitionView(SideSectionDefs &parent, UserFunction &f)
: parent(parent), f_id(f.oid())
{
}
BOOL DefinitionView::PreCreateWindow(CREATESTRUCT &cs)
{
cs.style |= WS_CHILD;
cs.dwExStyle |= WS_EX_CONTROLPARENT | WS_EX_TRANSPARENT;
return CWnd::PreCreateWindow(cs);
}
BOOL DefinitionView::Create(const RECT &rect, CWnd *parent, UINT ID)
{
static bool init = false;
if (!init)
{
WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS));
wndcls.style = CS_DBLCLKS;
wndcls.lpfnWndProc = ::DefWindowProc;
wndcls.hInstance = AfxGetInstanceHandle();
wndcls.hCursor = theApp.LoadStandardCursor(IDC_ARROW);
wndcls.lpszMenuName = NULL;
wndcls.lpszClassName = _T("DefinitionView");
wndcls.hbrBackground = NULL;
if (!AfxRegisterClass(&wndcls)) throw std::runtime_error("AfxRegisterClass(DefinitionView) failed");
init = true;
}
return CWnd::Create(_T("DefinitionView"), NULL, WS_CHILD | WS_TABSTOP, rect, parent, ID);
}
int DefinitionView::OnCreate(LPCREATESTRUCT cs)
{
if (CWnd::OnCreate(cs) < 0) return -1;
EnableScrollBarCtrl(SB_BOTH, FALSE);
START_CREATE;
BUTTONLABEL(def);
return 0;
}
void DefinitionView::Update(bool full)
{
CRect bounds; GetClientRect(bounds);
UserFunction *f = function();
if (!f) return;
def.SetWindowText(Convert(f->formula()));
if (!full) return;
Layout layout(*this, 0, 20); SET(-1); USE(&def);
}
void DefinitionView::OnInitialUpdate()
{
Update(true);
}
void DefinitionView::OnSize(UINT type, int w, int h)
{
CWnd::OnSize(type, w, h);
EnableScrollBarCtrl(SB_BOTH, FALSE);
Update(true);
}
void DefinitionView::OnEdit()
{
auto *f = function(); if (!f) return;
parent.OnEdit(f);
}
| 21.29 | 102 | 0.721465 | TrevorShelton |
702ebc555e0536e62e3091d3c25c340bddce8033 | 878 | hpp | C++ | src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/crossserver/crossserver/crossactivity/impl/crossactivitycrossboss.hpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #ifndef __CROSS_ACTIVITY_CROSS_BOSS_HPP__
#define __CROSS_ACTIVITY_CROSS_BOSS_HPP__
#include "crossactivity/crossactivity.hpp"
#include "servercommon/internalprotocal/crossgameprotocal.h"
#include <map>
class CrossActivityCrossBoss : public CrossActivity
{
public:
CrossActivityCrossBoss(CrossActivityManager *cross_activity_manager);
~CrossActivityCrossBoss();
virtual void Init(const CrossActivityData &data);
virtual void OnCrossUserLogin(CrossUser *cross_user);
virtual bool CheckCanStartCross(const UniqueUserID &unique_user_id, int merge_server_id = 0) { return true; }
void OnPlayerInfoResult(crossgameprotocal::GameCrossBossSyncPlayerInfo *tzsfr);
private:
virtual void OnChangeToNextStatus();
typedef std::map<long long, int> CrossBossSceneMap;
typedef std::map<long long, int>::iterator CrossBossSceneMapIt;
};
#endif // __CROSS_ACTIVITY_1V1_HPP__
| 29.266667 | 110 | 0.823462 | mage-game |
70319f9109bd638d460b7dc5701da2e20d4cc9f9 | 1,322 | cpp | C++ | CrimeEngine/source/Core/Input/Event.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | 1 | 2021-07-21T17:14:35.000Z | 2021-07-21T17:14:35.000Z | CrimeEngine/source/Core/Input/Event.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | null | null | null | CrimeEngine/source/Core/Input/Event.cpp | boschman32/Crime-Engine | 128529634011d41a1f7fc1a356245d7f7ef77cb3 | [
"MIT"
] | 3 | 2021-03-07T15:51:03.000Z | 2021-07-13T20:01:34.000Z | #include "cepch.h"
#include "Core/Input/Event.h"
#include "Core/Input/KeyEvent.h"
void Event::NotifyHandlers(const KeyEvent& a_notifyKey)
{
std::vector<std::shared_ptr<EventHandler>>::iterator handle = m_handlers.begin();
for (; handle != m_handlers.end(); ++handle)
{
if (*handle != nullptr) {
(*(*handle))(a_notifyKey);
}
}
}
void Event::AddHandler(EventHandler& a_newHandler)
{
m_handlers.push_back(std::make_shared<EventHandler>(a_newHandler));
}
void Event::AddHandler(std::function<void(const KeyEvent&)> a_newHandler)
{
m_handlers.push_back(std::make_shared<EventHandler>(a_newHandler));
}
void Event::RemoveHandler(EventHandler& a_handlerToRemove)
{
std::vector<std::shared_ptr<EventHandler>>::iterator handle = m_handlers.begin();
for (; handle != m_handlers.end(); ++handle)
{
if (*(*handle) == a_handlerToRemove) {
m_handlers.erase(handle);
}
}
}
void Event::operator()(const KeyEvent& a_notifyKey)
{
NotifyHandlers(a_notifyKey);
}
Event& Event::operator+=(EventHandler& a_newHandler)
{
AddHandler(a_newHandler);
return *this;
}
Event& Event::operator+=(std::function<void(const KeyEvent&)> a_newHandler)
{
AddHandler(EventHandler(a_newHandler));
return *this;
}
Event& Event::operator-=(EventHandler& a_handlerToRemove)
{
RemoveHandler(a_handlerToRemove);
return *this;
} | 22.793103 | 82 | 0.728442 | boschman32 |
70352f5fc6776a15b8dc643421f35ea9b5fc9982 | 1,170 | cc | C++ | CPP/No73.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No73.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No73.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Xiaozhong on 2020/7/24.
* Copyright (c) 2020/7/24 Xiaozhong. All rights reserved.
*/
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
void setZeroes(vector<vector<int>> &matrix) {
set<int> row;
set<int> col;
// 首先遍历第一遍,用set记录下来元素值为 0 的行标和列标
int m = matrix.size(), n = matrix[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row.insert(i);
col.insert(j);
}
}
}
// 第二遍遍历的时候,需要把行标或者列标为 0 的地方置为0
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (row.count(i) || col.count(j))
matrix[i][j] = 0;
}
}
}
};
int main() {
vector<vector<int>> matrix = {
{1, 1, 1},
{1, 0, 1},
{1, 1, 1}
};
Solution s;
s.setZeroes(matrix);
for (vector<int> item : matrix) {
for (int i : item) {
cout << i << " ";
}
cout << endl;
}
} | 22.941176 | 58 | 0.41453 | hxz1998 |
70392118b102124f1f9745e03372a8deb357bbf9 | 1,249 | cpp | C++ | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/TOOLS/TOOLSX/atlmfc/src/mfc/appdlg.cpp | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
/////////////////////////////////////////////////////////////////////////////
// WinApp features for new and open
void CWinApp::OnFileNew()
{
if (m_pDocManager != NULL)
m_pDocManager->OnFileNew();
}
/////////////////////////////////////////////////////////////////////////////
void CWinApp::OnFileOpen()
{
ENSURE(m_pDocManager != NULL);
m_pDocManager->OnFileOpen();
}
// prompt for file name - used for open and save as
BOOL CWinApp::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags,
BOOL bOpenFileDialog, CDocTemplate* pTemplate)
// if pTemplate==NULL => all document templates
{
ENSURE(m_pDocManager != NULL);
return m_pDocManager->DoPromptFileName(fileName, nIDSTitle, lFlags,
bOpenFileDialog, pTemplate);
}
/////////////////////////////////////////////////////////////////////////////
| 29.046512 | 79 | 0.614091 | intj-t |