hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k โ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 โ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 โ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k โ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 โ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 โ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k โ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 โ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 โ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82aefa5aedb5b6aabd5779e6299924032700efa5 | 12,903 | cpp | C++ | src/programs/mdrun/tests/freeenergy.cpp | HITS-MBM/gromacs-developments | 2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c | [
"BSD-2-Clause"
] | 384 | 2015-01-02T19:44:15.000Z | 2022-03-27T15:13:15.000Z | src/programs/mdrun/tests/freeenergy.cpp | HITS-MBM/gromacs-developments | 2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c | [
"BSD-2-Clause"
] | 9 | 2015-04-07T20:48:00.000Z | 2022-01-24T21:29:26.000Z | src/programs/mdrun/tests/freeenergy.cpp | HITS-MBM/gromacs-developments | 2a1f23a0ad2fc7fee8ea0cd65c080f0476b3104c | [
"BSD-2-Clause"
] | 258 | 2015-01-19T11:19:57.000Z | 2022-03-18T08:59:52.000Z | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2020,2021, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief
* Tests to compare free energy simulations to reference
*
* \author Pascal Merz <pascal.merz@me.com>
* \ingroup module_mdrun_integration_tests
*/
#include "gmxpre.h"
#include "config.h"
#include "gromacs/topology/ifunc.h"
#include "gromacs/utility/filestream.h"
#include "gromacs/utility/path.h"
#include "gromacs/utility/stringutil.h"
#include "testutils/mpitest.h"
#include "testutils/refdata.h"
#include "testutils/setenv.h"
#include "testutils/simulationdatabase.h"
#include "testutils/xvgtest.h"
#include "moduletest.h"
#include "simulatorcomparison.h"
namespace gmx::test
{
namespace
{
/*! \brief Test fixture base for free energy calculations
*
* This test ensures that selected free energy perturbation calculations produce
* results identical to an earlier version. The results of this earlier version
* have been verified manually to ensure physical correctness.
*/
using MaxNumWarnings = int;
using ListOfInteractionsToTest = std::vector<int>;
using FreeEnergyReferenceTestParams = std::tuple<std::string, MaxNumWarnings, ListOfInteractionsToTest>;
class FreeEnergyReferenceTest :
public MdrunTestFixture,
public ::testing::WithParamInterface<FreeEnergyReferenceTestParams>
{
public:
struct PrintParametersToString
{
template<class ParamType>
std::string operator()(const testing::TestParamInfo<ParamType>& parameter) const
{
auto simulationName = std::get<0>(parameter.param);
std::replace(simulationName.begin(), simulationName.end(), '-', '_');
return simulationName + (GMX_DOUBLE ? "_d" : "_s");
}
};
};
TEST_P(FreeEnergyReferenceTest, WithinTolerances)
{
const auto& simulationName = std::get<0>(GetParam());
const auto maxNumWarnings = std::get<1>(GetParam());
const auto& interactionsList = std::get<2>(GetParam());
// As these tests check reproducibility, we restrict the maximum number
// of ranks to allow us to keep the tolerances tight. See also #3741.
const int numRanksAvailable = getNumberOfTestMpiRanks();
constexpr int maxNumRanks = 8;
if (numRanksAvailable > maxNumRanks)
{
fprintf(stdout,
"The FEP tests cannot run with %d ranks.\n"
"The maximum number of ranks supported is %d.",
numRanksAvailable,
maxNumRanks);
return;
}
SCOPED_TRACE(formatString("Comparing FEP simulation '%s' to reference", simulationName.c_str()));
// Tolerance set to pass with identical code version and a range of different test setups for most tests
const auto defaultEnergyTolerance = relativeToleranceAsFloatingPoint(50.0, GMX_DOUBLE ? 1e-5 : 1e-4);
// Some simulations are significantly longer, so they need a larger tolerance
const auto longEnergyTolerance = relativeToleranceAsFloatingPoint(50.0, GMX_DOUBLE ? 1e-4 : 1e-3);
const bool isLongSimulation = (simulationName == "expanded");
const auto energyTolerance = isLongSimulation ? longEnergyTolerance : defaultEnergyTolerance;
EnergyTermsToCompare energyTermsToCompare{ { interaction_function[F_EPOT].longname, energyTolerance } };
for (const auto& interaction : interactionsList)
{
energyTermsToCompare.emplace(interaction_function[interaction].longname, defaultEnergyTolerance);
}
// Specify how trajectory frame matching must work (only testing forces).
TrajectoryFrameMatchSettings trajectoryMatchSettings{ false,
false,
false,
ComparisonConditions::NoComparison,
ComparisonConditions::NoComparison,
ComparisonConditions::MustCompare };
TrajectoryTolerances trajectoryTolerances = TrajectoryComparison::s_defaultTrajectoryTolerances;
trajectoryTolerances.forces = relativeToleranceAsFloatingPoint(100.0, GMX_DOUBLE ? 5.0e-5 : 5.0e-4);
// Build the functor that will compare reference and test
// trajectory frames in the chosen way.
TrajectoryComparison trajectoryComparison{ trajectoryMatchSettings, trajectoryTolerances };
// Set simulation file names
auto simulationTrajectoryFileName = fileManager_.getTemporaryFilePath("trajectory.trr");
auto simulationEdrFileName = fileManager_.getTemporaryFilePath("energy.edr");
auto simulationDhdlFileName = fileManager_.getTemporaryFilePath("dhdl.xvg");
// Run grompp
runner_.tprFileName_ = fileManager_.getTemporaryFilePath("sim.tpr");
runner_.useTopGroAndMdpFromFepTestDatabase(simulationName);
runGrompp(&runner_, { SimulationOptionTuple("-maxwarn", std::to_string(maxNumWarnings)) });
// Do mdrun
runner_.fullPrecisionTrajectoryFileName_ = simulationTrajectoryFileName;
runner_.edrFileName_ = simulationEdrFileName;
runner_.dhdlFileName_ = simulationDhdlFileName;
runMdrun(&runner_);
/* Currently used tests write trajectory (x/v/f) frames every 20 steps.
* Except for the expanded ensemble test, all tests run for 20 steps total.
* As the tolerances are relatively strict, we need to restrict the number of
* force frames we can expect to match.
* Testing more than the first force frame is only feasible in double precision
* using a single rank.
* Testing one force frame is only feasible in double precision.
* Note that this only concerns trajectory frames, energy frames are checked
* in all cases. */
const bool testTwoTrajectoryFrames = (GMX_DOUBLE && (getNumberOfTestMpiRanks() == 1));
const bool testOneTrajectoryFrame = GMX_DOUBLE;
// Compare simulation results
TestReferenceData refData;
TestReferenceChecker rootChecker(refData.rootChecker());
// Check that the energies agree with the refdata within tolerance.
checkEnergiesAgainstReferenceData(simulationEdrFileName, energyTermsToCompare, &rootChecker);
// Check that the trajectories agree with the refdata within tolerance.
if (testTwoTrajectoryFrames)
{
checkTrajectoryAgainstReferenceData(
simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(2));
}
else if (testOneTrajectoryFrame)
{
checkTrajectoryAgainstReferenceData(
simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(1));
}
else
{
checkTrajectoryAgainstReferenceData(
simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(0));
}
if (File::exists(simulationDhdlFileName, File::returnFalseOnError))
{
TextInputFile dhdlFile(simulationDhdlFileName);
auto settings = XvgMatchSettings();
settings.tolerance = defaultEnergyTolerance;
checkXvgFile(&dhdlFile, &rootChecker, settings);
}
}
// TODO: The time for OpenCL kernel compilation means these tests time
// out. Once that compilation is cached for the whole process, these
// tests can run in such configurations.
#if !GMX_GPU_OPENCL
INSTANTIATE_TEST_SUITE_P(
FreeEnergyCalculationsAreEquivalentToReference,
FreeEnergyReferenceTest,
::testing::Values(
FreeEnergyReferenceTestParams{ "coulandvdwsequential_coul",
MaxNumWarnings(0),
{ F_DVDL_COUL, F_DVDL_VDW } },
FreeEnergyReferenceTestParams{ "coulandvdwsequential_vdw",
MaxNumWarnings(0),
{ F_DVDL_COUL, F_DVDL_VDW } },
FreeEnergyReferenceTestParams{ "coulandvdwtogether", MaxNumWarnings(0), { F_DVDL } },
FreeEnergyReferenceTestParams{ "expanded", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } },
// Tolerated warnings: No default bonded interaction types for perturbed atoms (10x)
FreeEnergyReferenceTestParams{ "relative",
MaxNumWarnings(10),
{ F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED } },
// Tolerated warnings: No default bonded interaction types for perturbed atoms (10x)
FreeEnergyReferenceTestParams{
"relative-position-restraints",
MaxNumWarnings(10),
{ F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED, F_DVDL_RESTRAINT } },
FreeEnergyReferenceTestParams{ "restraints", MaxNumWarnings(0), { F_DVDL_RESTRAINT } },
FreeEnergyReferenceTestParams{ "simtemp", MaxNumWarnings(0), {} },
FreeEnergyReferenceTestParams{ "transformAtoB", MaxNumWarnings(0), { F_DVDL } },
FreeEnergyReferenceTestParams{ "vdwalone", MaxNumWarnings(0), { F_DVDL } }),
FreeEnergyReferenceTest::PrintParametersToString());
#else
INSTANTIATE_TEST_SUITE_P(
DISABLED_FreeEnergyCalculationsAreEquivalentToReference,
FreeEnergyReferenceTest,
::testing::Values(
FreeEnergyReferenceTestParams{ "coulandvdwsequential_coul",
MaxNumWarnings(0),
{ F_DVDL_COUL, F_DVDL_VDW } },
FreeEnergyReferenceTestParams{ "coulandvdwsequential_vdw",
MaxNumWarnings(0),
{ F_DVDL_COUL, F_DVDL_VDW } },
FreeEnergyReferenceTestParams{ "coulandvdwtogether", MaxNumWarnings(0), { F_DVDL } },
FreeEnergyReferenceTestParams{ "expanded", MaxNumWarnings(0), { F_DVDL_COUL, F_DVDL_VDW } },
// Tolerated warnings: No default bonded interaction types for perturbed atoms (10x)
FreeEnergyReferenceTestParams{ "relative",
MaxNumWarnings(10),
{ F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED } },
// Tolerated warnings: No default bonded interaction types for perturbed atoms (10x)
FreeEnergyReferenceTestParams{
"relative-position-restraints",
MaxNumWarnings(10),
{ F_DVDL, F_DVDL_COUL, F_DVDL_VDW, F_DVDL_BONDED, F_DVDL_RESTRAINT } },
FreeEnergyReferenceTestParams{ "restraints", MaxNumWarnings(0), { F_DVDL_RESTRAINT } },
FreeEnergyReferenceTestParams{ "simtemp", MaxNumWarnings(0), {} },
FreeEnergyReferenceTestParams{ "transformAtoB", MaxNumWarnings(0), { F_DVDL } },
FreeEnergyReferenceTestParams{ "vdwalone", MaxNumWarnings(0), { F_DVDL } }),
FreeEnergyReferenceTest::PrintParametersToString());
#endif
} // namespace
} // namespace gmx::test
| 49.626923 | 108 | 0.663179 | HITS-MBM |
82b1726633c4e99570f12e8e0181b124cb80872e | 454 | hpp | C++ | pbxbuild/build_file.hpp | GuardianEngine/pbxbuild | 90af1e5b963137766d486a918eaedab7c8b21c1a | [
"MIT"
] | 1 | 2017-06-09T15:58:55.000Z | 2017-06-09T15:58:55.000Z | pbxbuild/build_file.hpp | GuardianEngine/pbxbuild | 90af1e5b963137766d486a918eaedab7c8b21c1a | [
"MIT"
] | null | null | null | pbxbuild/build_file.hpp | GuardianEngine/pbxbuild | 90af1e5b963137766d486a918eaedab7c8b21c1a | [
"MIT"
] | 2 | 2017-06-09T15:58:59.000Z | 2020-08-15T05:37:19.000Z | #pragma once
#include "base_object.hpp"
#include "file_element.hpp"
#include "project.hpp"
#include "../libpbxparser/value.hpp"
#include <string>
namespace pbx
{
class BuildFile : public pbx::BaseObject
{
std::string _file_ref;
pbx::Dictionary _settings;
public:
BuildFile(const std::shared_ptr<pbx::Project>& project, const std::string& uid, const pbx::Dictionary& data);
std::shared_ptr<const pbx::FileReference> file() const;
};
} | 20.636364 | 111 | 0.720264 | GuardianEngine |
a1121af0b14432210bb859cef5e2658a503cc9be | 381 | cpp | C++ | src/string/MANACHER.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | src/string/MANACHER.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | src/string/MANACHER.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | auto manacher(const string &in) {
int n = in.size();
string s(2 * n - 1, '#');
rep(i, n) s[2 * i] = in[i];
n = 2 * n - 1;
vector<int> r(n);
int i = 0, j = 0, k;
while (i < n) {
while (0 <= i - j && i + j < n && s[i - j] == s[i + j])j++;
r[i] = j, k = 1;
while (0 <= i - k && i + k < n && k + r[i - k] < r[i])r[i + k] = r[i - k], k++;
i += k, j -= k;
}
return r;
} | 23.8125 | 81 | 0.377953 | hec12 |
a119af717649001bca7689721bc5eb5e52d8bd4b | 772 | cpp | C++ | source/polyvec/utils/color.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | source/polyvec/utils/color.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | source/polyvec/utils/color.cpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | #include <polyvec/utils/color.hpp>
#include <polyvec/utils/num.hpp>
NAMESPACE_BEGIN(polyfit)
NAMESPACE_BEGIN(Color)
const vec3 COLOR_MIN(22. / 255, 64. / 255, 229. / 255);
const vec3 COLOR_MID(30. / 255, 255. / 255, 97. / 255);
const vec3 COLOR_MAX(255. / 255, 45. / 255, 30. / 255);
// Returns some kind of interpolated color
// <= t_min -> blue
// .5 (t_min + t_max) -> green
// > t_max -> red
// requires t_min < t_max
vec3 error(double t_min, double t_max, double t) {
const double t_mid = polyvec::Num::lerp(t_min, t_max, .5);
if (t <= t_mid) {
return polyvec::Num::lerp(COLOR_MIN, COLOR_MID, t / t_mid);
} else {
return polyvec::Num::lerp(COLOR_MID, COLOR_MAX, polyvec::Num::saturate((t - t_mid) / t_mid));
}
}
NAMESPACE_END(Color)
NAMESPACE_END(polyfit) | 29.692308 | 95 | 0.67487 | ShnitzelKiller |
a11c62ca958a645c8e8bec7d57e8065665ffa874 | 3,029 | cc | C++ | crypto/cipher/rc4.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 3 | 2017-04-24T07:00:59.000Z | 2020-04-13T04:53:06.000Z | crypto/cipher/rc4.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 1 | 2017-01-10T04:23:55.000Z | 2017-01-10T04:23:55.000Z | crypto/cipher/rc4.cc | chronos-tachyon/mojo | 8d268932dd927a24a2b5de167d63869484e1433a | [
"MIT"
] | 1 | 2020-04-13T04:53:07.000Z | 2020-04-13T04:53:07.000Z | // Copyright ยฉ 2017 by Donald King <chronos@chronos-tachyon.net>
// Available under the MIT License. See LICENSE for details.
#include "crypto/cipher/rc4.h"
#include "base/logging.h"
#include "crypto/primitives.h"
#include "crypto/security.h"
namespace crypto {
namespace cipher {
inline namespace implementation {
struct RC4State {
uint8_t state[256];
uint8_t i;
uint8_t j;
void rekey(const uint8_t* key, uint32_t len);
void encrypt(uint8_t* dst, const uint8_t* src, std::size_t len);
};
void RC4State::rekey(const uint8_t* key, uint32_t len) {
unsigned int x, y;
for (x = 0; x < 256; ++x) {
state[x] = x;
}
y = 0;
for (x = 0; x < 256; ++x) {
y = (y + state[x] + key[x % len]) & 0xff;
std::swap(state[x], state[y]);
}
i = j = 0;
}
void RC4State::encrypt(uint8_t* dst, const uint8_t* src, std::size_t len) {
for (std::size_t x = 0; x < len; x++) {
i += 1;
j += state[i];
std::swap(state[i], state[j]);
dst[x] = src[x] ^ state[(state[i] + state[j]) & 0xff];
}
}
class RC4Crypter : public Crypter {
public:
RC4Crypter(base::Bytes key, base::Bytes nonce);
bool is_streaming() const noexcept override { return true; }
bool is_seekable() const noexcept override { return false; }
uint16_t block_size() const noexcept override { return RC4_BLOCKSIZE; }
void encrypt(base::MutableBytes dst, base::Bytes src) noexcept override;
void decrypt(base::MutableBytes dst, base::Bytes src) noexcept override;
private:
void set_counter(uint64_t value) noexcept;
void set_position(uint64_t value) noexcept;
uint64_t fetch_counter() const noexcept;
uint64_t fetch_position() const noexcept;
void next();
crypto::subtle::SecureMemory<RC4State> state_;
};
RC4Crypter::RC4Crypter(base::Bytes key, base::Bytes nonce) {
if (key.size() < 1 || key.size() > 256) {
throw std::invalid_argument("key size not supported for RC4");
}
if (nonce.size() != 0) {
throw std::invalid_argument("nonce size not supported for RC4");
}
state_->rekey(key.data(), key.size());
}
void RC4Crypter::encrypt(base::MutableBytes dst, base::Bytes src) noexcept {
CHECK_GE(dst.size(), src.size());
state_->encrypt(dst.data(), src.data(), src.size());
}
void RC4Crypter::decrypt(base::MutableBytes dst, base::Bytes src) noexcept {
encrypt(dst, src);
}
} // inline namespace implementation
std::unique_ptr<Crypter> new_rc4(base::Bytes key, base::Bytes nonce) {
return base::backport::make_unique<RC4Crypter>(key, nonce);
}
} // namespace cipher
} // namespace crypto
static const crypto::StreamCipher RC4 = {
crypto::cipher::RC4_BLOCKSIZE, // block_size
crypto::cipher::RC4_KEYSIZE, // key_size
crypto::cipher::RC4_NONCESIZE, // nonce_size
crypto::Security::weak, // security
0, // flags
"RC4", // name
crypto::cipher::new_rc4, // newfn
};
static void init() __attribute__((constructor));
static void init() { crypto::register_stream_cipher(&RC4); }
| 28.847619 | 76 | 0.657643 | chronos-tachyon |
a11f5bc3bebbbae05fd0ca7a47ecce47da3b6ee7 | 20,045 | cpp | C++ | KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 13 | 2019-10-19T17:41:19.000Z | 2021-11-04T18:50:03.000Z | KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 3 | 2019-12-09T06:22:43.000Z | 2020-05-28T09:33:44.000Z | KRender/Internal/Vulkan/KVulkanHeapAllocator.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | null | null | null | #include "KVulkanHeapAllocator.h"
#include "KVulkanGlobal.h"
#include "KVulkanHelper.h"
#include "KBase/Publish/KNumerical.h"
#include "KBase/Interface/IKLog.h"
#include <algorithm>
#include <mutex>
#define KVUALKAN_HEAP_TRUELY_ALLOC
//#define KVUALKAN_HEAP_BRUTE_CHECK
namespace KVulkanHeapAllocator
{
struct BlockInfo;
struct PageInfo;
struct MemoryHeap;
static VkDevice DEVICE = nullptr;
static VkPhysicalDevice PHYSICAL_DEVICE = nullptr;
static uint32_t MEMORY_TYPE_COUNT = 0;
static std::vector<VkDeviceSize> MIN_PAGE_SIZE;
static std::vector<VkDeviceSize> HEAP_REMAIN_SIZE;
static std::vector<MemoryHeap*> MEMORY_TYPE_TO_HEAP;
static VkDeviceSize ALLOC_FACTOR = 1024;
static VkDeviceSize MAX_ALLOC_COUNT = 0;
static VkDeviceSize BLOCK_SIZE_FACTOR = 4;
static std::mutex ALLOC_FREE_LOCK;
enum MemoryAllocateType
{
MAT_DEFAULT,
MAT_ACCELERATION_STRUCTURE,
MAT_DEVICE_ADDRESS,
MAT_COUNT
};
struct MemoryAllocateTypeProperty
{
bool needDeviceAddress;
};
static MemoryAllocateTypeProperty MEMORY_ALLOCATE_TYPE_PROPERITES[MAT_COUNT] =
{
// MAT_DEFAULT
{ false },
// MAT_ACCELERATION_STRUCTURE
{ true },
// MAT_DEVICE_ADDRESS
{ true },
};
struct BlockInfo
{
// ๆฌblockๅจpage็ๅ็งป้
VkDeviceSize offset;
// ๆฌblockๅคงๅฐ
VkDeviceSize size;
int isFree;
BlockInfo* pNext;
BlockInfo* pPre;
// ้ขๅคไฟกๆฏ ็จไบ้ๆพๆถ็ดขๅผ
PageInfo* pParent;
BlockInfo(PageInfo* _pParent)
{
assert(_pParent);
isFree = true;
offset = 0;
size = 0;
pNext = pPre = nullptr;
pParent = _pParent;
}
};
struct MemoryHeap;
struct PageInfo
{
VkDevice vkDevice;
#ifdef KVUALKAN_HEAP_TRUELY_ALLOC
VkDeviceMemory vkMemroy;
#else
void* vkMemroy;
#endif
VkDeviceSize size;
MemoryAllocateType type;
uint32_t memoryTypeIndex;
uint32_t memoryHeapIndex;
BlockInfo* pHead;
PageInfo* pPre;
PageInfo* pNext;
// ้ขๅคไฟกๆฏ ็จไบ้ๆพๆถ็ดขๅผ
MemoryHeap* pParent;
int noShare;
PageInfo(MemoryHeap* _pParent, VkDevice _vkDevice, VkDeviceSize _size,
MemoryAllocateType _type, uint32_t _memoryTypeIndex, uint32_t _memoryHeapIndex, int _noShare)
{
vkDevice = _vkDevice;
size = _size;
type = _type;
memoryTypeIndex = _memoryTypeIndex;
memoryHeapIndex = _memoryHeapIndex;
vkMemroy = VK_NULL_HANDLE;
pHead = nullptr;
pPre = pNext = nullptr;
pParent = _pParent;
noShare = _noShare;
}
~PageInfo()
{
assert(vkMemroy == VK_NULL_HANDLE);
}
void Check()
{
#ifdef KVUALKAN_HEAP_BRUTE_CHECK
if(pHead)
{
VkDeviceSize sum = 0;
for(BlockInfo* p = pHead; p; p = p->pNext)
{
sum += p->size;
}
assert(sum == size);
}
#endif
}
BlockInfo* Alloc(VkDeviceSize sizeToFit, VkDeviceSize alignment)
{
if(sizeToFit > size)
{
return nullptr;
}
if(vkMemroy == VK_NULL_HANDLE)
{
assert(pHead == nullptr);
#ifdef KVUALKAN_HEAP_TRUELY_ALLOC
{
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = size;
allocInfo.pNext = nullptr;
allocInfo.memoryTypeIndex = memoryTypeIndex;
if (MEMORY_ALLOCATE_TYPE_PROPERITES[type].needDeviceAddress)
{
// If the buffer has VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT set we also need to enable the appropriate flag during allocation
VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = {};
allocFlagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR;
allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
allocInfo.pNext = &allocFlagsInfo;
}
VK_ASSERT_RESULT(vkAllocateMemory(DEVICE, &allocInfo, nullptr, &vkMemroy));
HEAP_REMAIN_SIZE[memoryHeapIndex] -= size;
}
#else
{
vkMemroy = malloc((size_t)size);
}
#endif
pHead = KNEW BlockInfo(this);
pHead->isFree = true;
pHead->offset = 0;
pHead->pPre = pHead->pNext = nullptr;
pHead->size = size;
pHead->pParent = this;
// ๆๅคไฝ็็ฉบ้ดๅ่ฃๅบๆฅ
Split(pHead, 0, sizeToFit);
// ๅทฒ่ขซๅ ็จ
pHead->isFree = false;
Check();
return pHead;
}
else
{
assert(pHead);
VkDeviceSize offset = 0;
VkDeviceSize extraSize = 0;
BlockInfo* pTemp = Find(sizeToFit, alignment, &offset, &extraSize);
if(pTemp)
{
// ๆๅคไฝ็็ฉบ้ดๅ่ฃๅบๆฅ
Split(pTemp, offset, sizeToFit);
// ๅทฒ่ขซๅ ็จ
pTemp->isFree = false;
Check();
return pTemp;
}
Check();
return nullptr;
}
}
void Free(BlockInfo* pBlock)
{
assert(pBlock->pParent == this);
assert(!pBlock->isFree);
assert(pHead);
// ๅทฒ่ขซ้ๆพ
pBlock->isFree = true;
// ไธๅๅ็freeblockๅๅนถ
Trim(pBlock);
// ๅชๅฉไธๆๅไธไธช่็น ้ๆพๅ
ๅญ
if(pHead->pNext == nullptr)
{
SAFE_DELETE(pHead);
assert(vkMemroy != VK_NULL_HANDLE);
#ifdef KVUALKAN_HEAP_TRUELY_ALLOC
vkFreeMemory(vkDevice, vkMemroy, nullptr);
HEAP_REMAIN_SIZE[memoryHeapIndex] += size;
#else
free(vkMemroy);
#endif
vkMemroy = VK_NULL_HANDLE;
}
}
// ้ๆพๆfreeblock
void Trim()
{
BlockInfo* pTemp = pHead;
while(pTemp)
{
Trim(pTemp);
pTemp = pTemp->pNext;
}
}
void Clear()
{
if(vkMemroy)
{
#ifdef KVUALKAN_HEAP_TRUELY_ALLOC
vkFreeMemory(vkDevice, vkMemroy, nullptr);
HEAP_REMAIN_SIZE[memoryHeapIndex] += size;
#else
free(vkMemroy);
#endif
vkMemroy = VK_NULL_HANDLE;
}
for(BlockInfo* p = pHead; p != nullptr;)
{
BlockInfo* pNext = p->pNext;
SAFE_DELETE(p);
p = pNext;
}
pHead = nullptr;
}
BlockInfo* Find(VkDeviceSize sizeToFit, VkDeviceSize alignment, VkDeviceSize* pOffset, VkDeviceSize* pExtraSize)
{
BlockInfo* pTemp = pHead;
while(pTemp)
{
if(pTemp->isFree && pTemp->size >= sizeToFit)
{
VkDeviceSize offset = (pTemp->offset % size) ? pTemp->offset + alignment - (pTemp->offset % alignment) : pTemp->offset;
VkDeviceSize extraSize = offset - pTemp->offset + sizeToFit;
assert(offset % alignment == 0);
if(extraSize <= pTemp->size)
{
if(pOffset)
{
*pOffset = offset;
}
if(pExtraSize)
{
*pExtraSize = extraSize;
}
return pTemp;
}
}
pTemp = pTemp->pNext;
}
return nullptr;
}
bool HasSpace(VkDeviceSize sizeToFit, VkDeviceSize alignment)
{
if(pHead)
{
return Find(sizeToFit, alignment, nullptr, nullptr) != nullptr;
}
else
{
return sizeToFit <= size;
}
}
static void Split(BlockInfo* pBlock, VkDeviceSize offset, VkDeviceSize sizeToFit)
{
assert(pBlock->isFree && pBlock->size >= sizeToFit);
if(pBlock->isFree && pBlock->size >= sizeToFit)
{
if(offset > 0)
{
BlockInfo* pPre = KNEW BlockInfo(pBlock->pParent);
pPre->pPre = pBlock->pPre;
if(pPre->pPre)
pPre->pPre->pNext = pPre;
pPre->pNext = pBlock;
pBlock->pPre = pPre;
if(pBlock == pBlock->pParent->pHead)
{
pBlock->pParent->pHead = pPre;
}
pPre->isFree = true;
pPre->offset = pBlock->offset;
pPre->size = offset - pBlock->offset;
pBlock->offset += pPre->size;
pBlock->size -= pPre->size;
}
VkDeviceSize remainSize = pBlock->size - sizeToFit;
BlockInfo* pNext = pBlock->pNext;
// ๅฆๆไธไธไธชblockๅฏไปฅๆฟๆๅฉไฝ็ฉบ้ด
if(pNext && pNext->isFree)
{
pNext->offset -= remainSize;
pNext->size += remainSize;
}
// ๅฆๅๅ่ฃๅคไธไธชblockๆฅ่ฎฐๅฝๅฉไฝ็ฉบ้ด
else if(remainSize > 0)
{
// ๆๅฉไฝ็็ฉบ้ดๅ้
ๅฐๆฐ่็นไธ
BlockInfo* pNewBlock = KNEW BlockInfo(pBlock->pParent);
pNewBlock->isFree = true;
pNewBlock->size = remainSize;
pNewBlock->offset = pBlock->offset + sizeToFit;
pNewBlock->pNext = pNext;
pNewBlock->pPre = pBlock;
if(pNext)
pNext->pPre = pNewBlock;
pBlock->pNext = pNewBlock;
}
// ้ๆฐๅ้
ๆฌblock็ฉบ้ด
pBlock->size = sizeToFit;
}
}
static void Trim(BlockInfo* pBlock)
{
assert(pBlock->isFree);
BlockInfo* pTemp = nullptr;
if(pBlock->isFree)
{
// ไธๅ้ข็freeblockๅๅนถ
while(pBlock->pNext && pBlock->pNext->isFree)
{
pBlock->size += pBlock->pNext->size;
pTemp = pBlock->pNext;
pBlock->pNext = pTemp->pNext;
if(pTemp->pNext)
{
pTemp->pNext->pPre = pBlock;
}
SAFE_DELETE(pTemp);
}
// ไธๅ้ข็freeblockๅๅนถ
while(pBlock->pPre && pBlock->pPre->isFree)
{
pBlock->size += pBlock->pPre->size;
pBlock->offset = pBlock->pPre->offset;
pTemp = pBlock->pPre;
pBlock->pPre = pTemp->pPre;
if(pTemp->pPre)
{
pTemp->pPre->pNext = pBlock;
}
SAFE_DELETE(pTemp);
}
// ๆไธบๅคด็ป็น
if(pBlock->pPre == nullptr)
{
assert(pBlock->pParent);
pBlock->pParent->pHead = pBlock;
}
}
}
};
struct MemoryHeap
{
VkDevice vkDevice;
uint32_t memoryTypeIndex;
uint32_t memoryHeapIndex;
PageInfo* pHead[MAT_COUNT];
PageInfo* pNoShareHead[MAT_COUNT];
VkDeviceSize lastPageSize[MAT_COUNT];
VkDeviceSize totalPageSize[MAT_COUNT];
MemoryHeap(VkDevice _device, uint32_t _memoryTypeIndex, uint32_t _memoryHeapIndex)
{
vkDevice = _device;
memoryTypeIndex = _memoryTypeIndex;
memoryHeapIndex = _memoryHeapIndex;
for (uint32_t i = 0; i < MAT_COUNT; ++i)
{
pHead[i] = nullptr;
pNoShareHead[i] = nullptr;
lastPageSize[i] = 0;
totalPageSize[i] = 0;
}
}
void Check()
{
#ifdef KVUALKAN_HEAP_BRUTE_CHECK
for (uint32_t i = 0; i < MAT_COUNT; ++i)
{
if (pHead[i])
{
VkDeviceSize sum = 0;
for (PageInfo* p = pHead[i]; p; p = p->pNext)
{
p->Check();
sum += p->size;
}
assert(sum == totalPageSize[i]);
}
}
#endif
}
void Clear()
{
PageInfo* pTemp = nullptr;
for (uint32_t i = 0; i < MAT_COUNT; ++i)
{
lastPageSize[i] = totalPageSize[i] = 0;
pTemp = pHead[i];
while (pTemp)
{
PageInfo* pNext = pTemp->pNext;
pTemp->Clear();
SAFE_DELETE(pTemp);
pTemp = pNext;
}
pTemp = pNoShareHead[i];
while (pTemp)
{
PageInfo* pNext = pTemp->pNext;
pTemp->Clear();
SAFE_DELETE(pTemp);
pTemp = pNext;
}
}
}
VkDeviceSize NewPageSize(MemoryAllocateType type)
{
VkDeviceSize newSize = lastPageSize[type] ? lastPageSize[type] << 1 : MIN_PAGE_SIZE[memoryHeapIndex];
newSize = std::max(MIN_PAGE_SIZE[memoryHeapIndex], newSize);
return newSize;
}
VkDeviceSize FindPageFitSize(VkDeviceSize pageSize, VkDeviceSize sizeToFit)
{
VkDeviceSize newPageSize = KNumerical::Factor2GreaterEqual(sizeToFit);
newPageSize = std::max(newPageSize, MIN_PAGE_SIZE[memoryHeapIndex]);
newPageSize = std::min(newPageSize, pageSize);
return newPageSize;
}
BlockInfo* Alloc(VkDeviceSize sizeToFit, VkDeviceSize alignment, bool noShared, MemoryAllocateType type)
{
std::lock_guard<decltype(ALLOC_FREE_LOCK)> guard(ALLOC_FREE_LOCK);
if(noShared)
{
PageInfo* pPage = KNEW PageInfo(this, vkDevice, sizeToFit, type, memoryTypeIndex, memoryHeapIndex, true);
BlockInfo* pBlock = pPage->Alloc(sizeToFit, alignment);
pPage->pNext = pNoShareHead[type];
if(pNoShareHead[type])
{
pNoShareHead[type]->pPre = pPage;
}
pNoShareHead[type] = pPage;
assert(pBlock && !pBlock->isFree);
return pBlock;
}
else
{
VkDeviceSize allocFactor = ALLOC_FACTOR;
// ๅ้
ๅคงๅฐๅฟ
้กปๆฏallocFactor็ๆดๆฐๅ
// ๅฝๆฏๆฌกๅ้
้ฝๆฏallocFactor็ๆดๆฐๅๆถๅ ๅฐฑ่ฝไฟ่ฏๅไธไธชpage้็offsetไนๆฏallocFactor็ๆดๆฐๅ
// sizeToFit = ((sizeToFit + ALLOC_FACTOR - 1) / ALLOC_FACTOR) * ALLOC_FACTOR;
// assert(sizeToFit % ALLOC_FACTOR == 0);
alignment = KNumerical::LCM(alignment, ALLOC_FACTOR);
PageInfo* pPage = Find(sizeToFit, alignment, type);
if(!pPage)
{
// ๅฝๅๆๆpage้ๆพไธๅฐ่ถณๅค็ฉบ้ด ๅ้
ไธไธชๆฐ็ๆๅ
ฅๅฐๆๅ ไฟ่ฏheapๆป็ฉบ้ด2ๅ้ๅข
while (true)
{
pPage = Nail(type);
VkDeviceSize newSize = NewPageSize(type);
lastPageSize[type] = newSize;
totalPageSize[type] += newSize;
PageInfo* pNewPage = KNEW PageInfo(this, vkDevice, newSize, type, memoryTypeIndex, memoryHeapIndex, false);
if(pPage)
pPage->pNext = pNewPage;
pNewPage->pPre = pPage;
pNewPage->pNext = nullptr;
// ๅคด็ป็น
if(pHead[type] == nullptr)
{
pHead[type] = pNewPage;
}
if(pNewPage->size >= sizeToFit)
{
pPage = pNewPage;
break;
}
}
}
// ๆๅคไฝ็็ฉบ้ดๅ่ฃๅบๆฅ ๅฐฝ้่็ๅฎ้
ๅ้
็ๅ
ๅญ
if(pPage->vkMemroy == VK_NULL_HANDLE)
{
VkDeviceSize newPageSize = FindPageFitSize(pPage->size, sizeToFit);
Split(pPage, newPageSize);
}
BlockInfo* pBlock = pPage->Alloc(sizeToFit, alignment);
assert(pBlock && !pBlock->isFree);
Check();
return pBlock;
}
}
void Free(BlockInfo* pBlock)
{
std::lock_guard<decltype(ALLOC_FREE_LOCK)> guard(ALLOC_FREE_LOCK);
assert(pBlock->pParent != nullptr);
PageInfo* pPage = pBlock->pParent;
assert(pPage->pParent == this);
MemoryAllocateType type = pPage->type;
// ็นๆฎๆ
ๅตๅช่ฝ็ฌๅ ไธไธชvkAllocateMemory็นๆฎๅค็ ่ฟ้่ฟๅpageๅๆถๅ ้ค
if(pPage->noShare)
{
if(pPage == pNoShareHead[type])
{
pNoShareHead[type] = pPage->pNext;
}
if(pPage->pPre)
{
pPage->pPre->pNext = pPage->pNext;
}
if(pPage->pNext)
{
pPage->pNext->pPre = pPage->pPre;
}
pPage->Clear();
SAFE_DELETE(pPage);
Check();
}
else
{
pPage->Free(pBlock);
Check();
// ็ฉบ้ดไธบ็ฉบ ๅฐ่ฏๅๅนถไธด่ฟpage
if(pPage->vkMemroy == VK_NULL_HANDLE)
{
Trim(pPage);
}
Check();
}
}
PageInfo* Find(VkDeviceSize sizeToFit, VkDeviceSize alignment, MemoryAllocateType type)
{
PageInfo* pTemp = pHead[type];
while(pTemp)
{
if(pTemp->size >= sizeToFit)
{
if(pTemp->HasSpace(sizeToFit, alignment))
{
return pTemp;
}
}
pTemp = pTemp->pNext;
}
return nullptr;
}
PageInfo* Nail(MemoryAllocateType type)
{
PageInfo* pTemp = pHead[type];
while(pTemp && pTemp->pNext)
{
pTemp = pTemp->pNext;
}
return pTemp;
}
static void Trim(PageInfo* pPage)
{
assert(pPage->vkMemroy == VK_NULL_HANDLE);
PageInfo* pTemp = nullptr;
if(pPage->vkMemroy == VK_NULL_HANDLE)
{
// ไธๅ้ข็freepageๅๅนถ
while(pPage->pNext && pPage->pNext->vkMemroy == VK_NULL_HANDLE)
{
pPage->size += pPage->pNext->size;
pTemp = pPage->pNext;
pPage->pNext = pTemp->pNext;
if(pTemp->pNext)
{
pTemp->pNext->pPre = pPage;
}
SAFE_DELETE(pTemp);
pPage->Check();
}
// ไธๅ้ข็freepageๅๅนถ
while(pPage->pPre && pPage->pPre->vkMemroy == VK_NULL_HANDLE)
{
pPage->size += pPage->pPre->size;
pTemp = pPage->pPre;
pPage->pPre = pTemp->pPre;
if(pTemp->pPre)
{
pTemp->pPre->pNext = pPage;
}
SAFE_DELETE(pTemp);
pPage->Check();
}
// ๆไธบๅคด็ป็น
if(pPage->pPre == nullptr)
{
assert(pPage->pParent);
MemoryAllocateType type = pPage->type;
pPage->pParent->pHead[type] = pPage;
}
}
}
static void Split(PageInfo* pPage, VkDeviceSize sizeToFit)
{
assert(pPage->vkMemroy == VK_NULL_HANDLE && pPage->size >= sizeToFit);
if(pPage->vkMemroy == VK_NULL_HANDLE && pPage->size >= sizeToFit)
{
// page็ๆฐๅคงๅฐไธๆฏALLOC_FACTOR็ๆดๆฐๅ ๆ ๆณๅ่ฃ
if(sizeToFit % ALLOC_FACTOR != 0)
{
return;
}
VkDeviceSize remainSize = pPage->size - sizeToFit;
PageInfo* pNext = pPage->pNext;
// ๅฆๆไธไธไธชpageๅฏไปฅๆฟๆๅฉไฝ็ฉบ้ด
if(pNext && pNext->vkMemroy == VK_NULL_HANDLE)
{
pNext->size += remainSize;
}
// ๅฆๅๅ่ฃๅคไธไธชpageๆฅ่ฎฐๅฝๅฉไฝ็ฉบ้ด
else if(remainSize > 0)
{
// ๆๅฉไฝ็็ฉบ้ดๅ้
ๅฐๆฐ่็นไธ
PageInfo* pNewPage = KNEW PageInfo(pPage->pParent, pPage->vkDevice, remainSize, pPage->type, pPage->memoryTypeIndex, pPage->memoryHeapIndex, false);
pNewPage->vkMemroy = VK_NULL_HANDLE;
pNewPage->size = remainSize;
pNewPage->pNext = pNext;
pNewPage->pPre = pPage;
if(pNext)
pNext->pPre = pNewPage;
pPage->pNext = pNewPage;
}
// ้ๆฐๅ้
ๆฌpage็ฉบ้ด
pPage->size = sizeToFit;
}
}
};
bool Init()
{
if(KVulkanGlobal::deviceReady)
{
DEVICE = KVulkanGlobal::device;
PHYSICAL_DEVICE = KVulkanGlobal::physicalDevice;
VkPhysicalDeviceProperties deviceProperties = {};
vkGetPhysicalDeviceProperties(PHYSICAL_DEVICE, &deviceProperties);
MAX_ALLOC_COUNT = deviceProperties.limits.maxMemoryAllocationCount;
/*
Linear buffer 0xXX is aliased with non-linear image 0xXX which may indicate a bug.
For further info refer to the Buffer-Image Granularity section of the Vulkan specification. >
(https://www.khronos.org/registry/vulkan/specs/1.0-extensions/xhtml/vkspec.html#resources-bufferimagegranularity)
*/
// ็ฑไบ่ฟ้imageไธbufferๅ
ฑไบซๅไธไปฝVkDeviceMemory ๅ ๆญคๆฏๆฌกๅ้
ๅ ็จ็็ฉบ้ดๅคงๅฐๅฟ
้กปๆฏ่ฏฅfactor็ๆดๆฐๅ
ALLOC_FACTOR = deviceProperties.limits.bufferImageGranularity;
VkPhysicalDeviceMemoryProperties memoryProperties = {};
vkGetPhysicalDeviceMemoryProperties(PHYSICAL_DEVICE, &memoryProperties);
MEMORY_TYPE_COUNT = memoryProperties.memoryTypeCount;
MEMORY_TYPE_TO_HEAP.resize(memoryProperties.memoryTypeCount);
for(uint32_t memTypeIdx = 0; memTypeIdx < memoryProperties.memoryTypeCount; ++memTypeIdx)
{
uint32_t memHeapIndex = memoryProperties.memoryTypes[memTypeIdx].heapIndex;
MEMORY_TYPE_TO_HEAP[memTypeIdx] = KNEW MemoryHeap(KVulkanGlobal::device, memTypeIdx, memHeapIndex);
}
HEAP_REMAIN_SIZE.resize(memoryProperties.memoryHeapCount);
MIN_PAGE_SIZE.resize(memoryProperties.memoryHeapCount);
for(uint32_t memHeapIdx = 0; memHeapIdx < memoryProperties.memoryHeapCount; ++memHeapIdx)
{
HEAP_REMAIN_SIZE[memHeapIdx] = memoryProperties.memoryHeaps[memHeapIdx].size;
MIN_PAGE_SIZE[memHeapIdx] = std::min
(
HEAP_REMAIN_SIZE[memHeapIdx],
BLOCK_SIZE_FACTOR * KNumerical::Pow2GreaterEqual(memoryProperties.memoryHeaps[memHeapIdx].size * memoryProperties.memoryHeapCount / MAX_ALLOC_COUNT)
);
}
return true;
}
else
{
#ifdef KVUALKAN_HEAP_TRUELY_ALLOC
return false;
#else
MEMORY_TYPE_COUNT = 1;
MEMORY_TYPE_TO_HEAP.resize(1);
MEMORY_TYPE_TO_HEAP[0] = KNEW MemoryHeap(KVulkanGlobal::device, 0, 0);
HEAP_REMAIN_SIZE.resize(1);
HEAP_REMAIN_SIZE[0] = static_cast<VkDeviceSize>(512U * 1024U * 1024U);
MIN_PAGE_SIZE.resize(1);
MIN_PAGE_SIZE[0] = static_cast<VkDeviceSize>(1);
MAX_PAGE_SIZE.resize(1);
MAX_PAGE_SIZE[0] = static_cast<VkDeviceSize>(512U * 1024U * 1024U);
return true;
#endif
}
}
bool UnInit()
{
for(uint32_t memoryTypeIndex = 0; memoryTypeIndex < MEMORY_TYPE_COUNT; ++memoryTypeIndex)
{
MemoryHeap* pHeap = MEMORY_TYPE_TO_HEAP[memoryTypeIndex];
if(pHeap)
{
pHeap->Clear();
SAFE_DELETE(pHeap);
}
}
MEMORY_TYPE_COUNT = 0;
MEMORY_TYPE_TO_HEAP.clear();
HEAP_REMAIN_SIZE.clear();
MIN_PAGE_SIZE.clear();
return true;
}
bool Alloc(VkDeviceSize size, VkDeviceSize alignment, uint32_t memoryTypeIndex, VkMemoryPropertyFlags memoryUsage, VkBufferUsageFlags bufferUsage, AllocInfo& info)
{
if(memoryTypeIndex < MEMORY_TYPE_COUNT)
{
MemoryHeap* pHeap = MEMORY_TYPE_TO_HEAP[memoryTypeIndex];
bool noShared = false;
MemoryAllocateType type = MAT_DEFAULT;
if (memoryUsage & ~VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
{
noShared = true;
}
if (bufferUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT)
{
type = MAT_DEVICE_ADDRESS;
}
// ๅ
่ฟฝๅ ้็ปๆไธ่ฝๅคไธๅ
ถไป่ตๆบๅ
ฑไบซVkDeviceMemory ่ฟๆฏๅฆๆฏ้ฉฑๅจ็BUG
if (bufferUsage & VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR)
{
type = MAT_ACCELERATION_STRUCTURE;
}
info.internalData = pHeap->Alloc(size, alignment, noShared, type);
if(info.internalData)
{
BlockInfo* pBlock = (BlockInfo*)info.internalData;
PageInfo* pPage = (PageInfo*)pBlock->pParent;
info.vkMemroy = static_cast<VkDeviceMemory>(pPage->vkMemroy);
info.vkOffset = pBlock->offset;
return true;
}
}
return false;
}
bool Free(const AllocInfo& data)
{
BlockInfo* pBlock = (BlockInfo*)data.internalData;
if(pBlock)
{
MemoryHeap* pHeap = pBlock->pParent->pParent;
pHeap->Free(pBlock);
return true;
}
return false;
}
} | 22.88242 | 164 | 0.659317 | King19931229 |
a1217c84f390c7b4ccaca56a570e71deecf726ba | 2,473 | cpp | C++ | Section11/Section11Challenge/Section11Challenge/main.cpp | tslothorst/Learning-Cpp | ad7fd6fdcf6678202cc376e910cbdae454fd9273 | [
"MIT"
] | null | null | null | Section11/Section11Challenge/Section11Challenge/main.cpp | tslothorst/Learning-Cpp | ad7fd6fdcf6678202cc376e910cbdae454fd9273 | [
"MIT"
] | null | null | null | Section11/Section11Challenge/Section11Challenge/main.cpp | tslothorst/Learning-Cpp | ad7fd6fdcf6678202cc376e910cbdae454fd9273 | [
"MIT"
] | null | null | null | #include "main.h"
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void print_menu();
void add_number(vector<int> &userNumbers);
void display_list(const vector<int> &userNumbers);
double get_avgnum(const vector<int> &userNumbers);
int get_smallnum(const vector<int> &userNumbers);
int get_largenum(const vector<int> &userNumbers);
int main()
{
vector<int> userNumbers{};
while (true)
{
char choice{};
print_menu();
cin >> choice;
if (tolower(choice) == 'q')
{
cout << "Goodbye\n";
break;
}
if (towlower(choice) == 'a')
{
add_number(userNumbers);
}
if (tolower(choice) == 'p')
{
display_list(userNumbers);
}
if (tolower(choice) == 'm')
{
cout << "Average of the elements in the list is: " << get_avgnum(userNumbers) << endl;
}
if (tolower(choice) == 's')
{
cout << "The smallest number in the list is: " << get_smallnum(userNumbers) << endl;
}
if (tolower(choice) == 'l')
{
cout << "The largest number in the list is: " << get_largenum(userNumbers) << endl;
}
}
return 0;
}
void print_menu()
{
cout << "\nPlease make a choice from these options" << endl;
cout << "P - Print numbers\nA - Add a number\nM - Display mean of the numbers\nS - Display the smallest number\nL - Display the largest number\nQ - Quit\n";
cout << "Input: ";
}
void add_number(vector<int> &userNumbers)
{
int userNum{};
cout << "Please enter an integer: ";
cin >> userNum;
userNumbers.push_back(userNum);
cout << userNum << " added to list!" << endl;
}
void display_list(const vector<int> &userNumbers)
{
if (userNumbers.size() == 0)
{
cout << "[] - the list is empty" << endl;
}
for (size_t i = 0; i < userNumbers.size(); i++)
{
cout << userNumbers.at(i) << endl;
}
}
double get_avgnum(const vector<int> &userNumbers)
{
double buffer{};
double avgNum{};
for (size_t i = 0; i < userNumbers.size(); i++)
{
buffer += userNumbers[i];
avgNum = buffer / userNumbers.size();
}
return avgNum;
}
int get_smallnum(const vector<int> &userNumbers)
{
auto result = min_element(userNumbers.begin(), userNumbers.end());
int smallpos = distance(userNumbers.begin(), result);
int smallnum = userNumbers.at(smallpos);
return smallnum;
}
int get_largenum(const vector<int> &userNumbers)
{
auto result = max_element(userNumbers.begin(), userNumbers.end());
int largepos = distance(userNumbers.begin(), result);
int largenum = userNumbers.at(largepos);
return largenum;
}
| 22.688073 | 157 | 0.66114 | tslothorst |
a12692f2069db6fd63b1d5df08529db6910bf3cf | 11,998 | cpp | C++ | newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp | execomrt/newton-dynamics | b38363000bed09cf514cdad92013b0c0b4c48f3f | [
"Zlib"
] | null | null | null | newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp | execomrt/newton-dynamics | b38363000bed09cf514cdad92013b0c0b4c48f3f | [
"Zlib"
] | null | null | null | newton-4.00/applications/ndSandbox/toolbox/ndVehicleUI.cpp | execomrt/newton-dynamics | b38363000bed09cf514cdad92013b0c0b4c48f3f | [
"Zlib"
] | null | null | null | /* Copyright (c) <2003-2021> <Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
// this vehicle UI class was implemented by Dave Gravel,
// so sole some of the Open Gl errors with legacy glBegin/GlEnd
// operation with deprecated since OpenGl 3.3
// Thank you very much Dave
#include "ndSandboxStdafx.h"
#include "ndVehicleUI.h"
#include "ndDemoEntityManager.h"
//ndDemoMesh* CreateDialMesh(ndDemoEntityManager* const scene, const char* const texName)
//{
// ndMeshEffect mesh;
//
// dArray<ndMeshEffect::dMaterial>& materialArray = mesh.GetMaterials();
// ndMeshEffect::dMaterial material;
// strcpy(material.m_textureName, texName);
// materialArray.PushBack(material);
//
// dFloat32 gageSize = 100.0f;
// mesh.BeginBuild();
// mesh.BeginBuildFace();
// mesh.AddPoint(-gageSize, gageSize, 0.0f);
// mesh.AddUV0(0.0f, 1.0f);
// mesh.AddMaterial(0);
//
// mesh.AddPoint(-gageSize, -gageSize, 0.0f);
// mesh.AddUV0(0.0f, 0.0f);
// mesh.AddMaterial(0);
//
// mesh.AddPoint(gageSize, -gageSize, 0.0f);
// mesh.AddUV0(1.0f, 0.0f);
// mesh.AddMaterial(0);
// mesh.EndBuildFace();
//
// mesh.BeginBuildFace();
// mesh.AddPoint(-gageSize, gageSize, 0.0f);
// mesh.AddUV0(0.0f, 1.0f);
// mesh.AddMaterial(0);
//
// mesh.AddPoint(gageSize, -gageSize, 0.0f);
// mesh.AddUV0(1.0f, 0.0f);
// mesh.AddMaterial(0);
//
// mesh.AddPoint(gageSize, gageSize, 0.0f);
// mesh.AddUV0(1.0f, 1.0f);
// mesh.AddMaterial(0);
// mesh.EndBuildFace();
//
// mesh.EndBuild(0.0f);
// return new ndDemoMesh("dialMesh", &mesh, scene->GetShaderCache());
//}
const GLchar* ndVehicleUI::m_vertexShader =
"in vec3 Position;\n"
"in vec2 UV;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"uniform mat4 ProjMtx;\n"
"uniform mat4 ModMtx;\n"
"uniform float ptsize;\n"
"uniform vec4 color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = color;\n"
" gl_Position = ProjMtx * ModMtx * vec4(Position.xy * ptsize,0.0,1.0);\n"
"}\n"
;
const GLchar* ndVehicleUI::m_fragmentShader =
"uniform sampler2D UIText;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(UIText, Frag_UV.st);\n"
"}\n"
;
const GLchar* ndVehicleUI::m_vertexShaderWithVersion[2] = { "#version 330 core\n", m_vertexShader };
const GLchar* ndVehicleUI::m_fragmentShaderWithVersion[2] = { "#version 330 core\n", m_fragmentShader };
ndVehicleUI::ndVehicleUI()
:dClassAlloc()
,m_shaderHandle(0)
,m_vboDyn(0)
,m_vboSta(0)
,m_vaoDyn(0)
,m_vaoSta(0)
,m_iboDyn(0)
,m_iboSta(0)
{
};
ndVehicleUI::~ndVehicleUI()
{
if (m_shaderHandle)
{
glDeleteProgram(m_shaderHandle);
}
if (m_iboSta)
{
glDeleteBuffers(1, &m_iboSta);
}
if (m_vboSta)
{
glDeleteBuffers(1, &m_vboSta);
}
if (m_vaoSta)
{
glDeleteVertexArrays(1, &m_vaoSta);
}
if (m_iboDyn)
{
glDeleteBuffers(1, &m_iboDyn);
}
if (m_vboDyn)
{
glDeleteBuffers(1, &m_vboDyn);
}
if (m_vaoDyn)
{
glDeleteVertexArrays(1, &m_vaoDyn);
}
};
void ndVehicleUI::CreateOrthoViewMatrix(ndDemoEntityManager* const uscene, dFloat32 origin_x, const dFloat32 origin_y, dMatrix& projmatrix)
{
dFloat32 sizeX = (dFloat32)(1.0f * uscene->GetWidth());
dFloat32 sizeY = (dFloat32)(1.0f * uscene->GetHeight());
dFloat32 L = origin_x;
dFloat32 R = origin_x + sizeX;
dFloat32 T = origin_y;
dFloat32 B = origin_y + sizeY;
projmatrix = dMatrix({ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f });
}
void ndVehicleUI::CreateBufferUI()
{
if (!m_vaoDyn)
{
m_shaderHandle = glCreateProgram();
GLuint m_vertHandle = glCreateShader(GL_VERTEX_SHADER);
GLuint m_fragHandle = glCreateShader(GL_FRAGMENT_SHADER);
GLint Result = GL_FALSE;
dInt32 InfoLogLength = 0;
glShaderSource(m_vertHandle, 2, m_vertexShaderWithVersion, NULL);
glCompileShader(m_vertHandle);
// Check Vertex Shader
glGetShaderiv(m_vertHandle, GL_COMPILE_STATUS, &Result);
glGetShaderiv(m_vertHandle, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0)
{
printf("Vertex shader error! \n");
// std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
// glGetShaderInfoLog(g_VertHandle3D, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
// printf("Vertex %s\n", &VertexShaderErrorMessage[0]);
}
glShaderSource(m_fragHandle, 2, m_fragmentShaderWithVersion, NULL);
glCompileShader(m_fragHandle);
// Check Fragment Shader
glGetShaderiv(m_fragHandle, GL_COMPILE_STATUS, &Result);
glGetShaderiv(m_fragHandle, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0)
{
printf("Fragment shader error! \n");
// std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1);
// glGetShaderInfoLog(g_FragHandle3D, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
// printf("Fragment %s\n", &FragmentShaderErrorMessage[0]);
}
glAttachShader(m_shaderHandle, m_vertHandle);
glAttachShader(m_shaderHandle, m_fragHandle);
glLinkProgram(m_shaderHandle);
glDetachShader(m_shaderHandle, m_vertHandle);
glDetachShader(m_shaderHandle, m_fragHandle);
glDeleteShader(m_vertHandle);
glDeleteShader(m_fragHandle);
m_vertDyn[0].m_posit.m_x = -1.0f;
m_vertDyn[0].m_posit.m_y = -1.0f;
m_vertDyn[0].m_posit.m_z = 0.0f;
m_vertDyn[0].m_uv.m_u = 0.0f;
m_vertDyn[0].m_uv.m_v = 0.0f;
//
m_vertDyn[1].m_posit.m_x = -1.0f;
m_vertDyn[1].m_posit.m_y = 1.0f;
m_vertDyn[1].m_posit.m_z = 0.0f;
m_vertDyn[1].m_uv.m_u = 0.0f;
m_vertDyn[1].m_uv.m_v = 1.0f;
m_vertDyn[2].m_posit.m_x = 1.0f;
m_vertDyn[2].m_posit.m_y = 1.0f;
m_vertDyn[2].m_posit.m_z = 0.0f;
m_vertDyn[2].m_uv.m_u = -1.0f;
m_vertDyn[2].m_uv.m_v = 1.0f;
m_vertDyn[3].m_posit.m_x = 1.0f;
m_vertDyn[3].m_posit.m_y = -1.0f;
m_vertDyn[3].m_posit.m_z = 0.0f;
m_vertDyn[3].m_uv.m_u = -1.0f;
m_vertDyn[3].m_uv.m_v = 0.0f;
m_indxDyn[0] = 0;
m_indxDyn[1] = 1;
m_indxDyn[2] = 2;
m_indxDyn[3] = 2;
m_indxDyn[4] = 3;
m_indxDyn[5] = 0;
glGenVertexArrays(1, &m_vaoDyn);
glBindVertexArray(m_vaoDyn);
glGenBuffers(1, &m_vboDyn);
glBindBuffer(GL_ARRAY_BUFFER, m_vboDyn);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertDyn), &m_vertDyn[0], GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)(offsetof(glPositionUV, m_uv)));
glGenBuffers(1, &m_iboDyn);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboDyn);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_indxDyn), &m_indxDyn[0], GL_STATIC_DRAW);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
// Don't unbind this buffer, Let's it in opengl memory.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// remove this buffer from memory because it is updated in runtime.
// you need to bind this buffer at any render pass.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Gear dynamic buffer
memcpy(m_vertSta, m_vertDyn, sizeof(m_vertDyn));
memcpy(m_indxSta, m_indxDyn, sizeof(m_indxDyn));
//
//
glGenVertexArrays(1, &m_vaoSta);
glBindVertexArray(m_vaoSta);
//
glGenBuffers(1, &m_vboSta);
glBindBuffer(GL_ARRAY_BUFFER, m_vboSta);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertSta), &m_vertSta[0], GL_STATIC_DRAW);
//
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)0);
//
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(glPositionUV), (void*)(offsetof(glPositionUV, m_uv)));
glGenBuffers(1, &m_iboSta);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboSta);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_indxSta), &m_indxSta[0], GL_STATIC_DRAW);
//
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
//
// Static buffer, Let's it in opengl memory.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
//
glBindVertexArray(0);
}
};
void ndVehicleUI::RenderGageUI(ndDemoEntityManager* const uscene, const GLuint tex1, const dFloat32 origin_x, const dFloat32 origin_y, const dFloat32 ptsize, dFloat32 cparam, dFloat32 minAngle, dFloat32 maxAngle)
{
if (m_vaoSta)
{
dMatrix aprojm(dGetIdentityMatrix());
CreateOrthoViewMatrix(uscene, origin_x, origin_y, aprojm);
//
minAngle *= -dDegreeToRad;
maxAngle *= -dDegreeToRad;
//
dFloat32 angle = minAngle + (maxAngle - minAngle) * cparam;
dMatrix modm(dRollMatrix(-angle));
dVector color(1.0f, 1.0f, 1.0f, 1.0f);
glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ProjMtx"), 1, GL_FALSE, &aprojm[0][0]);
glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ModMtx"), 1, GL_FALSE, &modm[0][0]);
glUniform1f(glGetUniformLocation(m_shaderHandle, "ptsize"), ptsize);
glUniform4fv(glGetUniformLocation(m_shaderHandle, "color"), 1, &color[0]);
glBindVertexArray(m_vaoSta);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// This buffer is already in the opengl memory.
// Don't need to bind it again.
//glBindBuffer(GL_ARRAY_BUFFER, m_vboSta);
if (tex1)
{
glBindTexture(GL_TEXTURE_2D, tex1);
}
// This buffer is already in the memory.
// Don't need to bind it again.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboSta);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
// Don't unbind this buffers from the opengl memory.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
};
void ndVehicleUI::RenderGearUI(ndDemoEntityManager* const uscene, const dInt32 gearid, GLuint tex1, dFloat32 origin_x, dFloat32 origin_y, dFloat32 ptsize)
{
if (m_vaoDyn)
{
dMatrix aprojm(dGetIdentityMatrix());
CreateOrthoViewMatrix(uscene, origin_x, origin_y, aprojm);
dMatrix origin(dGetIdentityMatrix());
origin[1][1] = -1.0f;
origin.m_posit = dVector(origin_x + ptsize * 1.9f, 50.0f, 0.0f, 1.0f);
dFloat32 uwith = 0.1f;
dFloat32 u0 = uwith * gearid;
dFloat32 u1 = u0 + uwith;
dFloat32 xy1 = 10.0f;
dVector color;
if (gearid == 0)
{
color = dVector(1.0f, 0.5f, 0.0f, 1.0f);
}
else if (gearid == 1)
{
color = dVector(1.0f, 1.0f, 0.0f, 1.0f);
}
else
{
color = dVector(0.0f, 1.0f, 0.0f, 1.0f);
}
glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ProjMtx"), 1, GL_FALSE, &aprojm[0][0]);
glUniformMatrix4fv(glGetUniformLocation(m_shaderHandle, "ModMtx"), 1, GL_FALSE, &origin[0][0]);
glUniform1f(glGetUniformLocation(m_shaderHandle, "ptsize"), xy1);
glUniform4fv(glGetUniformLocation(m_shaderHandle, "color"), 1, &color[0]);
glBindVertexArray(m_vaoDyn);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
//
glBindBuffer(GL_ARRAY_BUFFER, m_vboDyn);
m_vertDyn[0].m_uv.m_u = u0;
m_vertDyn[1].m_uv.m_u = u0;
m_vertDyn[2].m_uv.m_u = u1;
m_vertDyn[3].m_uv.m_u = u1;
// Bind and update the dynamic buffer uv data
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(m_vertDyn), &m_vertDyn[0]);
if (tex1)
{
glBindTexture(GL_TEXTURE_2D, tex1);
}
// This buffer is static, Don't need to bind it again.
// The buffer is already bind in the opengl memory.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboDyn);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
// Don't unbind this buffer to let's it in opengl memory.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
};
| 28.364066 | 212 | 0.710202 | execomrt |
a1288a15b926eea092a4e59aaa532cb9750c1713 | 5,178 | cpp | C++ | src/CoreGenPortal/PortalUserPrefWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 1 | 2019-06-25T13:06:14.000Z | 2019-06-25T13:06:14.000Z | src/CoreGenPortal/PortalUserPrefWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 128 | 2018-10-23T12:45:15.000Z | 2021-12-28T13:09:39.000Z | src/CoreGenPortal/PortalUserPrefWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 1 | 2021-01-20T23:17:34.000Z | 2021-01-20T23:17:34.000Z | //
// _PORTALUSERPREFWIN_CPP_
//
// Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC
// All Rights Reserved
// contact@tactcomplabs.com
//
// See LICENSE in the top level directory for licensing details
//
#include "PortalUserPrefWin.h"
// Event Table
wxBEGIN_EVENT_TABLE(PortalUserPrefWin, wxDialog)
EVT_BUTTON(wxID_OK, PortalUserPrefWin::OnPressOk)
EVT_BUTTON(wxID_CANCEL, PortalUserPrefWin::OnPressCancel)
wxEND_EVENT_TABLE()
PortalUserPrefWin::PortalUserPrefWin( wxWindow *parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
CoreUserConfig *U): wxDialog( parent,
id,
title,
pos,
size,
style ),
User(U) {
// init the internals
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
// create the box sizers
wxBoxSizer *bSizer1 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer *bSizer2 = new wxBoxSizer( wxVERTICAL );
m_panel1 = new wxPanel( this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxTAB_TRAVERSAL );
bSizer2->Add( m_panel1, 1, wxEXPAND | wxALL, 5 );
// init all the options
// -- project directory static text
ProjectDirText = new wxStaticText( this,
wxID_ANY,
wxT("Default project directory"),
wxDefaultPosition,
wxDefaultSize,
0 );
ProjectDirText->Wrap(-1);
bSizer2->Add( ProjectDirText, 0, wxALIGN_CENTER|wxALL, 5 );
// -- project directory input box
ProjectDirCtrl = new wxTextCtrl( this,
wxID_ANY,
User->wxGetProjectDir(),
wxDefaultPosition,
wxSize(400,25),
0,
wxDefaultValidator,
wxT("ProjectDirectory") );
bSizer2->Add( ProjectDirCtrl, 0, wxALIGN_CENTER|wxALL, 5 );
// -- archive directory static text
ArchiveDirText = new wxStaticText( this,
wxID_ANY,
wxT("Default archive directory"),
wxDefaultPosition,
wxDefaultSize,
0 );
ArchiveDirText->Wrap(-1);
bSizer2->Add( ArchiveDirText, 0, wxALIGN_CENTER|wxALL, 5 );
// -- archive directory input box
ArchiveDirCtrl = new wxTextCtrl( this,
wxID_ANY,
User->wxGetArchiveDir(),
wxDefaultPosition,
wxSize(400,25),
0,
wxDefaultValidator,
wxT("Archive Directory") );
bSizer2->Add( ArchiveDirCtrl, 0, wxALIGN_CENTER|wxALL, 5 );
// add the static line
FinalStaticLine = new wxStaticLine( this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxLI_HORIZONTAL );
bSizer2->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 );
bSizer1->Add( bSizer2, 1, wxEXPAND, 5 );
// setup all the buttons
wxBoxSizer *bSizer3 = new wxBoxSizer( wxVERTICAL );
m_userbuttonsizer = new wxStdDialogButtonSizer();
m_userOK = new wxButton( this, wxID_OK );
m_userbuttonsizer->AddButton( m_userOK );
m_userCancel = new wxButton( this, wxID_CANCEL );
m_userbuttonsizer->AddButton( m_userCancel );
m_userbuttonsizer->Realize();
bSizer3->Add( m_userbuttonsizer, 1, wxEXPAND, 5 );
bSizer1->Add( bSizer3, 1, wxEXPAND, 5 );
// draw the diag box until we get more info
this->SetSizer( bSizer1 );
this->Layout();
bSizer1->Fit(this);
this->Centre( wxBOTH );
}
void PortalUserPrefWin::OnPressOk( wxCommandEvent& ok ){
// user pressed 'ok', walk through all the options and update
// the configuration
User->SetProjectDir(ProjectDirCtrl->GetValue());
User->SetArchiveDir(ArchiveDirCtrl->GetValue());
User->WriteConfig();
this->EndModal( wxID_OK );
}
void PortalUserPrefWin::OnPressCancel( wxCommandEvent& ok ){
// cancel everything and close the window
this->EndModal(wxID_CANCEL);
}
PortalUserPrefWin::~PortalUserPrefWin(){
}
// EOF
| 36.723404 | 79 | 0.486288 | opensocsysarch |
a128e7fe9b346a83fd79072dd2db2f935fa76914 | 4,153 | hpp | C++ | query_optimizer/expressions/SubqueryExpression.hpp | yuanchenl/quickstep | cc20fed6e56b0e583ae15a0219c070c8bacf14ba | [
"Apache-2.0"
] | 1 | 2021-08-22T19:16:59.000Z | 2021-08-22T19:16:59.000Z | query_optimizer/expressions/SubqueryExpression.hpp | udippant/incubator-quickstep | 8169306c2923d68235ba3c0c8df4c53f5eee9a68 | [
"Apache-2.0"
] | null | null | null | query_optimizer/expressions/SubqueryExpression.hpp | udippant/incubator-quickstep | 8169306c2923d68235ba3c0c8df4c53f5eee9a68 | [
"Apache-2.0"
] | 1 | 2021-11-30T13:50:59.000Z | 2021-11-30T13:50:59.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#ifndef QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_
#define QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "query_optimizer/expressions/AttributeReference.hpp"
#include "query_optimizer/expressions/ExprId.hpp"
#include "query_optimizer/expressions/Expression.hpp"
#include "query_optimizer/expressions/ExpressionType.hpp"
#include "query_optimizer/expressions/Scalar.hpp"
#include "query_optimizer/logical/Logical.hpp"
#include "query_optimizer/OptimizerTree.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
class CatalogAttribute;
class Scalar;
class Type;
namespace optimizer {
namespace expressions {
/** \addtogroup OptimizerExpressions
* @{
*/
class SubqueryExpression;
typedef std::shared_ptr<const SubqueryExpression> SubqueryExpressionPtr;
/**
* @brief A subquery used in an expression.
*/
class SubqueryExpression : public Scalar {
public:
ExpressionType getExpressionType() const override {
return ExpressionType::kSubqueryExpression;
}
std::string getName() const override { return "SubqueryExpression"; }
const Type& getValueType() const override {
return output_attribute_->getValueType();
}
bool isConstant() const override {
return output_attribute_->isConstant();
}
/**
* @return The referenced logical subquery node.
*/
const logical::LogicalPtr& subquery() const {
return subquery_;
}
std::vector<AttributeReferencePtr> getReferencedAttributes() const override;
ExpressionPtr copyWithNewChildren(
const std::vector<ExpressionPtr> &new_children) const override {
DCHECK(new_children.empty());
return Create(subquery_);
}
::quickstep::Scalar* concretize(
const std::unordered_map<ExprId, const CatalogAttribute*> &substitution_map) const override;
/**
* @brief Creates a subquery expression.
* @note This expression can only be used in a logical plan.
*
* @param subquery The logical subquery node.
* @return An immutable SubqueryExpression.
*/
static SubqueryExpressionPtr Create(const logical::LogicalPtr &subquery) {
return SubqueryExpressionPtr(new SubqueryExpression(subquery));
}
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<OptimizerTreeBaseNodePtr> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<OptimizerTreeBaseNodePtr>> *container_child_fields) const override;
private:
explicit SubqueryExpression(const logical::LogicalPtr &subquery)
: subquery_(subquery),
output_attribute_(subquery->getOutputAttributes()[0]) {
DCHECK(!subquery->getOutputAttributes().empty());
}
logical::LogicalPtr subquery_;
// Set to the first output attribute if the subquery is a multi-column table query.
const AttributeReferencePtr output_attribute_;
DISALLOW_COPY_AND_ASSIGN(SubqueryExpression);
};
/** @} */
} // namespace expressions
} // namespace optimizer
} // namespace quickstep
#endif /* QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_SUBQUERY_EXPRESSION_HPP_ */
| 31.225564 | 98 | 0.75921 | yuanchenl |
a12b8188fb1a107d82a09bb3331f62b662b228e8 | 16,474 | cpp | C++ | src/circuits/BooleanCircuits.cpp | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 160 | 2016-05-11T09:45:56.000Z | 2022-03-06T09:32:19.000Z | src/circuits/BooleanCircuits.cpp | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 57 | 2016-12-26T07:02:12.000Z | 2022-03-06T16:34:31.000Z | src/circuits/BooleanCircuits.cpp | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 67 | 2016-10-10T17:56:22.000Z | 2022-03-15T22:56:39.000Z | /**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#include "../../include/circuits/BooleanCircuits.hpp"
/****************************************************/
/* Gate */
/****************************************************/
void Gate::compute(map<int, Wire> & computedWires) {
// we call the calculateIndexOfTruthTable method to tell us the position of the output value in the truth table
// and look up the value at that position.
bool bVal = truthTable.at(calculateIndexOfTruthTable(computedWires));
byte outputValue = (byte)(bVal ? 1 : 0);
int numberOfOutputs = outputWireIndices.size();
// assigns output value to each of this gate's output Wires.
for (int i = 0; i < numberOfOutputs; i++)
computedWires[outputWireIndices[i]] = Wire(outputValue);
}
bool Gate::operator==(const Gate &other) const {
// first we verify that the gates' numbers are the same.
if (gateNumber_ != other.gateNumber_)
return false;
// next we verify that the gates' respective truth tables are the same.
if (truthTable != other.truthTable)
return false;
// next we verify that the number of input and output wires to the two respective gates are equal.
if ((inputWireIndices.size() != other.inputWireIndices.size()) || (outputWireIndices.size() != other.outputWireIndices.size()))
return false;
/*
* Having determined that the number of input Wire's are the same, we now check that corresponding input wires
* have the same index. As we demonstrated above (in the comments on the imputWireIndices field), the order of the
* wires is significant as not all functions are symmetric. So not only do we care that Wire have the same indices,
* but we also care that the wires with the same index are in the same position of the inputWireIndices array.
*/
int numberOfInputs = inputWireIndices.size();
for (int i = 0; i < numberOfInputs; i++)
if (inputWireIndices[i] != other.inputWireIndices[i])
return false;
/*
* Having determined that the number of output Wire's are the same, we now check that corresponding output wires have
* the same index.
*/
int numberOfOutputs = outputWireIndices.size();
for (int i = 0; i < numberOfOutputs; i++)
if (outputWireIndices[i] != other.outputWireIndices[i])
return false;
// If we've reached this point, then the Gate's are equal so we return true.
return true;
}
int Gate::calculateIndexOfTruthTable(map<int, Wire> computedWires) const {
/*
* Since a truth tables order is the order of binary counting, the index of a desired row can be calculated as follows:
* For a truth table with L inputs whose input columns are labeled aL...ai...a2,a1,
* the output index for a given input set is given by: summation from 0 to L : ai *2^i.
* This is calculated below:
*/
int truthTableIndex = 0;
int numberOfInputs = inputWireIndices.size();
for (int i = numberOfInputs - 1, j = 0; j < numberOfInputs; i--, j++)
truthTableIndex += (int) computedWires[inputWireIndices[i]].getValue() * pow(2, j);
return truthTableIndex;
}
/****************************************************/
/* BooleanCircuit */
/****************************************************/
BooleanCircuit::BooleanCircuit(scannerpp::Scanner s) {
//Read the number of gates.
int numberOfGates = atoi(read(s).c_str());
gates.resize(numberOfGates);
//Read the number of parties.
numberOfParties = atoi(read(s).c_str());
isInputSet.resize(numberOfParties);
//For each party, read the party's number, number of input wires and their indices.
for (int i = 0; i < numberOfParties; i++) {
if (atoi(read(s).c_str()) != i + 1) {//add 1 since parties are indexed from 1, not 0
throw runtime_error("Circuit file format is wrong");
}
//Read the number of input wires.
int numberOfInputsForCurrentParty = atoi(read(s).c_str());
if (numberOfInputsForCurrentParty < 0) {
throw runtime_error("Circuit file format is wrong");
}
bool isThisPartyInputSet = numberOfInputsForCurrentParty == 0 ? true : false;
isInputSet[i] = isThisPartyInputSet;
vector<int> currentPartyInput(numberOfInputsForCurrentParty);
//Read the input wires indices.
for (int j = 0; j < numberOfInputsForCurrentParty; j++) {
currentPartyInput[j] = atoi(read(s).c_str());
}
eachPartysInputWires.push_back(currentPartyInput);
}
/*
* The ouputWireIndices are the outputs from this circuit. However, this circuit may actually be a single layer of a
* larger layered circuit. So this output can be part of the input to another layer of the circuit.
*/
if (numberOfParties == 2){
int numberOfCircuitOutputs = atoi(read(s).c_str());
vector<int> currentPartyOutput(numberOfCircuitOutputs);
//Read the input wires indices.
for (int j = 0; j < numberOfCircuitOutputs; j++) {
currentPartyOutput[j] = atoi(read(s).c_str());
}
eachPartysOutputWires.push_back(currentPartyOutput);
} else {
//For each party, read the party's number, number of output wires and their indices.
for (int i = 0; i < numberOfParties; i++) {
if (atoi(read(s).c_str()) != i + 1) {//add 1 since parties are indexed from 1, not 0
throw runtime_error("Circuit file format is wrong");
}
//Read the number of input wires.
int numberOfOutputForCurrentParty = atoi(read(s).c_str());
if (numberOfOutputForCurrentParty < 0) {
throw runtime_error("Circuit file format is wrong");
}
vector<int> currentPartyOutput(numberOfOutputForCurrentParty);
//Read the input wires indices.
for (int j = 0; j < numberOfOutputForCurrentParty; j++) {
currentPartyOutput[j] = atoi(read(s).c_str());
}
eachPartysOutputWires.push_back(currentPartyOutput);
}
}
int numberOfGateInputs, numberOfGateOutputs;
//For each gate, read the number of input and output wires, their indices and the truth table.
for (int i = 0; i < numberOfGates; i++) {
numberOfGateInputs = atoi(read(s).c_str());
numberOfGateOutputs = atoi(read(s).c_str());
vector<int> inputWireIndices(numberOfGateInputs);
vector<int> outputWireIndices(numberOfGateOutputs);
for (int j = 0; j < numberOfGateInputs; j++) {
inputWireIndices[j] = atoi(read(s).c_str());
}
for (int j = 0; j < numberOfGateOutputs; j++) {
outputWireIndices[j] = atoi(read(s).c_str());
}
/*
* We create a BitSet representation of the truth table from the 01 String
* that we read from the file.
*/
vector<bool> truthTable;
string tTable = read(s);
for (size_t j = 0; j < tTable.length(); j++) {
if (tTable.at(j) == '1')
truthTable.push_back(true);
else
truthTable.push_back(false);
}
//Construct the gate.
gates[i] = Gate(i, truthTable, inputWireIndices, outputWireIndices);
}
}
void BooleanCircuit::setInputs(const map<int, Wire> & presetInputWires, int partyNumber) {
if (partyNumber < 1 || partyNumber > numberOfParties)
throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber));
if (!isInputSet[partyNumber - 1]) {
computedWires.insert(presetInputWires.begin(), presetInputWires.end());
} else {
int numberOfInputWires = getNumberOfInputs(partyNumber);
auto inputIndices = getInputWireIndices(partyNumber);
for (int i = 0; i < numberOfInputWires; i++) {
computedWires[inputIndices[i]] = presetInputWires.at(inputIndices[i]).getValue();
}
}
isInputSet[partyNumber - 1] = true;
}
void BooleanCircuit::setInputs(scannerpp::File * inputWiresFile, int partyNumber) {
if (partyNumber < 1 || partyNumber > numberOfParties)
throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber));
scannerpp::Scanner s(inputWiresFile);
int numberOfInputWires = getNumberOfInputs(partyNumber);
auto inputIndices = getInputWireIndices(partyNumber);
map<int, Wire> presetInputWires;
for (int i = 0; i < numberOfInputWires; i++) {
presetInputWires[inputIndices[i]] = Wire(stoi(read(s)));
}
setInputs(presetInputWires, partyNumber);
}
map<int, Wire> BooleanCircuit::compute() {
for (int i = 0; i < numberOfParties; i++)
if (!isInputSet[i])
throw NotAllInputsSetException("not all inputs set");
/* Computes each Gate.
* Since the Gates are provided in topological order, by the time the compute function on a given Gate is called,
* its input Wires will have already been assigned values
*/
for (Gate g : getGates())
g.compute(computedWires);
/*
* The computedWires array contains all the computed wire values, even those that it is no longer necessary to retain.
* So, we create a new Map called outputMap which only stores the Wires that are output Wires to the circuit.
* We return outputMap.
*/
map<int, Wire> outputMap;
for (int i=0; i<numberOfParties; i++) {
auto outputWireIndices = eachPartysOutputWires[i];
for (int w : outputWireIndices)
outputMap[w] = computedWires[w];
}
return outputMap;
}
bool BooleanCircuit::operator==(const BooleanCircuit &other) const {
// first tests to see that the number of Gates is the same for each circuit. If it's not, then the two are not equal.
if (getGates().size() != other.getGates().size()) {
return false;
}
// calls the equals method of the Gate class to compare each corresponding Gate.
// if any of them return false, the circuits are not the same.
for (size_t i = 0; i < getGates().size(); i++)
if ( getGates()[i]!= other.getGates()[i] )
return false;
return true;
}
vector<int> BooleanCircuit::getInputWireIndices(int partyNumber) const {
if (partyNumber < 1 || partyNumber > numberOfParties)
throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber));
// we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0
return eachPartysInputWires[partyNumber - 1];
}
vector<int> BooleanCircuit::getOutputWireIndices(int partyNumber) const {
if (partyNumber < 1 || partyNumber > numberOfParties)
throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber));
// we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0
return eachPartysOutputWires[partyNumber - 1];
}
vector<int> BooleanCircuit::getOutputWireIndices() const {
if (numberOfParties != 2){
throw IllegalStateException("This function should be called in case of two party only");
}
// we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0
return eachPartysOutputWires[0];
}
int BooleanCircuit::getNumberOfInputs(int partyNumber) const {
if (partyNumber < 1 || partyNumber > numberOfParties)
throw NoSuchPartyException("wrong number of party. got: " + to_string(partyNumber));
// we subtract one from the party number since the parties are indexed beginning from one, but the ArrayList is indexed from 0
return (int) eachPartysInputWires[partyNumber - 1].size();
}
string BooleanCircuit::read(scannerpp::Scanner s) {
string token = s.next();
while (boost::starts_with(token, "#")) {
s.nextLine();
token = s.next();
}
return token;
}
void BooleanCircuit::write(string outputFileName){
ofstream outputFile;
outputFile.open(outputFileName);
if (outputFile.is_open()) {
//write the number of gates.
int numberOfGates = gates.size();
outputFile << numberOfGates << endl;
//write the number of parties.
outputFile << numberOfParties << endl;
outputFile << endl;
//For each party, read the party's number, number of input wires and their indices.
for (int i = 0; i < numberOfParties; i++) {
outputFile << i+1 << " ";//add 1 since parties are indexed from 1, not 0
int numberOfInputsForCurrentParty = eachPartysInputWires[i].size();
//Read the number of input wires.
outputFile << numberOfInputsForCurrentParty << endl;
//Read the input wires indices.
for (int j = 0; j < numberOfInputsForCurrentParty; j++) {
outputFile << eachPartysInputWires[i][j] << endl;
}
outputFile << endl;
}
//Write the outputs number
if (numberOfParties == 2) {
int numberOfOutputs = eachPartysOutputWires[0].size();
outputFile << numberOfOutputs << endl;
//Write the output wires indices.
for (int i = 0; i < numberOfOutputs; i++) {
outputFile << eachPartysOutputWires[0][i] << endl;
}
} else {
//For each party, read the party's number, number of input wires and their indices.
for (int i = 0; i < numberOfParties; i++) {
outputFile << i+1 << " ";//add 1 since parties are indexed from 1, not 0
int numberOfOutputForCurrentParty = eachPartysOutputWires[i].size();
//Read the number of input wires.
outputFile << numberOfOutputForCurrentParty << endl;
//Read the input wires indices.
for (int j = 0; j < numberOfOutputForCurrentParty; j++) {
outputFile << eachPartysOutputWires[i][j] << endl;
}
outputFile << endl;
}
}
outputFile << endl;
//For each gate, write the number of input and output wires, their indices and the truth table.
int numberOfGateInputs, numberOfGateOutputs;
for (int i = 0; i < numberOfGates; i++) {
numberOfGateInputs = gates[i].getInputWireIndices().size();
numberOfGateOutputs = gates[i].getOutputWireIndices().size();
outputFile << numberOfGateInputs << " ";
outputFile << numberOfGateOutputs << " ";
for (int j = 0; j < numberOfGateInputs; j++) {
outputFile << gates[i].getInputWireIndices()[j] << " ";
}
for (int j = 0; j < numberOfGateOutputs; j++) {
outputFile << gates[i].getOutputWireIndices()[j] << " ";
}
/*
* We create a BitSet representation of the truth table from the 01 String
* that we read from the file.
*/
auto tTable = gates[i].getTruthTable();
for (size_t j = 0; j < tTable.size(); j++) {
if (tTable[j])
outputFile << "1";
else
outputFile <<"0";
}
outputFile << endl;
}
}
outputFile.close();
}
| 41.60101 | 158 | 0.657824 | cryptobiu |
a12e1de881cb1f29545e43285b1fdb13eb451d73 | 2,642 | cpp | C++ | src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | 6 | 2018-12-30T15:09:26.000Z | 2020-04-20T09:27:59.000Z | src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | null | null | null | src/test/cpp/Balau/Resource/FileUtf32To8WriteResourceTest.cpp | borasoftware/balau | 8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14 | [
"Apache-2.0"
] | 2 | 2019-11-12T08:07:16.000Z | 2019-11-29T11:19:47.000Z | // @formatter:off
//
// Balau core C++ library
//
// Copyright (C) 2008 Bora Software (contact@borasoftware.com)
//
// 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 <TestResources.hpp>
#include <Balau/Type/OnScopeExit.hpp>
#include <Balau/Util/Files.hpp>
namespace Balau {
using Testing::is;
namespace Resource {
struct FileUtf32To8WriteResourceTest : public Testing::TestGroup<FileUtf32To8WriteResourceTest> {
explicit FileUtf32To8WriteResourceTest() {
RegisterTestCase(test);
}
static File prepWritePath(const std::string & testName, const std::string & text) {
const std::string filename = std::string("FileUtf32To8WriteResourceTest-") + testName + ".log";
File file = TestResources::TestResultsFolder / "Resource" / filename;
const std::string fileUriStr = file.toUriString();
file.getParentDirectory().createDirectories();
AssertThat(file.getParentDirectory().exists(), is(true));
file.removeFile();
AssertThat(file.exists(), is(false));
return file;
}
void test() {
const std::string expected =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
File fileA = prepWritePath("test_a", expected);
File fileB = prepWritePath("test_b", expected);
OnScopeExit removeFileA([=] () mutable { fileA.removeFile(); });
OnScopeExit removeFileB([=] () mutable { fileB.removeFile(); });
auto fileWriteResource = fileA.getUtf32To8WriteResource();
auto uriWriteResource = fileB.utf32To8WriteResource();
std::u32ostream & fileWriteStream = fileWriteResource.writeStream();
std::u32ostream & uriWriteStream = uriWriteResource->writeStream();
fileWriteStream << toString32(expected);
uriWriteStream << toString32(expected);
fileWriteStream.flush();
uriWriteStream.flush();
fileWriteResource.close();
uriWriteResource->close();
const std::string actualA = Util::Files::readToString(fileA);
const std::string actualB = Util::Files::readToString(fileA);
AssertThat(actualA, is(expected));
AssertThat(actualB, is(expected));
}
};
} // namespace Resource
} // namespace Balau
| 31.082353 | 97 | 0.735428 | borasoftware |
a132a9281ce212aa497879d7c91326a33d50b0aa | 11,305 | hh | C++ | Networking/BLIP/LoopbackProvider.hh | tophatch/couchbase-lite-core | f457d9bc74af276516d868b61a48b81b5d717e5c | [
"Apache-2.0"
] | null | null | null | Networking/BLIP/LoopbackProvider.hh | tophatch/couchbase-lite-core | f457d9bc74af276516d868b61a48b81b5d717e5c | [
"Apache-2.0"
] | null | null | null | Networking/BLIP/LoopbackProvider.hh | tophatch/couchbase-lite-core | f457d9bc74af276516d868b61a48b81b5d717e5c | [
"Apache-2.0"
] | null | null | null | //
// LoopbackProvider.hh
//
// Copyright 2017-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
//
#pragma once
#include "WebSocketInterface.hh"
#include "Headers.hh"
#include "Actor.hh"
#include "Error.hh"
#include "Logging.hh"
#include "NumConversion.hh"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <iomanip>
#include <memory>
#include <sstream>
#include <cinttypes>
namespace litecore { namespace websocket {
class LoopbackProvider;
static constexpr size_t kSendBufferSize = 256 * 1024;
/** A WebSocket connection that relays messages to another instance of LoopbackWebSocket. */
class LoopbackWebSocket final : public WebSocket {
protected:
class Driver;
private:
Retained<Driver> _driver;
actor::delay_t _latency;
public:
LoopbackWebSocket(const fleece::alloc_slice &url,
Role role,
actor::delay_t latency =actor::delay_t::zero())
:WebSocket(url, role)
,_latency(latency)
{ }
/** Binds two LoopbackWebSocket objects to each other, so after they open, each will
receive messages sent by the other. When one closes, the other will receive a close
event.
MUST be called before the socket objects' connect() methods are called! */
static void bind(WebSocket *c1, WebSocket *c2,
const websocket::Headers &responseHeaders ={})
{
auto lc1 = dynamic_cast<LoopbackWebSocket*>(c1);
auto lc2 = dynamic_cast<LoopbackWebSocket*>(c2);
lc1->bind(lc2, responseHeaders);
lc2->bind(lc1, responseHeaders);
}
virtual void connect() override {
Assert(_driver && _driver->_peer);
_driver->enqueue(FUNCTION_TO_QUEUE(Driver::_connect));
}
virtual bool send(fleece::slice msg, bool binary) override {
auto newValue = (_driver->_bufferedBytes += msg.size);
_driver->enqueue(FUNCTION_TO_QUEUE(Driver::_send), fleece::alloc_slice(msg), binary);
return newValue <= kSendBufferSize;
}
virtual void close(int status =1000, fleece::slice message =fleece::nullslice) override {
_driver->enqueue(FUNCTION_TO_QUEUE(Driver::_close), status, fleece::alloc_slice(message));
}
protected:
void bind(LoopbackWebSocket *peer, const websocket::Headers &responseHeaders) {
Assert(!_driver);
_driver = createDriver();
_driver->bind(peer, responseHeaders);
}
virtual Driver* createDriver() {
return new Driver(this, _latency);
}
Driver* driver() const {return _driver;}
void peerIsConnecting(actor::delay_t latency = actor::delay_t::zero()) {
_driver->enqueueAfter(latency, FUNCTION_TO_QUEUE(Driver::_peerIsConnecting));
}
virtual void ack(size_t msgSize) {
_driver->enqueue(FUNCTION_TO_QUEUE(Driver::_ack), msgSize);
}
void received(Message *message,
actor::delay_t latency = actor::delay_t::zero())
{
_driver->enqueueAfter(latency, FUNCTION_TO_QUEUE(Driver::_received), retained(message));
}
void closed(CloseReason reason =kWebSocketClose,
int status =1000,
const char *message =nullptr,
actor::delay_t latency = actor::delay_t::zero())
{
_driver->enqueueAfter(latency,
FUNCTION_TO_QUEUE(Driver::_closed),
CloseStatus(reason, status, fleece::slice(message)));
}
class LoopbackMessage : public Message {
public:
template <class SLICE>
LoopbackMessage(LoopbackWebSocket *ws, SLICE data, bool binary)
:Message(data, binary)
,_size(data.size)
,_webSocket(ws)
{ }
~LoopbackMessage() {
_webSocket->ack(_size);
}
private:
size_t _size;
Retained<LoopbackWebSocket> _webSocket;
};
// The internal Actor that does the real work
class Driver final : public actor::Actor {
public:
Driver(LoopbackWebSocket *ws, actor::delay_t latency)
:Actor(WSLogDomain)
,_webSocket(ws)
,_latency(latency)
{ }
virtual std::string loggingIdentifier() const override {
return _webSocket ? _webSocket->name() : "[Already closed]";
}
virtual std::string loggingClassName() const override {
return "LoopbackWS";
}
void bind(LoopbackWebSocket *peer, const websocket::Headers &responseHeaders) {
// Called by LoopbackProvider::bind, which is called before my connect() method,
// so it's safe to set the member variables directly instead of on the actor queue.
_peer = peer;
_responseHeaders = responseHeaders;
}
bool connected() const {
return _state == State::connected;
}
protected:
enum class State {
unconnected,
peerConnecting,
connecting,
connected,
closed
};
~Driver() {
DebugAssert(!connected());
}
virtual void _connect() {
// Connecting uses a handshake, to ensure both sides have notified their delegates
// they're connected before either side sends a message. In other words, to
// prevent one side from receiving a message from the peer before it's ready.
logVerbose("Connecting to peer...");
Assert(_state < State::connecting);
_peer->peerIsConnecting(_latency);
if (_state == State::peerConnecting)
connectCompleted();
else
_state = State::connecting;
}
void _peerIsConnecting() {
logVerbose("(Peer is connecting...)");
switch (_state) {
case State::unconnected:
_state = State::peerConnecting;
break;
case State::connecting:
connectCompleted();
break;
case State::closed:
// ignore in this state
break;
default:
Assert(false, "illegal state");
break;
}
}
void connectCompleted() {
logInfo("CONNECTED");
_state = State::connected;
_webSocket->delegate().onWebSocketGotHTTPResponse(200, _responseHeaders);
_webSocket->delegate().onWebSocketConnect();
}
virtual void _send(fleece::alloc_slice msg, bool binary) {
if (_peer) {
Assert(_state == State::connected);
logDebug("SEND: %s", formatMsg(msg, binary).c_str());
Retained<Message> message(new LoopbackMessage(_webSocket, msg, binary));
_peer->received(message, _latency);
} else {
logInfo("SEND: Failed, socket is closed");
}
}
virtual void _received(Retained<Message> message) {
if (!connected())
return;
logDebug("RECEIVED: %s", formatMsg(message->data, message->binary).c_str());
_webSocket->delegate().onWebSocketMessage(message);
}
virtual void _ack(size_t msgSize) {
if (!connected())
return;
auto newValue = (_bufferedBytes -= msgSize);
if (newValue <= kSendBufferSize && newValue + msgSize > kSendBufferSize) {
logDebug("WRITEABLE");
_webSocket->delegate().onWebSocketWriteable();
}
}
virtual void _close(int status, fleece::alloc_slice message) {
if (_state != State::unconnected) {
Assert(_state == State::connecting || _state == State::connected);
logInfo("CLOSE; status=%d", status);
std::string messageStr(message);
if (_peer)
_peer->closed(kWebSocketClose, status, messageStr.c_str(), _latency);
}
_closed({kWebSocketClose, status, message});
}
virtual void _closed(CloseStatus status) {
if (_state == State::closed)
return;
if (_state >= State::connecting) {
logInfo("CLOSED with %-s %d: %.*s",
status.reasonName(), status.code,
fleece::narrow_cast<int>(status.message.size),
(char *)status.message.buf);
_webSocket->delegate().onWebSocketClose(status);
} else {
logInfo("CLOSED");
}
_state = State::closed;
_peer = nullptr;
_webSocket->clearDelegate();
_webSocket = nullptr; // breaks cycle
}
static std::string formatMsg(fleece::slice msg, bool binary, size_t maxBytes = 64) {
std::stringstream desc;
size_t size = std::min(msg.size, maxBytes);
if (binary) {
desc << std::hex;
for (size_t i = 0; i < size; i++) {
if (i > 0) {
if ((i % 32) == 0)
desc << "\n\t\t";
else if ((i % 4) == 0)
desc << ' ';
}
desc << std::setw(2) << std::setfill('0') << (unsigned)msg[i];
}
desc << std::dec;
} else {
desc.write((char*)msg.buf, size);
}
if (size < msg.size)
desc << "... [" << msg.size << "]";
return desc.str();
}
private:
friend class LoopbackWebSocket;
Retained<LoopbackWebSocket> _webSocket;
actor::delay_t _latency {0.0};
Retained<LoopbackWebSocket> _peer;
websocket::Headers _responseHeaders;
std::atomic<size_t> _bufferedBytes {0};
State _state {State::unconnected};
};
};
} }
| 35.888889 | 102 | 0.515789 | tophatch |
a135afa046cff6d9c021a331e0d1f070e399de6a | 228 | cpp | C++ | CustomWindow.Test.cpp | jmfb/wex | b012a7e5d8dfa978a432363bb11b64474e487f5f | [
"MIT"
] | 1 | 2017-01-08T14:11:58.000Z | 2017-01-08T14:11:58.000Z | CustomWindow.Test.cpp | jmfb/wex | b012a7e5d8dfa978a432363bb11b64474e487f5f | [
"MIT"
] | null | null | null | CustomWindow.Test.cpp | jmfb/wex | b012a7e5d8dfa978a432363bb11b64474e487f5f | [
"MIT"
] | null | null | null | #include "WindowsInclude.h"
#include "CustomWindow.h"
#include "Exception.h"
#include <UnitTest/UnitTest.h>
using UnitTest::Assert;
namespace Wex
{
TEST_CLASS(CustomWindowTest)
{
public:
CustomWindowTest()
{
}
};
}
| 12 | 30 | 0.710526 | jmfb |
a13654a0a2dfad380548bf3b0cd7837adec698c3 | 910 | hpp | C++ | sources/dansandu/glyph/error.hpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | sources/dansandu/glyph/error.hpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | sources/dansandu/glyph/error.hpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | #pragma once
#include <exception>
namespace dansandu::glyph::error
{
class GrammarError : public std::exception
{
public:
explicit GrammarError(std::string message) : message_{std::move(message)}
{
}
const char* what() const noexcept override
{
return message_.c_str();
}
private:
std::string message_;
};
class TokenizationError : public std::exception
{
public:
explicit TokenizationError(std::string message) : message_{std::move(message)}
{
}
const char* what() const noexcept override
{
return message_.c_str();
}
private:
std::string message_;
};
class SyntaxError : public std::exception
{
public:
explicit SyntaxError(std::string message) : message_{std::move(message)}
{
}
const char* what() const noexcept override
{
return message_.c_str();
}
private:
std::string message_;
};
}
| 15.964912 | 82 | 0.647253 | dansandu |
a1390401d6de5efb986f1ed268c0a972948b5742 | 4,269 | cpp | C++ | client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp | pertgame/battleframe | ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9 | [
"MIT"
] | 1 | 2020-10-28T15:19:15.000Z | 2020-10-28T15:19:15.000Z | client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp | pertgame/battleframe | ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9 | [
"MIT"
] | null | null | null | client_project/build/jsb-default/frameworks/cocos2d-x/cocos/editor-support/middleware-adapter.cpp | pertgame/battleframe | ffba8a7b4f7f45f1eed2c56060d9a2205fb1fdc9 | [
"MIT"
] | 1 | 2020-10-28T15:19:40.000Z | 2020-10-28T15:19:40.000Z | /****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "middleware-adapter.h"
#include "base/ccMacros.h"
#include "renderer/gfx/Texture.h"
using namespace cocos2d;
using namespace cocos2d::renderer;
MIDDLEWARE_BEGIN
Texture2D::Texture2D()
{
}
Texture2D::~Texture2D()
{
CC_SAFE_RELEASE(_texture);
_texParamCallback = nullptr;
}
int Texture2D::getPixelsWide() const
{
return _pixelsWide;
}
int Texture2D::getPixelsHigh() const
{
return _pixelsHigh;
}
void Texture2D::setPixelsWide(int wide)
{
this->_pixelsWide = wide;
}
void Texture2D::setPixelsHigh(int high)
{
this->_pixelsHigh = high;
}
int Texture2D::getRealTextureIndex() const
{
return this->_realTextureIndex;
}
void Texture2D::setRealTextureIndex(int textureIndex)
{
this->_realTextureIndex = textureIndex;
}
void Texture2D::setTexParamCallback(const texParamCallback& callback)
{
this->_texParamCallback = callback;
}
void Texture2D::setTexParameters(const TexParams& texParams)
{
if (_texParamCallback)
{
_texParamCallback(this->_realTextureIndex,texParams.minFilter,texParams.magFilter,texParams.wrapS,texParams.wrapT);
}
}
void Texture2D::setNativeTexture(Texture* texture)
{
if (_texture == texture) return;
CC_SAFE_RELEASE(_texture);
_texture = texture;
CC_SAFE_RETAIN(_texture);
}
Texture* Texture2D::getNativeTexture() const
{
return _texture;
}
SpriteFrame* SpriteFrame::createWithTexture(Texture2D *texture, const cocos2d::Rect& rect)
{
SpriteFrame *spriteFrame = new (std::nothrow) SpriteFrame();
spriteFrame->initWithTexture(texture, rect);
spriteFrame->autorelease();
return spriteFrame;
}
SpriteFrame* SpriteFrame::createWithTexture(Texture2D* texture, const cocos2d::Rect& rect, bool rotated, const cocos2d::Vec2& offset, const cocos2d::Size& originalSize)
{
SpriteFrame *spriteFrame = new (std::nothrow) SpriteFrame();
spriteFrame->initWithTexture(texture, rect, rotated, offset, originalSize);
spriteFrame->autorelease();
return spriteFrame;
}
bool SpriteFrame::initWithTexture(Texture2D* texture, const cocos2d::Rect& rect)
{
return initWithTexture(texture, rect, false, cocos2d::Vec2::ZERO, rect.size);
}
bool SpriteFrame::initWithTexture(Texture2D* texture, const cocos2d::Rect& rect, bool rotated, const cocos2d::Vec2& offset, const cocos2d::Size& originalSize)
{
_texture = texture;
if (texture)
{
texture->retain();
}
_rectInPixels = rect;
_offsetInPixels = offset;
_originalSizeInPixels = originalSize;
_rotated = rotated;
_anchorPoint = cocos2d::Vec2(NAN, NAN);
return true;
}
SpriteFrame::SpriteFrame()
{
}
SpriteFrame::~SpriteFrame()
{
CC_SAFE_RELEASE(_texture);
}
void SpriteFrame::setTexture(Texture2D * texture)
{
if( _texture != texture )
{
CC_SAFE_RELEASE(_texture);
CC_SAFE_RETAIN(texture);
_texture = texture;
}
}
Texture2D* SpriteFrame::getTexture()
{
return _texture;
}
MIDDLEWARE_END
| 25.562874 | 168 | 0.707191 | pertgame |
a13e9b36229a60c983d67c9876ab9ac18e4ca931 | 2,368 | hpp | C++ | src/polygon.hpp | npolar/reshp | 6389f48a1bd745c2c0e9ef485bf6d163d73416a3 | [
"MIT"
] | null | null | null | src/polygon.hpp | npolar/reshp | 6389f48a1bd745c2c0e9ef485bf6d163d73416a3 | [
"MIT"
] | 1 | 2015-01-13T10:15:56.000Z | 2015-01-13T10:15:56.000Z | src/polygon.hpp | npolar/reshp | 6389f48a1bd745c2c0e9ef485bf6d163d73416a3 | [
"MIT"
] | null | null | null | /* * * * * * * * * * * * *\
|* โโโ v0.4 *|
|* โโโฆโโฆโโโโฆโโโโฃ โโโฆโโฆโโ *|
|* โ โโโฃ 'โโฌโโโโฃ โ โ 'โ *|
|* โโโ โโโโโฉโโโโฉโโฉโโฃ โโโ *|
|* * * * * * * * * โโโ * *|
|* Manipulation tool for *|
|* ESRI Shapefiles *|
|* * * * * * * * * * * * *|
|* http://www.npolar.no/ *|
\* * * * * * * * * * * * */
#ifndef RESHP_POLYGON_HPP_
#define RESHP_POLYGON_HPP_
#include "point.hpp"
#include "aabb.hpp"
#include "shp.hpp"
#include "segment.hpp"
#include <vector>
namespace reshp
{
struct polygon
{
struct ring;
struct intersection
{
reshp::point point;
reshp::polygon::ring* ring;
reshp::segment* segment;
int segment_index;
struct intersector
{
reshp::polygon::ring* ring;
reshp::segment* segment;
int segment_index;
intersector(reshp::polygon::ring* = NULL);
} intersector;
intersection(reshp::polygon::ring* = NULL, reshp::polygon::ring* intersector_ring = NULL);
};
struct ring
{
ring();
reshp::aabb aabb;
enum { outer, inner } type;
std::vector<reshp::segment> segments;
void calculate_aabb();
bool contains(const reshp::point&) const;
void invert(); // Change direction (toggle inner/outer typed ring)
bool inside(const reshp::polygon::ring&) const;
bool intersects() const; // Self-intersection
bool intersects(const reshp::polygon::ring&, std::vector<reshp::polygon::intersection>* intersections = NULL) const;
};
polygon();
polygon(const reshp::polygon&);
polygon(const reshp::shp::polygon&);
reshp::aabb aabb;
std::vector<reshp::polygon::ring> rings;
void calculate_aabb();
bool contains(const reshp::point&) const;
bool inside(const reshp::polygon&) const;
bool intersects() const; // Self-intersection
bool intersects(const reshp::polygon&, std::vector<reshp::polygon::intersection>* intersections = NULL) const;
void operator>> (reshp::shp::polygon&) const;
};
}
#endif // RESHP_POLYGON_HPP_
| 29.234568 | 128 | 0.494932 | npolar |
a140a746eb600e0c2ab11b97d3ffbb028fec4b12 | 1,711 | cpp | C++ | Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp | MasumBhai/cse-216-presentation | 6c25dc537c949ab6b4e8ebeb20af7909fac4801c | [
"CC0-1.0"
] | null | null | null | Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp | MasumBhai/cse-216-presentation | 6c25dc537c949ab6b4e8ebeb20af7909fac4801c | [
"CC0-1.0"
] | null | null | null | Problem Solving/201914044/hackerearth_Oliver and the battle_201914044 .cpp | MasumBhai/cse-216-presentation | 6c25dc537c949ab6b4e8ebeb20af7909fac4801c | [
"CC0-1.0"
] | null | null | null | /*
auther : Abdullah Al Masum
MIST_roll : 201914044
problem Link : https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/oliver-and-the-battle-1/submissions/
*/
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
int n,m;
int mat[MAX][MAX];
int visited[MAX][MAX];
int bfs(int x, int y) {
visited[x][y] = 1;
int countt = 1;
queue<pair<int,int> > Queue;
Queue.push(make_pair(x,y));
while(!Queue.empty()) {
x = Queue.front().first;
y = Queue.front().second;
Queue.pop();
for(int i = -1 ; i<=1; i++ ) {
for(int j = -1; j<=1; j++) {
if(!visited[x+i][y+j] && mat[x+i][y+j]) {
countt++;
Queue.push(make_pair(x+i,y+j));
visited[x+i][y+j] = 1;
}
}
}
}
return countt;
}
int main() {
int test;
cin>>test;
while(test--) {
cin>>n>>m;
memset(mat,0,sizeof(mat));
memset(visited,0,sizeof(visited));
for(int i = 1; i<=n ; i++) {
for(int j = 1; j<= m; j++) {
int res;
cin>>res;
mat[i][j] = res;
}
}
int maxZomniKill = 0;
int zomnitroops = 0;
for(int i = 1; i <= n ; i++)
for(int j = 1; j<= m; j++) {
if(!visited[i][j] && mat[i][j]) {
maxZomniKill = max( bfs(i,j), maxZomniKill );
zomnitroops++;
}
}
cout<<zomnitroops<<" "<<maxZomniKill<<endl;
}
return 0;
}
| 26.734375 | 156 | 0.435418 | MasumBhai |
a141b8d8bc5d94757ea150d3ed4e91e0fa1bdc27 | 3,042 | cc | C++ | engines/ep/src/diskdockey.cc | hrajput89/kv_engine | 33fb1ab2c9787f55555e5f7edea38807b3dbc371 | [
"BSD-3-Clause"
] | 1 | 2019-06-13T07:33:09.000Z | 2019-06-13T07:33:09.000Z | engines/ep/src/diskdockey.cc | paolococchi/kv_engine | 40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45 | [
"BSD-3-Clause"
] | null | null | null | engines/ep/src/diskdockey.cc | paolococchi/kv_engine | 40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45 | [
"BSD-3-Clause"
] | 1 | 2020-01-15T16:52:37.000Z | 2020-01-15T16:52:37.000Z | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "diskdockey.h"
#include "item.h"
#include <mcbp/protocol/unsigned_leb128.h>
#include <sstream>
DiskDocKey::DiskDocKey(const DocKey& key, bool prepared) {
uint8_t keyOffset = 0;
if (prepared) {
// 1 byte for Prepare prefix
keydata.resize(1);
keydata[0] = CollectionID::DurabilityPrepare;
keyOffset++;
}
if (key.getEncoding() == DocKeyEncodesCollectionId::No) {
// 1 byte for the Default CollectionID
keydata.resize(keyOffset + 1);
keydata[keyOffset] = DefaultCollectionLeb128Encoded;
keyOffset++;
}
keydata.resize(keyOffset + key.size());
std::copy(key.data(), key.data() + key.size(), keydata.begin() + keyOffset);
}
DiskDocKey::DiskDocKey(const Item& item)
: DiskDocKey(item.getKey(),
item.isPending() || item.isAbort() /*Prepare namespace?*/) {
}
DiskDocKey::DiskDocKey(const char* ptr, size_t len) : keydata(ptr, len) {
}
std::size_t DiskDocKey::hash() const {
return std::hash<std::string>()(keydata);
}
DocKey DiskDocKey::getDocKey() const {
// Skip past Prepared prefix if present.
const auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
{data(), size()});
if (decoded.first == CollectionID::DurabilityPrepare) {
return {decoded.second.data(),
decoded.second.size(),
DocKeyEncodesCollectionId::Yes};
}
return {data(), size(), DocKeyEncodesCollectionId::Yes};
}
bool DiskDocKey::isCommitted() const {
return !isPrepared();
}
bool DiskDocKey::isPrepared() const {
const auto prefix = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
{data(), size()});
return prefix.first == CollectionID::DurabilityPrepare;
}
std::string DiskDocKey::to_string() const {
std::stringstream ss;
auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
{data(), size()});
if (decoded.first == CollectionID::DurabilityPrepare) {
ss << "pre:";
decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
decoded.second);
}
ss << "cid:0x" << std::hex << decoded.first << std::dec << ":"
<< std::string(reinterpret_cast<const char*>(decoded.second.data()),
decoded.second.size());
return ss.str();
}
| 33.428571 | 80 | 0.642998 | hrajput89 |
a145de89d4dd625c605d25cde097f39edeed0ec3 | 420 | hpp | C++ | pythran/pythonic/__builtin__/list/count.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/list/count.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/list/count.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_BUILTIN_LIST_COUNT_HPP
#define PYTHONIC_BUILTIN_LIST_COUNT_HPP
#include "pythonic/include/__builtin__/list/count.hpp"
#include "pythonic/__dispatch__/count.hpp"
#include "pythonic/utils/proxy.hpp"
namespace pythonic
{
namespace __builtin__
{
namespace list
{
ALIAS(count, pythonic::__dispatch__::count);
PROXY_IMPL(pythonic::__builtin__::list, count);
}
}
}
#endif
| 16.153846 | 54 | 0.738095 | artas360 |
a14afec67d4ea5ccf1a6c3c9dbdaecd1a93af368 | 671 | hpp | C++ | src/datastructures/boost.hpp | rvanvenetie/spacetime | b516419be2a59115d9b2d853aeea9fcd4f125c94 | [
"MIT"
] | null | null | null | src/datastructures/boost.hpp | rvanvenetie/spacetime | b516419be2a59115d9b2d853aeea9fcd4f125c94 | [
"MIT"
] | null | null | null | src/datastructures/boost.hpp | rvanvenetie/spacetime | b516419be2a59115d9b2d853aeea9fcd4f125c94 | [
"MIT"
] | null | null | null | #pragma once
#include <boost/container/deque.hpp>
#include <boost/container/options.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/static_vector.hpp>
template <typename I, size_t N>
using SmallVector = boost::container::small_vector<I, N>;
template <typename I, size_t N>
using StaticVector = boost::container::static_vector<I, N>;
// Boost deque container with default block size N. (REQUIRES LATEST BOOST).
template <typename I, size_t N = 128>
using Deque =
boost::container::deque<I, void,
typename boost::container::deque_options<
boost::container::block_size<N>>::type>;
| 37.277778 | 76 | 0.692996 | rvanvenetie |
a1567eda4a122071dce708a5314751c64b9599e6 | 10,663 | cpp | C++ | src/hsa_balance.cpp | TheRobotStudio/osa_control | cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c | [
"BSD-3-Clause"
] | null | null | null | src/hsa_balance.cpp | TheRobotStudio/osa_control | cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c | [
"BSD-3-Clause"
] | null | null | null | src/hsa_balance.cpp | TheRobotStudio/osa_control | cab89793ae64b9c5b49c2b0b31a84fe2ec3b7f5c | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019, The Robot Studio
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file hsa_balance.cpp
* @author Cyril Jourdan
* @author Rob Knight
* @date Sept 18, 2017
* @version 0.1.0
* @brief Implementation file for the High Speed Android balance algorithm
*
* Contact: contact@therobotstudio.com
* Created on : Sept 18, 2017
*/
#include <exception>
#include <stdexcept>
//ROS
#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <osa_control/hsa_balance_dyn_Config.h>
//ROS messages
#include <sensor_msgs/Joy.h>
#include <razor_imu_9dof/RazorImu.h>
#include <osa_msgs/MotorCmdMultiArray.h>
#include <osa_msgs/MotorDataMultiArray.h>
#include "robot_defines.h"
/*** Defines ***/
#define LOOP_RATE 15 //HEART_BEAT
#define NUMBER_OF_WHEELS 2
#define NUMBER_OF_MOTORS 10
using namespace std;
/*** Global variables ***/
osa_control::hsa_balance_dyn_Config pid_param;
sensor_msgs::Joy xbox_joy;
razor_imu_9dof::RazorImu razor_imu;
osa_msgs::MotorDataMultiArray motor_data_array;
osa_msgs::MotorCmdMultiArray motor_cmd_array;
bool joy_arrived = false;
bool imu_arrived = false;
bool motor_data_array_arrived = true;
/*** Callback functions ***/
void HSABalanceDynCallback(osa_control::hsa_balance_dyn_Config &config, uint32_t level)
{
ROS_INFO("Reconfigure Request: %f %f %f %f", config.p_double_param, config.i_double_param, config.d_double_param, config.pt_double_param);
pid_param = config;
}
void joyCallback(const sensor_msgs::JoyConstPtr& joy)
{
xbox_joy = *joy;
joy_arrived = true;
}
void imuRawCallback(const razor_imu_9dof::RazorImuConstPtr& imu)
{
razor_imu = *imu;
imu_arrived = true;
}
void motorDataArrayCallback(const osa_msgs::MotorDataMultiArrayConstPtr& data)
{
motor_data_array = *data;
motor_data_array_arrived = true;
}
/*** Main ***/
int main(int argc, char** argv)
{
//Initialize ROS
ros::init(argc, argv, "osa_hsa_balance_node");
ros::NodeHandle nh("~");
ros::Rate r(LOOP_RATE);
// Parameters
string dof_wheel_name[NUMBER_OF_WHEELS];
int joy_axis_left_right_idx, joy_axis_up_down_idx;
ROS_INFO("OSA High Speed Android balance node.");
ROS_INFO("Setup dynamic_reconfigure parameters.");
dynamic_reconfigure::Server<osa_control::hsa_balance_dyn_Config> hsa_balance_dyn_server;
dynamic_reconfigure::Server<osa_control::hsa_balance_dyn_Config>::CallbackType f;
f = boost::bind(&HSABalanceDynCallback, _1, _2);
hsa_balance_dyn_server.setCallback(f);
ROS_INFO("Grab the parameters.");
// Grab the parameters
try
{
nh.param("dof_right_wheel", dof_wheel_name[0], string("/dof1"));
nh.param("dof_left_wheel", dof_wheel_name[1], string("/dof2"));
nh.param("joy_axis_left_right", joy_axis_left_right_idx, 3);
nh.param("joy_axis_up_down", joy_axis_up_down_idx, 4);
}
catch(ros::InvalidNameException const &e)
{
ROS_ERROR(e.what());
}
string name[NUMBER_OF_WHEELS];
string type[NUMBER_OF_WHEELS];
int node_id[NUMBER_OF_WHEELS] = {0};
string controller[NUMBER_OF_WHEELS];
string motor[NUMBER_OF_WHEELS];
bool inverted[NUMBER_OF_WHEELS];
string mode[NUMBER_OF_WHEELS];
int value[NUMBER_OF_WHEELS] = {0};
//Publishers
ros::Publisher pub_motor_cmd_array = nh.advertise<osa_msgs::MotorCmdMultiArray>("/set_motor_commands", 100);
//Subscribers
ros::Subscriber sub_joy = nh.subscribe ("/joy", 10, joyCallback);
ros::Subscriber sub_imu = nh.subscribe ("/imuRaw", 10, imuRawCallback);
ros::Subscriber sub_motor_data_array = nh.subscribe("/motor_data_array", 10, motorDataArrayCallback);
// Grab the parameters
try
{
//start with controller 1
//int dof_idx = 1;
//string rad_str = "dof"; //common radical name
for(int i=0; i<NUMBER_OF_WHEELS; i++)
{
//create the string "controller+index" to search for the controller parameter with that index number
ostringstream dof_idx_path;
dof_idx_path << dof_wheel_name[i]; //rad_str << dof_idx;
string absolute_str = "absolute_str";
ROS_INFO("string=%s", dof_idx_path.str().c_str());
if(nh.searchParam(dof_idx_path.str(), absolute_str))
{
//grab the parameters of the current controller
//name
ostringstream name_path;
name_path << absolute_str << "/name";
if(!nh.getParam(name_path.str(), name[i]))
{
ROS_ERROR("Can't grab param name for %s", dof_idx_path.str().c_str());
return false;
}
//type
ostringstream type_path;
type_path << absolute_str << "/type";
if(!nh.getParam(type_path.str(), type[i]))
{
ROS_ERROR("Can't grab param type for %s", dof_idx_path.str().c_str());
return false;
}
/*
//check that the type is "WHEEL"
if(type[i] == string("WHEEL"))
{
throw runtime_error("Selected DOF is not of type WHEEL.");
}
*/
//node_id
ostringstream node_id_path;
node_id_path << absolute_str << "/node_id";
if(!nh.getParam(node_id_path.str(), node_id[i]))
{
ROS_ERROR("Can't grab param node_id for %s", dof_idx_path.str().c_str());
return false;
}
//controller
ostringstream controller_path;
controller_path << absolute_str << "/controller";
if(!nh.getParam(controller_path.str(), controller[i]))
{
ROS_ERROR("Can't grab param controller for %s", dof_idx_path.str().c_str());
return false;
}
//motor
ostringstream motor_path;
motor_path << absolute_str << "/motor";
if(!nh.getParam(motor_path.str(), motor[i]))
{
ROS_ERROR("Can't grab param motor for %s", dof_idx_path.str().c_str());
return false;
}
//inverted
ostringstream inverted_path;
inverted_path << absolute_str << "/inverted";
if(!nh.getParam(inverted_path.str(), inverted[i]))
{
ROS_ERROR("Can't grab param inverted for %s", dof_idx_path.str().c_str());
return false;
}
//mode
ostringstream mode_path;
mode_path << absolute_str << "/mode";
if(!nh.getParam(mode_path.str(), mode[i]))
{
ROS_ERROR("Can't grab param mode for %s", dof_idx_path.str().c_str());
return false;
}
//value
ostringstream value_path;
value_path << absolute_str << "/value";
if(!nh.getParam(value_path.str(), value[i]))
{
ROS_ERROR("Can't grab param value for %s", dof_idx_path.str().c_str());
return false;
}
//print the dof parameters
ROS_INFO("%s : name[%s], type[%s], node_id[%d], controller[%s], motor[%s], inverted[%d], mode[%s], value[%d]", dof_idx_path.str().c_str(),
name[i].c_str(), type[i].c_str(), node_id[i], controller[i].c_str(), motor[i].c_str(), inverted[i], mode[i].c_str(), value[i]);
}
else
{
//dof_exist = false;
ROS_WARN("Controllers not found in YAML config file");
}
//dof_exist = false;
}
ROS_INFO("Wheels parameters found successfully!\n");
}
catch(ros::InvalidNameException const &e)
{
ROS_ERROR(e.what());
ROS_ERROR("Wrong parameters in config file or launch file!");
ROS_ERROR("Please modify your YAML config file or launch file and try again.");
return false;
}
//create the command array
motor_cmd_array.layout.dim.push_back(std_msgs::MultiArrayDimension());
motor_cmd_array.layout.dim[0].size = NUMBER_OF_MOTORS;
motor_cmd_array.layout.dim[0].stride = NUMBER_OF_MOTORS;
motor_cmd_array.layout.dim[0].label = "motors";
motor_cmd_array.layout.data_offset = 0;
motor_cmd_array.motor_cmd.clear();
motor_cmd_array.motor_cmd.resize(NUMBER_OF_MOTORS);
//Initialization
for(int i=0; i<NUMBER_OF_MOTORS; i++)
{
motor_cmd_array.motor_cmd[i].node_id = i+1;
motor_cmd_array.motor_cmd[i].command = SET_TARGET_POSITION;
motor_cmd_array.motor_cmd[i].value = 0;
}
motor_cmd_array.motor_cmd[8].command = SET_TARGET_VELOCITY; //For the drive wheels
motor_cmd_array.motor_cmd[9].command = SET_TARGET_VELOCITY;
/* Main loop */
ROS_INFO("Main loop");
while(ros::ok())
{
// Get imu and motor data through callbacks.
ros::spinOnce();
if(joy_arrived) //Will only be true if values have changed
{
//Joystick control
//xbox_joy.buttons[0];
//xbox_joy.axes[0];
}
// Check that both imu and motor data has arrived.
if(imu_arrived && motor_data_array_arrived)
{
//--------------------- PID loop ---------------------
// Variables
float angle = razor_imu.pitch; //in rad
float velocity_f = 0.0;
int velocity_i = 0;
float dt = 1/LOOP_RATE;
//PID parameters are accessed with config.p_double_param, config.i_double_param, config.d_double_param.
//Pitch Trim parameter is accessed with config.pt_double_param
// Computation
velocity_f = -(angle*4000)/M_PI;
velocity_i = (int)velocity_f;
// Print velocity value
ROS_INFO("angle = %f, velocity = %d", angle, velocity_i);
// Set final motor velocity
motor_cmd_array.motor_cmd[8].value = velocity_i;
motor_cmd_array.motor_cmd[9].value = velocity_i;
// Publish the motor commands topic, caught by the command_builder node
// which send it to the CAN bus via topic_to_socketcan_node
pub_motor_cmd_array.publish(motor_cmd_array);
}
imu_arrived = false;
motor_data_array_arrived = false;
joy_arrived = false;
if(!r.sleep()) ROS_WARN("sleep: desired rate %dhz not met!", LOOP_RATE);
}//while ros ok
return 0;
}
| 30.640805 | 142 | 0.710119 | TheRobotStudio |
a15aeebbf3a10b8093e2aab3fe289f48403d4884 | 11,028 | cc | C++ | ssTableCache.cc | q4x3/KVStore | 51190a9487d32f26046de4638f6b8d1b85fbc079 | [
"MIT"
] | null | null | null | ssTableCache.cc | q4x3/KVStore | 51190a9487d32f26046de4638f6b8d1b85fbc079 | [
"MIT"
] | null | null | null | ssTableCache.cc | q4x3/KVStore | 51190a9487d32f26046de4638f6b8d1b85fbc079 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <algorithm>
#include <queue>
#include "utils.h"
#include "ssTableCache.h"
std::vector<entryForMerge> ssTableCache::genSortedEntry(std::vector<uint64_t> &&keyArray, ssTable *table) {
std::vector<entryForMerge> res;
for (uint32_t i = 0; i < keyArray.size(); ++i) {
res.emplace_back(keyArray[i], i, table);
}
return res;
}
void ssTableCache::mergesort(std::vector<entryForMerge> &array, uint64_t start, uint64_t end) {
uint64_t mid = (start + end) >> 1;
if (end <= start) return;
mergesort(array, start, mid);
mergesort(array, mid + 1, end);
uint64_t i = start, j = mid + 1, k = 0;
std::vector<entryForMerge> tmpArray(end - start + 1);
while (i <= mid && j <= end) {
if (array[i].key > array[j].key) tmpArray[k++] = array[j++];
else tmpArray[k++] = array[i++];
}
while (i <= mid) tmpArray[k++] = array[i++];
while (j <= end) tmpArray[k++] = array[j++];
for (i = start, k = 0; i <= end; ++i, ++k) {
array[i] = tmpArray[k];
}
}
void ssTableCache::compaction(uint32_t targetLevel, std::vector<ssTable *> &targetCells) {
std::vector<entryForMerge> array;
std::vector<entryForMerge> uniqueArray;
for (auto &it: targetCells) {
auto tmp = genSortedEntry(it->getKeySeq(), it);
array.insert(array.cend(), tmp.cbegin(), tmp.cend());
}
mergesort(array, 0, array.size() - 1);
uint32_t lastInd = 0;
for (uint32_t i = 1; i < array.size(); ++i) {
if (array[i].key != array[lastInd].key) {
uniqueArray.emplace_back(array[lastInd]);
lastInd = i;
} else {
if (array[i].table->header.timeStamp > array[lastInd].table->header.timeStamp) {
lastInd = i;
}
}
}
uniqueArray.emplace_back(array[lastInd]);
array.clear();
std::vector<std::pair<uint64_t, std::string>> tmp;
const uint32_t MAX_SIZE = 2 * 1024 * 1024 - sstableHeader::HEADER_SIZE - bloomFilter::FILTER_SIZE;
uint64_t tmpTimeStamp = 0;
uint32_t tmpSize = 0;
bool needHandleDeleteFlag = targetLevel >= levelArray.size() - 1;
for (auto &it: uniqueArray) {
std::string val = it.table->getValInd(it.ind);
if (needHandleDeleteFlag && val == DELETE_FLAG) {
continue;
}
if (tmpSize + val.size() + sizeof (uint64_t) + sizeof (uint32_t) > MAX_SIZE) {
std::string targetDir = filePath + "/level-" + std::to_string(targetLevel);
if (!utils::dirExists(targetDir)) {
if (utils::mkdir(targetDir.c_str())) {
std::cerr << "ERROR: Fail to create directory." << std::endl;
exit(1);
}
levelArray.emplace_back();
nextLabel.push_back(0);
}
std::string fileName = targetDir + '/' + std::to_string(nextLabel[targetLevel]) + ".sst";
levelArray[targetLevel].emplace_back(ssTable::genTable(fileName, tmpTimeStamp, tmp));
++nextLabel[targetLevel];
tmp.clear();
tmpTimeStamp = 0;
tmpSize = 0;
}
tmp.emplace_back(it.key, val);
tmpSize += val.size() + sizeof (uint64_t) + sizeof (uint32_t);
if (it.table->header.timeStamp > tmpTimeStamp) {
tmpTimeStamp = it.table->header.timeStamp;
}
}
if (!tmp.empty()) {
std::string targetDir = filePath + "/level-" + std::to_string(targetLevel);
if (!utils::dirExists(targetDir)) {
if (utils::mkdir(targetDir.c_str())) {
std::cerr << "ERROR: Fail to create directory." << std::endl;
exit(1);
}
levelArray.emplace_back();
nextLabel.push_back(0);
}
std::string fileName = targetDir + '/' + std::to_string(nextLabel[targetLevel]) + ".sst";
levelArray[targetLevel].emplace_back(ssTable::genTable(fileName, tmpTimeStamp, tmp));
++nextLabel[targetLevel];
tmp.clear();
}
for (auto &it: targetCells) {
it->clearTable();
delete it;
it = nullptr;
}
}
void ssTableCache::modify() {
uint32_t level = 0;
while (level < levelArray.size() && levelArray[level].size() > (0b10 << level)) {
std::vector<ssTable *> targetCells;
uint64_t minKey;
uint64_t maxKey;
if (level == 0) {
minKey = levelArray[0][0]->header.minKey;
maxKey = levelArray[0][0]->header.maxKey;
for (auto &it: levelArray[0]) {
targetCells.emplace_back(it);
minKey = std::min(minKey, it->header.minKey);
maxKey = std::max(maxKey, it->header.maxKey);
}
levelArray[0].clear();
} else {
std::deque<ssTable *> &tmpCells = levelArray[level];
std::priority_queue<entryForCmp, std::vector<entryForCmp>, std::greater<>> q;
for (uint32_t i = 0; i < tmpCells.size(); ++i) {
q.emplace(tmpCells[i]->header.timeStamp, tmpCells[i]->header.minKey, tmpCells[i]->header.maxKey, i, tmpCells[i]);
}
minKey = q.top().minKey;
maxKey = q.top().maxKey;
std::vector<uint32_t> deleteList;
uint32_t n = tmpCells.size() - (0b10 << level);
while (n--) {
targetCells.emplace_back(q.top().table);
deleteList.emplace_back(q.top().index);
minKey = std::min(minKey, q.top().minKey);
maxKey = std::max(maxKey, q.top().maxKey);
q.pop();
}
std::sort(deleteList.begin(), deleteList.end());
auto iter = tmpCells.begin();
uint32_t iterTimes = deleteList[0];
while (iterTimes--) ++iter;
iter = tmpCells.erase(iter);
for (uint32_t i = 1; i < deleteList.size(); ++i) {
iterTimes = deleteList[i] - deleteList[i - 1] - 1;
while (iterTimes--) ++iter;
iter = tmpCells.erase(iter);
}
}
if (level + 1 < levelArray.size()) {
std::deque<ssTable *> &tmpCells = levelArray[level + 1];
auto iter = tmpCells.begin();
while (iter != tmpCells.end()) {
if (minKey <= (*iter)->header.maxKey && maxKey >= (*iter)->header.minKey) {
targetCells.emplace_back(*iter);
iter = tmpCells.erase(iter);
} else {
++iter;
}
}
}
compaction(level + 1, targetCells);
++level;
}
}
ssTableCache::ssTableCache(std::string f): filePath(std::move(f)){
if (!utils::dirExists(filePath) && utils::mkdir(filePath.c_str())) {
std::cerr << "ERROR: Fail to create directory." << std::endl;
exit(1);
}
uint64_t level = 0;
std::string subDir;
nextTimeStamp = 1;
while (utils::dirExists(subDir = filePath + "/level-" + std::to_string(level))) {
uint64_t fileNum;
uint64_t nextFileNum = 0;
std::vector<std::string> ret;
utils::scanDir(subDir, ret);
levelArray.emplace_back();
std::deque<ssTable *> &ssTableArray = levelArray[levelArray.size() - 1];
for (const auto &it: ret) {
std::string subFile = subDir;
subFile += "/" + it;
ssTableArray.emplace_back(new ssTable);
ssTableArray[ssTableArray.size() - 1]->read(subFile);
uint64_t tmp = ssTableArray[ssTableArray.size() - 1]->header.timeStamp;
if (tmp >= nextTimeStamp) nextTimeStamp = tmp + 1;
fileNum = stoul(it.substr(0, it.find('.')));
if (nextFileNum <= fileNum) {
nextFileNum = fileNum + 1;
}
}
nextLabel.push_back(nextFileNum);
++level;
}
if (levelArray.empty()) {
if ( utils::mkdir((filePath + "/level-0").c_str()) ) {
std::cerr << "ERROR: Fail to create directory." << std::endl;
exit(1);
}
levelArray.emplace_back();
nextLabel.push_back(0);
}
}
ssTableCache::~ssTableCache() {
for (auto & it : levelArray) {
for (auto & item : it) {
delete item;
item = nullptr;
}
}
}
void ssTableCache::addTable(const std::vector<std::pair<uint64_t, std::string>> &kVarray) {
std::string fileName = filePath + "/level-0/" + std::to_string(nextLabel[0]) + ".sst";
levelArray[0].emplace_back(ssTable::genTable(fileName, nextTimeStamp, kVarray));
++nextTimeStamp;
++nextLabel[0];
modify();
}
std::pair<bool, std::string> ssTableCache::getValKey(uint64_t key) const {
std::pair<bool, std::string> res(false, "");
uint64_t maxTimeStamp;
if (!levelArray.empty()) {
for (const auto &it: levelArray[0]) {
std::pair<bool, std::string> test = it->getValKey(key);
if (test.first) {
if (res.first) {
if (maxTimeStamp < it->header.timeStamp) {
maxTimeStamp = it->header.timeStamp;
res.second = test.second;
}
} else {
maxTimeStamp = it->header.timeStamp;
res.first = true;
res.second = test.second;
}
}
}
uint64_t i = 1;
while (i < levelArray.size()) {
for (const auto &it: levelArray[i]) {
std::pair<bool, std::string> test = it->getValKey(key);
if (test.first) {
if (res.first) {
if (maxTimeStamp < it->header.timeStamp) {
maxTimeStamp = it->header.timeStamp;
res.second = test.second;
}
} else {
maxTimeStamp = it->header.timeStamp;
res.first = true;
res.second = test.second;
}
break;
}
}
++i;
}
}
return res;
}
void ssTableCache::reset() {
for (auto & it : levelArray) {
for (auto & item : it) {
item->clearTable();
delete item;
item = nullptr;
}
it.clear();
}
for (uint64_t i = 0; i < levelArray.size(); ++i) {
if( utils::rmdir((filePath + "/level-" + std::to_string(i)).c_str()) ) {
std::cerr << "ERROR: Fail to delete directory." << std::endl;
exit(1);
}
}
levelArray.clear();
nextLabel.clear();
if ( utils::mkdir((filePath + "/level-0").c_str()) ) {
std::cerr << "ERROR: Fail to create directory." << std::endl;
exit(1);
}
levelArray.emplace_back();
nextLabel.push_back(0);
nextTimeStamp = 1;
}
| 37.256757 | 129 | 0.518589 | q4x3 |
a15e698a959b763c6365cae82d35603508491a89 | 1,501 | cpp | C++ | practice/Artist.cpp | jordanjohnston/console-music-player | 35c80d9b083a04f75b3959e10cb4c91da56f4b1b | [
"MIT"
] | null | null | null | practice/Artist.cpp | jordanjohnston/console-music-player | 35c80d9b083a04f75b3959e10cb4c91da56f4b1b | [
"MIT"
] | null | null | null | practice/Artist.cpp | jordanjohnston/console-music-player | 35c80d9b083a04f75b3959e10cb4c91da56f4b1b | [
"MIT"
] | null | null | null | #include "Artist.h"
#include <iostream>
using std::vector;
using std::map;
using std::wstring;
Artist::Artist()
{
m_name = L"";
m_albumTitles = vector<wstring>();
m_albumMap = map<wstring, vector<Song>>();
}
Artist::Artist(const wstring name)
:m_name(name)
{
m_albumTitles = vector<wstring>();
m_albumMap = map<wstring, vector<Song>>();
}
Artist::Artist(const wstring name, const map<wstring, vector<Song>> albumMap)
:m_name(name), m_albumMap(albumMap)
{
m_albumTitles = vector<wstring>();
}
Artist::~Artist()
{
}
wstring Artist::getName() const
{
return m_name;
}
void Artist::setName(const wstring& name)
{
m_name = name;
}
map<wstring, vector<Song>> Artist::getAlbums() const
{
return m_albumMap;
}
void Artist::setAlbumMap(const map<wstring, vector<Song>>& albums)
{
m_albumMap = albums;
}
void Artist::addSongToAlbum(const wstring& album, const Song& song)
{
m_albumTitles.push_back(album);
m_albumMap[album].push_back(song);
}
vector<Song> Artist::getAlbumName(const wstring& album) const
{
try
{
return m_albumMap.at(album);
}
catch (const std::out_of_range e)
{
std::wcerr << L"Couldn't find album: " << album << std::endl;
return vector<Song>();
}
}
vector<wstring> Artist::getAllAlbumTitles() const
{
return m_albumTitles;
}
void Artist::addAlbumToList(const wstring albumKey, const wstring albumName, const vector<Song> album)
{
std::pair<wstring, vector<Song>> ap(albumKey, album);
m_albumMap.insert(ap);
m_albumTitles.push_back(albumName);
}
| 17.869048 | 102 | 0.710193 | jordanjohnston |
a168f706c026d400cb7ade7000eb2eff43cc3136 | 387 | hpp | C++ | Paramedic.hpp | rotemish7/wargame-a | 6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661 | [
"MIT"
] | null | null | null | Paramedic.hpp | rotemish7/wargame-a | 6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661 | [
"MIT"
] | null | null | null | Paramedic.hpp | rotemish7/wargame-a | 6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661 | [
"MIT"
] | null | null | null | //
// Created by rotem levy on 27/05/2020.
//
#pragma once
#include "Soldier.hpp"
using namespace std;
class Paramedic: public Soldier
{
public:
static const uint MAX_HP = 100;
Paramedic() {};
virtual ~Paramedic() {};
Paramedic(uint num);
void attack(vector<vector<Soldier*>> &b, pair<int,int> location);
virtual uint getMaxHP();
};
| 16.125 | 70 | 0.612403 | rotemish7 |
a16f864cd332112cd327e49ef24b8a43908e0fdf | 677 | cpp | C++ | ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp | dmkozh/TestAdapter_Catch2 | 6584596594f11bf477fddebfd1211483ca091ee3 | [
"MIT"
] | null | null | null | ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp | dmkozh/TestAdapter_Catch2 | 6584596594f11bf477fddebfd1211483ca091ee3 | [
"MIT"
] | null | null | null | ReferenceTests_v3/src/tests/Catch_Hidden/UT_NotHidden.cpp | dmkozh/TestAdapter_Catch2 | 6584596594f11bf477fddebfd1211483ca091ee3 | [
"MIT"
] | null | null | null | /** Basic Info **
Copyright: 2019 Johnny Hendriks
Author : Johnny Hendriks
Year : 2019
Project: VSTestAdapter for Catch2
Licence: MIT
Notes: None
** Basic Info **/
/************
* Includes *
************/
// Catch2
#include <catch2/catch_test_macros.hpp>
/**************
* Start code *
**************/
namespace CatchHidden
{
// Shift one line to distinguish test case line numbers from the UT_Hidden.cpp file
TEST_CASE( "NotHidden. One tag", "[Tag1]" )
{
CHECK(true);
}
TEST_CASE( "NotHidden. Two tags", "[Tag1][Tag2]" )
{
CHECK(true);
}
} // End namespace: CatchHidden
/************
* End code *
************/
| 15.044444 | 87 | 0.55096 | dmkozh |
a171f05454e22d638a2f450d95e3fc0d1e5a1118 | 1,763 | hpp | C++ | include/evt/evtapproach.hpp | AlterB/chronovise | 5c5fac329b143f3e62ebbc8523d7e205835dd4cb | [
"Apache-2.0"
] | 2 | 2021-02-04T18:22:41.000Z | 2021-12-08T10:57:00.000Z | include/evt/evtapproach.hpp | AlterB/chronovise | 5c5fac329b143f3e62ebbc8523d7e205835dd4cb | [
"Apache-2.0"
] | 9 | 2018-03-20T10:24:22.000Z | 2018-08-27T21:53:56.000Z | include/evt/evtapproach.hpp | AlterB/chronovise | 5c5fac329b143f3e62ebbc8523d7e205835dd4cb | [
"Apache-2.0"
] | 4 | 2018-05-16T14:27:55.000Z | 2022-01-28T17:18:24.000Z | #ifndef EVT_EVTAPPROACH_HPP_
#define EVT_EVTAPPROACH_HPP_
#include "measures_pool.hpp"
namespace chronovise {
/**
* The abstract class implementing one of the EVT approach (BM or PoT).
*/
template <typename T_INPUT, typename T_TIME=unsigned long>
class EVTApproach {
public:
/**
* A default virtual costructor
*/
virtual ~EVTApproach() = default;
/**
* It performs the analysis on the provided pool of data. It also splits the pool
* according to the iterators of the pool itself
* @param original_pool The raw pool from which the sample are drawned
* @throw std::runtime_error In case of failure.
*/
virtual void perform(const MeasuresPoolSet<T_INPUT, T_TIME>& original_pool) = 0;
/**
* It returns the training pool. Calling this method before `perform` returns an
* empty pool.
*/
MeasuresPool<T_INPUT, T_TIME>& get_training_pool() noexcept {
return this->training_pool;
}
/**
* It returns the test pool. Calling this method before `perform` returns an
* empty pool.
*/
MeasuresPool<T_INPUT, T_TIME>& get_test_pool() noexcept {
return this->test_pool;
}
/**
* @brief It returns the minimal sample size to run the estimator. If a sample with lower
* size is provided to run() function, it will probably fail.
*/
virtual unsigned long get_minimal_sample_size() const noexcept = 0;
/**
* @brief A method returning a constant character string identifying the
* EVT method
*/
virtual const char* to_string() const noexcept = 0;
protected:
MeasuresPool<T_INPUT, T_TIME> training_pool;
MeasuresPool<T_INPUT, T_TIME> test_pool;
};
} // namespace chronovise
#endif
| 26.313433 | 93 | 0.673284 | AlterB |
a1727dfcaa0d68978b242b0f18757785f8c40668 | 2,334 | hpp | C++ | source/triceratone/mechanics/cylinderMath.hpp | a-day-old-bagel/at3 | 868cec7672fd109760cae740b1acf26cec5eb85e | [
"MIT"
] | null | null | null | source/triceratone/mechanics/cylinderMath.hpp | a-day-old-bagel/at3 | 868cec7672fd109760cae740b1acf26cec5eb85e | [
"MIT"
] | null | null | null | source/triceratone/mechanics/cylinderMath.hpp | a-day-old-bagel/at3 | 868cec7672fd109760cae740b1acf26cec5eb85e | [
"MIT"
] | null | null | null |
#pragma once
#include "math.hpp"
namespace at3 {
/**
* Get the faked cylinder gravity to apply to a mass.
* This attempts to take into account cylinder-tangential velocity of the mass, and provide a complete picure of the
* way an object would move inside the cylinder from the perspective of the cylinder's own reference frame.
* I may have gotten this wrong.
* The non-tangential component of a mass's motion might need to be rotated every step to match the tangent.
* Right now I'm just applying a negative cylinder-gravity and hoping that it's equivalent (I haven't done the math.)
*
* EDIT: TODO: FIXME: This is not completely right - a projectile shot "upwards" from the ground surface should curve,
* but right now I'm only applying the curve based on tangential velocity, while neglecting change to radial velocity.
* It might not be correct to just add another curve factor multiplied by 1 - dot(tangential, vel), but that might
* be closer and good enough.
*
* @param pos
* @param nativeVel
* @return
*/
glm::vec3 getCylGrav(const glm::vec3 & pos, const glm::vec3 & nativeVel);
/**
* Get the faked cylinder gravity to apply to a mass.
* This neglects any velocity component of the mass in the cylinder-tangential direction, and thus is wrong.
* But it's useful for some things, like finding an appropriate "up" for some objects
* @param pos The center of the mass in standard R3
* @return A likely-incorrect gravity vector
*/
glm::vec3 getNaiveCylGrav(const glm::vec3 &pos);
/**
* Get only the directional part of the naive gravity vector returned by getNaiveCylGrav.
* @param pos The center of the mass in standard R3
* @return A likely-incorrect gravity direction vector
*/
glm::vec3 getNaiveCylGravDir(const glm::vec3 &pos);
/**
* Get a full view rotation from a planar z=up ground plane while facing foward to a cylinder-gravity-up orientation
* including pitch and yaw rotations.
* @param pos The camera position in standard R3
* @param pitch
* @param yaw
* @return A rotation described by pitch and yaw and exhibiting cylinder-gravity-up orientation
*/
glm::mat3 getCylStandingRot(const glm::vec3 &pos, const float &pitch, const float &yaw);
}
| 44.037736 | 121 | 0.705656 | a-day-old-bagel |
a177afd778c2c8658ac4c0e155a6e4f60fd502c5 | 1,420 | hpp | C++ | iceoryx_examples/iceperf/base.hpp | kwallner/iceoryx | f7fee3c237bfe8ae15da434aa78937dba0b0c8ec | [
"Apache-2.0"
] | null | null | null | iceoryx_examples/iceperf/base.hpp | kwallner/iceoryx | f7fee3c237bfe8ae15da434aa78937dba0b0c8ec | [
"Apache-2.0"
] | null | null | null | iceoryx_examples/iceperf/base.hpp | kwallner/iceoryx | f7fee3c237bfe8ae15da434aa78937dba0b0c8ec | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_EXAMPLES_ICEPERF_BASE_HPP
#define IOX_EXAMPLES_ICEPERF_BASE_HPP
#include "topic_data.hpp"
#include <chrono>
#include <iostream>
class IcePerfBase
{
public:
static constexpr uint32_t ONE_KILOBYTE = 1024U;
virtual void initLeader() noexcept = 0;
virtual void initFollower() noexcept = 0;
virtual void shutdown() noexcept = 0;
void prePingPongLeader(uint32_t payloadSizeInBytes) noexcept;
void postPingPongLeader() noexcept;
void releaseFollower() noexcept;
double pingPongLeader(uint64_t numRoundTrips) noexcept;
void pingPongFollower() noexcept;
private:
virtual void sendPerfTopic(uint32_t payloadSizeInBytes, bool runFlag) noexcept = 0;
virtual PerfTopic receivePerfTopic() noexcept = 0;
};
#endif // IOX_EXAMPLES_ICEPERF_BASE_HPP
| 34.634146 | 87 | 0.757042 | kwallner |
a17a64c91b43e614bf6b36375f887d65184bb7bc | 1,322 | cpp | C++ | src/Test/src/TestSyncModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/Test/src/TestSyncModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/Test/src/TestSyncModel.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "SyncModel.h"
#include "EnNoteTranslator.h"
#include "MockEnService.h"
#include "MockMessagePump.h"
#include "MockLogger.h"
#include "MockUserModel.h"
#include "SignalCheck.h"
#include <boost/ref.hpp>
using namespace boost;
using namespace std;
//-----------------------
// auxilliary definitions
//-----------------------
struct SyncModelFixture
{
EnNoteTranslator enNoteTranslator;
MockEnService enService;
MockMessagePump messagePump;
MockLogger logger;
MockUserModel userModel;
SyncModel syncModel;
SyncModelFixture()
: syncModel
( enNoteTranslator
, enService
, messagePump
, userModel
, logger
)
{
enService.userStore->authenticationResult.IsGood = true;
}
};
//-----------
// test cases
//-----------
BOOST_FIXTURE_TEST_CASE(SyncModel_Test, SyncModelFixture)
{
BOOST_CHECK(!messagePump.wokeUp);
SignalCheck signalSyncCompleteCheck;
syncModel.ConnectSyncComplete(ref(signalSyncCompleteCheck));
syncModel.BeginSync(L"username", L"password", Guid("guid"));
::Sleep(20);
BOOST_CHECK(!signalSyncCompleteCheck);
BOOST_CHECK(messagePump.wokeUp);
syncModel.ProcessMessages();
BOOST_CHECK(signalSyncCompleteCheck);
BOOST_CHECK_EQUAL(userModel.loadCount, 1);
}
| 20.030303 | 62 | 0.68003 | don-reba |
a17b841b28943f028b469353b4832dd177a45977 | 299 | cpp | C++ | contest/AtCoder/abc033/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AtCoder/abc033/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AtCoder/abc033/B.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "string.hpp"
#include "vector.hpp"
int main() {
int n(in);
Vector<String> s(n);
Vector<int> p(n);
read(s, p);
int sum = p.accumulate();
for (int i = 0; i < n; ++i) {
if (sum < p[i] * 2) {
cout << s[i] << endl;
return 0;
}
}
cout << "atcoder" << endl;
}
| 16.611111 | 31 | 0.481605 | not522 |
a17fe363176498410537a0ebeeb01e55614b19c6 | 2,857 | cpp | C++ | test/algebra/test_linear_polynomial.cpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | test/algebra/test_linear_polynomial.cpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | test/algebra/test_linear_polynomial.cpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | #ifndef _ALGEBRA_TEST_LINEAR_POLYNOMIAL_HPP_
#define _ALGEBRA_TEST_LINEAR_POLYNOMIAL_HPP_
#include "gtest/gtest.h"
#include "algebra/misc/linear_polynomial.hpp"
namespace carpio{
TEST(linear_polynomial, lp){
typedef LinearPolynomial_<double, std::string> Poly;
Poly poly;
poly["a"] = 1;
poly["b"] = 2;
poly["b"] +=3;
Poly pb;
pb = poly;
ASSERT_EQ(pb.value(), 0.0);
pb += 3;
ASSERT_EQ(pb.value(), 3.0);
pb -= 5;
ASSERT_EQ(pb.value(), -2.0);
pb *= 2;
ASSERT_EQ(pb.value(), -4.0);
ASSERT_EQ(pb["a"], 2.0);
pb /= 3;
ASSERT_EQ(pb["a"], 2.0/3.0);
}
TEST(linear_polynomial, op_add){
typedef LinearPolynomial_<double, std::string> Poly;
Poly poly;
poly["a"] = 1;
poly["b"] = 2;
poly["c"] = 3;
Poly pb;
pb = poly;
pb += 3;
pb["c"] = 5;
pb["d"] =-2;
ASSERT_EQ(pb["c"] , 5.0);
ASSERT_EQ(pb["d"] ,-2.0);
pb += poly;
ASSERT_EQ(pb["c"], 8.0);
ASSERT_EQ(pb["d"],-2.0);
pb -= poly;
pb -= poly;
ASSERT_EQ(pb["c"], 2.0);
ASSERT_EQ(pb["d"],-2.0);
}
TEST(linear_polynomial, op_add2){
typedef LinearPolynomial_<double, std::string> Poly;
Poly poly;
poly["a"] = 1;
poly["b"] = 2;
poly["c"] = 3;
std::cout << "poly :\n";
std::cout << poly << std::endl;
Poly pb;
pb = poly;
pb += 3;
pb["c"] = 5;
pb["d"] =-2;
std::cout << "pb :\n";
std::cout << pb << std::endl;
std::cout << " pb + poly \n";
std::cout << pb + poly << std::endl;
std::cout << " pb - poly \n";
std::cout << pb - poly << std::endl;
std::cout << " poly - pb \n";
std::cout << poly - pb << std::endl;
std::cout << " pb - 3 \n";
std::cout << pb - 300.0 << std::endl;
std::cout << " 100 - pb \n";
std::cout << 100.0 - pb << std::endl;
}
TEST(linear_polynomial, op_multi){
typedef LinearPolynomial_<double, std::string> Poly;
Poly poly;
poly["a"] = 1;
poly["b"] = 2;
poly["c"] = 3;
std::cout << "poly :\n";
std::cout << poly << std::endl;
Poly pb;
pb = poly;
pb += 3;
pb["c"] = 5;
pb["d"] =-2;
std::cout << "pb :\n";
std::cout << pb << std::endl;
std::cout << " pb * 2\n";
std::cout << pb * 2.0 << std::endl;
std::cout << " 3 * pb\n";
std::cout << 3.0 * pb << std::endl;
std::cout << " pb / 2\n";
std::cout << pb / 2.0 << std::endl;
}
TEST(linear_polynomial, op_add_term){
typedef LinearPolynomial_<double, std::string> Poly;
Poly poly;
poly["a"] = 1;
poly["b"] = 2;
poly["c"] = 3;
std::cout << "poly :\n";
std::cout << poly << std::endl;
Poly pb;
pb = poly;
pb += 3;
pb["c"] = 5;
pb["d"] =-2;
std::cout << "pb :\n";
std::cout << pb << std::endl;
std::cout << " pb + \"c\"\n";
std::string str = "c";
std::cout << pb + str << std::endl;
std::cout << " pb + \"e\"\n";
str = "e";
std::cout << pb + str << std::endl;
std::cout << " \"c\" + pb\n";
str = "c";
std::cout << str + pb << std::endl;
std::cout << " \"e\" + pb\n";
str = "e";
std::cout << str + pb << std::endl;
}
}
#endif
| 18.432258 | 53 | 0.535527 | hyperpower |
a1801bb58f2b27d40ff849ce8de2c833463e291f | 1,249 | cc | C++ | CPPQEDscripts/PTLA_Evolved.cc | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 5 | 2021-02-21T14:00:54.000Z | 2021-07-29T15:12:11.000Z | CPPQEDscripts/PTLA_Evolved.cc | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 10 | 2020-04-14T11:18:02.000Z | 2021-07-04T20:11:23.000Z | CPPQEDscripts/PTLA_Evolved.cc | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 2 | 2021-01-25T10:16:35.000Z | 2021-01-28T18:29:01.000Z | // Copyright Andrรกs Vukics 2006โ2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)
#include "Evolution_.h"
#include "PumpedTwoLevelAtom.h"
#include "Qbit.h"
#include "StateVector.h"
#include "DensityOperator.h"
#include "Simulated.h"
using namespace std ;
using namespace cppqedutils ;
using namespace trajectory;
using namespace qbit ;
typedef DArray<1> Array;
int main(int argc, char* argv[])
{
ParameterTable p;
evolution::Pars<> pt(p);
ParsPumpedLossy pp2la(p);
// Parameter finalization
update(p,argc,argv,"--");
PumpedTwoLevelAtomSch atom(pp2la);
double dtinit=.1/atom.highestFrequency();
Array zxy(3);
{
quantumdata::DensityOperator<1> rho(qbit::init(pp2la));
zxy=
2*real(rho(0)(0))-1,
2*real(rho(0)(1)) ,
-2*imag(rho(0)(1)) ;
}
run(simulated::makeBoost(zxy,[&](const Array& b, Array& dbdt, double) {
double z=b(0);
dcomp Omega(-pp2la.gamma,pp2la.delta), s(b(1),-b(2));
dcomp temp(-2.*conj(pp2la.eta)*z+conj(Omega)*s);
dbdt=
2.*real(pp2la.eta*s)+2*pp2la.gamma*(1-z),
real(temp),
-imag(temp);
},{"2*real(rho00)-1","2*real(rho01)","-2*imag(rho01)"},dtinit,pt),pt);
}
| 21.169492 | 132 | 0.638911 | vukics |
a189472ebd6dca27ed8af391104a4b3c674074bf | 492 | cpp | C++ | Source/Inventory/Private/Main/HBGameInstance.cpp | DeltaTimeDev/Inventory | a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284 | [
"MIT"
] | null | null | null | Source/Inventory/Private/Main/HBGameInstance.cpp | DeltaTimeDev/Inventory | a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284 | [
"MIT"
] | null | null | null | Source/Inventory/Private/Main/HBGameInstance.cpp | DeltaTimeDev/Inventory | a4cd76f459a2c2458e219bc1f9ac1c1a9cd2a284 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Main/HBGameInstance.h"
UHBGameInstance::UHBGameInstance()
{
//SoundManager = CreateDefaultSubobject<UHBSoundManager>(TEXT("ItemConfig"));
}
void UHBGameInstance::Init()
{
//SoundManager = NewObject<UHBSoundManager>(this,SoundManagerClass);
SoundManager = GetWorld()->SpawnActor<AHBSoundManager>(SoundManagerClass);
}
AHBSoundManager* UHBGameInstance::GetSoundManager()
{
return SoundManager;
}
| 23.428571 | 78 | 0.786585 | DeltaTimeDev |
a18b75261b0a48786230e2df4b08adff993f2d1c | 10,714 | cpp | C++ | templates/ros_msg_io.cpp | shuklaayush/v_repExtRosInterface | d4bd7cb8e1079f9506af18381db7632da6237a33 | [
"BSD-3-Clause"
] | 19 | 2017-06-29T07:41:26.000Z | 2021-11-03T18:48:48.000Z | templates/ros_msg_io.cpp | kasperg3/vrep_ros_interface | 8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e | [
"BSD-3-Clause"
] | 175 | 2017-06-29T09:37:43.000Z | 2021-07-09T12:55:28.000Z | templates/ros_msg_io.cpp | kasperg3/vrep_ros_interface | 8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e | [
"BSD-3-Clause"
] | 8 | 2017-10-31T08:53:12.000Z | 2021-07-21T06:14:43.000Z | #include <ros_msg_io.h>
#include <v_repLib.h>
#include <stubs.h>
#include <cstring>
#py from parse_messages_and_services import get_msgs_info, get_msgs_srvs_info, TypeSpec
#py msgs = get_msgs_srvs_info(pycpp.params['messages_file'], pycpp.params['services_file'])
#py for msg, info in msgs.items():
void write__`info.typespec.normalized()`(const `info.typespec.ctype()`& msg, int stack, const WriteOptions *opt)
{
try
{
simPushTableOntoStackE(stack);
#py for n, t in info.fields.items():
#py if t.array:
#py if t.builtin and t.mtype in TypeSpec.fast_write_types:
try
{
// write field '`n`' (using fast specialized function)
simPushStringOntoStackE(stack, "`n`", 0);
simPush`TypeSpec.fast_write_types[t.mtype]`TableOntoStackE(stack, &(msg.`n`[0]), msg.`n`.size());
simInsertDataIntoStackTableE(stack);
}
catch(exception& ex)
{
std::string msg = "field '`n`': ";
msg += ex.what();
throw exception(msg);
}
#py elif t.builtin and t.mtype == 'uint8':
try
{
// write field '`n`' (using fast specialized function)
simPushStringOntoStackE(stack, "`n`", 0);
if(opt && opt->uint8array_as_string)
simPushStringOntoStackE(stack, (simChar*)&(msg.`n`[0]), msg.`n`.size());
else
simPushUInt8TableOntoStackE(stack, &(msg.`n`[0]), msg.`n`.size());
simInsertDataIntoStackTableE(stack);
}
catch(exception& ex)
{
std::string msg = "field '`n`': ";
msg += ex.what();
throw exception(msg);
}
#py else:
try
{
// write field '`n`'
simPushStringOntoStackE(stack, "`n`", 0);
simPushTableOntoStackE(stack);
for(int i = 0; i < msg.`n`.size(); i++)
{
write__int32(i + 1, stack, opt);
write__`t.normalized()`(msg.`n`[i], stack, opt);
simInsertDataIntoStackTableE(stack);
}
simInsertDataIntoStackTableE(stack);
}
catch(exception& ex)
{
std::string msg = "field '`n`': ";
msg += ex.what();
throw exception(msg);
}
#py endif
#py else:
try
{
// write field '`n`'
simPushStringOntoStackE(stack, "`n`", 0);
write__`t.normalized()`(msg.`n`, stack, opt);
simInsertDataIntoStackTableE(stack);
}
catch(exception& ex)
{
std::string msg = "field '`n`': ";
msg += ex.what();
throw exception(msg);
}
#py endif
#py endfor
}
catch(exception& ex)
{
std::string msg = "write__`info.typespec.normalized()`: ";
msg += ex.what();
throw exception(msg);
}
}
void read__`info.typespec.normalized()`(int stack, `info.typespec.ctype()` *msg, const ReadOptions *opt)
{
try
{
int r = simGetStackTableInfoE(stack, 0);
if(r != sim_stack_table_map && r != sim_stack_table_empty)
throw exception("expected a table");
int oldsz = simGetStackSizeE(stack);
simUnfoldStackTableE(stack);
int numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2;
char *str;
int strSz;
while(numItems >= 1)
{
simMoveStackItemToTopE(stack, oldsz - 1); // move key to top
if((str = simGetStackStringValueE(stack, &strSz)) != NULL && strSz > 0)
{
simPopStackItemE(stack, 1);
simMoveStackItemToTopE(stack, oldsz - 1); // move value to top
if(0) {}
#py for n, t in info.fields.items():
#py if t.array:
#py if t.builtin and t.mtype in TypeSpec.fast_write_types:
else if(strcmp(str, "`n`") == 0)
{
try
{
// read field '`n`' (using fast specialized function)
int sz = simGetStackTableInfoE(stack, 0);
if(sz < 0)
throw exception("expected array");
if(simGetStackTableInfoE(stack, 2) != 1)
throw exception("fast_write_type reader exception #1");
#py if t.array_size:
// field has fixed size -> no need to reserve space into vector
#py else:
msg->`n`.resize(sz);
#py endif
simGetStack`TypeSpec.fast_write_types[t.mtype]`TableE(stack, &(msg->`n`[0]), sz);
simPopStackItemE(stack, 1);
}
catch(exception& ex)
{
std::string msg = "field `n`: ";
msg += ex.what();
throw exception(msg);
}
}
#py elif t.builtin and t.mtype == 'uint8':
else if(strcmp(str, "`n`") == 0)
{
try
{
if(opt && opt->uint8array_as_string)
{
// read field '`n`' (uint8[]) as string
simChar *str;
simInt sz;
if((str = simGetStackStringValueE(stack, &sz)) != NULL && sz > 0)
{
/*
* XXX: if an alternative version of simGetStackStringValue woudl exist
* working on an externally allocated buffer, we won't need this memcpy:
*/
#py if t.array_size:
// field has fixed size -> no need to reserve space into vector
#py else:
msg->`n`.resize(sz);
#py endif
std::memcpy(&(msg->`n`[0]), str, sz);
simReleaseBufferE(str);
}
else throw exception("string read error when trying to read uint8[]");
}
else
{
// read field '`n`' (using fast specialized function)
int sz = simGetStackTableInfoE(stack, 0);
if(sz < 0)
throw exception("expected uint8 array");
if(simGetStackTableInfoE(stack, 2) != 1)
throw exception("fast_write_type uint8[] reader exception #1");
#py if t.array_size:
// field has fixed size -> no need to reserve space into vector
#py else:
msg->`n`.resize(sz);
#py endif
simGetStackUInt8TableE(stack, &(msg->`n`[0]), sz);
simPopStackItemE(stack, 1);
}
}
catch(exception& ex)
{
std::string msg = "field `n`: ";
msg += ex.what();
throw exception(msg);
}
}
#py else: # array not fast func
else if(strcmp(str, "`n`") == 0)
{
try
{
// read field '`n`'
if(simGetStackTableInfoE(stack, 0) < 0)
throw exception("expected array");
int oldsz1 = simGetStackSizeE(stack);
simUnfoldStackTableE(stack);
int numItems1 = (simGetStackSizeE(stack) - oldsz1 + 1) / 2;
for(int i = 0; i < numItems1; i++)
{
simMoveStackItemToTopE(stack, oldsz1 - 1); // move key to top
int j;
read__int32(stack, &j, opt);
simMoveStackItemToTopE(stack, oldsz1 - 1); // move value to top
`t.ctype()` v;
read__`t.normalized()`(stack, &v, opt);
#py if t.array_size:
msg->`n`[i] = (v);
#py else:
msg->`n`.push_back(v);
#py endif
}
}
catch(exception& ex)
{
std::string msg = "field `n`: ";
msg += ex.what();
throw exception(msg);
}
}
#py endif
#py else: # not array
else if(strcmp(str, "`n`") == 0)
{
try
{
// read field '`n`'
read__`t.normalized()`(stack, &(msg->`n`), opt);
}
catch(exception& ex)
{
std::string msg = "field `n`: ";
msg += ex.what();
throw exception(msg);
}
}
#py endif
#py endfor
else
{
std::string msg = "unexpected key: ";
msg += str;
throw exception(msg);
}
simReleaseBuffer(str);
}
else
{
throw exception("malformed table (bad key type)");
}
numItems = (simGetStackSizeE(stack) - oldsz + 1) / 2;
}
}
catch(exception& ex)
{
std::string msg = "read__`info.typespec.normalized()`: ";
msg += ex.what();
throw exception(msg);
}
}
#py endfor
#py msgs = get_msgs_info(pycpp.params['messages_file'])
#py for msg, info in msgs.items():
void ros_callback__`info.typespec.normalized()`(const boost::shared_ptr<`info.typespec.ctype()` const>& msg, SubscriberProxy *proxy)
{
int stack = -1;
try
{
stack = simCreateStackE();
write__`info.typespec.normalized()`(*msg, stack, &(proxy->wr_opt));
simCallScriptFunctionExE(proxy->topicCallback.scriptId, proxy->topicCallback.name.c_str(), stack);
simReleaseStackE(stack);
stack = -1;
}
catch(exception& ex)
{
if(stack != -1)
simReleaseStack(stack); // don't throw
std::string msg = "ros_callback__`info.typespec.normalized()`: ";
msg += ex.what();
simSetLastError(proxy->topicCallback.name.c_str(), msg.c_str());
}
}
#py endfor
| 36.074074 | 132 | 0.444932 | shuklaayush |
a18df0c3b4b67cd95f755754268d3a84d951b7a5 | 2,247 | cpp | C++ | export/windows/obj/src/lime/system/Endian.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/system/Endian.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/system/Endian.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | 1 | 2021-07-16T22:57:01.000Z | 2021-07-16T22:57:01.000Z | // Generated by Haxe 4.0.0-rc.2+77068e10c
#include <hxcpp.h>
#ifndef INCLUDED_lime_system_Endian
#include <lime/system/Endian.h>
#endif
namespace lime{
namespace _hx_system{
::lime::_hx_system::Endian Endian_obj::_hx_BIG_ENDIAN;
::lime::_hx_system::Endian Endian_obj::_hx_LITTLE_ENDIAN;
bool Endian_obj::__GetStatic(const ::String &inName, ::Dynamic &outValue, hx::PropertyAccess inCallProp)
{
if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) { outValue = Endian_obj::_hx_BIG_ENDIAN; return true; }
if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) { outValue = Endian_obj::_hx_LITTLE_ENDIAN; return true; }
return super::__GetStatic(inName, outValue, inCallProp);
}
HX_DEFINE_CREATE_ENUM(Endian_obj)
int Endian_obj::__FindIndex(::String inName)
{
if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return 1;
if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return 0;
return super::__FindIndex(inName);
}
int Endian_obj::__FindArgCount(::String inName)
{
if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return 0;
if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return 0;
return super::__FindArgCount(inName);
}
hx::Val Endian_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
if (inName==HX_("BIG_ENDIAN",9a,d5,89,b2)) return _hx_BIG_ENDIAN;
if (inName==HX_("LITTLE_ENDIAN",04,50,ec,fb)) return _hx_LITTLE_ENDIAN;
return super::__Field(inName,inCallProp);
}
static ::String Endian_obj_sStaticFields[] = {
HX_("LITTLE_ENDIAN",04,50,ec,fb),
HX_("BIG_ENDIAN",9a,d5,89,b2),
::String(null())
};
hx::Class Endian_obj::__mClass;
Dynamic __Create_Endian_obj() { return new Endian_obj; }
void Endian_obj::__register()
{
hx::Static(__mClass) = hx::_hx_RegisterClass(HX_("lime.system.Endian",41,85,63,b4), hx::TCanCast< Endian_obj >,Endian_obj_sStaticFields,0,
&__Create_Endian_obj, &__Create,
&super::__SGetClass(), &CreateEndian_obj, 0
#ifdef HXCPP_VISIT_ALLOCS
, 0
#endif
#ifdef HXCPP_SCRIPTABLE
, 0
#endif
);
__mClass->mGetStaticField = &Endian_obj::__GetStatic;
}
void Endian_obj::__boot()
{
_hx_BIG_ENDIAN = hx::CreateConstEnum< Endian_obj >(HX_("BIG_ENDIAN",9a,d5,89,b2),1);
_hx_LITTLE_ENDIAN = hx::CreateConstEnum< Endian_obj >(HX_("LITTLE_ENDIAN",04,50,ec,fb),0);
}
} // end namespace lime
} // end namespace system
| 28.443038 | 138 | 0.739208 | arturspon |
08487d3497d5d5c73e51fa16d195cbde96c231cf | 952 | cpp | C++ | Backtracking/CombinationSum2.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | Backtracking/CombinationSum2.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | Backtracking/CombinationSum2.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void backtrack(int start, vector<int> &row, int sum, set<vector<int>> &res, vector<int> &A, int B)
{
if (sum >= B)
{
if (sum == B)
res.insert(row);
return;
}
if (start == A.size())
return;
row.push_back(A[start]);
sum += A[start];
backtrack(start + 1, row, sum, res, A, B);
sum -= row[row.size() - 1];
row.pop_back();
backtrack(start + 1, row, sum, res, A, B);
}
vector<vector<int>> combinationSum(vector<int> &A, int B)
{
set<vector<int>> res;
vector<int> row;
sort(A.begin(), A.end());
backtrack(0, row, 0, res, A, B);
vector<vector<int>> v(res.begin(), res.end());
return v;
}
int main()
{
vector<int> v1{10, 1, 2, 7, 6, 1, 5};
vector<vector<int>> v2 = combinationSum(v1, 8);
for (int i = 0; i < v2.size(); i++)
{
for (int j = 0; j < v2[i].size(); j++)
{
cout << v2[i][j] << " ";
}
cout << endl;
}
return 0;
}
| 18.307692 | 98 | 0.534664 | aviral243 |
084d70e1266daa9ebdef51884042946721dea121 | 4,898 | cpp | C++ | src/transport_catalogue.cpp | BigBoyMato/CityRouter | 5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b | [
"MIT"
] | null | null | null | src/transport_catalogue.cpp | BigBoyMato/CityRouter | 5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b | [
"MIT"
] | null | null | null | src/transport_catalogue.cpp | BigBoyMato/CityRouter | 5a76f410206645fce2cdbb33fbc3e8dfe0b5bf2b | [
"MIT"
] | null | null | null | #include "transport_catalogue.h"
#include <algorithm>
#include <utility>
#include <iostream>
namespace transport_catalogue{
namespace detail{
size_t StringPairHash::operator() (const std::pair<std::string, std::string>& stops) const {
return hash_s(stops.first) + hash_s(stops.second) * 101;
}
size_t StopHash::operator() (const std::pair<Stop*, Stop*>& stops) const {
return hash_v(stops.first) + hash_v(stops.second) * 101;
}
}
void TransportCatalogue::AddRoute(const Bus& bus){
buses.push_back(bus);
// calculate length
double length_c = 0;
double length_f = 0;
// one stop on route handler
if (buses.back().stops.size() == 1){
const auto stop = FindStop(buses.back().stops[0]->name);
auto found_stop = stop_to_buses.find(stop->name);
if (found_stop != stop_to_buses.end()){
found_stop->second.insert(&buses.back());
}
}
// if route stops is equal to 1 -> doesnt reach here
for(size_t i = 1; i < buses.back().stops.size(); i++){
const auto prev_stop = FindStop(buses.back().stops[i - 1]->name);
const auto stop = FindStop(buses.back().stops[i]->name);
length_c += geo::ComputeDistance(prev_stop->coordinates, stop->coordinates);
const auto prev_stop_to_stop_distance = GetDistance(std::make_pair(prev_stop, stop));
const auto stop_to_prev_stop_distance = GetDistance(std::make_pair(stop, prev_stop));
if (!prev_stop_to_stop_distance.has_value()
&& !stop_to_prev_stop_distance.has_value()){
length_f += -1; // set by authors
}else{
if (prev_stop_to_stop_distance.has_value()){
length_f += prev_stop_to_stop_distance.value();
}else{
length_f += stop_to_prev_stop_distance.value();
}
}
auto found_stop = stop_to_buses.find(stop->name);
if (found_stop != stop_to_buses.end()){
found_stop->second.insert(&buses.back());
}
}
buses.back().factual_length = length_f;
buses.back().length_by_coordinates = length_c;
routes[buses.back().name] = &buses.back();
}
void TransportCatalogue::AddStop(const Stop& stop){
stops.push_back(stop);
stops_by_names[stops.back().name] = &stops.back();
if (stop_to_buses.find(stops.back().name) == stop_to_buses.end()){
stop_to_buses[stops.back().name] = {};
}
}
Stop* TransportCatalogue::FindStop(const std::string_view stop_name) const {
if (stops_by_names.count(stop_name) != 0){
return stops_by_names.at(stop_name);
}
return nullptr;
}
Bus* TransportCatalogue::FindRoute(const std::string_view bus_name) const {
if (routes.count(bus_name) != 0){
return routes.at(bus_name);
}
return nullptr;
}
std::pair<std::string_view, const std::optional<Bus*>>
TransportCatalogue::GetRouteInfo(const std::string_view bus_name) const {
if (routes.count(bus_name)){
return {bus_name, FindRoute(bus_name)};
}
return {bus_name, std::nullopt};
}
std::pair<std::string_view, const std::optional<std::set<std::string_view>>>
TransportCatalogue::GetStopInfo(const std::string_view stop_name) const {
if (stop_to_buses.count(stop_name)){
std::set<std::string_view> buses;
for (const auto& bus : stop_to_buses.at(stop_name)){
buses.insert(bus->name);
}
return {stop_name, buses};
}
return {stop_name, std::nullopt};
}
void TransportCatalogue::SetDistances(const std::unordered_map<std::pair<std::string, std::string>, int,
detail::StringPairHash>& pair_from_to) {
for (const auto& [key, val] : pair_from_to) {
distances[std::make_pair(FindStop(key.first), FindStop(key.second))] = val;
}
}
std::optional<int> TransportCatalogue::GetDistance(const std::pair<Stop*, Stop*>& pair_from_to) const {
const auto elem = distances.find(pair_from_to);
if (elem != distances.end()){
return (*elem).second;
}
return {};
}
std::unordered_map<std::pair<Stop*, Stop*>, int, detail::StopHash> TransportCatalogue::GetDistances() const{
return distances;
}
std::unordered_set<Bus*> TransportCatalogue::GetBusesOnStop(const std::string& stop_name) const {
return stop_to_buses.at(stop_name);
}
std::map<std::string, Bus*> TransportCatalogue::GetSortedBuses() const{
std::map<std::string, Bus*> buses_sorted;
for (const auto& [bus_name_view, bus] : routes) {
buses_sorted.emplace(std::make_pair(
std::string(bus_name_view.begin(), bus_name_view.end()), bus));
}
return buses_sorted;
}
std::deque<Stop> TransportCatalogue::GetStops() const{
return stops;
}
std::deque<Bus> TransportCatalogue::GetBuses() const{
return buses;
}
std::unordered_map<std::string_view, Stop*> TransportCatalogue::GetStopsByNames() const{
return stops_by_names;
}
std::unordered_map<std::string_view, Bus*> TransportCatalogue::GetRoutes() const{
return routes;
}
}
| 31 | 113 | 0.675174 | BigBoyMato |
084f92f4353a681b1c460b1ffd4d40d29a287145 | 5,496 | cc | C++ | common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc | swapnil119/chromeos_smart_card_connector | c01ec7e9aad61ede90f1eeaf8554540ede988d2d | [
"Apache-2.0"
] | 79 | 2017-09-22T05:09:54.000Z | 2022-03-13T01:11:06.000Z | common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc | QPC-database/chromeos_smart_card_connector | 3ced08b30ce3f2a557487c3bfba1d1cd36c5011c | [
"Apache-2.0"
] | 191 | 2017-10-23T22:34:58.000Z | 2022-03-05T18:10:06.000Z | common/cpp/src/google_smart_card_common/requesting/async_request_unittest.cc | QPC-database/chromeos_smart_card_connector | 3ced08b30ce3f2a557487c3bfba1d1cd36c5011c | [
"Apache-2.0"
] | 32 | 2017-10-21T07:39:59.000Z | 2021-11-10T22:55:32.000Z | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <google_smart_card_common/requesting/async_request.h>
#include <chrono>
#include <functional>
#include <thread>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include <google_smart_card_common/requesting/request_result.h>
#include <google_smart_card_common/value.h>
namespace google_smart_card {
namespace {
class TestAsyncRequestCallback {
public:
void operator()(GenericRequestResult request_result) {
request_result_ = std::move(request_result);
++call_count_;
}
int call_count() const { return call_count_; }
const GenericRequestResult& request_result() const { return request_result_; }
private:
int call_count_ = 0;
GenericRequestResult request_result_;
};
} // namespace
TEST(RequestingAsyncRequestTest, AsyncRequestStateBasic) {
TestAsyncRequestCallback callback;
// Initially the request state is constructed with no request result, and the
// callback is not executed
GenericAsyncRequestState request_state(std::ref(callback));
ASSERT_EQ(0, callback.call_count());
// The first set of the request result is successful and triggers the callback
const int kValue = 123;
ASSERT_TRUE(request_state.SetResult(
GenericRequestResult::CreateSuccessful(Value(kValue))));
ASSERT_EQ(1, callback.call_count());
ASSERT_TRUE(callback.request_result().payload().is_integer());
EXPECT_EQ(callback.request_result().payload().GetInteger(), kValue);
// The subsequent set of the request result does not change the stored value
// and does not trigger the callback
ASSERT_FALSE(request_state.SetResult(GenericRequestResult::CreateFailed("")));
ASSERT_EQ(1, callback.call_count());
ASSERT_TRUE(callback.request_result().payload().is_integer());
EXPECT_EQ(callback.request_result().payload().GetInteger(), kValue);
}
#ifdef __EMSCRIPTEN__
// TODO(#185): Crashes in Emscripten due to out-of-memory.
#define MAYBE_AsyncRequestStateMultiThreading \
DISABLED_AsyncRequestStateMultiThreading
#else
#define MAYBE_AsyncRequestStateMultiThreading AsyncRequestStateMultiThreading
#endif
TEST(RequestingAsyncRequestTest, MAYBE_AsyncRequestStateMultiThreading) {
const int kIterationCount = 300;
const int kStateCount = 100;
const int kThreadCount = 10;
const auto kThreadsStartTimeout = std::chrono::milliseconds(10);
for (int iteration = 0; iteration < kIterationCount; ++iteration) {
std::vector<TestAsyncRequestCallback> callbacks(kStateCount);
std::vector<std::unique_ptr<GenericAsyncRequestState>> states;
for (int index = 0; index < kStateCount; ++index) {
states.emplace_back(
new GenericAsyncRequestState(std::ref(callbacks[index])));
}
std::vector<std::thread> threads;
const auto threads_start_time =
std::chrono::high_resolution_clock::now() + kThreadsStartTimeout;
for (int thread_index = 0; thread_index < kThreadCount; ++thread_index) {
threads.emplace_back([&states, threads_start_time] {
std::this_thread::sleep_until(threads_start_time);
for (int index = 0; index < kStateCount; ++index)
states[index]->SetResult(GenericRequestResult::CreateFailed(""));
});
}
for (int thread_index = 0; thread_index < kThreadCount; ++thread_index)
threads[thread_index].join();
for (int index = 0; index < kStateCount; ++index)
EXPECT_EQ(1, callbacks[index].call_count());
}
}
TEST(RequestingAsyncRequestTest, AsyncRequestBasic) {
TestAsyncRequestCallback callback;
// Initially the request is constructed with an empty request state
const auto request_state =
std::make_shared<GenericAsyncRequestState>(std::ref(callback));
GenericAsyncRequest request(request_state);
ASSERT_EQ(0, callback.call_count());
// The request state receives the result, which triggers the callback
ASSERT_TRUE(request_state->SetResult(GenericRequestResult::CreateFailed("")));
ASSERT_EQ(1, callback.call_count());
// After the result is already set, request cancellation has no effect
request.Cancel();
ASSERT_EQ(1, callback.call_count());
}
TEST(RequestingAsyncRequestTest, AsyncRequestCancellation) {
TestAsyncRequestCallback callback;
// Initially the request is constructed with an empty request state
const auto request_state =
std::make_shared<GenericAsyncRequestState>(std::ref(callback));
GenericAsyncRequest request(request_state);
ASSERT_EQ(0, callback.call_count());
// The request is canceled, which sets the result to "canceled"
request.Cancel();
ASSERT_EQ(1, callback.call_count());
EXPECT_TRUE(callback.request_result().status() ==
RequestResultStatus::kCanceled);
// After the request is canceled, request result assignment has no effect
ASSERT_FALSE(
request_state->SetResult(GenericRequestResult::CreateFailed("")));
ASSERT_EQ(1, callback.call_count());
}
} // namespace google_smart_card
| 35.921569 | 80 | 0.75091 | swapnil119 |
085421df1899e82807b32c078f1ce197ead31708 | 3,503 | cc | C++ | bitmap_bench_sdsl.cc | timjb/rankselect | 566182d9e2f5861b34dde0807d95c806776baf0d | [
"Apache-2.0"
] | 15 | 2017-06-06T20:04:34.000Z | 2020-06-29T21:33:29.000Z | bitmap_bench_sdsl.cc | timjb/rankselect | 566182d9e2f5861b34dde0807d95c806776baf0d | [
"Apache-2.0"
] | null | null | null | bitmap_bench_sdsl.cc | timjb/rankselect | 566182d9e2f5861b34dde0807d95c806776baf0d | [
"Apache-2.0"
] | 4 | 2017-11-02T18:00:08.000Z | 2022-02-03T18:37:52.000Z | /* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include "rank_support.hpp"
#include "select_support_scan.hpp"
#include "select_support_mcl.hpp"
#include "bitmap.h"
#include "shared.h"
using namespace sdsl;
double densityL = 0.1;
double densityR = 0.1;
uint64 numOnesL = 0;
uint64 numOnesR = 0;
const int numIters = 10;
const int numQueries = 10000000;
uint64 queries[numQueries];
uint64 indices[numQueries];
uint64 queries64[numQueries];
uint32 seed = 1;
inline uint32 xRand()
{
return seed = (279470273ULL * seed) % 4294967291ULL;
}
inline uint64 xRand64()
{
return (uint64) xRand() << 32 | xRand();
}
void intVectorRandomBit(uint64 nbits, bit_vector &vector, uint32 thresholdL, uint32 thresholdR)
{
fprintf(stderr, "nbits to create: %" PRIu64 "\n", nbits);
fprintf(stderr, "allocated bits: %" PRIu64 " bytes\n", nbits/8);
for (uint64 i = 0; i < nbits / 2; i++) {
if (xRand() < thresholdL) {
uint64 val = vector.get_int(i / 64, 64);
val |= 1ul << (i % 64);
vector.set_int(i / 64, val, 64);
++numOnesL;
} else {
uint64 val = vector.get_int(i / 64, 64);
val &= ~(1ull << (i % 64));
vector.set_int(i / 64, val, 64);
}
}
for (uint64 i = nbits / 2; i < nbits; i++) {
if (xRand() < thresholdR) {
uint64 val = vector.get_int(i / 64, 64);
val |= 1ull << (i % 64);
vector.set_int(i / 64, val, 64);
++numOnesR;
} else {
uint64 val = vector.get_int(i / 64, 64);
val &= ~(1ull << (i % 64));
vector.set_int(i / 64, val, 64);
}
}
}
enum benchmode {
BENCH_RANK,
BENCH_SELECT,
};
int main(int argc, char **argv)
{
extern int optind;
int ch;
uint64 nbits;
benchmode mode = BENCH_RANK;
while ((ch = getopt(argc, argv, "sn:d:")) != -1) {
switch (ch) {
case 's':
mode = BENCH_SELECT;
break;
case 'n':
nbits = atoi(optarg);
nbits = 1ULL << nbits;
break;
case 'd':
densityL = densityR = atof(optarg);
break;
}
}
printf("benchmode: %s\n", mode == BENCH_RANK ? "rank" : "select");
uint32 thresholdL = (uint32) (UINT32_MAX * densityL);
uint32 thresholdR = (uint32) (UINT32_MAX * densityR);
uint64 numWords = (nbits + 63)/64;
bit_vector vector(nbits, 0, 1);
intVectorRandomBit(nbits, vector, thresholdL, thresholdR);
uint64 cnt = rank_support_v<0>(&vector)(vector.size());
bit_vector::select_0_type bit_select(&vector);
uint64 dummy = 0x1234567890ABCDEF;
if (mode == BENCH_RANK) {
for (int i = 0; i < numQueries; i++) {
queries[i] = xRand64() % nbits + 1;
}
} else {
assert(mode == BENCH_SELECT);
for (int i = 0; i < numQueries / 2; i++) {
queries[i] = ((xRand64() % numOnesL + 1) % (cnt - 1)) + 1;
}
for (int i = numQueries / 2; i < numQueries; i++) {
queries[i] = ((xRand64() % numOnesR + 1 + numOnesL) % (cnt - 1)) + 1;
}
}
struct timeval tv_start, tv_end;
double elapsed_seconds;
gettimeofday(&tv_start, NULL);
assert(mode == BENCH_SELECT);
for (int iter = 0; iter < numIters; iter++)
for (int i = 0; i < numQueries; i++)
dummy ^= bit_select(queries[i]);
gettimeofday(&tv_end, NULL);
elapsed_seconds = timeval_diff(&tv_start, &tv_end);
printf("%" PRIu64 " ops, %.2f seconds, ns/op: %.2f\n",
(uint64) numIters * numQueries,
elapsed_seconds,
elapsed_seconds * 1000000000 / ((uint64) numIters * numQueries));
if (dummy == 42) printf("42\n");
return 0;
}
| 23.353333 | 96 | 0.625178 | timjb |
08555da4ee2fbf5f8d8ac59b9ed4600b31cea14c | 8,522 | cpp | C++ | modules/audio_coding/main/test/EncodeDecodeTest.cpp | stoiczek/WebRTC | 6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c | [
"BSD-3-Clause"
] | 1 | 2017-02-08T09:47:04.000Z | 2017-02-08T09:47:04.000Z | modules/audio_coding/main/test/EncodeDecodeTest.cpp | stoiczek/WebRTC | 6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c | [
"BSD-3-Clause"
] | null | null | null | modules/audio_coding/main/test/EncodeDecodeTest.cpp | stoiczek/WebRTC | 6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c | [
"BSD-3-Clause"
] | 5 | 2015-10-30T17:35:19.000Z | 2021-06-04T01:39:27.000Z | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "EncodeDecodeTest.h"
#include "common_types.h"
#include <stdlib.h>
#include <string.h>
#include "trace.h"
#include "utility.h"
Receiver::Receiver()
:
_playoutLengthSmpls(WEBRTC_10MS_PCM_AUDIO),
_payloadSizeBytes(MAX_INCOMING_PAYLOAD)
{
}
void Receiver::Setup(AudioCodingModule *acm, RTPStream *rtpStream)
{
struct CodecInst recvCodec;
int noOfCodecs;
acm->InitializeReceiver();
noOfCodecs = acm->NumberOfCodecs();
for (int i=0; i < noOfCodecs; i++)
{
acm->Codec((WebRtc_UWord8)i, recvCodec);
if (acm->RegisterReceiveCodec(recvCodec) != 0)
{
printf("Unable to register codec: for run: codecId: %d\n", codeId);
exit(1);
}
}
char filename[128];
_rtpStream = rtpStream;
int playSampFreq;
if (testMode == 1)
{
playSampFreq=recvCodec.plfreq;
//output file for current run
sprintf(filename,"./modules/audio_coding/main/test/res_tests/out%dFile.pcm",codeId);
_pcmFile.Open(filename, recvCodec.plfreq, "wb+");
}
else if (testMode == 0)
{
playSampFreq=32000;
//output file for current run
sprintf(filename,"./modules/audio_coding/main/test/res_autotests/encodeDecode_out%d.pcm",codeId);
_pcmFile.Open(filename, 32000/*recvCodec.plfreq*/, "wb+");
}
else
{
printf("\nValid output frequencies:\n");
printf("8000\n16000\n32000\n-1, which means output freq equal to received signal freq");
printf("\n\nChoose output sampling frequency: ");
scanf("%d", &playSampFreq);
char fileName[] = "./modules/audio_coding/main/test/outFile.pcm";
_pcmFile.Open(fileName, 32000, "wb+");
}
_realPayloadSizeBytes = 0;
_playoutBuffer = new WebRtc_Word16[WEBRTC_10MS_PCM_AUDIO];
_frequency = playSampFreq;
_acm = acm;
_firstTime = true;
}
void Receiver::Teardown()
{
delete [] _playoutBuffer;
_pcmFile.Close();
if (testMode > 1) Trace::ReturnTrace();
}
bool Receiver::IncomingPacket()
{
if (!_rtpStream->EndOfFile())
{
if (_firstTime)
{
_firstTime = false;
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload, _payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile())
{
_firstTime = true;
return true;
}
}
WebRtc_Word32 ok = _acm->IncomingPacket(_incomingPayload, _realPayloadSizeBytes, _rtpInfo);
if (ok != 0)
{
printf("Error when inserting packet to ACM, for run: codecId: %d\n", codeId);
exit(1);
}
_realPayloadSizeBytes = _rtpStream->Read(&_rtpInfo, _incomingPayload, _payloadSizeBytes, &_nextTime);
if (_realPayloadSizeBytes == 0 && _rtpStream->EndOfFile())
{
_firstTime = true;
}
}
return true;
}
bool Receiver::PlayoutData()
{
AudioFrame audioFrame;
if (_acm->PlayoutData10Ms(_frequency, audioFrame) != 0)
{
printf("Error when calling PlayoutData10Ms, for run: codecId: %d\n", codeId);
exit(1);
}
if (_playoutLengthSmpls == 0)
{
return false;
}
_pcmFile.Write10MsData(audioFrame._payloadData, audioFrame._payloadDataLengthInSamples);
return true;
}
void Receiver::Run()
{
WebRtc_UWord8 counter500Ms = 50;
WebRtc_UWord32 clock = 0;
while (counter500Ms > 0)
{
if (clock == 0 || clock >= _nextTime)
{
IncomingPacket();
if (clock == 0)
{
clock = _nextTime;
}
}
if ((clock % 10) == 0)
{
if (!PlayoutData())
{
clock++;
continue;
}
}
if (_rtpStream->EndOfFile())
{
counter500Ms--;
}
clock++;
}
}
EncodeDecodeTest::EncodeDecodeTest()
{
_testMode = 2;
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
EncodeDecodeTest::EncodeDecodeTest(int testMode)
{
//testMode == 0 for autotest
//testMode == 1 for testing all codecs/parameters
//testMode > 1 for specific user-input test (as it was used before)
_testMode = testMode;
if(_testMode != 0)
{
Trace::CreateTrace();
Trace::SetTraceFile("acm_encdec_test.txt");
}
}
void EncodeDecodeTest::Perform()
{
if(_testMode == 0)
{
printf("Running Encode/Decode Test");
WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceAudioCoding, -1, "---------- EncodeDecodeTest ----------");
}
int numCodecs = 1;
int codePars[3]; //freq, pacsize, rate
int playoutFreq[3]; //8, 16, 32k
int numPars[52]; //number of codec parameters sets (rate,freq,pacsize)to test, for a given codec
codePars[0]=0;
codePars[1]=0;
codePars[2]=0;
if (_testMode == 1)
{
AudioCodingModule *acmTmp = AudioCodingModule::Create(0);
struct CodecInst sendCodecTmp;
numCodecs = acmTmp->NumberOfCodecs();
printf("List of supported codec.\n");
for(int n = 0; n < numCodecs; n++)
{
acmTmp->Codec(n, sendCodecTmp);
if (STR_CASE_CMP(sendCodecTmp.plname, "telephone-event") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "cn") == 0) {
numPars[n] = 0;
} else if (STR_CASE_CMP(sendCodecTmp.plname, "red") == 0) {
numPars[n] = 0;
} else {
numPars[n] = 1;
printf("%d %s\n", n, sendCodecTmp.plname);
}
}
AudioCodingModule::Destroy(acmTmp);
playoutFreq[1]=16000;
}
else if (_testMode == 0)
{
AudioCodingModule *acmTmp = AudioCodingModule::Create(0);
numCodecs = acmTmp->NumberOfCodecs();
AudioCodingModule::Destroy(acmTmp);
struct CodecInst dummyCodec;
//chose range of testing for codecs/parameters
for(int i = 0 ; i < numCodecs ; i++)
{
numPars[i] = 1;
acmTmp->Codec(i, dummyCodec);
if (STR_CASE_CMP(dummyCodec.plname, "telephone-event") == 0)
{
numPars[i] = 0;
} else if (STR_CASE_CMP(dummyCodec.plname, "cn") == 0) {
numPars[i] = 0;
} else if (STR_CASE_CMP(dummyCodec.plname, "red") == 0) {
numPars[i] = 0;
}
}
playoutFreq[1] = 16000;
}
else
{
numCodecs = 1;
numPars[0] = 1;
playoutFreq[1]=16000;
}
_receiver.testMode = _testMode;
//loop over all codecs:
for(int codeId=0;codeId<numCodecs;codeId++)
{
//only encode using real encoders, not telephone-event anc cn
for(int loopPars=1;loopPars<=numPars[codeId];loopPars++)
{
if (_testMode == 1)
{
printf("\n");
printf("***FOR RUN: codeId: %d\n",codeId);
printf("\n");
}
else if (_testMode == 0)
{
printf(".");
}
EncodeToFileTest::Perform(1, codeId, codePars, _testMode);
AudioCodingModule *acm = AudioCodingModule::Create(10);
RTPFile rtpFile;
char fileName[] = "outFile.rtp";
rtpFile.Open(fileName, "rb");
_receiver.codeId = codeId;
rtpFile.ReadHeader();
_receiver.Setup(acm, &rtpFile);
_receiver.Run();
_receiver.Teardown();
rtpFile.Close();
AudioCodingModule::Destroy(acm);
if (_testMode == 1)
{
printf("***COMPLETED RUN FOR: codecID: %d ***\n",
codeId);
}
}
}
if (_testMode == 0)
{
printf("Done!\n");
}
if (_testMode == 1) Trace::ReturnTrace();
}
| 28.032895 | 120 | 0.553861 | stoiczek |
085bb94713b361dc2d9ff2c71932646f2aa86425 | 2,992 | hpp | C++ | doc/quickbook/oglplus/quickref/bound/buffer.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | doc/quickbook/oglplus/quickref/bound/buffer.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | doc/quickbook/oglplus/quickref/bound/buffer.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /*
* Automatically generated file, do not edit manually!
*
* Copyright 2010-2019 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)
*/
//[oglplus_object_BoundObjOps_Buffer
template <>
class __BoundObjOps<__tag_Buffer> {
private:
using ExplicitOps =
typename __ObjectOps_Explicit_Buffer<__tag_ExplicitSel, __tag_Buffer>;
public:
using Target = typename ExplicitOps::Target;
Target target;
BoundObjOps();
BoundObjOps(Target init_tgt);
GLint GetIntParam(GLenum query) const;
__Boolean Mapped() const;
const BoundObjOps& Resize(
__BufferSize size, __BufferUsage usage = BufferUsage::StaticDraw) const;
const BoundObjOps& Data(
const __BufferData& data,
__BufferUsage usage = BufferUsage::StaticDraw) const;
const BoundObjOps& RawData(
__BufferSize size,
const GLvoid* data,
__BufferUsage usage = BufferUsage::StaticDraw) const;
template <typename GLtype>
const BoundObjOps& Data(
__SizeType count,
const GLtype* data,
__BufferUsage usage = BufferUsage::StaticDraw) const;
const BoundObjOps& SubData(
__BufferSize offset, const __BufferData& data) const;
template <typename GLtype>
const BoundObjOps& SubData(
__BufferSize offset, __SizeType count, const GLtype* data) const;
#if GL_VERSION_4_3
template <typename GLtype>
const BoundObjOps& ClearData(
__PixelDataInternalFormat internal_format,
__PixelDataFormat format,
const GLtype* data) const;
#endif
#if GL_VERSION_4_3
template <typename GLtype>
const BoundObjOps& ClearSubData(
__PixelDataInternalFormat internal_format,
__BufferSize offset,
__BufferSize size,
__PixelDataFormat format,
const GLtype* data) const;
#endif
#if GL_VERSION_4_4 || GL_ARB_buffer_storage
const BoundObjOps& Storage(
const __BufferData& data, __Bitfield<__BufferStorageBit> flags) const;
#endif
#if GL_VERSION_4_4 || GL_ARB_buffer_storage
const BoundObjOps& Storage(
__BufferSize size,
const void* data,
__Bitfield<__BufferStorageBit> flags) const;
#endif
#if GL_VERSION_4_4 || GL_ARB_buffer_storage
__Boolean ImmutableStorage() const;
#endif
#if GL_VERSION_4_4 || GL_ARB_buffer_storage
__Bitfield<__BufferStorageBit> StorageFlags() const;
#endif
#if GL_ARB_sparse_buffer
const BoundObjOps& PageCommitment(
__BufferSize offset, __BufferSize size, __Boolean commit) const;
#endif
__SizeType Size() const;
__BufferUsage Usage() const;
__Bitfield<__BufferMapAccess> __Access() const;
#if GL_NV_shader_buffer_load
const BoundObjOps& MakeResident(__AccessSpecifier access) const;
#endif
#if GL_NV_shader_buffer_load
const BoundObjOps& MakeNonResident() const;
#endif
#if GL_NV_shader_buffer_load
__BufferGPUAddress GPUAddress() const;
#endif
};
//]
| 26.017391 | 78 | 0.735963 | matus-chochlik |
0867f6604f233f61edbe96d8713581b3d474c5f5 | 764 | cpp | C++ | 725/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | 725/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | 725/src.cpp | sabingoyek/uva-online-judge | 78be271d440ff3b9b1b038fb83343ba46ea60843 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int N;
bool first = true;
while(scanf("%d", &N)){
if(N == 0)
break;
bool ans = false;
if(! first){
printf("\n");
}
for(int fghij = 1234; fghij <= 98765 / N; fghij++){
int abcde = fghij * N;
int tmp, used = (fghij < 10000); // if digit f=0, then we have to flag it
//cout << used << "\n";
tmp = abcde;
while(tmp){
used |= 1 << (tmp % 10);
tmp /= 10;
}
tmp = fghij;
while(tmp){
used |= 1 << (tmp % 10);
tmp /= 10;
}
if(used == (1<<10) - 1){
printf("%0.5d / %0.5d = %d\n", abcde, fghij, N);
ans = true;
}
}
if(!ans)
printf("There are no solutions for %d.\n", N);
first = false;
}
return 0;
}
| 18.190476 | 76 | 0.494764 | sabingoyek |
08682d1ad8ab55ac1101978e350d51149d14b187 | 5,691 | cpp | C++ | Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp | Karshilov/Dorothy-SSR | cce19ed2218d76f941977370f6b3894e2f87236a | [
"MIT"
] | 1 | 2021-07-19T11:30:54.000Z | 2021-07-19T11:30:54.000Z | Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp | Jilliana8397/Dorothy-SSR | 5ad647909c5e20cb7ebde9a1a054cdb944969dcb | [
"MIT"
] | null | null | null | Source/3rdParty/PlayRho/Dynamics/WorldContact.cpp | Jilliana8397/Dorothy-SSR | 5ad647909c5e20cb7ebde9a1a054cdb944969dcb | [
"MIT"
] | null | null | null | /*
* Original work Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
* Modified work Copyright (c) 2020 Louis Langholtz https://github.com/louis-langholtz/PlayRho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "PlayRho/Dynamics/WorldContact.hpp"
#include "PlayRho/Dynamics/World.hpp"
#include "PlayRho/Dynamics/WorldBody.hpp"
#include "PlayRho/Dynamics/WorldShape.hpp"
#include "PlayRho/Dynamics/Body.hpp" // for GetBody
#include "PlayRho/Dynamics/Contacts/Contact.hpp"
#include "PlayRho/Collision/Manifold.hpp"
#include "PlayRho/Collision/WorldManifold.hpp"
namespace playrho {
namespace d2 {
ContactCounter GetContactRange(const World& world) noexcept
{
return world.GetContactRange();
}
std::vector<KeyedContactPtr> GetContacts(const World& world) noexcept
{
return world.GetContacts();
}
const Contact& GetContact(const World& world, ContactID id)
{
return world.GetContact(id);
}
void SetContact(World& world, ContactID id, const Contact& value)
{
world.SetContact(id, value);
}
bool IsTouching(const World& world, ContactID id)
{
return IsTouching(GetContact(world, id));
}
bool IsAwake(const World& world, ContactID id)
{
return IsActive(GetContact(world, id));
}
void SetAwake(World& world, ContactID id)
{
// Note awakening bodies wakens the contact.
SetAwake(world, GetBodyA(world, id));
SetAwake(world, GetBodyB(world, id));
}
ChildCounter GetChildIndexA(const World& world, ContactID id)
{
return GetChildIndexA(GetContact(world, id));
}
ChildCounter GetChildIndexB(const World& world, ContactID id)
{
return GetChildIndexB(GetContact(world, id));
}
ShapeID GetShapeA(const World& world, ContactID id)
{
return GetShapeA(GetContact(world, id));
}
ShapeID GetShapeB(const World& world, ContactID id)
{
return GetShapeB(GetContact(world, id));
}
BodyID GetBodyA(const World& world, ContactID id)
{
return GetBodyA(GetContact(world, id));
}
BodyID GetBodyB(const World& world, ContactID id)
{
return GetBodyB(GetContact(world, id));
}
TimestepIters GetToiCount(const World& world, ContactID id)
{
return GetToiCount(GetContact(world, id));
}
bool NeedsFiltering(const World& world, ContactID id)
{
return NeedsFiltering(GetContact(world, id));
}
bool NeedsUpdating(const World& world, ContactID id)
{
return NeedsUpdating(GetContact(world, id));
}
bool HasValidToi(const World& world, ContactID id)
{
return HasValidToi(GetContact(world, id));
}
Real GetToi(const World& world, ContactID id)
{
return GetToi(GetContact(world, id));
}
Real GetFriction(const World& world, ContactID id)
{
return GetFriction(GetContact(world, id));
}
Real GetRestitution(const World& world, ContactID id)
{
return GetRestitution(GetContact(world, id));
}
void SetFriction(World& world, ContactID id, Real value)
{
auto contact = GetContact(world, id);
SetFriction(contact, value);
SetContact(world, id, contact);
}
void SetRestitution(World& world, ContactID id, Real value)
{
auto contact = GetContact(world, id);
SetRestitution(contact, value);
SetContact(world, id, contact);
}
const Manifold& GetManifold(const World& world, ContactID id)
{
return world.GetManifold(id);
}
LinearVelocity GetTangentSpeed(const World& world, ContactID id)
{
return GetTangentSpeed(GetContact(world, id));
}
void SetTangentSpeed(World& world, ContactID id, LinearVelocity value)
{
auto contact = GetContact(world, id);
SetTangentSpeed(contact, value);
SetContact(world, id, contact);
}
bool IsEnabled(const World& world, ContactID id)
{
return IsEnabled(GetContact(world, id));
}
void SetEnabled(World& world, ContactID id)
{
auto contact = GetContact(world, id);
SetEnabled(contact);
SetContact(world, id, contact);
}
void UnsetEnabled(World& world, ContactID id)
{
auto contact = GetContact(world, id);
UnsetEnabled(contact);
SetContact(world, id, contact);
}
Real GetDefaultFriction(const World& world, ContactID id)
{
const auto& c = world.GetContact(id);
return GetDefaultFriction(world.GetShape(GetShapeA(c)), world.GetShape(GetShapeB(c)));
}
Real GetDefaultRestitution(const World& world, ContactID id)
{
const auto& c = world.GetContact(id);
return GetDefaultRestitution(world.GetShape(GetShapeA(c)), world.GetShape(GetShapeB(c)));
}
WorldManifold GetWorldManifold(const World& world, ContactID id)
{
return GetWorldManifold(world, GetContact(world, id), GetManifold(world, id));
}
ContactCounter GetTouchingCount(const World& world) noexcept
{
const auto contacts = world.GetContacts();
return static_cast<ContactCounter>(count_if(cbegin(contacts), cend(contacts),
[&](const auto &c) {
return IsTouching(world, std::get<ContactID>(c));
}));
}
} // namespace d2
} // namespace playrho
| 26.347222 | 94 | 0.728167 | Karshilov |
086ea28a347a5dcf536b720dcd1b334d96a12a70 | 8,293 | cpp | C++ | 32blit/graphics/blend.cpp | mikerr/32blit-beta | 38ceca02226ec405d2de6883fc75376242a61778 | [
"MIT"
] | null | null | null | 32blit/graphics/blend.cpp | mikerr/32blit-beta | 38ceca02226ec405d2de6883fc75376242a61778 | [
"MIT"
] | null | null | null | 32blit/graphics/blend.cpp | mikerr/32blit-beta | 38ceca02226ec405d2de6883fc75376242a61778 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <cstring>
#include "surface.hpp"
#ifdef WIN32
#define __attribute__(A)
#endif
// note:
// for performance reasons none of the blending functions make any attempt
// to validate input, adhere to clipping, or source/destination bounds. it
// is assumed that all validation has been done by the caller.
namespace blit {
__attribute__((always_inline)) inline uint32_t alpha(const uint32_t &a1, const uint32_t &a2) {
return ((a1 + 1) * (a2 + 1)) >> 8;
}
__attribute__((always_inline)) inline uint32_t alpha(const uint32_t &a1, const uint32_t &a2, const uint32_t &a3) {
return ((a1 + 1) * (a2 + 1) * (a3 + 1)) >> 16;
}
__attribute__((always_inline)) inline uint8_t blend(const uint8_t &s, const uint8_t &d, const uint8_t &a) {
return d + ((a * (s - d) + 127) >> 8);
}
__attribute__((always_inline)) inline void blend_rgba_rgb(const Pen *s, uint8_t *d, const uint8_t &a, uint32_t c) {
if (c == 1) {
// fast case for single pixel draw
*d = blend(s->r, *d, a); d++;
*d = blend(s->g, *d, a); d++;
*d = blend(s->b, *d, a); d++;
return;
}
if (c <= 4) {
// fast case for small number of pixels
while (c--) {
*d = blend(s->r, *d, a); d++;
*d = blend(s->g, *d, a); d++;
*d = blend(s->b, *d, a); d++;
}
return;
}
// create packed 32bit source
// s32 now contains RGBA
uint32_t s32 = *((uint32_t*)(s));
// replace A with R so s32 is now RGBR
s32 = (s32 & 0x00ffffff) | ((s32 & 0x000000ff) << 24);
// if destination is not double-word aligned copy at most three bytes until it is
uint8_t* de = d + c * 3;
while (uintptr_t(d) & 0b11) {
*d = blend((s32 & 0xff), *d, a); d++;
// rotate the aligned rgbr/gbrg/brgb quad
s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24;
}
// destination is now double-word aligned
if (d < de) {
// get a double-word aligned pointer to the destination surface
uint32_t *d32 = (uint32_t*)d;
// copy four bytes at a time until we have fewer than four bytes remaining
uint32_t c32 = uint32_t(de - d) >> 2;
while (c32--) {
uint32_t dd32 = *d32;
*d32++ = blend((s32 & 0xff), (dd32 & 0xff), a) |
(blend((s32 & 0xff00) >> 8, (dd32 & 0xff00) >> 8, a) << 8) |
(blend((s32 & 0xff0000) >> 16, (dd32 & 0xff0000) >> 16, a) << 16) |
(blend((s32 & 0xff000000) >> 24, (dd32 & 0xff000000) >> 24, a) << 24);
// rotate the aligned rgbr/gbrg/brgb quad
s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24;
}
// copy the trailing bytes as needed
d = (uint8_t*)d32;
while (d < de) {
*d = blend((s32 & 0xff), *d, a); s32 >>= 8; d++;
}
}
}
__attribute__((always_inline)) inline void copy_rgba_rgb(const Pen* s, uint8_t *d, uint32_t c) {
if (c == 1) {
// fast case for single pixel draw
*(d + 0) = s->r; *(d + 1) = s->g; *(d + 2) = s->b;
return;
}
if (c <= 4) {
// fast case for small number of pixels
do {
*(d + 0) = s->r; *(d + 1) = s->g; *(d + 2) = s->b; d += 3;
} while (--c);
return;
}
// create packed 32bit source
// s32 now contains RGBA
uint32_t s32 = *((uint32_t*)(s));
// replace A with R so s32 is now RGBR
s32 = (s32 & 0x00ffffff) | ((s32 & 0x000000ff) << 24);
// if destination is not double-word aligned copy at most three bytes until it is
uint8_t* de = d + c * 3;
while (uintptr_t(d) & 0b11) {
*d = s32 & 0xff; d++;
// rotate the aligned rgbr/gbrg/brgb quad
s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24;
}
// destination is now double-word aligned
if (d < de) {
// get a double-word aligned pointer to the destination surface
uint32_t *d32 = (uint32_t*)d;
// copy four bytes at a time until we have fewer than four bytes remaining
uint32_t c32 = uint32_t(de - d) >> 2;
while (c32--) {
*d32++ = s32;
// rotate the aligned rgbr/gbrg/brgb quad
s32 >>= 8; s32 |= uint8_t(s32 & 0xff) << 24;
}
// copy the trailing bytes as needed
d = (uint8_t*)d32;
while (d < de) {
*d = (s32 & 0xff); s32 >>= 8; d++;
}
}
}
void RGBA_RGBA(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) {
uint8_t* d = dest->data + (off * 4);
uint8_t* m = dest->mask ? dest->mask->data + off : nullptr;
uint16_t a1 = alpha(pen->a, dest->alpha);
do {
uint16_t a = m ? alpha(a1, *m++) : a1;
if (a >= 255) {
*d++ = pen->r; *d++ = pen->g; *d++ = pen->b; *d++ = 255;
} else if (a > 0) {
*d = blend(pen->r, *d, a); d++;
*d = blend(pen->g, *d, a); d++;
*d = blend(pen->b, *d, a); d++;
*d = blend(pen->a, *d, a); d++;
}else{
d += 4;
}
} while (--cnt);
}
void RGBA_RGB(const Pen* pen, const Surface* dest, uint32_t off, uint32_t c) {
uint8_t* d = dest->data + (off * 3);
uint8_t* m = dest->mask ? dest->mask->data + off : nullptr;
uint16_t a = alpha(pen->a, dest->alpha);
if (!m) {
// no mask
if (a >= 255) {
// no alpha, just copy
copy_rgba_rgb(pen, d, c);
}
else {
// alpha, blend
blend_rgba_rgb(pen, d, a, c);
}
} else {
// mask enabled, slow blend
do {
uint16_t ma = alpha(a, *m++);
blend_rgba_rgb(pen, d, ma, 1);
d += 3;
} while (--c);
}
}
void P_P(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) {
uint8_t* d = dest->data + off;
do {
if (pen->a != 0) {
*d = pen->a;
}
d++;
} while (--cnt);
}
void M_M(const Pen* pen, const Surface* dest, uint32_t off, uint32_t cnt) {
uint8_t* d = dest->data + off;
do {
*d = blend(pen->a, *d, dest->alpha); d++;
} while (--cnt);
}
void RGBA_RGBA(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) {
uint8_t* s = src->palette ? src->data + soff : src->data + (soff * 4);
uint8_t* d = dest->data + (doff * 3);
uint8_t* m = dest->mask ? dest->mask->data + doff : nullptr;
do {
Pen *pen = src->palette ? &src->palette[*s] : (Pen *)s;
uint16_t a = m ? alpha(pen->a, *m++, dest->alpha) : alpha(pen->a, dest->alpha);
if (a >= 255) {
*d++ = pen->r; *d++ = pen->g; *d++ = pen->b; d++;
} else if (a > 0) {
*d = blend(pen->r, *d, a); d++;
*d = blend(pen->g, *d, a); d++;
*d = blend(pen->b, *d, a); d++;
*d = blend(pen->b, *d, a); d++;
}else{
d += 4;
}
s += (src->palette ? 1 : 4) * src_step;
} while (--cnt);
}
void RGBA_RGB(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) {
uint8_t* s = src->palette ? src->data + soff : src->data + (soff * 4);
uint8_t* d = dest->data + (doff * 3);
uint8_t* m = dest->mask ? dest->mask->data + doff : nullptr;
do {
Pen *pen = src->palette ? &src->palette[*s] : (Pen *)s;
uint16_t a = m ? alpha(pen->a, *m++, dest->alpha) : alpha(pen->a, dest->alpha);
if (a >= 255) {
*d++ = pen->r; *d++ = pen->g; *d++ = pen->b;
} else if (a > 0) {
*d = blend(pen->r, *d, a); d++;
*d = blend(pen->g, *d, a); d++;
*d = blend(pen->b, *d, a); d++;
}else{
d += 3;
}
s += (src->palette ? 1 : 4) * src_step;
} while (--cnt);
}
void P_P(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) {
uint8_t *s = src->data + soff;
uint8_t *d = dest->data + doff;
do {
if (*s != 0) {
*d = *s;
}
d++; s += src_step;
} while (--cnt);
}
void M_M(const Surface* src, uint32_t soff, const Surface* dest, uint32_t doff, uint32_t cnt, int32_t src_step) {
uint8_t *s = src->data + soff;
uint8_t *d = dest->data + doff;
do {
*d = blend(*s, *d, dest->alpha); d++;
s += src_step;
} while (--cnt);
}
} | 30.156364 | 123 | 0.503798 | mikerr |
086f58ca69e3f3dfbf81b52233b5c0abac904053 | 2,428 | hh | C++ | include/sea_dsa/Cloner.hh | igcontreras/sea-dsa | 19dae890dc482c10832a9cf604e0f9847a7ac57d | [
"BSD-3-Clause"
] | 120 | 2017-07-10T19:03:55.000Z | 2022-03-27T05:54:16.000Z | include/sea_dsa/Cloner.hh | igcontreras/sea-dsa | 19dae890dc482c10832a9cf604e0f9847a7ac57d | [
"BSD-3-Clause"
] | 90 | 2017-07-03T01:17:07.000Z | 2022-03-28T22:37:30.000Z | include/sea_dsa/Cloner.hh | igcontreras/sea-dsa | 19dae890dc482c10832a9cf604e0f9847a7ac57d | [
"BSD-3-Clause"
] | 34 | 2017-12-22T15:10:42.000Z | 2021-12-24T02:24:05.000Z | #pragma once
#include "sea_dsa/Graph.hh"
namespace sea_dsa {
struct CloningContext {
llvm::Optional<const llvm::Instruction *> m_cs;
enum DirectionKind { Unset, BottomUp, TopDown };
DirectionKind m_dir;
CloningContext(const llvm::Instruction &cs, DirectionKind dir)
: m_cs(&cs), m_dir(dir) {}
static CloningContext mkNoContext() { return {}; }
private:
CloningContext() : m_cs(llvm::None), m_dir(DirectionKind::Unset) {}
};
/**
* \brief Recursively clone DSA sub-graph rooted at a given Node
*/
class Cloner {
public:
enum Options : unsigned {
Basic = 0,
StripAllocas = 1 << 0,
TrackAllocaCallPaths = 1 << 1,
};
template <typename... Os> static Options BuildOptions(Os... os) {
Options options = Basic;
Options unpacked[] = {os...};
for (Options o : unpacked)
options = Options(options | o);
return options;
}
Cloner(Graph &g, CloningContext context, Cloner::Options options)
: m_graph(g), m_context(context),
m_strip_allocas(options & Cloner::Options::StripAllocas) {}
/// Returns a clone of a given node in the new graph
/// Recursive clones nodes linked by this node as necessary
Node &clone(const Node &n, bool forceAddAlloca = false,
const llvm::Value *onlyAllocSite = nullptr);
/// Returns a cloned node that corresponds to the given node
Node &at(const Node &n) {
assert(hasNode(n));
auto it = m_map.find(&n);
assert(it != m_map.end());
return *(it->second.first);
}
/// Returns true if the node has already been cloned
bool hasNode(const Node &n) { return m_map.count(&n) > 0; }
private:
enum CachingLevel { SingleAllocSite, NoAllocas, Full };
Graph &m_graph;
llvm::DenseMap<const Node *, std::pair<Node *, CachingLevel>> m_map;
llvm::DenseMap<const Node *, llvm::SmallDenseSet<Node *, 4>> m_deferredUnify;
CloningContext m_context;
bool m_strip_allocas;
bool isTopDown() const { return m_context.m_dir == CloningContext::TopDown; }
bool isBottomUp() const {
return m_context.m_dir == CloningContext::BottomUp;
}
bool isUnset() const { return !(isTopDown() || isBottomUp()); }
void copyAllocationSites(const Node &from, Node &to, bool forceAddAlloca,
const llvm::Value *onlyAllocSite = nullptr);
void importCallPaths(DsaAllocSite &site,
llvm::Optional<DsaAllocSite *> other);
};
} // namespace sea_dsa
| 29.975309 | 79 | 0.667628 | igcontreras |
08715a656689a96d283d4314a02e3510aa1041d4 | 2,059 | cpp | C++ | ote/Themes/theme.cpp | JuBan1/OpenTextEdit | 78543d95887c89824405f610f41f9783e6347f27 | [
"MIT"
] | 3 | 2018-02-05T12:47:32.000Z | 2021-06-12T00:43:20.000Z | ote/Themes/theme.cpp | JuBan1/OpenTextEdit | 78543d95887c89824405f610f41f9783e6347f27 | [
"MIT"
] | null | null | null | ote/Themes/theme.cpp | JuBan1/OpenTextEdit | 78543d95887c89824405f610f41f9783e6347f27 | [
"MIT"
] | 1 | 2021-06-12T05:22:29.000Z | 2021-06-12T05:22:29.000Z | #include "theme.h"
#include "themedata.h"
#include "themedatabase.h"
namespace ote {
#define CASE(item) case item: return #item;
#define IF(item) if(strcmp(elem, #item)==0) return item;
const char* Theme::elementToString(Theme::HighlightElements elem)
{
switch(elem) {
CASE(TextEditText)
CASE(TextEditActiveText)
CASE(TextEditBackground)
CASE(TextEditActiveBackground)
CASE(GutterText)
CASE(GutterActiveText)
CASE(GutterBackground)
CASE(GutterActiveBackground)
CASE(SyntaxComment)
CASE(SyntaxString)
CASE(SyntaxNumber)
CASE(SyntaxConstant)
CASE(SyntaxType)
CASE(SyntaxKeyword)
CASE(SyntaxMatchingBracket)
CASE(SyntaxOperator)
CASE(SyntaxSymbol)
CASE(SyntaxVariable)
CASE(SearchHighlight)
CASE(MAX_ITEMS)
}
}
Theme::HighlightElements Theme::stringToElement(const char* elem)
{
IF(TextEditText)
IF(TextEditActiveText)
IF(TextEditBackground)
IF(TextEditActiveBackground)
IF(GutterText)
IF(GutterActiveText)
IF(GutterBackground)
IF(GutterActiveBackground)
IF(SyntaxComment)
IF(SyntaxString)
IF(SyntaxNumber)
IF(SyntaxConstant)
IF(SyntaxType)
IF(SyntaxKeyword)
IF(SyntaxMatchingBracket)
IF(SyntaxOperator)
IF(SyntaxSymbol)
IF(SyntaxVariable)
IF(SearchHighlight)
IF(MAX_ITEMS)
return MAX_ITEMS;
}
Theme::HighlightElements Theme::stringToElement(const QString& elem)
{
return stringToElement(static_cast<const char*>(elem.toLatin1()));
}
Theme::Theme()
: m_data( ThemeDatabase::getTheme("").m_data ) {}
Theme::Theme(QString name)
: m_data( ThemeDatabase::getTheme(name).m_data ) {}
Theme::Theme(ThemeData* data)
: m_data(data) {}
QString Theme::getName() const
{
return m_data->getName();
}
bool Theme::isDefault() const
{
return getName().isEmpty();
}
QTextCharFormat Theme::getFormat(HighlightElements c) const
{
return m_data->getFormat(c);
}
QColor Theme::getColor(HighlightElements c) const {
return m_data->getColor(c);
}
} // namespace ote
| 21.226804 | 70 | 0.708596 | JuBan1 |
087a22be0db7730bf7dba1d4b8f81e5ed859a840 | 12,364 | cc | C++ | WinNTKline/KlineUtil/mygl/House.cc | TsyQi/MyAutomatic | 2afd3dcabba818051c7119fac7e6c099ff7954a7 | [
"Apache-2.0"
] | 4 | 2016-08-19T08:16:49.000Z | 2020-04-15T12:30:25.000Z | WinNTKline/KlineUtil/mygl/House.cc | TsyQi/MyAutomatic | 2afd3dcabba818051c7119fac7e6c099ff7954a7 | [
"Apache-2.0"
] | null | null | null | WinNTKline/KlineUtil/mygl/House.cc | TsyQi/MyAutomatic | 2afd3dcabba818051c7119fac7e6c099ff7954a7 | [
"Apache-2.0"
] | 3 | 2019-03-23T03:40:24.000Z | 2020-04-15T00:57:43.000Z | #include "House.h"
extern TEXTURE_2D **TextureList;
House::House()
{
texnum = 0;
}
// Create an OpenGL rendering context
BOOL House::CreateViewGLContext(HDC hDC)
{
m_hGLContext = wglCreateContext(hDC);
if (m_hGLContext == NULL)
return FALSE;
if (wglMakeCurrent(hDC, m_hGLContext) == FALSE)
return FALSE;
return TRUE;
}
void House::InitGeometry(void)
{
GLfloat fogColor[4] = { 0.75, 0.75, 1.0, 1.0 };
speed = 0;
srand(224);
srand((unsigned)time(NULL));
// Default mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
glFogi(GL_FOG_MODE, GL_LINEAR);
glFogfv(GL_FOG_COLOR, fogColor);
glFogf(GL_FOG_DENSITY, 0.8f);
glFogf(GL_FOG_START, 400.0f);
glFogf(GL_FOG_END, 500.0f);
glClearColor(0.75f, 0.75f, 1.0f, 1.0f);
// light must be disabled
// while rendering the terrain
// because it has no normal definition
glEnable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
}
// Function that moves the eye or turns the angle of sight.
// Updates scene if update != 0.
void House::MoveEye(int type, GLfloat amount, int update)
{
GLfloat a;
switch (type) {
case FORWARD:
a = sqrt((cx - ex)*(cx - ex) + (cz - ez)*(cz - ez));
ex = (amount*(cx - ex) + a * ex) / a;
ez = (amount*(cz - ez) + a * ez) / a;
cx = (amount*(cx - ex) + a * cx) / a;
cz = (amount*(cz - ez) + a * cz) / a;
break;
case MOVELR:
a = sqrt((cx - ex)*(cx - ex) + (cy - ey)*(cy - ey));
ex = (amount*(cx - ex) + a * ex) / a;
ey = (amount*(cy - ey) + a * ey) / a;
cx = (amount*(cx - ex) + a * cx) / a;
cy = (amount*(cy - ey) + a * cy) / a;
case TURNLEFT:
cx = (cx - ex)*(float)cos(amount / 360.0f) + (cz - ez)*(float)sin(amount / 360.0f) + ex;
cz = (cz - ez)*(float)cos(amount / 360.0f) - (cx - ex)*(float)sin(amount / 360.0f) + ez;
break;
case UPDOWN:
ey += amount;
break;
case LOOKUP:
cy += amount;
break;
case DEFAULT:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
break;
}
if (update) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz);
}
}
void House::ReadData()
{
int i;
unsigned j, l;
FILE *fp;
char stemp[100];
POINT3D *plist;
INT4U nAllVertexNum;
INT4U *pchlist;
strcpy_s(gEnergyFile, "data/ROOM.ED");
fopen_s(&fp, gEnergyFile, "r");
if (fp == NULL)
{
printf("\n Can not open energy data file:%s\n", gEnergyFile);
exit(0);
}
fseek(fp, 0, SEEK_SET);
/****** read texture list ******/
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "texnum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%d", &texnum);
TextureList = (TEXTURE_2D **)malloc(sizeof(TEXTURE_2D)*(texnum + 1));
for (i = 1; i <= texnum; i++)
{
TextureList[i] = (TEXTURE_2D *)malloc(sizeof(TEXTURE_2D));
fscanf_s(fp, "%s%s", TextureList[i]->fname, sizeof(TextureList[i]->fname), stemp, sizeof(stemp));
if (strcmp(stemp, "REPEAT_TEXTURE") == 0)
TextureList[i]->type = 1;
else if (strcmp(stemp, "CLAMP_TEXTURE") == 0)
TextureList[i]->type = 0;
}
/****** Read object list ******/
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "ObjectNum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%ld", &ObjectNum);
ObjectList = (OBJECT *)malloc(sizeof(OBJECT) * ObjectNum);
for (i = 0; i < ObjectNum; i++)
{
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "SurfaceNum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%ld", &(ObjectList[i].SurfNum));
ObjectList[i].surflist = (SURFACE *)malloc(sizeof(SURFACE) * ObjectList[i].SurfNum);
for (j = 0; j < ObjectList[i].SurfNum; j++)
{
/****** Read surface infor ******/
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "TextureId") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].texId));
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "pointnum") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].pointn));
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "triangle") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].triangle));
fscanf_s(fp, "%s", stemp, sizeof(stemp));
while (strcmp(stemp, "quadrangle") != 0) fscanf_s(fp, "%s", stemp, sizeof(stemp));
fscanf_s(fp, "%d", &(ObjectList[i].surflist[j].quadric));
/****** Read point list ******/
ObjectList[i].surflist[j].pointlist = (POINT3D*)malloc(sizeof(POINT3D) *
ObjectList[i].surflist[j].pointn);
plist = ObjectList[i].surflist[j].pointlist;
for (l = 0; l < ObjectList[i].surflist[j].pointn; l++)
fscanf_s(fp, "%f%f%f%f%f%f%f%f",
&(plist[l].r), &(plist[l].g), &(plist[l].b),
&(plist[l].u), &(plist[l].v),
&(plist[l].x), &(plist[l].y), &(plist[l].z));
/****** Read patchlist ******/
nAllVertexNum = ObjectList[i].surflist[j].triangle * 3 +
ObjectList[i].surflist[j].quadric * 4;
ObjectList[i].surflist[j].patchlist = (INT4U *)malloc(sizeof(INT4U) * nAllVertexNum);
pchlist = ObjectList[i].surflist[j].patchlist;
for (l = 0; l < nAllVertexNum; l++)
fscanf_s(fp, "%ld", &(pchlist[l]));
}
}
fclose(fp);
}
void House::InitLookAt()
{
FILE *fp;
strcpy_s(sLookAtFN, "data/ROOM.LK");
fopen_s(&fp, sLookAtFN, "rb");
if (fp == NULL)
{
ex = ey = ez = 1.0f;
cx = cy = cz = 0.0f;
Near = 0.1f;
angle = 30.0f;
}
else
fscanf_s(fp, "%f%f%f%f%f%f%f%f", &angle, &Near, &ex, &ey, &ez, &cx, &cy, &cz);
fclose(fp);
}
void House::InitRenderWin()
{
glShadeModel(GL_SMOOTH);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluPerspective(angle, (float)Width / (float)Height, Near, 1000000000.0);
gluLookAt(ex, ey, ez, cx, cy, cz, 0.0, 1.0, 0.0);
}
void House::Render(void)
{
int i;
unsigned j, k, l, m, TexIndex;
POINT3D *plist;
INT4U *pchlist;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ACCUM_BUFFER_BIT);
for (i = 0; i < ObjectNum; i++)
for (j = 0; j < ObjectList[i].SurfNum; j++)
{
TexIndex = ObjectList[i].surflist[j].texId;
if (TexIndex > 0)
InitTex(TexIndex);
plist = ObjectList[i].surflist[j].pointlist;
pchlist = ObjectList[i].surflist[j].patchlist;
l = 0;
for (k = 0; k < ObjectList[i].surflist[j].triangle; k++)
{
glBegin(GL_TRIANGLES);
for (m = 0; m < 3; m++)
{
glColor3f(plist[pchlist[l]].r,
plist[pchlist[l]].g,
plist[pchlist[l]].b);
glTexCoord2f(plist[pchlist[l]].u,
plist[pchlist[l]].v);
glVertex3f(plist[pchlist[l]].x,
plist[pchlist[l]].y,
plist[pchlist[l]].z);
l++;
}/* m */
glEnd();
}/* k */
for (k = 0; k < ObjectList[i].surflist[j].quadric; k++)
{
glBegin(GL_QUADS);
for (m = 0; m < 4; m++)
{
glColor3f(plist[pchlist[l]].r,
plist[pchlist[l]].g,
plist[pchlist[l]].b);
glTexCoord2f(plist[pchlist[l]].u,
plist[pchlist[l]].v);
glVertex3f(plist[pchlist[l]].x,
plist[pchlist[l]].y,
plist[pchlist[l]].z);
l++;
}/* m */
glEnd();
}/* k */
glFlush();
KillTex();
}
}
void House::CleanList()
{
int i;
unsigned j;
for (i = 0; i < ObjectNum; i++)
{
for (j = 0; j < ObjectList[i].SurfNum; j++)
{
free(ObjectList[i].surflist[j].pointlist);
free(ObjectList[i].surflist[j].patchlist);
}
free(ObjectList[i].surflist);
}
free(ObjectList);
for (i = 1; i <= texnum; i++)
free(TextureList[i]);
free(TextureList);
}
/********************************/
/* function : OpenTexImage */
/********************************/
unsigned char *House::OpenTexImage(INT2U TexIndex, INT2U *rslx, INT2U *rsly)
{
unsigned char *image;
FILE *fp;
INT2U srcx, srcy;
INT4U i, j;
char ImageName[30];
unsigned char *SImageData;
int width, height;
strcpy_s(ImageName, TextureList[TexIndex]->fname);
/* load a image */
fopen_s(&fp, ImageName, "rb");
if (!fp) return 0;
fseek(fp, 18L, 0);
fread(&width, sizeof(long), 1, fp);
fread(&height, sizeof(long), 1, fp);
*rslx = srcx = width; *rsly = srcy = height;
fseek(fp, 54L, 0);
image = (unsigned char *)malloc(width*height * 3);
fread(image, width*height * 3, 1, fp);
fclose(fp);
SImageData = (unsigned char *)malloc(srcx*srcy * 3);
for (i = 0; i < srcx; i++) {
for (j = 0; j < srcy; j++) {
(unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 0) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 2);
(unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 1) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 1);
(unsigned char)*(SImageData + i * srcx * 3 + j * 3 + 2) = (unsigned char)*(image + i * srcx * 3 + j * 3 + 0);
}
}
free(image);
printf("%s : %ld=%ld\n", ImageName, srcx*srcy * 3, (long)(i*j * 3));
return(SImageData);
}
/********************************/
/* function : InitTex */
/********************************/
void House::InitTex(int TexIndex)
{
INT2U TextType;
unsigned char *ImageData;
static int OldIndex = -1;
if (TexIndex <= 0) return;
if (TexIndex == OldIndex)
{
glEnable(GL_TEXTURE_2D);
return;
}
ImageData = ImageDatas[TexIndex - 1];
TextType = TextureList[TexIndex]->type;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if (TextType == CLAMP_TEXTURE)
{
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
else
{
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
glTexImage2D(GL_TEXTURE_2D, 0, 3, rslxs[TexIndex - 1], rslys[TexIndex - 1],
0, GL_RGB, GL_UNSIGNED_BYTE, ImageData);
glEnable(GL_TEXTURE_2D);
OldIndex = TexIndex;
}
/********************************/
/* function : KillTex */
/********************************/
void House::KillTex()
{
glDisable(GL_TEXTURE_2D);
}
void House::LoadAllTexture()
{
int i;
for (i = 0; i < texnum; i++)
ImageDatas[i] = OpenTexImage(i + 1, &rslxs[i], &rslys[i]);
}
void House::CleanAllTexture()
{
for (int i = 0; i < texnum; i++)
free(ImageDatas[i]);
}
House::~House()
{
}
#ifdef __error //ws2tcpip.h 'Error' redefined.
#undef __error
#endif
| 30.082725 | 121 | 0.518036 | TsyQi |
08803fc56e85f2a45f1bb7370616ef7b54a31dc7 | 6,169 | cpp | C++ | StereoKitC/systems/d3d.cpp | gongminmin/StereoKit | 3f83990ed6de0807735d8485664bf9350c37fc8a | [
"MIT"
] | null | null | null | StereoKitC/systems/d3d.cpp | gongminmin/StereoKit | 3f83990ed6de0807735d8485664bf9350c37fc8a | [
"MIT"
] | null | null | null | StereoKitC/systems/d3d.cpp | gongminmin/StereoKit | 3f83990ed6de0807735d8485664bf9350c37fc8a | [
"MIT"
] | null | null | null | #pragma comment(lib,"D3D11.lib")
#pragma comment(lib,"Dxgi.lib") // CreateSwapChainForHwnd
#include "../stereokit.h"
#include "d3d.h"
namespace sk {
///////////////////////////////////////////
ID3D11Device *d3d_device = nullptr;
ID3D11DeviceContext *d3d_context = nullptr;
ID3D11InfoQueue *d3d_info = nullptr;
ID3D11DepthStencilState *d3d_depthstate = nullptr;
ID3D11RasterizerState *d3d_rasterstate = nullptr;
int d3d_screen_width = 640;
int d3d_screen_height = 480;
///////////////////////////////////////////
bool d3d_init(LUID *adapter_id) {
UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#ifdef _DEBUG
creation_flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// Find the right adapter to use:
IDXGIAdapter1 *final_adapter = nullptr;
if (adapter_id != nullptr) {
IDXGIFactory1 *dxgi_factory;
CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **)(&dxgi_factory));
int curr = 0;
IDXGIAdapter1 *curr_adapter = nullptr;
while (dxgi_factory->EnumAdapters1(curr++, &curr_adapter) == S_OK) {
DXGI_ADAPTER_DESC1 adapterDesc;
curr_adapter->GetDesc1(&adapterDesc);
if (memcmp(&adapterDesc.AdapterLuid, adapter_id, sizeof(adapter_id)) == 0) {
log_diagf("Using graphics adapter: %ws", adapterDesc.Description);
final_adapter = curr_adapter;
break;
}
curr_adapter->Release();
}
dxgi_factory->Release();
}
D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 };
if (FAILED(D3D11CreateDevice(final_adapter, final_adapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN, 0, creation_flags, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, &d3d_device, nullptr, &d3d_context)))
return false;
if (final_adapter != nullptr)
final_adapter->Release();
// Hook into debug information
ID3D11Debug *d3dDebug = nullptr;
if (SUCCEEDED(d3d_device->QueryInterface(__uuidof(ID3D11Debug), (void**)&d3dDebug))) {
d3d_info = nullptr;
if (SUCCEEDED(d3dDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&d3d_info))) {
D3D11_MESSAGE_ID hide[] = {
D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
(D3D11_MESSAGE_ID)351,
(D3D11_MESSAGE_ID)49, // TODO: Figure out the Flip model for backbuffers!
// Add more message IDs here as needed
};
D3D11_INFO_QUEUE_FILTER filter = {};
filter.DenyList.NumIDs = _countof(hide);
filter.DenyList.pIDList = hide;
d3d_info->ClearStorageFilter();
d3d_info->AddStorageFilterEntries(&filter);
}
d3dDebug->Release();
}
D3D11_DEPTH_STENCIL_DESC desc_depthstate = {};
desc_depthstate.DepthEnable = true;
desc_depthstate.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
desc_depthstate.DepthFunc = D3D11_COMPARISON_LESS;
desc_depthstate.StencilEnable = true;
desc_depthstate.StencilReadMask = 0xFF;
desc_depthstate.StencilWriteMask = 0xFF;
desc_depthstate.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
desc_depthstate.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
desc_depthstate.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc_depthstate.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc_depthstate.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
desc_depthstate.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
desc_depthstate.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc_depthstate.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
d3d_device->CreateDepthStencilState(&desc_depthstate, &d3d_depthstate);
d3d_context->OMSetDepthStencilState(d3d_depthstate, 1);
D3D11_RASTERIZER_DESC desc_rasterizer = {};
desc_rasterizer.FillMode = D3D11_FILL_SOLID;
desc_rasterizer.CullMode = D3D11_CULL_BACK;
desc_rasterizer.FrontCounterClockwise = true;
d3d_device->CreateRasterizerState(&desc_rasterizer, &d3d_rasterstate);
d3d_context->RSSetState(d3d_rasterstate);
d3d_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return true;
}
///////////////////////////////////////////
void d3d_shutdown() {
if (d3d_context) { d3d_context->Release(); d3d_context = nullptr; }
if (d3d_device ) { d3d_device->Release(); d3d_device = nullptr; }
}
///////////////////////////////////////////
void d3d_update() {
#ifdef _DEBUG
if (d3d_info == nullptr)
return;
for(size_t i = 0; i < d3d_info->GetNumStoredMessages(); i++) {
SIZE_T size = 0;
d3d_info->GetMessage(0, nullptr, &size);
D3D11_MESSAGE * pMessage = (D3D11_MESSAGE*)malloc(size);
if (SUCCEEDED(d3d_info->GetMessage(i, pMessage, &size)) && pMessage->Severity <= D3D11_MESSAGE_SEVERITY_WARNING) {
const char *cat = "None";
switch(pMessage->Category) {
case D3D11_MESSAGE_CATEGORY_APPLICATION_DEFINED: cat = "App"; break;
case D3D11_MESSAGE_CATEGORY_MISCELLANEOUS: cat = "Misc"; break;
case D3D11_MESSAGE_CATEGORY_INITIALIZATION: cat = "Init"; break;
case D3D11_MESSAGE_CATEGORY_CLEANUP: cat = "Cleanup"; break;
case D3D11_MESSAGE_CATEGORY_COMPILATION: cat = "Compile"; break;
case D3D11_MESSAGE_CATEGORY_STATE_CREATION: cat = "State Create"; break;
case D3D11_MESSAGE_CATEGORY_STATE_SETTING: cat = "State Set"; break;
case D3D11_MESSAGE_CATEGORY_STATE_GETTING: cat = "State Get"; break;
case D3D11_MESSAGE_CATEGORY_RESOURCE_MANIPULATION:cat = "Resource"; break;
case D3D11_MESSAGE_CATEGORY_EXECUTION: cat = "Exec"; break;
case D3D11_MESSAGE_CATEGORY_SHADER: cat = "Shader"; break;
}
log_ level;
switch (pMessage->Severity) {
case D3D11_MESSAGE_SEVERITY_MESSAGE:
case D3D11_MESSAGE_SEVERITY_INFO: level = log_inform; break;
case D3D11_MESSAGE_SEVERITY_WARNING: level = log_warning; break;
case D3D11_MESSAGE_SEVERITY_CORRUPTION:
case D3D11_MESSAGE_SEVERITY_ERROR: level = log_error; break;
default: level = log_inform;
}
log_writef(level, "%s: [%d] %s", cat, pMessage->ID, pMessage->pDescription);
}
free(pMessage);
}
d3d_info->ClearStoredMessages();
#endif
}
} // namespace sk | 39.8 | 239 | 0.71065 | gongminmin |
08806b55c90ff8268bc5e6c35ad64b30151e5907 | 7,849 | cpp | C++ | include/card-gen/detail/rich_text.cpp | jonathansharman/card-gen | 8a7b16baa8c17457959300a8b7825b29ed12051e | [
"Zlib",
"MIT"
] | null | null | null | include/card-gen/detail/rich_text.cpp | jonathansharman/card-gen | 8a7b16baa8c17457959300a8b7825b29ed12051e | [
"Zlib",
"MIT"
] | null | null | null | include/card-gen/detail/rich_text.cpp | jonathansharman/card-gen | 8a7b16baa8c17457959300a8b7825b29ed12051e | [
"Zlib",
"MIT"
] | null | null | null | //! @file
//! @copyright See <a href="RichText-LICENSE.txt">RichText-LICENSE.txt</a>.
#include "rich_text.hpp"
#include <SFML/Graphics.hpp>
#include <fmt/format.h>
#include <map>
namespace {
struct format {
sf::Font* font = nullptr;
sf::Uint32 style_flags = sf::Text::Regular;
sf::Color fill_color = sf::Color::White;
sf::Color outline_color = sf::Color::White;
float outline_thickness = 0;
};
struct chunk {
format format;
sf::String text;
};
enum class align { left, center, right };
struct line {
std::vector<chunk> chunks;
align alignment = align::left;
};
std::map<std::string, sf::Font> _fonts;
std::map<std::string, sf::Color> _colors = { //
{"default", sf::Color::White},
{"black", sf::Color::Black},
{"blue", sf::Color::Blue},
{"cyan", sf::Color::Cyan},
{"green", sf::Color::Green},
{"magenta", sf::Color::Magenta},
{"red", sf::Color::Red},
{"white", sf::Color::White},
{"yellow", sf::Color::Yellow}};
auto color_from_hex(unsigned argb_hex) -> sf::Color {
argb_hex |= 0xff000000;
return sf::Color(argb_hex >> 16 & 0xff, argb_hex >> 8 & 0xff, argb_hex >> 0 & 0xff, argb_hex >> 24 & 0xff);
}
auto color_from_string(std::string const& source) -> sf::Color {
auto result = _colors.find(source);
if (result != _colors.end()) { return result->second; }
try {
return color_from_hex(std::stoi(source, 0, 16));
} catch (...) {
// Conversion failed; use default color.
return sf::Color::White;
}
}
}
namespace sfe {
auto rich_text::add_color(sf::String const& name, sf::Color const& color) -> void {
_colors[name] = color;
}
auto rich_text::add_color(sf::String const& name, unsigned argb_hex) -> void {
_colors[name] = color_from_hex(argb_hex);
}
rich_text::rich_text(sf::String const& source, unsigned character_size) : _character_size(character_size) {
set_source(source);
}
auto rich_text::get_source() const -> sf::String {
return _source;
}
auto rich_text::set_source(sf::String const& source) -> void {
_source = source;
clear();
format current_format;
std::vector<line> lines{line{{chunk{current_format}}}};
for (auto it = source.begin(); it != source.end(); ++it) {
static auto apply_formatting = [&] {
if (!lines.back().chunks.back().text.isEmpty()) {
// Start a new chunk if the current chunk has text.
lines.back().chunks.push_back(chunk{current_format});
} else {
// Otherwise, update current chunk.
lines.back().chunks.back().format = current_format;
}
};
switch (*it) {
case '/': // Italic
current_format.style_flags ^= sf::Text::Italic;
apply_formatting();
break;
case '*': // Bold
current_format.style_flags ^= sf::Text::Bold;
apply_formatting();
break;
case '_': // Underline
current_format.style_flags ^= sf::Text::Underlined;
apply_formatting();
break;
case '~': // Strikethrough
current_format.style_flags ^= sf::Text::StrikeThrough;
apply_formatting();
break;
case '[': { // Tag
++it;
// Find the end of the tag and advance the iterator.
auto const tag_end = std::find(it, source.end(), sf::Uint32{']'});
if (tag_end == source.end()) { throw std::domain_error{"Missing ']' in tag."}; }
// Split into command and argument.
auto const command_end = std::find(it, tag_end, sf::Uint32{' '});
auto const command = sf::String::fromUtf32(it, command_end);
auto const arg = sf::String::fromUtf32(command_end + 1, tag_end).toAnsiString();
// Handle the tag.
if (command == "fill-color") {
current_format.fill_color = color_from_string(arg);
apply_formatting();
} else if (command == "outline-color") {
current_format.outline_color = color_from_string(arg);
apply_formatting();
} else if (command == "outline-thickness") {
current_format.outline_thickness = std::stof(arg);
apply_formatting();
} else if (command == "font") {
// First = (font name, font) pair; second = whether insertion occurred.
auto result = _fonts.try_emplace(arg);
if (result.second) {
// Cache miss. Need to load font.
if (!result.first->second.loadFromFile(arg)) {
throw std::runtime_error{fmt::format("Could not load font from \"{}\".", arg)};
}
}
current_format.font = &result.first->second;
apply_formatting();
} else if (command == "align") {
if (arg == "left") {
lines.back().alignment = align::left;
} else if (arg == "center") {
lines.back().alignment = align::center;
} else if (arg == "right") {
lines.back().alignment = align::right;
} else {
throw std::domain_error{fmt::format("Invalid alignment: {}.", arg)};
}
}
// Advance the iterator to the end of the tag (it will be incremented past at the end by the
// loop).
it = tag_end;
break;
}
case '\\': // Escape sequence
++it;
if (it == source.end()) {
throw std::domain_error{"Expected formatting control character after '\\'."};
}
switch (*it) {
case '/':
case '*':
case '_':
case '~':
case '[':
case '\\':
lines.back().chunks.back().text += *it;
break;
default:
throw std::domain_error{
fmt::format("Cannot escape non-control character '{}'.", static_cast<char>(*it))};
}
break;
case '\n': // New line
lines.push_back(line{{chunk{current_format}}});
break;
default:
lines.back().chunks.back().text += *it;
break;
}
}
// Build texts and formatting-stripped string and compute bounds.
sf::Vector2f next_position{};
_bounds = {0, 0, 0, 0};
for (auto const& line : lines) {
float line_spacing = 0;
for (auto const& chunk : line.chunks) {
// Construct text.
if (chunk.format.font == nullptr) { throw std::domain_error{"Text missing font specification."}; }
line_spacing = std::max(line_spacing, chunk.format.font->getLineSpacing(_character_size));
_texts.push_back({chunk.text, *chunk.format.font, _character_size});
_texts.back().setStyle(chunk.format.style_flags);
_texts.back().setFillColor(chunk.format.fill_color);
_texts.back().setOutlineColor(chunk.format.outline_color);
_texts.back().setOutlineThickness(chunk.format.outline_thickness);
// Round next_position to avoid text blurriness.
_texts.back().setPosition(std::roundf(next_position.x), std::roundf(next_position.y));
// Move next position to the end of the text.
next_position = _texts.back().findCharacterPos(chunk.text.getSize());
// Extend bounds.
auto const text_bounds = _texts.back().getGlobalBounds();
auto const right = text_bounds.left + text_bounds.width;
_bounds.width = std::max(_bounds.width, right - _bounds.left);
auto const bottom = text_bounds.top + text_bounds.height;
_bounds.height = std::max(_bounds.height, bottom - _bounds.top);
}
//! @todo Align line.
if (&line != &lines.back()) {
// Handle new lines.
next_position = {0, next_position.y + line_spacing};
}
}
}
auto rich_text::clear() -> void {
_texts.clear();
_bounds = sf::FloatRect{};
}
auto rich_text::get_character_size() const -> unsigned {
return _character_size;
}
auto rich_text::set_character_size(unsigned size) -> void {
_character_size = std::max(size, 1u);
set_source(_source);
}
auto rich_text::get_local_bounds() const -> sf::FloatRect {
return _bounds;
}
auto rich_text::get_global_bounds() const -> sf::FloatRect {
return getTransform().transformRect(_bounds);
}
auto rich_text::draw(sf::RenderTarget& target, sf::RenderStates states) const -> void {
states.transform *= getTransform();
for (auto const& text : _texts) {
target.draw(text, states);
}
}
}
| 31.270916 | 109 | 0.631928 | jonathansharman |
08814127e99b0faf8f69413dc1720419c1475490 | 1,299 | hpp | C++ | headers/vivace/iterator/filter_map.hpp | KyleMayes/vivace | 3baacc0785590c807e40e74a064c5c68a02c9c94 | [
"Apache-2.0"
] | null | null | null | headers/vivace/iterator/filter_map.hpp | KyleMayes/vivace | 3baacc0785590c807e40e74a064c5c68a02c9c94 | [
"Apache-2.0"
] | null | null | null | headers/vivace/iterator/filter_map.hpp | KyleMayes/vivace | 3baacc0785590c807e40e74a064c5c68a02c9c94 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Kyle Mayes
//
// 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.
template <class T, class I, class F>
class FilterMap : public Iterator<T, FilterMap<T, I, F>> {
I source;
F f;
template <class S>
Option<T> impl(S&& source) {
for (auto item : source) {
auto option = std::invoke(f, item);
if (option.is_some()) {
return option;
}
}
return {};
}
protected:
Bounds bounds_impl() const {
return {0, source.bounds().upper};
}
Option<T> next_impl() {
return impl(source);
}
Option<T> next_back_impl() {
return impl(source.as_ref().reverse());
}
public:
FilterMap(I source, F f) : source{std::move(source)}, f{std::move(f)} { }
};
| 27.638298 | 77 | 0.622787 | KyleMayes |
088152c73e437f17af152cdf6e83700ffacbef48 | 700 | cpp | C++ | export/debug/macos/obj/src/resources/__res_17.cpp | EnvyBun/KB-FNF-MOD | f7541661229c587bf99f0508cc3eba7043f8c177 | [
"Apache-2.0"
] | null | null | null | export/debug/macos/obj/src/resources/__res_17.cpp | EnvyBun/KB-FNF-MOD | f7541661229c587bf99f0508cc3eba7043f8c177 | [
"Apache-2.0"
] | null | null | null | export/debug/macos/obj/src/resources/__res_17.cpp | EnvyBun/KB-FNF-MOD | f7541661229c587bf99f0508cc3eba7043f8c177 | [
"Apache-2.0"
] | null | null | null | // Generated by Haxe 4.1.5
namespace hx {
unsigned char __res_17[] = {
0x80, 0x00, 0x00, 0x80,
137,80,78,71,13,10,26,10,0,0,
0,13,73,72,68,82,0,0,0,11,
0,0,0,11,8,6,0,0,0,169,
172,119,38,0,0,0,25,116,69,88,
116,83,111,102,116,119,97,114,101,0,
65,100,111,98,101,32,73,109,97,103,
101,82,101,97,100,121,113,201,101,60,
0,0,0,84,73,68,65,84,120,218,
148,144,81,14,192,32,8,67,11,183,
220,5,185,102,183,37,83,153,86,221,
94,2,33,164,188,15,140,36,190,226,
105,142,171,184,168,176,100,190,7,91,
136,233,201,136,153,177,197,71,14,177,
67,109,93,16,226,96,8,151,32,196,
129,52,199,179,11,101,118,252,65,88,
102,188,254,188,229,20,96,0,3,5,
232,22,166,15,127,92,0,0,0,0,
73,69,78,68,174,66,96,130,0x00 };
}
| 29.166667 | 38 | 0.67 | EnvyBun |
08824c36bfdcdae1ddf40e4080c3d8265a4b1ea0 | 3,779 | cc | C++ | Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Source/Meta/Descriptor/WidgetTextMetaInformation.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Meta/Descriptor/WidgetTextMetaInformation.h>
#include <nlohmann/json.hpp>
#include <Dy/Helper/Library/HelperJson.h>
#include <Dy/Helper/Type/DColorRGB24.h>
namespace dy
{
std::unique_ptr<PDyMetaWidgetTextDescriptor>
PDyMetaWidgetTextDescriptor::CreateMetaInformation(_MIN_ const nlohmann::json& itemAtlas)
{
/* Template
{
{ "Name": "WidgetName", "Type": "Text", "Parent": "", "ZOrder": 0,
"Details": {
"InitialPosition": { "X": 0, "Y": 0 },
"WidgetSize": { "X": 200, "Y": 100 },
"Origin": "Center_Center",
"InitialString": "This is test for general UI.",
"InitialColor": { "R": 1.0, "G": 1.0, "B": 1.0, "A": 1.0 },
"EdgeColor": { "R": 1.0, "G": 1.0, "B": 1.0 },
"FontSize": 10,
"FontSpecifierName": "Arial",
"IsUsingEdge": false,
"Alignment": "Left"
}
}
}
*/
static MDY_SET_IMMUTABLE_STRING(sHeader_InitialString, "InitialString");
static MDY_SET_IMMUTABLE_STRING(sHeader_InitialPosition, "InitialPosition");
static MDY_SET_IMMUTABLE_STRING(sHeader_InitialColor, "InitialColor");
static MDY_SET_IMMUTABLE_STRING(sHeader_FontSize, "FontSize");
static MDY_SET_IMMUTABLE_STRING(sHeader_FontSpecifierName, "FontSpecifierName");
static MDY_SET_IMMUTABLE_STRING(sHeader_IsUsingEdge, "IsUsingEdge");
using TPDyMWCBD = PDyMetaWidgetCommonBaseDesc;
//! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//! FUNCTIONBODY โจ
//! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Common
auto instance = std::make_unique<PDyMetaWidgetTextDescriptor>();
instance->mUiObjectSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Name);
instance->mComponentType = EDyWidgetComponentType::Text;
instance->mParentSpecifierName = json::GetValueFrom<std::string>(itemAtlas, TPDyMWCBD::sHeader_Parent);
json::GetValueFromTo(itemAtlas, "IsActivated", instance->mIsActivated);
json::GetValueFromTo(itemAtlas, "ZOrder", instance->mZOrder);
// Detail (TEXT)
const auto& detailAtlas = itemAtlas[(TPDyMWCBD::sHeader_Details)];
const auto string = json::GetValueFrom<std::string>(detailAtlas, sHeader_InitialString);
instance->mTextString = string;
instance->mTextColor = json::GetValueFrom<DColorRGBA>(detailAtlas, sHeader_InitialColor);;
instance->mFontSize = json::GetValueFrom<TU32>(detailAtlas, sHeader_FontSize);
instance->mFontName = json::GetValueFrom<std::string>(detailAtlas, sHeader_FontSpecifierName);
instance->mEdgeColor = json::GetValueFrom<DColorRGB>(detailAtlas, "EdgeColor");
instance->mIsUsingEdge = json::GetValueFrom<bool>(detailAtlas, sHeader_IsUsingEdge);
instance->mInitialPosition = DIVec2{json::GetValueFrom<DVec2>(detailAtlas, sHeader_InitialPosition)};
instance->mOrigin = json::GetValueFrom<EDyOrigin>(detailAtlas, "Origin");
instance->mWidgetSize = json::GetValueFrom<DIVec2>(detailAtlas, "WidgetSize");
json::GetValueFromTo(detailAtlas, "Alignment", instance->mAlignment);
return instance;
}
} /// ::dy namespace | 43.94186 | 107 | 0.677163 | liliilli |
0882dd8c60c42df44e794bcd69bfb71c3276c64c | 4,737 | cpp | C++ | OGLApp/src/oaAnimationLoader.cpp | Consalv0/OGLApp | 45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd | [
"MIT"
] | null | null | null | OGLApp/src/oaAnimationLoader.cpp | Consalv0/OGLApp | 45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd | [
"MIT"
] | null | null | null | OGLApp/src/oaAnimationLoader.cpp | Consalv0/OGLApp | 45bc0e3a4460f3d094b1ac5b9c6ac0d6fc40d4fd | [
"MIT"
] | null | null | null |
#include "oaLoaderUtils.h"
#include <math.h>
#include <codecvt>
#include <locale>
#include "oaJoint.h"
#include "rapidxml\rapidxml.hpp"
#include "rapidxml\rapidxml_iterators.hpp"
#include "rapidxml\rapidxml_print.hpp"
#include "rapidxml\rapidxml_utils.hpp"
#include "oaAnimationLoader.h"
std::unordered_map<std::string, std::vector<oaAnimation>> oaAnimationLoader::animationIDs = std::unordered_map<std::string, std::vector<oaAnimation>>();
std::vector<oaAnimation>* oaAnimationLoader::loadAnimation(const char * filePath) {
if (animationIDs.find(filePath) != animationIDs.end()) {
return &animationIDs.at(filePath);
}
std::string fileExt = oaGetFileExtension(filePath);
std::vector<oaAnimation>* animation;
// OBJ parser
if (fileExt == "dae") {
animation = loadDAE(
filePath
);
// Format not supported
} else {
printf("File extension no supported: '%s'", fileExt.c_str());
return NULL;
}
// Format supported, file unsopported
if (animation == NULL || animation->empty()) {
printf("Unable to load '%s'\n", filePath);
return NULL;
}
// All right, add to the list of meshes
animationIDs.insert({ std::string(filePath), *animation });
printf("Animation loaded : %s\n", filePath);
return &animationIDs.find(filePath)->second;
}
std::vector<oaAnimation>* oaAnimationLoader::loadDAE(const char * filePath) {
using namespace rapidxml;
std::vector<oaAnimation>* animations = new std::vector<oaAnimation>();
xml_document<wchar_t> doc;
// Open file
file<wchar_t> fileXml(filePath);
doc.parse<0>(fileXml.data()); // 0 means default parse flags
xml_node<wchar_t> *collada = doc.first_node(L"COLLADA");
xml_node<wchar_t> *up_axis = collada->first_node(L"asset")->first_node(L"up_axis");
// Get the model orientation, OpenGl is Y-Up oriented
glm::mat4 orientation = glm::mat4();
if (up_axis) {
if (wcscmp(up_axis->value(), L"Z_UP") == 0) {
orientation = { 1, 0, 0, 0,
0, 0, 1, 0,
0, -1, 0, 0,
0, 0, 0, 1 };
}
//else if (wcscmp(up_axis->value(), L"Y_UP") == 0) {
// orientation = { 1, 0, 0,
// 0, 1, 0,
// 0, 0, 1, };
//}
else if (wcscmp(up_axis->value(), L"X_UP") == 0) {
orientation = { 0, -1, 0, 0,
1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
}
}
xml_node<wchar_t> *library_animations = collada->first_node(L"library_animations");
xml_node<wchar_t> *animation = library_animations->first_node(L"animation");
while (animation) {
xml_node<wchar_t> *source = animation->first_node(L"source");
oaAnimation currentAnimation;
while (source) {
if (auto technique_common = source->first_node(L"technique_common")) {
if (auto accessor = technique_common->first_node(L"accessor")) {
wchar_t* type = accessor->first_node(L"param")->first_attribute(L"name")->value();
if (wcscmp(L"TIME", type) == 0) {
int keys = _wtoi(accessor->first_attribute(L"count")->value());
currentAnimation.size = keys;
currentAnimation.keyTimes = new float[keys];
xml_node<wchar_t> *farray = source->first_node(L"float_array");
std::wistringstream iss(farray->value());
std::wstring s;
for (int i = 0; i < keys; i++) {
s.clear(); iss >> s;
currentAnimation.keyTimes[i] = (float)_wtof(s.c_str());
}
}
if (wcscmp(L"TRANSFORM", type) == 0) {
int keys = _wtoi(accessor->first_attribute(L"count")->value());
currentAnimation.transforms = new oaAnimation::JointTransforms[keys];
xml_node<wchar_t> *farray = source->first_node(L"float_array");
std::wistringstream iss(farray->value());
std::wstring s;
for (int i = 0; i < keys; i++) {
glm::mat4 transform;
for (int j = 0; j < 4; j++) {
s.clear(); iss >> s;
transform[j][0] = (float)_wtof(s.c_str());
s.clear(); iss >> s;
transform[j][1] = (float)_wtof(s.c_str());
s.clear(); iss >> s;
transform[j][2] = (float)_wtof(s.c_str());
s.clear(); iss >> s;
transform[j][3] = (float)_wtof(s.c_str());
}
currentAnimation.transforms[i] = oaAnimation::JointTransforms(transform);
}
}
}
}
source = source->next_sibling(L"source");
}
if (auto channel = animation->first_node(L"channel")) {
if (auto target = channel->first_attribute(L"target")) {
currentAnimation.name = target->value();
}
}
animations->push_back(currentAnimation);
animation = animation->next_sibling(L"animation");
}
if (!animations || animations->empty()) {
delete animations;
return NULL;
}
return animations;
}
| 31.791946 | 153 | 0.615368 | Consalv0 |
08880d8906f8f3089c63dc941a5c7df11ebedb90 | 3,504 | inl | C++ | src/dcc/unit-import-source.c.inl | GrieferAtWork/dcc | e70803aef1d7dc83ecedc6134c3e7902e6b6bbca | [
"Zlib"
] | 19 | 2017-08-27T16:27:44.000Z | 2021-12-02T21:17:17.000Z | src/dcc/unit-import-source.c.inl | GrieferAtWork/dcc | e70803aef1d7dc83ecedc6134c3e7902e6b6bbca | [
"Zlib"
] | null | null | null | src/dcc/unit-import-source.c.inl | GrieferAtWork/dcc | e70803aef1d7dc83ecedc6134c3e7902e6b6bbca | [
"Zlib"
] | 1 | 2022-02-17T18:51:21.000Z | 2022-02-17T18:51:21.000Z | /* Copyright (c) 2017 Griefer@Work *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL
#define GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL 1
#define DCC(x) x
#include <dcc/common.h>
#include <dcc/target.h>
#include <dcc/compiler.h>
#include <dcc/lexer.h>
#include <dcc/assembler.h>
#include <dcc/addr2line.h>
#include "unit-import.h"
DCC_DECL_BEGIN
PRIVATE void load_std_sections(void) {
unit.u_text = DCCUnit_NewSecs(".text",DCC_SYMFLAG_SEC_X|DCC_SYMFLAG_SEC_R);
unit.u_data = DCCUnit_NewSecs(".data",DCC_SYMFLAG_SEC_R);
unit.u_bss = DCCUnit_NewSecs(".bss",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_W);
unit.u_string = DCCUnit_NewSecs(".string",DCC_SYMFLAG_SEC_R|DCC_SYMFLAG_SEC_M);
/* NOTE: Symbols within '.dbgstr' cannot be merged! */
unit.u_dbgstr = DCCUnit_NewSecs(A2L_STRING_SECTION,DCC_SYMFLAG_SEC_R);
}
INTERN void DCCUNIT_IMPORTCALL
DCCUnit_LoadSrc_C(struct DCCLibDef *__restrict def) {
(void)def;
compiler.c_flags |= (DCC_COMPILER_FLAG_NOCGEN);
/*CURRENT.l_flags |= (TPPLEXER_FLAG_TERMINATE_STRING_LF);*/
/* Load standard sections. */
load_std_sections();
CURRENT.l_extokens &= (TPPLEXER_TOKEN_EQUALBINOP);
CURRENT.l_extokens |= (TPPLEXER_TOKEN_LANG_C|
TPPLEXER_TOKEN_TILDETILDE);
/* Yield the initial token. */
TPPLexer_Yield();
/* Select the text section and begin compiling. */
DCCUnit_SetCurr(unit.u_text);
DCCParse_AllGlobal();
DCCUnit_SetCurr(NULL);
}
INTERN void DCCUNIT_IMPORTCALL
DCCUnit_LoadSrc_ASM(struct DCCLibDef *__restrict def) {
(void)def;
CURRENT.l_flags |= (TPPLEXER_FLAG_ASM_COMMENTS|
/*TPPLEXER_FLAG_TERMINATE_STRING_LF|*/
TPPLEXER_FLAG_COMMENT_NOOWN_LF|
TPPLEXER_FLAG_WANTLF);
CURRENT.l_extokens = TPPLEXER_TOKEN_LANG_ASM;
compiler.c_flags |= DCC_COMPILER_FLAG_INASM;
load_std_sections();
/* Yield the initial token. */
TPPLexer_Yield();
/* Select the text section and begin compiling. */
DCCUnit_SetCurr(unit.u_text);
while (TOK > 0) {
unsigned long old_num = TOKEN.t_num;
DCCParse_AsmInstr();
if (old_num == TOKEN.t_num) YIELD();
}
DCCUnit_SetCurr(NULL);
}
DCC_DECL_END
#endif /* !GUARD_DCC_UNIT_IMPORT_SOURCE_C_INL */
| 36.884211 | 80 | 0.646404 | GrieferAtWork |
08892b6b615c227d047d8f35065a06969c30845c | 480 | cc | C++ | tests/babel/compression/zstd.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/babel/compression/zstd.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | null | null | null | tests/babel/compression/zstd.cc | project-arcana/arcana-samples | 7dbe2cab765d4d86c6e96b4ab542cac75608a0b0 | [
"MIT"
] | 1 | 2020-01-22T18:04:53.000Z | 2020-01-22T18:04:53.000Z | #include <nexus/fuzz_test.hh>
#include <babel-serializer/compression/zstd.hh>
FUZZ_TEST("zstd fuzzer")(tg::rng& rng)
{
auto cnt = uniform(rng, 0, 10);
if (uniform(rng))
cnt = uniform(rng, 100, 1000);
auto orig_data = cc::vector<std::byte>(cnt);
for (auto& d : orig_data)
d = uniform(rng);
auto comp_data = babel::zstd::compress(orig_data);
auto uncomp_data = babel::zstd::uncompress(comp_data);
CHECK(orig_data == uncomp_data);
}
| 22.857143 | 58 | 0.639583 | project-arcana |
08896b378a2aeaad13f8403f615158078cbf95bc | 1,271 | cpp | C++ | example/example.cpp | maxcong001/empty001 | b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e | [
"MIT"
] | null | null | null | example/example.cpp | maxcong001/empty001 | b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e | [
"MIT"
] | null | null | null | example/example.cpp | maxcong001/empty001 | b8bce7693ccd2801d788eee4d0fc6fbcb79fd47e | [
"MIT"
] | null | null | null | #include "MessageBus.hpp"
MessageBus g_bus;
const string Topic = "Drive";
const string CallBackTopic = "DriveOK";
struct Subject
{
Subject()
{
g_bus.Attach([this]{DriveOK();},CallBackTopic);
}
void SendReq(const string& topic)
{
g_bus.SendReq<void, int>(50, topic);
}
void DriveOK()
{
cout<<"drive OK"<<endl;
}
};
struct Car
{
Car()
{
g_bus.Attach([this](int speed){Drive(speed);}, Topic);
}
void Drive(int speed)
{
cout<<"car drives "<<speed<<endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
struct Bus
{
Bus()
{
g_bus.Attach([this](int speed){Drive(speed);});
}
void Drive(int speed)
{
cout<<"Bus drives "<<speed<<endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
struct Truck
{
Truck()
{
g_bus.Attach([this](int speed){Drive(speed);});
}
void Drive(int speed)
{
cout<<"Truck drives "<<speed<<endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
void TestBus()
{
Subject subject;
Car car;
Bus bus;
Truck truck;
//subject.SendReq(Topic);
for (int i = 0; i < 10000; i++)
{
subject.SendReq("");
}
}
int main()
{
TestBus();
return 0;
} | 15.8875 | 62 | 0.540519 | maxcong001 |
0895e18f2cdcf1f77701cbbe0a26580eeb0da3d8 | 525 | cpp | C++ | Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp | AkhilSoni0102/Learning-Data-Structures | 27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6 | [
"MIT"
] | 2 | 2021-04-03T11:50:42.000Z | 2021-05-06T16:45:06.000Z | Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp | AkhilSoni0102/Learning-Data-Structures | 27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6 | [
"MIT"
] | null | null | null | Dynamic Programming AV/Unbounded Knapsack Problems/Coin Change Maximum no of ways.cpp | AkhilSoni0102/Learning-Data-Structures | 27f2d4d0b09f2bf47242242d3a6b0e65c149bbf6 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main(){
int n, sum;
cin>>n>>sum;
int coin[n];
for(int i = 0;i < n;i++)
cin>>coin[i];
int t[n+1][sum+1];
for(int i = 0;i < sum+1;i++)
t[0][i] = 0;
for(int i = 0;i < n + 1;i++)
t[i][0] = 1;
for(int i = 1;i < n+1;i++)
for(int j = 1;j < sum + 1;j++)
if(coin[i-1] <= j)
t[i][j] = t[i][j-coin[i-1]] + t[i-1][j];
else
t[i][j] = t[i-1][j];
cout <<t[n][sum];
} | 25 | 56 | 0.373333 | AkhilSoni0102 |
08977ddae548d0bfbf421be88bd8b7a67d5dfde7 | 1,753 | hpp | C++ | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | 1 | 2021-08-18T03:54:22.000Z | 2021-08-18T03:54:22.000Z | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | null | null | null | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | null | null | null | //===============================================================================================//
/*!
* \file MeshEdge.hpp
* \author Loรฏc Corenthy
* \version 1.0
*/
//===============================================================================================//
#pragma once
#include <iostream>
namespace miniGL
{
/*!
* \brief Helper class to store a simple edge
* \details Stores an edge by its vertices and forces a specific order between them
*/
class MeshEdge
{
public:
/*!
* \brief Constructor with vertices
* @param pA is the index of the first vertex
* @param pB is the index of the second vertex
*/
MeshEdge(unsigned int pA, unsigned int pB);
/*!
* \brief Display the indices
*/
void display(void) const;
/*!
* \brief Set the index associated to the first vertex
* @param pIndex is the index associated to vertex "a"
*/
void a(unsigned int pIndex) noexcept;
/*!
* \brief Set the index associated to the second vertex
* @param pIndex is the index associated to vertex "b"
*/
void b(unsigned int pIndex) noexcept;
/*!
* \brief Get the index associated to the first vertex
* @return the index associated to vertex "a"
*/
unsigned int a(void) const noexcept;
/*!
* \brief Get the index associated to the second vertex
* @return the index associated to vertex "b"
*/
unsigned int b(void) const noexcept;
private:
unsigned int mA;
unsigned int mB;
}; // class MeshEdge
} // namespace miniGL
| 26.969231 | 99 | 0.494581 | Loic-Corenthy |
0899ccf06636c1042c59495e100b31d6e944693b | 1,211 | cc | C++ | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*----------------------------------//
/**
* @file WGPreconditioner.cc
* @brief WGPreconditioner
* @author Jeremy Roberts
* @date Nov 11, 2012
*/
//---------------------------------------------------------------------------//
#include "WGPreconditioner.hh"
namespace detran
{
//---------------------------------------------------------------------------//
WGPreconditioner::WGPreconditioner(SP_input input,
SP_material material,
SP_mesh mesh,
std::string name)
: Base(name)
, d_input(input)
, d_material(material)
, d_mesh(mesh)
{
// Preconditions
Require(d_input);
Require(d_material);
Require(d_mesh);
// Number of groups
d_number_groups = d_material->number_groups();
// Size the solver and operator vectors
d_solver.resize(d_number_groups);
d_operator.resize(d_number_groups);
}
} // end namespace detran
//---------------------------------------------------------------------------//
// end of file WGPreconditioner.cc
//---------------------------------------------------------------------------//
| 27.522727 | 79 | 0.410405 | RLReed |
08a4f58321af313b9087d71f731a466cc776acf1 | 2,668 | cpp | C++ | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | #include "../../../include/emp/base/vector.hpp"
#include "../../../include/emp/config/command_line.hpp"
#include "../../../include/emp/config/SettingConfig.hpp"
#include "../../../include/emp/data/DataLog.hpp"
#include "../../../include/emp/io/File.hpp"
#include "../../../include/emp/datastructs/vector_utils.hpp"
#include "../../../include/emp/math/stats.hpp"
int main(int argc, char* argv[])
{
emp::SettingConfig config;
size_t num_bins = 40;
config.AddSetting("num_bins", "How many bins in histogram?", 'b', num_bins) = 40;
config.ProcessOptions(argc, argv);
auto unused_args = config.GetUnusedArgs();
if (unused_args.size() != 1) {
std::cout << "Must include a single filename for data." << std::endl;
exit(1);
}
emp::File file(unused_args[0]);
file.RemoveWhitespace(); // Clear out all whitespace in file.
file.RemoveEmpty(); // Remove all now-empty lines from file.
if (file.GetNumLines() == 0) {
std::cout << "No data found. Exiting." << std::endl;
exit(2);
}
std::cout << "Found data for " << file.GetNumLines() << " histograms." << std::endl;
auto data = file.ToData<double>();
// Analyze base data.
double min_val = data[0][0];
double max_val = min_val;
double total_val = 0.0;
size_t num_vals = 0;
for (auto & row : data) {
for (double val : row) {
if (val < min_val) min_val = val;
if (val > max_val) max_val = val;
total_val += val;
num_vals++;
}
}
// Collect the full histogram.
double full_span = (max_val - min_val) * 1.00001;
double bin_width = full_span / (double) num_bins;
emp::vector<size_t> bin_counts(num_bins, 0);
for (auto & row : data) {
for (double val : row) {
size_t cur_bin = (size_t) ((val - min_val) / bin_width);
bin_counts[cur_bin]++;
}
}
size_t max_bin_count = 0;
for (size_t count : bin_counts) if (count > max_bin_count) max_bin_count = count;
while (file.GetNumLines()) {
emp::DataLog<double> row = file.ExtractRowAs<double>();
std::cout << "MIN_VAL: " << min_val << std::endl;
row.AsciiHistogram();
std::cout << "MAX_VAL: " << max_val << std::endl;
}
std::cout << "OVERALL COUNT: " << num_vals << std::endl;
std::cout << "OVERALL MIN: " << min_val << std::endl;
std::cout << "OVERALL MAX: " << max_val << std::endl;
std::cout << "OVERALL MEAN: " << (total_val/(double) num_vals) << std::endl;
emp::AsciiBarGraph(bin_counts);
double scale = ((double) max_bin_count) / 80.0;
if (scale < 1.0) scale = 1.0;
for (size_t count : bin_counts) {
for (size_t i = 0; i < (count/scale); i++) std::cout << "*";
std::cout << std::endl;
}
}
| 29.977528 | 86 | 0.609445 | koellingh |
08a5df737092834f14a7425440bd9084c8edd30c | 646 | cc | C++ | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | 1 | 2021-01-11T14:19:51.000Z | 2021-01-11T14:19:51.000Z | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, The Toft Authors.
// All rights reserved.
//
// Author: Ye Shunping <yeshunping@gmail.com>
// toft/storage/sharding/fingerprint_sharding.cc
#include "utils/toft_storage_sharding_fingerprint_sharding.h"
#include "utils/toft_hash_fingerprint.h"
namespace bubblefs {
namespace mytoft {
FingerprintSharding::FingerprintSharding() {
}
FingerprintSharding::~FingerprintSharding() {
}
int FingerprintSharding::Shard(const std::string& key) {
int shard_id = Fingerprint64(key) % (shard_num_);
return shard_id;
}
MYTOFT_REGISTER_SHARDING_POLICY(FingerprintSharding);
} // namespace mytoft
} // namespace bubblefs
| 21.533333 | 61 | 0.764706 | pengdu |
08a5fb79be8d1ac00a44dc45b68db71184c74a7f | 672 | cpp | C++ | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | null | null | null | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | null | null | null | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | 1 | 2020-05-19T17:49:14.000Z | 2020-05-19T17:49:14.000Z | #include <iostream>
#include <cstdlib>
#include "denoiser.hpp"
#include <eigen3/Eigen/Dense>
std::istream& operator>>(std::istream& is, Eigen::VectorXd& v) {
int size;
is >> size;
v.resize(size);
for(int i = 0; i < size; ++i) {
is >> v(i);
}
return is;
}
int main() {
Denoiser den;
while(true) {
Eigen::Vector2d in_sample;
std::cin >> in_sample(0) >> in_sample(1);
if(std::cin.fail()) {
break;
}
auto out_sample = den.GetSmp(in_sample);
std::cout << out_sample(0) << ' ' << out_sample(1) << '\n';
};
return EXIT_SUCCESS;
} | 19.764706 | 68 | 0.5 | andrea993 |
08ad07d632934f68a5931ae4d3db330d740dffb1 | 4,849 | cpp | C++ | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | 1 | 2018-08-02T02:41:37.000Z | 2018-08-02T02:41:37.000Z | #include "batch.h"
#include "nanocv/timer.h"
#include "nanocv/logger.h"
#include "nanocv/sampler.h"
#include "nanocv/minimize.h"
#include "nanocv/accumulator.h"
#include "nanocv/log_search.hpp"
namespace ncv
{
namespace
{
opt_state_t train_batch(
trainer_data_t& data,
optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon,
timer_t& timer, trainer_result_t& result, bool verbose)
{
size_t iteration = 0;
// construct the optimization problem
auto fn_size = ncv::make_opsize(data);
auto fn_fval = ncv::make_opfval(data);
auto fn_grad = ncv::make_opgrad(data);
auto fn_wlog = verbose ? ncv::make_opwlog() : nullptr;
auto fn_elog = verbose ? ncv::make_opelog() : nullptr;
auto fn_ulog = [&] (const opt_state_t& state)
{
const scalar_t tvalue = data.m_gacc.value();
const scalar_t terror_avg = data.m_gacc.avg_error();
const scalar_t terror_var = data.m_gacc.var_error();
// validation samples: loss value
data.m_lacc.set_params(state.x);
data.m_lacc.update(data.m_task, data.m_vsampler.get(), data.m_loss);
const scalar_t vvalue = data.m_lacc.value();
const scalar_t verror_avg = data.m_lacc.avg_error();
const scalar_t verror_var = data.m_lacc.var_error();
// update the optimum state
const auto ret = result.update(
state.x, tvalue, terror_avg, terror_var, vvalue, verror_avg, verror_var,
++ iteration, scalars_t({ data.lambda() }));
if (verbose)
log_info()
<< "[train = " << tvalue << "/" << terror_avg
<< ", valid = " << vvalue << "/" << verror_avg
<< " (" << text::to_string(ret) << ")"
<< ", xnorm = " << state.x.lpNorm<Eigen::Infinity>()
<< ", gnorm = " << state.g.lpNorm<Eigen::Infinity>()
<< ", epoch = " << iteration
<< ", lambda = " << data.lambda()
<< ", calls = " << state.n_fval_calls() << "/" << state.n_grad_calls()
<< "] done in " << timer.elapsed() << ".";
return ret != trainer_result_return_t::overfitting;
};
// assembly optimization problem & optimize the model
return ncv::minimize(fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog,
data.m_x0, optimizer, iterations, epsilon);
}
}
trainer_result_t batch_train(
const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,
const loss_t& loss, const string_t& criterion,
optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon,
bool verbose)
{
vector_t x0;
model.save_params(x0);
// setup acumulators
accumulator_t lacc(model, nthreads, criterion, criterion_t::type::value);
accumulator_t gacc(model, nthreads, criterion, criterion_t::type::vgrad);
trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);
// tune the regularization factor (if needed)
const auto op = [&] (scalar_t lambda)
{
data.set_lambda(lambda);
trainer_result_t result;
timer_t timer;
train_batch(data, optimizer, iterations, epsilon, timer, result, verbose);
return result;
};
if (data.m_lacc.can_regularize())
{
return log10_min_search(op, -6.0, +0.0, 0.5, 4).first;
}
else
{
return op(0.0);
}
}
}
| 46.180952 | 128 | 0.43906 | 0x0all |
08b1219de4621cd2345956a8c8746dd7848ca4d1 | 1,770 | cpp | C++ | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | #include "Cloud.h"
#include "glew.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include <iostream>
#include <glm/gtx/compatibility.hpp>
#include "Core/Geometry/Vertex.h"
#include "Core/Random.h"
Cloud::Cloud(const glm::vec3& position, float radius, uint32_t count)
:m_Position(position), m_Radius(radius), m_BallCount(count)
{
Core::Geometry* sphere = Core::Geometry::Create(Core::PrimitiveType::Icosphere);
CloudDrawList = glGenLists(1);
glNewList(CloudDrawList, GL_COMPILE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
for (uint32_t i = 0; i < m_BallCount; i++)
{
glm::vec3 randomPositionInSphere = m_Position + glm::vec3(
Core::Random::RandomRange(-m_Radius, m_Radius),
Core::Random::RandomRange(-m_Radius, m_Radius),
Core::Random::RandomRange(-m_Radius, m_Radius));
const float distance = glm::length(m_Position - randomPositionInSphere);
// Bigger towards the center, lighter towards the center.
glm::vec3 randomScale = glm::lerp(glm::vec3(.5f), glm::vec3(3.0f), 1.5f - distance / m_Radius);
glm::vec3 randomColor = glm::lerp(m_DarkerColor, m_White, 1.0f - distance / m_Radius);
glPushMatrix();
glColor3f(randomColor.r, randomColor.g, randomColor.b);
glTranslatef(randomPositionInSphere.x, randomPositionInSphere.y, randomPositionInSphere.z);
glScalef(randomScale.x, randomScale.y, randomScale.z);
glBegin(GL_TRIANGLES);
for (auto index : sphere->GetIndices())
{
Core::Vertex vertex = sphere->GetVertices()[index];
glVertex3f(vertex.Position.x, vertex.Position.y, vertex.Position.z);
glNormal3f(vertex.Normal.x, vertex.Normal.y, vertex.Normal.z);
}
glEnd();
glPopMatrix();
}
glEndList();
delete sphere;
}
Cloud::~Cloud()
{
}
void Cloud::Draw()
{
glCallList(CloudDrawList);
}
| 26.818182 | 97 | 0.720339 | conholo |
08b22b604ea13976ec6e6d32cf5b2e2813015650 | 574 | hpp | C++ | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | //
// TimeStamp.hpp
//
// Created by Vincent Moscaritolo on 5/6/21.
//
#ifndef TimeStamp_hpp
#define TimeStamp_hpp
#include <stdlib.h>
#include <time.h>
#include <string>
namespace timestamp {
class TimeStamp{
public:
TimeStamp(bool isGMT = true);
TimeStamp(std::string str);
TimeStamp(time_t time) { _time = time;};
inline time_t getTime() { return _time; };
std::string RFC1123String();
std::string ISO8601String();
std::string logFileString();
std::string ClockString(bool isGMT = true);
private:
time_t _time;
};
};
#endif /* TimeStamp_hpp */
| 14.717949 | 45 | 0.689895 | vinthewrench |
08b543ad9ce1855d889cc85e9daf88d02bdffeaa | 351 | cpp | C++ | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | 2 | 2021-04-01T14:56:47.000Z | 2021-07-31T18:37:15.000Z | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | null | null | null | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | null | null | null | #include "outDynasty.h"
#include "CK3/Dynasties/Dynasty.h"
std::ostream& CK3::operator<<(std::ostream& output, const Dynasty& dynasty) {
// output ID, name and culture
output << dynasty.ID << " = {\n";
output << "\tname = \"" << dynasty.name << "\"\n";
output << "\tculture = " << dynasty.culture << "\n";
output << "}\n";
return output;
}
| 23.4 | 77 | 0.598291 | Idhrendur |
08b60c3a9be640a736a489285d5108a4b33269ca | 1,116 | cpp | C++ | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
void print(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << "\t";
}
cout << endl;
}
void merge(int arr[], int l, int r, int mid) {
int leftSize = (int) ceil( (double) ((r - l + 1) / 2));
int rightSize = (r - l + 1) / 2;
int *leftCopy = new int[leftSize];
int *rightCopy = new int[rightSize];
int i = l, j = mid + 1;
for (int a = 0; a < leftSize; a++) {
leftCopy[a] = arr[i++];
}
for (int b = 0; b < rightSize; b++) {
rightCopy[b] = arr[j++];
}
i = l, j = mid + 1;
int a = 0, b = 0;
while (a < leftSize && b < leftSize) {
if (leftCopy[a] < rightCopy[b]) {
arr[i++] = leftCopy[a++];
}
else {
arr[j++] = rightCopy[b++];
}
}
while (a < leftSize) {
arr[i++] = leftCopy[a++];
}
while (b < rightSize) {
arr[j++] = rightCopy[b++];
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int mid = (r + l) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, r, mid);
}
}
int main() {
int array[5]{ 1,2,3,4,5 };
mergeSort(array, 0, 4);
print(array, 5);
} | 18.295082 | 56 | 0.515233 | zementalist |
08b709ddb700803cc34fbaf6c69103642f64a530 | 63,953 | cc | C++ | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 118 | 2021-01-12T01:56:25.000Z | 2022-03-30T09:50:58.000Z | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 114 | 2021-01-29T08:21:43.000Z | 2022-03-28T11:58:10.000Z | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 56 | 2021-01-12T02:42:53.000Z | 2022-03-24T02:15:20.000Z | #include "tim/vx/ops/conv2d.h"
#include "gtest/gtest.h"
#include "test_utils.h"
#include "tim/vx/context.h"
#include "tim/vx/graph.h"
#include "tim/vx/types.h"
TEST(Conv2d, shape_4_2_1_1_float32_PaddingTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
1, 1, 1, 1, // row = 1
2, 2, 3, 2 // row = 2
};
// weight data oihw
std::vector<float> weight_data = {
1, 2, 3, 4, //first 2x2 filter
-1, 1, -1, 1, // second 2x2 filter
-1, -1, 1, 1, // third 2x2 filter
};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {// first channel
18, 22, 21, 8, 7, 9, 8, 3, 2, 3, 1, -1,
// second channel
2, 3, 1, 0, 5, 6, 6, 4, -1, -2, -2, 1};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_PointwiseTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 2, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data oihw
std::vector<float> weight_data = {
1, 2 // first filter
};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3,
1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_SimpleTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
// First batch
1, 1, 1, 1, // row = 1
2, 2, 2, 2, // row = 2
// Second batch
1, 2, 3, 4, // row = 1
1, 2, 3, 4, // row = 2
};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_SimpleChannelsTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data
std::vector<float> weight_data = {1, 2, 3, 4, 1, 2, 3, 4, -1, 1, -1, 1,
-1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_6_3_1_1_float32_SimpleAnisotropicStridesTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {3, 2, 1, -1, -2, -3, 4, 3, 2,
-2, -3, -4, 5, 4, 3, -3, -4, -5};
// weight data oihw
std::vector<float> weight_data = {
1, 2, //
3, 4, //
};
// bias data
std::vector<float> bias_data = {-1};
// nchw
std::vector<float> golden = {
30, -24, //
40, -34, //
};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({3, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {105, 150, 183, 95, 235, 312,
357, 178, 187, 234, 261, 121};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedConstFilterTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {105, 150, 183, 95, 235, 312,
357, 178, 187, 234, 261, 121};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedBiasTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {10};
// nchw
std::vector<float> golden = {115, 160, 193, 105, 245, 322,
367, 188, 197, 244, 271, 131};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedValidTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {312, 357};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_DisabledPointwiseMultifilterTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data oihw
std::vector<float> weight_data = {1, 2, 2, 3};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {
1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 2.5, 2.5, 2.5, 2.5, 5, 5, 5, 5,
1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6, 2.5, 5, 7.5, 10, 2.5, 5, 7.5, 10};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_9_9_1_1_float32_SimpleDilationTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {5, 5, 5, 5, 5, 5, 5, 5, 5};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({3, 3});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_StrideTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 3, 2,
1, 2, 3, 4, 1, 2, 4, 4};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {18, 22, 21, 2, 3, 1, 5, 6, 6,
17, 31, 40, 4, 5, 3, 3, 4, 4};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_InputAndFilterSameWidthHeightTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({4, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{1, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {10, 34};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest1) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1,
-1, 1, -1, -1, 1, 1};
// bias data
// scale:0.25 Zp:0
std::vector<float> bias_data_float = {1, 2, 3};
// golden data
//min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest2) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -128.5, input_max = 128, weight_min = -128.5, weight_max = 128,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-128.5 max:128 scale:1.00588 Zp:0
std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
// min:-128.5 max:128 scale:1.00588 Zp:0
std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1,
-1, 1, -1, -1, 1, 1};
// bias data
// scale:1.0116 Zp:0
std::vector<float> bias_data_float = {1, 2, 3};
// golden data
// min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_6_3_1_1_uint8_AnisotropicStridesQuantizedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 2, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 2, 1, -1, -2, -3, 4, 3, 2,
-2, -3, -4, 5, 4, 3, -3, -4, -5};
// weight data oihw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> weight_data_float = {1, 2, 3, 4};
// bias data
// scale:0.25 Zp:0
std::vector<float> bias_data_float = {-1};
// golden data
//min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {30, -24, 40, -34};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({3, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_9_9_1_1_uint8_DilationQuantizedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 3, weight_shape[3], input_shape[3]}); //whcn
float input_min = -128, input_max = 127, weight_min = -128, weight_max = 127,
output_min = 0, output_max = 255;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-128 max:127 scale:1 Zp:0
std::vector<float> input_data_float = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// weight data oihw
// min:-128 max:127 scale:1 Zp:0
std::vector<float> weight_data_float = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// bias data
// scale:1 Zp:0
std::vector<float> bias_data_float = {0};
// golden data
// min:0 max:255 scale:1 Zp:-128
std::vector<float> golden_float = {5, 5, 5, 5, 5, 5, 5, 5, 5};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({3, 3});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerTensorTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -63.5, output_max = 64;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {1};
std::vector<int32_t> zero_point_weight = {0};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3,
2, -1, -3, 3, -2, -4};
std::vector<int8_t> input_data =
Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]);
// weight_float_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2};
std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6,
7, 5, 3, 1, 8, 6, 4, 2};
// bias data
std::vector<float> bias_data_float = {3, -2};
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
// golden_int8_data = {61, -115, 111, -89}
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> golden_float = {31, -57, 56, -44};
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerChannelTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = 0, weight_max = 0,
output_min = -63.5, output_max = 64;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {1, 2};
std::vector<int32_t> zero_point_weight = {0, 0};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0],
scales_input[0] * scales_weight[1]};
std::vector<int32_t> zero_point_bias = {0, 0};
scales_zp = QuantizationParams<int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL,
3, scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0,
scales_bias, zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3,
2, -1, -3, 3, -2, -4};
std::vector<int8_t> input_data =
Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]);
// weight_data_float = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2};
std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6,
4, 3, 2, 1, 4, 3, 2, 1};
// bias_data_float ={3, -2};
std::vector<int32_t> bias_data = {6, -2};
// golden data
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> golden_float = {31, -57, 64, -46};
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_w_h_128_1_ksize_1_1_stride_2_int8_QuantizedPerChannelTest) {
std::map<uint32_t, std::vector<uint32_t>> input_shape_list;
input_shape_list[32] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
input_shape_list[63] = {18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62};
input_shape_list[95] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
input_shape_list[96] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
tim::vx::ShapeType input_shape({2, 2, 128, 1}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 128, 256}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{1, 1, weight_shape[3], input_shape[3]}); //whcn
std::vector<float> scales_input = {0.5};
std::vector<int32_t> zero_point_input = {-1};
std::vector<float> scales_weight(weight_shape[3]);
std::vector<int32_t> zero_point_weight(weight_shape[3]);
for (unsigned int i = 0; i < weight_shape[3]; i++) {
scales_weight[i] = 1;
zero_point_weight[i] = 0;
}
int32_t sizeofweight = scales_weight.size();
std::vector<float> scales_bias(sizeofweight);
std::vector<int32_t> zero_point_bias(sizeofweight);
for (int i = 0; i < sizeofweight; i++) {
scales_bias[i] = scales_input[0] * scales_weight[i];
zero_point_bias[i] = 0;
}
std::vector<float> scales_output = {0.5};
std::vector<int32_t> zero_point_output = {-1};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL,
3, scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0,
scales_bias, zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
uint32_t weight_size =
weight_shape[0] * weight_shape[1] * weight_shape[2] * weight_shape[3];
std::vector<float> weight_data_float(weight_size);
for (uint32_t i = 0; i < weight_size; i++) {
weight_data_float[i] = 1;
}
std::vector<int8_t> weight_data = Quantize<int8_t>(weight_data_float, 1, 0);
// bias_data
std::vector<int32_t> bias_data(weight_shape[3]);
for (uint32_t i = 0; i < weight_shape[3]; i++) {
bias_data[i] = 2;
}
for (std::map<uint32_t, std::vector<uint32_t>>::iterator iter =
input_shape_list.begin();
iter != input_shape_list.end(); iter++) {
for (uint32_t j = 0; j < iter->second.size(); j++) {
input_shape[0] = iter->first;
input_shape[1] = iter->second[j];
output_shape[0] = (input_shape[0] + 1) / 2;
output_shape[1] = (input_shape[1] + 1) / 2;
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT,
quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
uint32_t input_size =
input_shape[0] * input_shape[1] * input_shape[2] * input_shape[3];
std::vector<float> input_data_float(input_size);
for (uint32_t i = 0; i < input_size; i++) {
input_data_float[i] = 1;
}
std::vector<int8_t> input_data = Quantize<int8_t>(
input_data_float, scales_input[0], zero_point_input[0]);
uint32_t golden_size =
output_shape[0] * output_shape[1] * output_shape[2] * output_shape[3];
std::vector<float> golden_float(golden_size);
for (uint32_t i = 0; i < golden_size; i++) {
golden_float[i] = 129;
}
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
}
}
| 38.948234 | 83 | 0.623208 | onepick |
08bb772415dc12db3244ac534cbf01afcff0fb71 | 9,260 | cpp | C++ | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 7 | 2019-07-29T19:07:01.000Z | 2021-10-01T14:21:29.000Z | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 6 | 2019-07-26T20:54:12.000Z | 2021-12-14T01:22:31.000Z | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 3 | 2020-09-20T00:37:47.000Z | 2021-12-14T07:31:18.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
////// Blank Panel 8 HP module /////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Ohmer.hpp"
struct OhmerBlank8 : Module {
enum ParamIds {
NUM_PARAMS
};
enum InputIds {
NUM_INPUTS
};
enum OutputIds {
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
// Current selected plate model (color).
int Theme = 0; // 0 = Classic (default), 1 = Stage Repro, 2 = Absolute Night, 3 = Dark Signature, 4 = Deepblue Signature, 5 = Carbon Signature.
// Panel color (default is "Classic" beige model).
NVGcolor panelBackgroundColor = nvgRGB(0xd2, 0xd2, 0xcd);
OhmerBlank8() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
}
void process(const ProcessArgs &args) override {
// DSP processing...
// Depending current model (theme), set the relevant background color for panel.
panelBackgroundColor = tblPanelBackgroundColor[Theme];
}
json_t *dataToJson() override {
json_t *rootJ = json_object();
json_object_set_new(rootJ, "Theme", json_integer(Theme));
return rootJ;
}
void dataFromJson(json_t *rootJ) override {
json_t *ThemeJ = json_object_get(rootJ, "Theme");
if (ThemeJ)
Theme = json_integer_value(ThemeJ);
}
};
///////////////////////////////////////////////////// CONTEXT-MENU //////////////////////////////////////////////////////
struct OhmerBlank8ClassicMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 0; // Model: default Classic (beige).
}
};
struct OhmerBlank8StageReproMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 1; // Model: Stage Repro.
}
};
struct OhmerBlank8AbsoluteNightMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 2; // Model: Absolute Night.
}
};
struct OhmerBlank8DarkSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 3; // Model: Dark Signature.
}
};
struct OhmerBlank8DeepblueSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 4; // Model: Deepblue Signature.
}
};
struct OhmerBlank8CarbonSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 5; // Model: Carbon Signature.
}
};
struct OhmerBlank8SubMenuItems : MenuItem {
OhmerBlank8 *module;
Menu *createChildMenu() override {
Menu *menu = new Menu;
OhmerBlank8ClassicMenu *ohmerblank8menuitem1 = new OhmerBlank8ClassicMenu;
ohmerblank8menuitem1->text = "Classic (default)";
ohmerblank8menuitem1->rightText = CHECKMARK(module->Theme == 0);
ohmerblank8menuitem1->module = module;
menu->addChild(ohmerblank8menuitem1);
OhmerBlank8StageReproMenu *ohmerblank8menuitem2 = new OhmerBlank8StageReproMenu;
ohmerblank8menuitem2->text = "Stage Repro";
ohmerblank8menuitem2->rightText = CHECKMARK(module->Theme == 1);
ohmerblank8menuitem2->module = module;
menu->addChild(ohmerblank8menuitem2);
OhmerBlank8AbsoluteNightMenu *ohmerblank8menuitem3 = new OhmerBlank8AbsoluteNightMenu;
ohmerblank8menuitem3->text = "Absolute Night";
ohmerblank8menuitem3->rightText = CHECKMARK(module->Theme == 2);
ohmerblank8menuitem3->module = module;
menu->addChild(ohmerblank8menuitem3);
OhmerBlank8DarkSignatureMenu *ohmerblank8menuitem4 = new OhmerBlank8DarkSignatureMenu;
ohmerblank8menuitem4->text = "Dark \"Signature\"";
ohmerblank8menuitem4->rightText = CHECKMARK(module->Theme == 3);
ohmerblank8menuitem4->module = module;
menu->addChild(ohmerblank8menuitem4);
OhmerBlank8DeepblueSignatureMenu *ohmerblank8menuitem5 = new OhmerBlank8DeepblueSignatureMenu;
ohmerblank8menuitem5->text = "Deepblue \"Signature\"";
ohmerblank8menuitem5->rightText = CHECKMARK(module->Theme == 4);
ohmerblank8menuitem5->module = module;
menu->addChild(ohmerblank8menuitem5);
OhmerBlank8CarbonSignatureMenu *ohmerblank8menuitem6 = new OhmerBlank8CarbonSignatureMenu;
ohmerblank8menuitem6->text = "Carbon \"Signature\"";
ohmerblank8menuitem6->rightText = CHECKMARK(module->Theme == 5);
ohmerblank8menuitem6->module = module;
menu->addChild(ohmerblank8menuitem6);
return menu;
}
};
///////////////////////////////////////////////// PANEL BACKGROUND COLOR /////////////////////////////////////////////////
struct OhmerBlank8Background : TransparentWidget {
OhmerBlank8 *module;
OhmerBlank8Background() {
}
void draw(const DrawArgs &args) override {
nvgBeginPath(args.vg);
nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);
if (module)
nvgFillColor(args.vg, module->panelBackgroundColor);
else nvgFillColor(args.vg, nvgRGB(0xd2, 0xd2, 0xcd));
nvgFill(args.vg);
}
};
///////////////////////////////////////////////// MODULE WIDGET SECTION /////////////////////////////////////////////////
struct OhmerBlank8Widget : ModuleWidget {
// Panel (transparent widget).
OhmerBlank8Background *blankPanel;
// Silver Torx screws.
SvgScrew *topLeftScrewSilver;
SvgScrew *topRightScrewSilver;
SvgScrew *bottomLeftScrewSilver;
SvgScrew *bottomRightScrewSilver;
// Gold Torx screws.
SvgScrew *topLeftScrewGold;
SvgScrew *topRightScrewGold;
SvgScrew *bottomLeftScrewGold;
SvgScrew *bottomRightScrewGold;
OhmerBlank8Widget(OhmerBlank8 *module) {
setModule(module);
// 8 HP module, no SVG panel loaded, but using transparent widget instead.
box.size = Vec(8 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT);
{
blankPanel = new OhmerBlank8Background();
blankPanel->box.size = box.size;
blankPanel->module = module;
addChild(blankPanel);
}
// This 8 HP module uses 4 screws (may are silver or gold).
// Top-left silver screw.
topLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, 0));
addChild(topLeftScrewSilver);
// Top-right silver screw.
topRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0));
addChild(topRightScrewSilver);
// Bottom-left silver screw.
bottomLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomLeftScrewSilver);
// Bottom-right silver screw.
bottomRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomRightScrewSilver);
// Top-left gold screw.
topLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, 0));
addChild(topLeftScrewGold);
// Top-right gold screw.
topRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0));
addChild(topRightScrewGold);
// Bottom-left gold screw.
bottomLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomLeftScrewGold);
// Bottom-right gold screw.
bottomRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomRightScrewGold);
}
void step() override {
OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module);
if (module) {
// Torx screws metal (silver, gold) are visible or hidden, depending selected model (from module's context-menu).
// Silver Torx screws are visible only for non-"Signature" modules (Classic, Stage Repro or Absolute Night).
topLeftScrewSilver->visible = (module->Theme < 3);
topRightScrewSilver->visible = (module->Theme < 3);
bottomLeftScrewSilver->visible = (module->Theme < 3);
bottomRightScrewSilver->visible = (module->Theme < 3);
// Gold Torx screws are visible only for "Signature" modules (Dark Signature, Deepblue Signature or Carbon Signature).
topLeftScrewGold->visible = (module->Theme > 2);
topRightScrewGold->visible = (module->Theme > 2);
bottomLeftScrewGold->visible = (module->Theme > 2);
bottomRightScrewGold->visible = (module->Theme > 2);
}
else {
// Default panel theme is always "Classic" (beige, using silver screws, using silver button, LCD).
// Other panels are, of course, hidden.
// By default, silver screws are visible for default beige Classic panel...
topLeftScrewSilver->visible = true;
topRightScrewSilver->visible = true;
bottomLeftScrewSilver->visible = true;
bottomRightScrewSilver->visible = true;
// ...and, of course, golden screws are hidden.
topLeftScrewGold->visible = false;
topRightScrewGold->visible = false;
bottomLeftScrewGold->visible = false;
bottomRightScrewGold->visible = false;
}
ModuleWidget::step();
}
void appendContextMenu(Menu *menu) override {
OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module);
menu->addChild(new MenuEntry);
OhmerBlank8SubMenuItems *ohmerblank8submenuitems = new OhmerBlank8SubMenuItems;
ohmerblank8submenuitems->text = "Model";
ohmerblank8submenuitems->rightText = RIGHT_ARROW;
ohmerblank8submenuitems->module = module;
menu->addChild(ohmerblank8submenuitems);
}
};
Model *modelBlankPanel8 = createModel<OhmerBlank8, OhmerBlank8Widget>("OhmerBlank8");
| 35.891473 | 144 | 0.699784 | DomiKamu |
08bc69b1c7a19d0fbdd8e3181f145677e1ee5b97 | 2,162 | cpp | C++ | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | 1 | 2021-06-17T14:15:45.000Z | 2021-06-17T14:15:45.000Z | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | null | null | null | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | null | null | null |
#include "AudioManager.h"
#include "AudioPlayer.h"
#include "glm/detail/func_geometric.inl"
#include "Player.h"
void AudioManager::AddFile(Sounds::Type sndType, const char* filepath)
{
//filepaths[sndType] = filepath;
//auto ap = AudioPlayerFactory::createFromFile(filepath);
AudioPlayer* ap = new AudioPlayer(filepath);
if (ap == nullptr)
throw;
//ap->setFinishListener(this);
audioPlayers[sndType] = ap;
}
AudioManager::AudioManager()
{
instance = this;
AddFile(Jump1, "assets/Sounds/jump1.wav");
AddFile(Jump2, "assets/Sounds/jump2.wav");
AddFile(Jump3, "assets/Sounds/jump3.wav");
AddFile(PlayerDie, "assets/Sounds/laser6.wav");
AddFile(EnemyDie, "assets/Sounds/m_health.wav");
AddFile(Hit, "assets/Sounds/pl_pain6.wav");
AddFile(Shoot, "assets/Sounds/LaserZap04.wav");
AddFile(Ricochet, "assets/Sounds/bulletby02.wav");
AddFile(Ricochet2, "assets/Sounds/bulletby02.wav");
AddFile(Powerup, "assets/Sounds/powerUp8.wav");
AudioPlayer::Loaded();
}
AudioManager::~AudioManager()
{
//filepaths.clear();
instance = nullptr;
for (auto i = audioPlayers.begin(); i != audioPlayers.end();)
{
Sounds::Type sndtype = i->first;
AudioPlayer* ap = audioPlayers[sndtype];
i = audioPlayers.erase(i); // update iterator
delete ap;
}
}
void AudioManager::Run()
{
}
void Jelly::AudioManager::DoPlaySoundType3D(Sounds::Type sndType, float px, float py, float speed) const
{
if (sndType == Sounds::NONE)
return;
auto ppos = Player::instance->GetPosition();
auto pdiff = glm::vec2(ppos.x - px, ppos.y - py);
auto dist = glm::length(pdiff);
auto dx = (px - ppos.x);
auto lr = clamp(static_cast<int>(std::round(dx * 30)), -100, 100);
auto vol = clamp(static_cast<int>(std::round(100 - dist * 20)), 0, 100);
auto ap = audioPlayers.at(sndType);
ap->Play(vol * 0.01f, lr * 0.01f, speed);
}
void Jelly::AudioManager::DoPlaySoundType2D(Sounds::Type sndType, float speed) const
{
if (sndType == Sounds::NONE)
return;
auto ap = audioPlayers.at(sndType);
ap->Play(1, 0, speed);
}
| 27.367089 | 104 | 0.653099 | RikdeRooij |
08bfc6deaab93e37ad4ace6629735eaaad365ed5 | 88,979 | cpp | C++ | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | /**
* @file UnoTransport.cpp
* @author Ashwin Natarajan
* @brief This file contains the implementation of the protocol and methods specified in UnoTransport.hpp
* @version 0.1
* @date 2020-08-30
*
* @copyright MIT License
Copyright (c) 2020 Ashwin N
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*
*/
#include "UnoTransport.hpp"
#include <unistd.h> //for close, socket, etc
#include <fcntl.h> //for fcntl to set sockets as non blocking
#include <poll.h> //for poll()
#include <assert.h> //for asserts
#include <arpa/inet.h> //for IPv4 related stuff
#include <vector> //std::vector
#include <stdio.h> //for fprintf, perror, etc
#include <sys/timerfd.h> //for timerfd
#ifdef UNO_TRANSPORT_DEBUG
#include <inttypes.h> //for format specifiers to fixed width integers
#endif
/**************************************************************************************************************************/
//debug specific macros
#ifdef UNO_TRANSPORT_DEBUG
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define UNO_DBG_PREFIX ANSI_COLOR_RED "<====================>"
#define UNO_DBG_SUFFIX "<====================>" ANSI_COLOR_RESET "\n"
#endif
#ifndef UNO_TRANSPORT_DEBUG
#define NDEBUG //remove asserts if the debug macro is not set
#endif
/**************************************************************************************************************************/
//general purpose macros
#define UNO_CLEAR_BIT(x,n) ((x) & ~(1UL << n))
#define UNO_SET_BIT(x,n) ((x) | (1UL << n) )
#define UNO_IS_BIT_SET(x,n) ((x) & (1UL <<n))
#define UNO_SEC_TO_NS(x) ((x) * 1000 * 1000 * 1000)
#define UNO_MS_TO_NS(x) ((x) * 1000 * 1000)
#define UNO_MS_TO_SEC(x) ((x) / 1000)
#define UNO_NS_TO_SEC(x) ((x) / (1000 * 1000 * 1000))
/**************************************************************************************************************************/
//the version of this protocol
#define UNO_TRANSPORT_PROTO_VER 1
/**************************************************************************************************************************/
//header fields lengths
#define UNO_TRANSPORT_HDR_SEQ_LEN 2
#define UNO_TRANSPORT_HDR_RC_LEN 1
#define UNO_TRANSPORT_HDR_PROTO_VER_LEN 1
#define UNO_TRANSPORT_HDR_CMD_LEN 1
#define UNO_TRANSPORT_HDR_MSG_LEN_LEN 2
/**************************************************************************************************************************/
//header fields positions
#define UNO_TRANSPORT_HDR_SEQ_POS 0
#define UNO_TRANSPORT_HDR_RC_POS 2
#define UNO_TRANSPORT_HDR_PROTO_VER_POS 3
#define UNO_TRANSPORT_HDR_CMD_POS 4
#define UNO_TRANSPORT_HDR_MSG_LEN_POS 5
/**************************************************************************************************************************/
//general purpose header related macros
#define UNO_SEQ_ID_RESET 0
#define UNO_TRANSPORT_CTRL_MSG_MAX_SIZE (10)
/**************************************************************************************************************************/
//the below are the bits that are supported in the control flag, the number is their position
#define UNO_TRANSPORT_CMD_CONTROL_MSG (0)
#define UNO_TRANSPORT_CMD_RELIABLE_MSG (1)
#define UNO_TRANSPORT_CMD_ACK_MSG (2)
#define UNO_TRANSPORT_CMD_SPL_MSG (3) //a special msg is one that will be passed to the app layer without any header
//or connection validation, should be used for discovery, control msg flag must
//not be set
//In a control command, extra info will be placed on the data section of the message.
// the first byte will be the command ID, followed by data specific to that command.
// commands must be very simple
/**
* @brief The command ID for connection request. This command is used for both opening and
closing connections There will be one byte of additional data
byte 1 = mode
0 = conn open req
1 = conn close req by client
2 = conn close req by server (explicit, server wants the client gone)
3 = conn close req by server (timeout)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_REQ (1)
#define UNO_TRANSPORT_CTRL_CONN_REQ_LEN (2)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN (0)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ (1)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL (2)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO (3)
/**
* @brief The command ID for connection response. Additional data for connection response (if successful)
There will be no additional data (msg len = 0) if the server is full
bytes 1,2 = port number (in nwk byte order)
bytes 3,4 = keepalive interval in ms (in nwk byte order)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_RSP (2)
#define UNO_TRANSPORT_CTRL_CONN_RSP_LEN (5)
/**
* @brief The command ID for error status. Additional data:
byte = status code, depends on command, full list to be populated here
*
*/
#define UNO_TRANSPORT_CTRL_ERR_RSP (3)
#define UNO_TRANSPORT_CTRL_ERR_RSP_LEN (2)
/**
* @brief The command ID for connection keep alive. There is no additioanl data for this
*
*/
#define UNO_TRANSPORT_CTRL_KEEPALIVE (4)
#define UNO_TRANSPORT_CTRL_KEEPALIVE_LEN (1)
/**
* @brief The command ID for the connection closed command. This will only be sent by the server
There will be 1 byte of additional data
byte 1 = reason
0 = close requested by client
1 = timedout
2 = explicit close notified by server (the caller doesn't like this client)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_CLOSED (5)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_LEN (2)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_REQ (0)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_TIMEDOUT (1)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_EXPL (2)
/**************************************************************************************************************************/
/* HEADER FORMAT - drawn using the awesome website http://asciiflow.com/
+--------------------------------+----------+-------------------------------------+
| seq id |retry |proto.| cmd | msg len | data |
| |count |Ver | | | |
+------------------------+-------+----------+-------------------------------------+
0 2 3 4 5 6
NOTE: all multibyte fields will be in nwk byte order
*/
/**************************************************************************************************************************/
/**
* @brief This struct will hold the header in an easily accessible form. also supports
serialisation and deserialisation
*
*/
struct uno_hdr {
public:
uint16_t seq_id; //sequence id
uint8_t rc; //retry count
uint8_t proto_ver; //protocol version
uint8_t cmd; //command flags
uint16_t msg_len; //message length
/**
* @brief Construct a new uno hdr object with everything set to 0
*
*/
uno_hdr (void) {
seq_id = 0;
rc = 0;
proto_ver = UNO_TRANSPORT_PROTO_VER;
cmd = 0;
msg_len = 0;
}
/**
* @brief Construct a new uno hdr object by deserialising the given flag buffer containing the header
*
* @param hdr pointer to the buffer containing the header
*/
uno_hdr (const uint8_t *hdr) {
deserialise (hdr);
}
/**
* @brief Construct a new uno hdr object using the given paramters
*
* @param seq_id
* @param cmd
* @param msg_len
*/
uno_hdr (uint16_t seq_id, uint8_t cmd, uint16_t msg_len) {
this->seq_id = seq_id;
this->cmd = cmd;
this->msg_len = msg_len;
this->rc = 0;
this->proto_ver = UNO_TRANSPORT_PROTO_VER;
}
/**
* @brief Construct a new uno hdr object. copy the values of x into this
*
* @param x the object to copy from
*/
uno_hdr (const uno_hdr &x) {
seq_id = x.seq_id;
rc = x.rc;
proto_ver = x.proto_ver;
cmd = x.cmd;
msg_len = x.msg_len;
}
/**
* @brief serialise this struct into the given buffer
*
* @param hdr the buffer to which the data is to be serialised, which is assumed
to be not nullptr and large enough
*/
void serialise (uint8_t *hdr) {
//2 bytes seq_id in nwk byte order
hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] = (this->seq_id >> 8) & 0xFF;
hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] = (this->seq_id >> 0) & 0xFF;
//1 byte reboot count
hdr[UNO_TRANSPORT_HDR_RC_POS] = this->rc;
//1 byte proto ver
hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS]= UNO_TRANSPORT_PROTO_VER;
//1 byte cmd info
hdr[UNO_TRANSPORT_HDR_CMD_POS] = this->cmd;
//2 bytes msg len
hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0]= (this->msg_len >> 8) & 0xFF;
hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1]= (this->msg_len >> 0) & 0xFF;
}
/**
* @brief deserialise from the given buffer into this hdr struct
*
* @param hdr the buffer containing the header, which is assumed to be not nullptr and
large enough
*/
void deserialise (const uint8_t *hdr) {
//2 byte seq in nwk byte order
seq_id = 0;
seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] << 8;
seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] << 0;
//1 byte reboot count
rc = hdr[UNO_TRANSPORT_HDR_RC_POS];
//1 byte proto ver
proto_ver= hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS];
//1 byte cmd info
cmd = hdr[UNO_TRANSPORT_HDR_CMD_POS];
//2 byte msg len - in nwk byte order
msg_len = 0;
msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0] << 8;
msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1] << 0;
}
/**
* @brief checks if this header is valid or out of order or duplicate
*
* @param exp_seq the expected sequence number
* @return ret returns true if valid
*/
bool is_valid (uint16_t exp_seq) {
return true;
}
};
/**
* @brief This struct is the wrapper for the timer that will be used in this code. Currently, it
uses the linux timerfd
*
*/
struct uno_timer {
public:
int fd;
bool is_armed;
struct itimerspec last_config;
/**
* @brief Construct a new uno timer object. Creates the fd and initialises the fields
*
*/
uno_timer (void) {
//create the fd
fd = timerfd_create (CLOCK_MONOTONIC, 0);
if(fd == UNO_TRANSPORT_ERR) {
//raise exception
;
}
is_armed = false;
memset (&last_config, 0, sizeof(last_config));
}
/**
* @brief Destroy the uno timer object. Closes the fd and clears the fields
*
*/
~uno_timer (void) {
is_armed = false;
memset (&last_config, 0, sizeof(last_config));
close(fd);
fd = UNO_TRANSPORT_ERR;
}
/**
* @brief - sets the timer of this object
*
* @param timer_val - the const struct timespec structure containing the timer delay value
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure
*/
int arm_non_recurring (const struct timespec &timer_val) {
assert (timer_val.tv_sec>0 && timer_val.tv_nsec>0);
struct itimerspec val = {{0,},};
val.it_value.tv_sec = timer_val.tv_sec;
val.it_value.tv_nsec = timer_val.tv_nsec;
//arm the timer with the given value
int ret = timerfd_settime (fd, 0, &val, NULL);
if(ret == UNO_TRANSPORT_ERR) {
perror("timerfd_settime");
}
else {
//update the fields of the struct
is_armed = true;
memcpy (&last_config, &val, sizeof(val));
}
return ret;
}
/**
* @brief - clears the timer of this object
*
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure
*/
int disarm (void) {
//just returned if not armed
if(is_armed == false) {
return 0;
}
struct itimerspec val = {{0,},};
//disarm the timer
int ret = timerfd_settime (fd, 0, &val, NULL);
if(ret == UNO_TRANSPORT_ERR) {
perror("timerfd_settime");
}
else {
//update the fields of the struct
is_armed = false;
memcpy (&last_config, &val, sizeof(val));
}
return ret;
}
};
/**
* @brief the enum class of the msg types in the cmd field of the header
*
*/
enum class _uno_msg_type {
UNO_MSG_CTRL,
UNO_MSG_ACK,
UNO_MSG_DATA,
UNO_MSG_SPL,
UNO_MSG_UNKNOWN,
};
/**************************************************************************************************************************/
//static function declarations - descriptions will be placed above the definitions
static int _uno_create_client_fd (int broadcast);
static int _uno_create_server_fd (uint16_t port);
static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq);
static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms);
static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src);
static _uno_msg_type _uno_get_msg_type (uint8_t cmd);
static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src,
uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time);
static int _uno_get_port_from_fd (int fd);
static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes,
std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src,
uint8_t max_conn, const struct timespec &curr_time, bool &is_spl);
static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list,
const struct sockaddr_in &src);
static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr);
static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list);
static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list);
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list,
const struct sockaddr_in &dst);
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd);
static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq);
static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len,
const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval);
static bool _uno_is_reliable_msg (uint8_t cmd_flags);
static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr);
static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq);
static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list);
static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur,
const struct timespec &curr_time, struct timespec &_timer_val);
/**************************************************************************************************************************/
//code specific to UnoConnection
/**
* @brief Construct a new Uno Connection object
*
* @param fd The fd of the already created socket
* @param cli reference to the struct socakddr_in holding the client's IPv4 addr
* @param hdr reference to the structure containing the deserialised header
* @param ka_dur the keep alive interval
* @param curr_time const reference to the struct containing the curr time, this value is used
as the initial value for last_msg_time
*/
UnoConnection :: UnoConnection (int fd, const struct sockaddr_in &cli, uno_hdr &hdr, uint16_t ka_dur,
const struct timespec &curr_time)
{
this->fd = _uno_create_client_fd (false);
if(this->fd == UNO_TRANSPORT_ERR) {
;
//throw exception here
}
//get the self addr info from the fd
int temp = _uno_get_port_from_fd (this->fd);
if(temp == UNO_TRANSPORT_ERR) {
//throw exception here
}
self_port = (uint16_t) temp;
//update in structures
memcpy (&cli_addr, &cli, sizeof(cli_addr));
//send the new connection info to the client using the argument fd
this->connected = true;
this->send_connect_rsp (hdr, ka_dur);
this->client_seq = 0;
this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN;
//set the last msg time as the provided curr time
memcpy (&(this->last_msg_time), &curr_time, sizeof(curr_time));
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created new connection fd=%d port=%" PRIu16
" tv_sec=%ld tv_nsec=%ld" UNO_DBG_SUFFIX, this->fd, self_port,
this->last_msg_time.tv_sec, this->last_msg_time.tv_nsec);
#endif
}
/**
* @brief Construct a new Uno Connection object by copying the given one
*
* @param the object from which this one is to be copied from
*/
UnoConnection :: UnoConnection (const UnoConnection &cpy)
{
this->fd = cpy.fd;
this->self_port = cpy.self_port;
memcpy (&(this->cli_addr), &(cpy.cli_addr), sizeof(cpy.cli_addr));
this->client_seq = 0;
memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time));
this->connected = cpy.connected;
this->close_reason = cpy.close_reason;
}
/**
* @brief Destroy the Uno Connection object. Sends connection close req to the client if the
client is still connected
*
*/
UnoConnection :: ~UnoConnection (void)
{
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "in UnoConnection destructor for fd=%d: connected=%d" UNO_DBG_SUFFIX, fd, connected);
#endif
if(this->connected) {
assert (this->close_reason != _close_reason::CLOSE_REASON_UNKNOWN);
switch(this->close_reason) {
//no need to send anything if close was requested by client
case _close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT:
break;
//send explicit connection closure message
case _close_reason::CLOSE_REASON_REQUESTED_BY_SERVER:
_uno_send_conn_close_expl (this->fd, this->cli_addr, nullptr);
break;
//send connection timedout message
case _close_reason::CLOSE_REASON_TIMEDOUT:
_uno_send_conn_close_to (this->fd, this->cli_addr, nullptr);
break;
case _close_reason::CLOSE_REASON_UNKNOWN:
assert (0);
break;
}
this->connected = false;
this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN;
}
close (this->fd);
this->fd = UNO_TRANSPORT_ERR;
this->connected = false;
memset (&(this->self_port), 0, sizeof(this->self_port));
memset (&(this->cli_addr), 0, sizeof(this->cli_addr));
this->client_seq = 0;
memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time));
}
/**
* @brief Sends a connection response to the device sending the connection request
*
* @param hdr info in the header struct
* @param ka_dur the keepalive duration
* @return int retuns number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
int UnoConnection :: send_connect_rsp (uno_hdr &hdr, uint16_t ka_dur)
{
uint8_t data[UNO_TRANSPORT_CTRL_CONN_RSP_LEN] = {0,};
//cmd id
data[0] = UNO_TRANSPORT_CTRL_CONN_RSP;
//port number - in nwk byte order
data[1] = (self_port >> 8) & 0xFF;
data[2] = (self_port >> 0) & 0xFF;
//keep alive - in nwk byte order
data[3] = (ka_dur >> 8) & 0xFF;
data[4] = (ka_dur >> 0) & 0xFF;
hdr.msg_len = sizeof(data);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
hdr.serialise(hdr_ser);
return _uno_send (fd, hdr_ser, data, sizeof(data), &cli_addr, NULL);
}
/**
* @brief Set the close reason variable
*
* @param reason
*/
void UnoConnection :: set_close_reason (_close_reason reason)
{
this->close_reason = reason;
}
/**************************************************************************************************************************/
//code specific to UnoTransportClient
/**
* @brief The default constructor for the client class, creates a UDP socket at a random port
*
* @return UnoTransportClient
*/
UnoTransportClient :: UnoTransportClient (void)
{
fd = _uno_create_client_fd (0);
if(fd == UNO_TRANSPORT_ERR) {
//raise exception here
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = 0" UNO_DBG_SUFFIX, fd);
#endif
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = false;
connected = false;
self_port = (uint16_t) _uno_get_port_from_fd (fd);
}
/**
* @brief Constructor with capability to create a broadcast socket.
*
* @param broadcast set this to true if you want the socket to be able to broadcast
* @return UnoTransportClient N/A
*/
UnoTransportClient :: UnoTransportClient (bool broadcast)
{
//create a socket with broadcast permissions
int opt = (broadcast==true) ? (1) : (0);
fd = _uno_create_client_fd (opt);
if(fd == -1) {
//raise exception here
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = %d" UNO_DBG_SUFFIX, fd, broadcast);
#endif
//initialise other fields
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = broadcast;
connected = false;
self_port = (uint16_t) _uno_get_port_from_fd (fd);
}
/**
* @brief Destructor for the client class, will close the socket and reset all other fields
*
* @return UnoTransportClient N/A
*/
UnoTransportClient :: ~UnoTransportClient (void)
{
//if connected, disconnect
if(connected) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "closing connection in client destructor. fd=%d conn_port=%" PRIu16 UNO_DBG_SUFFIX,
fd, ntohs(addr.sin_port));
#endif
_uno_send_conn_close (fd, addr, &seq);
}
//close the socket
if(fd != UNO_TRANSPORT_ERR) {
close (fd);
fd = UNO_TRANSPORT_ERR;
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "destroyed client" UNO_DBG_SUFFIX);
#endif
//clear other fields
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = false;
connected = false;
self_port = 0;
}
/**
* @brief get the port number of the connection (on the server side) (TO BE REMOVED)
*
* @return uint16_t the port number value
*/
uint16_t UnoTransportClient :: _dbg_get_port (void)
{
return ntohs(this->addr.sin_port);
}
/**
* @brief get the port number of the client side socket (TO BE REMOVED)
*
* @return uint16_t the port number
*/
uint16_t UnoTransportClient :: _dbg_get_self_port (void)
{
return self_port;
}
/**
* @brief Connect to the specified server
*
* @param dst - reference to the struct sockaddr_in instance containing the server's IPv4 address
* @param to_ms - the timeout in milliseconds
* @return int - 0 if successful, UNO_TRANSPORT_ERR if failed
*/
int UnoTransportClient :: connect (const struct sockaddr_in &dst, int to_ms)
{
struct sockaddr_in src;
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &dst, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent connection req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
this->fd, ntohs(dst.sin_port));
#endif
//todo - check source address, and continue waiting if interrupted by other message
if(ret != UNO_TRANSPORT_ERR) {
memset (&src, 0, sizeof(src));
memset (hdr_ser, 0, sizeof(hdr_ser));
uint8_t data[UNO_TRANSPORT_CTRL_MSG_MAX_SIZE] = {0,};
ret = _uno_timed_recv (this->fd, hdr_ser, data, sizeof(data), MSG_WAITALL, &src, to_ms);
hdr.deserialise (hdr_ser);
//process connection response
if(_uno_get_msg_type(hdr.cmd) == _uno_msg_type::UNO_MSG_CTRL &&
data[0] == UNO_TRANSPORT_CTRL_CONN_RSP) {
//if msg len is 1, then the server is full/connection refused
if(hdr.msg_len == 1) {
ret = UNO_TRANSPORT_CONN_REFUSED;
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received conn refused" UNO_DBG_SUFFIX);
#endif
}
else {
//save the connection details
memcpy (&(this->addr), &src, sizeof(src));
//2 byte port in nwk byte order, save port in nwk byte order
memcpy (&(this->addr.sin_port), data+1, 2);
//2 byte keepalive duration in nwk byte order
this->keepalive_dur = 0;
this->keepalive_dur |= (data[3] << 8);
this->keepalive_dur |= (data[4] << 0);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received connection rsp %d bytes fd=%d port=%" PRIu16
" ka=%" PRIu16 UNO_DBG_SUFFIX, ret, this->fd, ntohs(this->addr.sin_port), this->keepalive_dur);
#endif
ret = 0;
connected = true;
}
}
}
return ret;
}
/**
* @brief Send a mesage to the server that this client is connected to
*
* @param msg - void pointer to the mesage
* @param len - length of the message
* @return int - returns UNO_TRANSPORT_ERR on failure, or number of bytes sent on success
*/
int UnoTransportClient :: send_msg (const void *msg, size_t len)
{
assert (msg!=nullptr);
assert (len<=UNO_TRANSPORT_MTU);
if(msg==nullptr || len > UNO_TRANSPORT_MTU) {
return UNO_TRANSPORT_ERR;
}
if(this->connected==false) {
return UNO_TRANSPORT_ERR;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
// uint8_t cmd_flags = 0;
uno_hdr hdr (seq, 0, len);
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, msg, len, &addr, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret);
#endif
return ret;
}
/**
* @brief Sends the given message to the server, expects an ACK from the server.
*
* @param msg - void pointer to the message
* @param len - length of the message
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_ERR on general failure
*/
int UnoTransportClient :: send_msg_reliable (const void *msg, size_t len)
{
assert (msg!=nullptr);
assert (len<=UNO_TRANSPORT_MTU);
if(msg==nullptr || len > UNO_TRANSPORT_MTU) {
return UNO_TRANSPORT_ERR;
}
if(this->connected==false) {
return UNO_TRANSPORT_ERR;
}
//need to set the reliable msg bit in the cmd section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq, cmd_flags, len);
hdr.serialise (hdr_ser);
int ret;
//send out the message
ret = _uno_send_reliable (this->fd, hdr_ser, msg, len, addr, &seq, UNO_TRANSPORT_REL_MAX_RETRIES,
UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sen reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret);
#endif
if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
//close the socket and clear all fields
close(this->fd);
memset (&(this->addr), 0, sizeof(this->addr));
this->seq = 0;
this->server_seq = 0;
this->connected = 0;
this->can_broadcast = 0;
this->self_port = 0;
}
return ret;
}
/**
* @brief Receives a message from the connected server into the specified server
*
* @param buffer - The buffer where the message is to be written
* @param buffer_size - The size of this buffer
* @param to_ms - The timeout in milliseconds
* @return int - The number of bytes received
*/
int UnoTransportClient :: recv_msg (void *buffer, size_t buffer_size, int to_ms)
{
if(buffer == nullptr || buffer_size == 0) {
return UNO_TRANSPORT_ERR;
}
if(connected == false) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
bool exit_condition = false;
ssize_t bytes;
int ret = UNO_TRANSPORT_ERR;
uno_hdr hdr;
//loop until we get a message intended for the caller
while(!exit_condition) {
memset (hdr_ser, 0, sizeof(hdr_ser));
/*
TODO - reduce to_ms after every iteration of the loop, the whole function should not take more
than to_ms milliseconds. This current version will keep waiting to_ms milliseconds on every
iteration
*/
bytes = _uno_timed_recv (this->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, NULL, to_ms);
//timedout
if(bytes == 0) {
ret = 0;
break;
}
//every message must be atleast UNO_TRANSPORT_HDR bytes long
if(bytes < UNO_TRANSPORT_HDR_LEN) {
//drop the messsage, continue
continue;
}
//check the validity of the sequence number
if(_is_seq_valid (this->fd, hdr.seq_id, server_seq) == false) {
//drop the packet;
continue;
}
//send ack if reliable message
hdr.deserialise (hdr_ser);
if(_uno_is_reliable_msg(hdr.cmd)) {
_uno_send_ack (this->fd, addr, hdr);
}
//process the message, now that we know it has a valid fmt
bytes = _uno_client_process_recv_msg (hdr, static_cast<uint8_t*>(buffer), bytes, server_seq);
if(bytes == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received conn close req from server" UNO_DBG_SUFFIX);
#endif
ret = (int)bytes;
exit_condition = true;
//close the socket and clear all fields
close(this->fd);
memset (&(this->addr), 0, sizeof(this->addr));
this->seq = 0;
this->server_seq = 0;
this->connected = 0;
this->can_broadcast = 0;
this->self_port = 0;
}
//if unknown message, ignore and continue waiting
else if (bytes == UNO_TRANSPORT_ERR) {
continue;
}
//for positive bytes, this is a data message that is to be delivered to the caller
else if (bytes > 0) {
ret = (int) (bytes - UNO_TRANSPORT_HDR_LEN);
}
//ack messages should not be caught in this function, drop them
else {
// assert (false && "this should never happen");
continue;
}
exit_condition = true;
}
return ret;
}
/**
* @brief - Sends a keepalive message to the server
*
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure, UNO_TRANSPORT_CLIENT_NOT_CONN if not connected
*/
int UnoTransportClient :: send_keepalive (void)
{
if(connected == false) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_KEEPALIVE_LEN];
data[0] = UNO_TRANSPORT_CTRL_KEEPALIVE; //command id
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &addr, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent keepalive ret=%d, fd=%d port %hu" UNO_DBG_SUFFIX, ret,
this->fd, ntohs(addr.sin_port));
#endif
return (ret==UNO_TRANSPORT_ERR) ? (UNO_TRANSPORT_ERR) : (0);
}
/**************************************************************************************************************************/
//code specific to the UnoTransportServer class
/**
* @brief Construct a new Uno Transport Server object. Does not create a socket
*
*/
UnoTransportServer :: UnoTransportServer(void)
{
//intialise all fields, don't create socket without port specified
fd = UNO_TRANSPORT_ERR;
seq = 0;
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = UNO_TRANSPORT_DFL_MAX_CONN;
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server WITHOUT socket" UNO_DBG_SUFFIX);
#endif
// client_list.reserve (max_conn);
}
/**
* @brief Construct a new Uno Transport Server object. Creates a socket with the specified port
*
* @param port - the port number of this server socket
*/
UnoTransportServer :: UnoTransportServer(uint16_t port)
{
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = UNO_TRANSPORT_DFL_MAX_CONN;
create_socket (port);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port);
#endif
seq = 0;
}
/**
* @brief Construct a new Uno Transport Server object. Creates a socket with the specified port
*
* @param port - the port number of this server socket
* @param max_connections - the max number of connections supported by this socket
*/
UnoTransportServer :: UnoTransportServer (uint16_t port, uint8_t max_connections)
{
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = max_connections;
create_socket (port);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port);
#endif
seq = 0;
}
/**
* @brief Destroy the Uno Transport Server object. Sends connection close message to all connected clients
and closes the server side socket
*
*/
UnoTransportServer :: ~UnoTransportServer(void)
{
//close the socket
if(fd != UNO_TRANSPORT_ERR) {
close (fd);
fd = UNO_TRANSPORT_ERR;
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "destroyed server" UNO_DBG_SUFFIX);
#endif
//clear other fields
seq = 0;
}
/**
* @brief Create a socket object at the specified port
*
* @param port - the port number of this server socket
* @return int - the fd number
*/
int UnoTransportServer :: create_socket (uint16_t port)
{
fd = _uno_create_server_fd (port);
if(fd == UNO_TRANSPORT_ERR) {
return fd;
}
seq = 0;
return 0;
}
/**
* @brief Receives the incoming message in the specified buffer. Does not bother the caller with the protocol specific
packets. Handles connection requests, acks, etc
*
* @param buffer - the buffer to store the incoming msg
* @param buffer_size - the size of this buffer
* @param src - optional pointer to the struct sockaddr_in object where the source address is to be filled in
* @param is_spl - reference to the bool variable that will be set if the incoming message is a spl message
* @return int - number of bytes received
*/
int UnoTransportServer :: recv_msg (void *buffer, size_t buffer_size, struct sockaddr_in *src_arg, bool &is_spl)
{
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
struct sockaddr_in src = {0,};
std::vector<struct pollfd> pfds;
ssize_t bytes;
bool exit_condition=false;
int success_count=0;
int ret;
uno_hdr hdr;
struct timespec curr_time;
uno_timer timer;
static std::list<UnoConnection>::iterator _most_stale;
struct timespec _timer_val;
while(!exit_condition) {
timer.disarm();
//clear all data structures
pfds.clear(); //this can probably be optimised
memset (&src, 0, sizeof(src));
memset (hdr_ser, 0, sizeof(hdr_ser));
//build the vector for poll
//first fd is always the server fd
pfds.push_back ({.fd = this->fd, .events = POLLIN});
//note down curr time - we use clock monotonic here because we're not bothered about the actual time
clock_gettime (CLOCK_MONOTONIC, &curr_time);
//find the connection that is going to timeout first
_most_stale = _uno_find_most_stale_connection (client_list);
if(_most_stale != client_list.end()) {
//determine the time remaining till timeout
memset (&_timer_val, 0, sizeof(_timer_val));
_uno_compute_timer_value (_most_stale->last_msg_time, keepalive_dur, curr_time, _timer_val);
timer.arm_non_recurring (_timer_val);
}
//second fd will be the timer fd - it does nothing if it is not armed, so no issue
pfds.push_back ({.fd = timer.fd, .events = POLLIN});
//add the other fd's after this
for(auto iter=this->client_list.begin(); iter!=this->client_list.end(); ++iter) {
pfds.push_back ({.fd = iter->fd, .events = POLLIN});
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "pollfd structure has %d fd's" UNO_DBG_SUFFIX, pfds.size());
#endif
//poll on this set of fd's
ret = poll (pfds.data(), pfds.size(), UNO_TRANSPORT_TIMEOUT_INFINITE);
if(ret == UNO_TRANSPORT_ERR) {
perror("poll");
exit_condition = true;
}
else if (ret == 0) {
//this must never happen since we're polling for an indefinite time period
assert (false && "This must never happen");
}
else {
//note down curr time - to minimise number of syscalls
clock_gettime (CLOCK_MONOTONIC, &curr_time);
//read from all fd's with data
success_count = 0;
int index=0;
for(auto iter=pfds.begin(); iter!=pfds.end(), success_count!=ret; index++, iter++) {
//ding ding ding, we have a winner!!!
if((iter->revents) & POLLIN) {
//check if this fd is the timer fd
if(iter->fd == timer.fd) {
assert (_most_stale != this->client_list.end());
//then close the most stale connection
_most_stale->set_close_reason (_close_reason::CLOSE_REASON_TIMEDOUT);
_uno_close_connection_requested_iter (_most_stale, client_list);
break;
}
//receive data from this fd
bytes = _uno_recv (iter->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, &src);
success_count++;
//the message must atleast by UNO_TRANSPORT_HDR_LEN bytes
if(bytes < UNO_TRANSPORT_HDR_LEN) {
//invalid msg, drop the packet
continue;
}
//deserialise the header
hdr.deserialise (hdr_ser);
//check if reliable msg
if(_uno_is_reliable_msg(hdr.cmd)) {
_uno_send_ack (this->fd, src, hdr);
}
//check if fd that's ready is the server fd
if(iter==pfds.begin()) {
bytes = _uno_process_server_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes,
this->client_list, this->keepalive_dur, src, max_conn, curr_time, is_spl);
}
//else it must be one of the client conneciton fd's
else {
//find the client in the list
auto _this_client = _find_client_in_list (this->client_list, iter->fd);
//update the last message time
memcpy (&(_this_client->last_msg_time), &curr_time, sizeof(curr_time));
//check the validity of the sequence number
if(_is_seq_valid (iter->fd, hdr.seq_id, _this_client->client_seq) == false) {
//drop the packet;
continue;
}
bytes = _uno_process_client_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes,
this->client_list, src);
}
//since our process function returns positive values if the messages are data messages
if(bytes > 0) {
ret = (int) bytes;
exit_condition = true;
if(src_arg) { memcpy (src_arg, &src, sizeof(src)); }
break;
}
} //end of if((iter->revents) & POLLIN)
} //end of for loop
} //end of else block
} //end of while(1) loop
return ret;
}
/**
* @brief Sends the given message to the specified client, if connected
*
* @param msg - void pointer to the message
* @param len - the length of the message
* @param dst - const reference to the structure containing the destination
* @return int - returns number of bytes sent on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found
in the client table, UNO_TRANSPORT_ERR on any general purpose failures
*/
int UnoTransportServer :: send_msg (const void *msg, size_t len, const struct sockaddr_in &dst)
{
if(msg==nullptr) {
return UNO_TRANSPORT_ERR;
}
if(len == 0 ) {
return len;
}
//check if we can find this destination address in the list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
//since this is a data message, no bits are to be set in the cmd_info section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
// uint8_t cmd_flags = 0;
uno_hdr hdr (seq, 0, len);
hdr.serialise (hdr_ser);
//send this header and the message
int ret = _uno_send (iter->fd, hdr_ser, msg, len, &dst, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret);
#endif
return ret;
}
/**
* @brief Sends the given message to the given client (if connected), expects an ACK from the recipient.
*
* @param msg - void pointer to the message
* @param len - length of the message
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_ERR on general failure
*/
int UnoTransportServer :: send_msg_reliable (const void *msg, size_t len, const struct sockaddr_in &dst)
{
if(msg==nullptr) {
return UNO_TRANSPORT_ERR;
}
if(len == 0 ) {
return len;
}
//check if we can find this destination address in the list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
//need to set the reliable msg bit in the cmd section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq, cmd_flags, len);
hdr.serialise (hdr_ser);
//send this header and the message
int ret = _uno_send_reliable (iter->fd, hdr_ser, msg, len, dst, &seq, UNO_TRANSPORT_REL_MAX_RETRIES,
UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret);
#endif
if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT);
_uno_close_connection_requested_iter (iter, client_list);
}
return ret;
}
/**
* @brief Sends the connection close requet to the specified client
*
* @param dst - reference to the structure containing the destination
* @return int - returns 0 on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found
in the client table, UNO_TRANSPORT_ERR on any general purpose failures
*/
int UnoTransportServer ::close_connection (struct sockaddr_in &dst)
{
//first check if we can find this client in the client list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
int ret = _uno_send_conn_close_expl (iter->fd, dst, &seq);
//close socket and cleanup
iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_SERVER);
_uno_close_connection_requested_iter (iter, client_list);
return ret;
}
/**************************************************************************************************************************/
/* STATIC FUNCTION DEFINITIONS */
/**************************************************************************************************************************/
/**
* @brief This function creates a client specific socket
*
* @param opt - the option value for SO_BROADCAST
* @return int - the fd value of the socket, returns UNO_TRANSPORT_ERR on failure
*/
static int _uno_create_client_fd (int opt)
{
struct sockaddr_in addr = {0,};
//create the socket
int fd = socket (AF_INET, SOCK_DGRAM, 0);
if(fd == -1) {
perror("socket");
return fd;
}
//set the socket as non blocking since we can use this to discard data
if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) {
perror("fcntl");
goto cleanup;
}
//set SO_BROADCAST
if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) == UNO_TRANSPORT_ERR) {
perror("setsockopt");
goto cleanup;
}
//bind to address - leave port as 0, the OS will select a random port
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_ANY);
if(bind(fd, (const struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) {
perror("bind");
goto cleanup;
}
return fd;
//if error, close the socket to avoid fd leaks
cleanup:
close(fd);
return UNO_TRANSPORT_ERR;
}
/**
* @brief This function creates a server specific socket
*
* @param port - the port to which this socket is to be bound to
* @return int - the fd of the socket, returns UNO_TRANSPORT_ERR on failure
*/
static int _uno_create_server_fd (uint16_t port)
{
struct sockaddr_in addr = {0,};
//create the socket
int fd = socket (AF_INET, SOCK_DGRAM, 0);
if(fd == UNO_TRANSPORT_ERR) {
perror("socket");
return fd;
}
//set the socket as non blocking since we can use this to discard data
if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) {
perror("fcntl");
goto cleanup;
}
//bind the socket
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_ANY);
addr.sin_port = htons (port);
if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) {
perror("bind");
goto cleanup;
}
return fd;
//close the fd before returning if failure
cleanup:
close(fd);
return UNO_TRANSPORT_ERR;
}
/**
* @brief THe local function for sending out a message with header and buffef, supports null buffer
*
* @param fd - The fd through which this has to be sent
* @param hdr - uint8_t pointer to the structure containing the fixed length header
* @param msg - the const void pointer to the buffer containing the message
* @param len - the length of the message
* @param dst - pointer to the struct containing the destination
* @param seq - optional pointer to the uint16_t variable tracking the sequence id, will be incremented on successful send
* @return ssize_t - number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq)
{
//initilase the io vector with the hdr and then the message
//unfortunately, we need a const_cast here because of the way the sendmsg() API is.
size_t iov_len = (msg==NULL) ? (1) : (2);
//prepare the array of vectors, 1st one being the header, followed by the message
struct iovec iov[] = { { .iov_base = hdr,
.iov_len = UNO_TRANSPORT_HDR_LEN},
{ .iov_base = const_cast<void*>(msg),
.iov_len = len},
};
//add these vectors to the message
struct msghdr msg_hdr = { .msg_name = (void*)dst,
.msg_namelen= sizeof(*dst),
.msg_iov = iov,
.msg_iovlen = iov_len,
};
ssize_t ret = sendmsg (fd, &msg_hdr, 0);
if(ret == UNO_TRANSPORT_ERR) {perror("sendmsg");}
else {
//increment the sequence number, if required
if(seq) (*seq)++;
}
return ret;
}
/**
* @brief Waits for the specified number of milliseconds to receive the message. uses poll() for timeout.
uses _uno_recv() for the actual socket recv
*
* @param fd - the fd through which the message is to be received
* @param hdr - pointer to the buffer where the header is to be filled.
* @param buffer - the buffer where the message is to be stored
* @param buffer_size - the size of the provided buffer
* @param flags - the syscall specific flags that are to be passed to _uno_recv()
* @param src - the optional struct sockaddr_in where the source address is to be stored
* @param to_ms - the timeout in milliseconds
* @return ssize_t - returns the number of bytes received if successful, 0 if timedout, UNO_TRANSPORT_ERR if failed
*/
static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms)
{
int ret;
if(to_ms == 0) {
//since it is a non blocking fd, if there is no data, the call will exit immediately
ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src);
}
else {
//poll on the specified fd
struct pollfd pfd = {.fd = fd, .events = POLLIN};
ret = poll (&pfd, 1, to_ms);
if(ret == UNO_TRANSPORT_ERR) {
//this must never happen
perror("poll");
return ret;
}
//data is ready to be read
else if (ret>0) {
ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src);
}
}
return ret;
}
/**
* @brief Receives the message into the given header buffer and message buffer provided using recvmsg()
*
* @param fd - the fd through which the data is to be received
* @param hdr - uint8_t pointer to the buffer where the fixed length header is to be received
* @param buffer - the buffer where the mesasge is to be received
* @param buffer_size - the size of the message buffer
* @param flags - flags to be passed to recvmsg()
* @param src - optional pointer to the struct sockaddr_in where the source address is to be filled
* @return ssize_t - returns number of bytes received if successful, UNO_TRANSPORT_ERR if failed
*/
static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src)
{
assert (fd > 2); //since fd's 0,1,2 are reserved
struct iovec iov[] = {{.iov_base = hdr, .iov_len = UNO_TRANSPORT_HDR_LEN}, {.iov_base = buffer, .iov_len = buffer_size}};
struct msghdr msg = { .msg_name = (void*)src,
.msg_namelen= sizeof(*src),
.msg_iov = iov,
.msg_iovlen = 2,
};
ssize_t ret = recvmsg (fd, &msg, flags);
if(ret == UNO_TRANSPORT_ERR) {
perror("recvmsg");
}
return ret;
}
/**
* @brief Returns the enum class value of _uno_msg_type by examining the cmd field of the header
*
* @param cmd The uint8_t value of the cmd_flags
* @return _uno_msg_type - the type of message that this is
*/
static _uno_msg_type _uno_get_msg_type (uint8_t cmd)
{
_uno_msg_type ret = _uno_msg_type :: UNO_MSG_UNKNOWN;
//check ACK bit
if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_ACK_MSG)) {
ret = _uno_msg_type :: UNO_MSG_ACK;
}
//check control bit
else if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) {
//ensure that spl bit is not set
if(!(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG))) {
ret = _uno_msg_type :: UNO_MSG_CTRL;
}
}
//check spl bit
else if (UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG)) {
//ensure that control bit is not set
if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) {
ret = _uno_msg_type :: UNO_MSG_SPL;
}
}
else {
ret = _uno_msg_type :: UNO_MSG_DATA;
}
assert (ret != _uno_msg_type::UNO_MSG_UNKNOWN);
return ret;
}
/**
* @brief Creates a new connection in the client list, or sends a server full message
*
* @param fd - The fd of the server
* @param client_list - reference to the client list
* @param src - reference to the sockaddr_in struct containing the source address
* @param hdr - reference to the structure containing the header
* @param ka_dur - the keepalive duration that is to be sent to the client
* @param max_conn - the max connections supported
* @param curr_time - const reference to the struct timespec containing this message's time
*/
static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src,
uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time)
{
bool found = false;
int index = 0;
//check if client already exists in the list - if so reuse the connection
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter, index++) {
if(memcmp(&src, &(*iter), sizeof(src)) == 0) {
found = true;
break;
}
}
if(found) {
//TODO
//1. create a new connection and destroy the old one?
//2. reuse the old connection
}
else {
//add the client if the server has space
if(client_list.size() < max_conn) {
//the constructor will send the conection response
client_list.emplace_back (fd, src, hdr, ka_dur, curr_time);
}
else {
//send a server full response
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "sending conn refused msg" PRIu8 UNO_DBG_SUFFIX);
#endif
_uno_send_server_full_rsp (fd, src, hdr);
}
}
}
/**
* @brief returns the port number of the given fd, in host byte order
*
* @param fd - the fd whose port needs to be determined
* @return int - the port number if successful, UNO_TRANSPORT_ERR if failed
*/
static int _uno_get_port_from_fd (int fd)
{
struct sockaddr_in addr = {0,};
socklen_t len = sizeof(addr);
int ret = UNO_TRANSPORT_ERR;
if(getsockname(fd, (struct sockaddr*)&addr, &len) == UNO_TRANSPORT_ERR) {
perror("getsockname");
}
else {
ret = (int)ntohs(addr.sin_port);
}
return ret;
}
/**
* @brief processes incoming messages addressed to the server (not connections)
*
* @param fd - the fd of the server
* @param hdr - rerference to the struct containing the header
* @param buffer - the buffer containing the message
* @param bytes - the length of the message (as returned by _uno_recv())
* @param client_list - reference to the client list of this server
* @param ka_dur - the keepalive duration of this server
* @param src - const reference to the struct containing the source address
* @param max_conn - max connections supported by this server
* @param is_spl - reference to the variable that will be set if the incoming msg is a spl message
* @return int - returns
-> a positive number is a data message and is intended for the caller (spl message)
-> 0 if it is a control message intended for the server, and NOT the caller
-> UNO_TRANSPORT_ERR if failed
*/
static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes,
std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src,
uint8_t max_conn, const struct timespec &curr_time, bool &is_spl)
{
int ret = 0;
is_spl = false;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//if
switch(buffer[1]) {
//process connection open request
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
_create_new_connection (fd, client_list, src, hdr, ka_dur, max_conn, curr_time);
ret = 0;
break;
//close connection request must not be coming to the server fd
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
break;
case _uno_msg_type :: UNO_MSG_DATA:
break;
//spl msg is a message from an unconnected client that is intended for the caller
case _uno_msg_type :: UNO_MSG_SPL:
is_spl = true;
ret = hdr.msg_len;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
break;
}
//clear the buffer since it is the caller's buffer, not our own
//bury the evidence
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief processes incoming messages addressed to the connection (not the server)
*
* @param fd - the fd of the connection
* @param hdr - reference to the struct containing the header
* @param buffer - the buffer containing the message
* @param bytes - the length of the message
* @param client_list - reference to the list of clients of this server
* @param src - const reference to the struct containing the source address
* @return int - returns
-> a positive number is a data message and is intended for the caller
-> 0 if it is a control message intended for the server/connection, and NOT the caller
-> UNO_TRANSPORT_ERR if failed
*/
static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list,
const struct sockaddr_in &src)
{
int ret = 0;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//check the options
switch(buffer[1]) {
//drop connection request since this is a connection fd, not the server fd
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
ret = UNO_TRANSPORT_ERR;
break;
//process the close connection request from the client
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received close connection for fd=%d" UNO_DBG_SUFFIX, fd);
#endif
_uno_close_connection_requested (fd, client_list);
ret = 0;
break;
//drop the below connection requests since these modes are reserved from server
//to client
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//keepalive message, don't do anything, just update the last msg time
case UNO_TRANSPORT_CTRL_KEEPALIVE:
ret = 0;
break;
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
ret = UNO_TRANSPORT_ERR;
break;
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
break;
//we need to pass the data message to the caller
case _uno_msg_type :: UNO_MSG_DATA:
ret = (int) hdr.msg_len;
break;
//spl messages are connectionless messages that are only supported in the server fd
case _uno_msg_type :: UNO_MSG_SPL:
ret = UNO_TRANSPORT_ERR;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
break;
}
//clear the buffer since it is the caller's buffer, not our own
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief Send a connection response message to the client saying that the server is full
*
* @param fd - fd through which the message is to be sent
* @param src - const reference to the sockaddr_in struct containing the source address
* @param hdr - reference to the header structure
* @return int - returns number of bytes sent if successful, UNO_TRANSPORT_ERR if not successful
*/
static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr)
{
hdr.msg_len = 1;
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
hdr.serialise(hdr_ser);
uint8_t data = UNO_TRANSPORT_CTRL_CONN_RSP;
return _uno_send (fd, hdr_ser, &data, 1, &src, NULL);
}
/**
* @brief Send a connection close message from the client. Called in destructor
*
* @param fd - The fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the uint16_t variable tracking the sequence number
* @return int
*/
static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send_reliable (fd, hdr_ser, data, sizeof(data), dst, seq,
UNO_TRANSPORT_REL_MAX_RETRIES, UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "send conn close cmd fd=%d, ret=%d" UNO_DBG_SUFFIX, fd, ret);
#endif
return ret;
}
/**
* @brief closes the connection of the given fd when a close request is received
*
* @param fd - the fd of the connection to be closexd
* @param client_list - reference to the client list
*/
static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list)
{
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(fd == iter->fd) {
//found the client in the list
iter->set_close_reason (_close_reason :: CLOSE_REASON_REQUESTED_BY_CLIENT);
_uno_close_connection_requested_iter (iter, client_list);
return;
}
}
}
/**
* @brief closes the connection at the given iterator when a close request is received
*
* @param iter iterator of the node in the client list
* @param client_list reference to the client list
*/
static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list)
{
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "closing conn of fd=%d" UNO_DBG_SUFFIX, iter->fd);
#endif
// iter->connected = false;
client_list.erase (iter);
}
/**
* @brief searches the list by IPv4 addr and returns the iterator of the node where the required client info is stored
*
* @param client_list reference to the client list
* @param dst reference to the struct containing the IPv4 address
* @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found
*/
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list,
const struct sockaddr_in &dst)
{
auto ret = client_list.end();
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(memcmp(&dst, &(iter->cli_addr), sizeof(dst)) == 0) {
ret = iter;
break;
}
}
return ret;
}
/**
* @brief searches the list by fd and returns the iterator of the node where the required client's info is stored
*
* @param client_list - reference to the client list
* @param fd - fd of the client to be found
* @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found
*/
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd)
{
auto ret = client_list.end();
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(iter->fd == fd) {
ret = iter;
break;
}
}
return ret;
}
/**
* @brief processes the received message on the client side
*
* @param hdr - reference to the struct containing the header
* @param buffer - pointer to the buffer containing the message
* @param bytes - number of bytes of the total message (including header, arithmetic will be handled here)
* @param server_seq - reference to the variable tracking the sequence numbers used by the server
* @return int - returns
-> positive number (number of bytes) if the message is a data message and should be passed to
the caller
-> 0 if the message is a control message and is not relevant to the caller
-> UNO_TRANSPORT_CONN_CLOSE_RECVD if the server has closed the connection
-> UNO_TRANSPORT_ERR for any other failure case
*/
static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq)
{
int ret = 0;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//if
switch(buffer[1]) {
//drop connection request since this is a client, not a server (we don't take connections here)
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
ret = UNO_TRANSPORT_ERR;
break;
//process the close connection request - the server wants to close the connection
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
ret = UNO_TRANSPORT_CONN_CLOSE_RECVD;
break;
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
//ACK packet, we coo'
break;
//we need to pass the data message to the caller
case _uno_msg_type :: UNO_MSG_DATA:
ret = (int) hdr.msg_len;
break;
//spl messages are connectionless messages that are only supported in the server fd
case _uno_msg_type :: UNO_MSG_SPL:
ret = UNO_TRANSPORT_ERR;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
ret = UNO_TRANSPORT_ERR;
break;
}
//clear the buffer since it is the caller's buffer, not our own
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief function that performs reliable send according to this protocol
*
* @param fd - the fd through which the message is to be sent and the ACK is to be received
* @param hdr_ser - pointer to the buffer containing the fixed length header
* @param msg - pointer to the buffer containing the message
* @param len - length of the message
* @param dst - reference to the struct containing the IPv4 address of the destination
* @param seq - optional pointer to the variable that is being used to track the sequence number of the sender
* @param max_retries - the max retries if ACK is not received
* @param retry_interval - the time to wait before every retry
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_CONN_CLOSE_RECVD if conn close msg is delivered
-> UNO_TRANSPORT_ERR on general failure
*/
static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len,
const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval)
{
//make sure that the reliable msg bit is set
assert (_uno_is_reliable_msg(hdr_ser[UNO_TRANSPORT_HDR_CMD_POS])==true);
int ret = 0;
uint8_t hdr[UNO_TRANSPORT_HDR_LEN];
struct sockaddr_in src;
int temp;
uint8_t data[2];
//loop and perform all attempts
for(int i=0; i<max_retries; i++) {
memset (hdr, 0, sizeof(hdr));
memset (&src, 0, sizeof(src));
//send out the message
temp = _uno_send (fd, hdr_ser, msg, len, &dst, NULL);
if(temp == UNO_TRANSPORT_ERR) {
ret = temp;
break;
}
//recv the message
temp = _uno_timed_recv (fd, hdr, data, sizeof(data), MSG_WAITALL, &src, retry_interval);
if(temp == UNO_TRANSPORT_ERR) {
break;
}
//if we received a response, check the response
if(temp > 0) {
//check if it is an ack response
if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_ACK) {
//TODO - validate seq id and msg len
//successful ack, set ret as temp
ret = temp;
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received ack msg for seq=%" PRIu16 UNO_DBG_SUFFIX,(*seq)-1);
#endif
break;
}
//else check if this is a connection close msg
if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_CTRL) {
if(data[0] == UNO_TRANSPORT_CTRL_CONN_CLOSED) {
ret = UNO_TRANSPORT_CONN_CLOSE_RECVD;
break;
}
}
}
//else increment retry count and try again
hdr_ser[UNO_TRANSPORT_HDR_RC_POS]++;
} //end of for loop
//update the sequence number if the send was successful (regardless of ACK)
if(ret != UNO_TRANSPORT_ERR && (seq!=nullptr)) {
(*seq)++;
}
return ret;
}
/**
* @brief Checks if the given cmd_flags indicates that this message is a reliable msg
*
* @param cmd_flags The 8 bit value containing the cmd_flags
* @return - self explanatory
*/
static bool _uno_is_reliable_msg (uint8_t cmd_flags)
{
if(UNO_IS_BIT_SET(cmd_flags,UNO_TRANSPORT_CMD_RELIABLE_MSG)) return true;
else return false;
}
/**
* @brief Sends the ACK to the specified node for the given header
*
* @param fd - the fd through which the data is to be sent
* @param dst - const reference to the struct containing the destination IPv4 address
* @param hdr - reference to the struct containing the header
* @return int - number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr)
{
//ack is the same header, but with msg len as 0 and ack bit as true
//and with no data
uno_hdr ack = hdr;
ack.msg_len = 0;
//make sure that the ACK bit is set
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
ack.cmd = UNO_SET_BIT(ack.cmd, UNO_TRANSPORT_CMD_ACK_MSG);
ack.serialise (hdr_ser);
//send out the message
int ret = _uno_send (fd, hdr_ser, NULL, 0, &dst, NULL);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received reliable msg at fd=%d of len=%" PRIu16 ", sending ack ret= %d" UNO_DBG_SUFFIX,
fd, hdr.msg_len, ret );
#endif
return ret;
}
/**
* @brief Checks if the sequence number is valid
*
* @param fd - the fd that is involved in this transaction (only for logging purpose)
* @param inc_seq - the incoming sequence number
* @param saved_seq - reference to the last saved sequence number (will be updated if this message is valid)
* @return - self explanatory
*/
static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq)
{
//if inc_seq is UNO_SEQ_ID_RESET (0), that means that the device is new or the sequence number has overflown
if(inc_seq == UNO_SEQ_ID_RESET) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "WARN::seq id has been overflown/reset for fd=%d" UNO_DBG_SUFFIX,
fd);
#endif
saved_seq = inc_seq;
return true;
}
//incoming must always be greater than saved
else if(inc_seq > saved_seq) {
#ifdef UNO_TRANSPORT_DEBUG
if((inc_seq-saved_seq) > 1) {
fprintf (stderr, UNO_DBG_PREFIX "WARN::possible lost packetsinc_seq-saved_seq=%" PRIu16 " for fd=%d"
UNO_DBG_SUFFIX, inc_seq-saved_seq, fd);
}
#endif
saved_seq = inc_seq;
return true;
}
else {
//invalid sequence
#ifdef UNO_TRANSPORT_DEBUG
if(inc_seq == saved_seq) {
fprintf (stderr, UNO_DBG_PREFIX "dropping duplicate packet with seq=%" PRIu16 " for fd=%d" UNO_DBG_SUFFIX,
inc_seq, fd);
}
else {
fprintf (stderr, UNO_DBG_PREFIX "dropping out of order packet with seq=%" PRIu16 " for fd=%d"
" expected=%" PRIu16 UNO_DBG_SUFFIX,
inc_seq, fd, saved_seq+1);
}
#endif
return false;
}
}
/**
* @brief - Sends an explicit connection closure message from the server (caller asked for connection closure)
*
* @param fd - the fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided
* @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure
*/
static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent explicit connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
fd, ntohs(dst.sin_port));
#endif
return ret;
}
/**
* @brief - Sends an explicit connection timedout message from the server (no data in the specified keepalive duration)
*
* @param fd - the fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided
* @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure
*/
static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent timedout connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
fd, ntohs(dst.sin_port));
#endif
return ret;
}
/**
* @brief - linearly searches through the list and finds the connection that is set to timeout the earliest
*
* @param client_list - reference to the client list
* @return std::list<UnoConnection>::iterator - returns an iterator at the position in the client list
*/
static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list)
{
if(client_list.empty()) {
return client_list.end();
}
//initialise the oldest time
struct timeval oldest;
auto ret = client_list.begin();
memcpy (&oldest, &(ret->last_msg_time), sizeof(oldest));
//skip the first item since it is already stored in oldest
auto iter=client_list.begin();
++iter;
//loop through the list
for(; iter!=client_list.end(); ++iter) {
//compare seconds field
if(iter->last_msg_time.tv_sec < oldest.tv_sec) {
//update oldest and ret
memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest));
ret = iter;
}
//if seconds are equal, compare nanoseconds field
else if(iter->last_msg_time.tv_nsec < iter->last_msg_time.tv_nsec) {
//update oldest and ret
memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest));
ret = iter;
}
//else ignore
else {
; //left here for readability, the compiler will optimise this out
}
}
return ret;
}
/**
* @brief - computes the difference between 2 timespec structs. performs (end-start)
*
* @param start - const reference to the timespec containing the start time
* @param end - const reference to the timespec containing the end time.
* @param result - reference to the struct where the result of the difference will be stored
*/
static void __uno_timespec_diff (const struct timespec &start, const struct timespec &end, struct timespec &result)
{
assert (end.tv_sec >= start.tv_sec);
//assumes end is greater than start, does not check, it is the caller's responsibility to ensure this
if(end.tv_nsec < start.tv_nsec) {
assert (end.tv_sec > start.tv_sec);
result.tv_sec = end.tv_sec - start.tv_sec - 1;
result.tv_nsec = end.tv_nsec - start.tv_nsec + UNO_SEC_TO_NS(1);
}
else {
result.tv_sec = end.tv_sec - start.tv_sec;
result.tv_nsec = end.tv_nsec - start.tv_nsec;
}
}
/**
* @brief - computes the sum between 2 timespec structs
*
* @param start - const reference to the timespec containing the start time
* @param end - const reference to the timespec containing the end time
* @param result - reference to the struct where the result will be stored
*/
static void __uno_timespec_sum (const struct timespec &start, const struct timespec &end, struct timespec &result)
{
result.tv_sec = start.tv_sec + end.tv_sec;
result.tv_nsec = start.tv_nsec + end.tv_nsec;
//now check for "overflow", if result.tv_nsec is greater than 10^9
if(result.tv_nsec > UNO_SEC_TO_NS(1)) {
result.tv_sec++;
result.tv_nsec = result.tv_nsec % UNO_SEC_TO_NS(1);
}
}
/**
* @brief - computes the value to be passed to timerfd_settime given the last message time, the keepalive duration (in ms),
the current time
*
* @param last_msg_time - const reference to the struct containing the last message time
* @param keepalive_dur_ms - the expected keepalive duration (in milliseconds)
* @param curr_time - const reference to the timespec containing the curr time
* @param timer_val - the timespec where the computed timer value is to be written
*/
static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur_ms,
const struct timespec &curr_time, struct timespec &timer_val)
{
//transform keepalive_dur_ms to struct timespec
struct timespec _keep_alive = {0,};
_keep_alive.tv_sec = UNO_MS_TO_SEC(keepalive_dur_ms);
if(keepalive_dur_ms % 1000) {
_keep_alive.tv_nsec = UNO_MS_TO_NS(keepalive_dur_ms % 1000);
}
//compute expiry time
struct timespec _expiry_time = {0,};
__uno_timespec_sum (last_msg_time, _keep_alive, _expiry_time);
//now the timervalue is the difference between _expiry_time and curr_time
__uno_timespec_diff (curr_time, _expiry_time, timer_val);
} | 39.094464 | 135 | 0.620371 | ashwin-nat |
08bff7998f296020b5eae82d91978a16d01d69da | 1,533 | cpp | C++ | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "./INCLUDE/LKH.h"
/*
* The ReadPenalties function attempts to read node penalties (Pi-values)
* from file.
*
* The first line of the file contains the number of nodes.
*
* Each of the following lines is of the form
* <integer> <integer>
* where the first integer is a node number, and the second integer
* is the Pi-value associated with the node.
*
* If reading succeeds, the function returns 1; otherwise 0.
*
* The function is called from the CreateCandidateSet function.
*/
namespace LKH {
static thread_local int PenaltiesRead = 0;
void LKHAlg::freeReadPenalties()
{
PenaltiesRead = 0;
}
int LKHAlg::ReadPenalties()
{
int i, Id;
Node *Na, *Nb = 0;
if (PiFileName == 0)
return 0;
if (PenaltiesRead || !strcmp(PiFileName, "0"))
return PenaltiesRead = 1;
if (!(PiFile = fopen(PiFileName, "r")))
return 0;
if (TraceLevel >= 1)
printff("Reading PI_FILE: \"%s\" ... ", PiFileName);
fscanint(PiFile, &i);
if (i != Dimension)
eprintf("PI_FILE \"%s\" does not match problem", PiFileName);
fscanint(PiFile, &Id);
assert(Id >= 1 && Id <= Dimension);
FirstNode = Na = &NodeSet[Id];
fscanint(PiFile, &Na->Pi);
for (i = 2; i <= Dimension; i++) {
fscanint(PiFile, &Id);
assert(Id >= 1 && Id <= Dimension);
Nb = &NodeSet[Id];
fscanint(PiFile, &Nb->Pi);
Nb->Pred = Na;
Na->Suc = Nb;
Na = Nb;
}
FirstNode->Pred = Nb;
Nb->Suc = FirstNode;
fclose(PiFile);
if (TraceLevel >= 1)
printff("done\n");
return PenaltiesRead = 1;
}
} | 24.333333 | 73 | 0.629485 | BaiChunhui-9803 |
08c2155ebd781021501c4901e5fec5cbdd2518dd | 1,511 | cpp | C++ | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 2,777 | 2015-01-02T17:20:34.000Z | 2021-10-20T12:34:27.000Z | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 3,537 | 2015-01-01T00:51:03.000Z | 2021-10-20T07:35:33.000Z | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 774 | 2015-01-07T19:44:39.000Z | 2021-10-19T18:10:38.000Z | #include <QTest>
#include "TestUtil.h"
#include "settings/INIFile.h"
class IniFileTest : public QObject
{
Q_OBJECT
private
slots:
void initTestCase()
{
}
void cleanupTestCase()
{
}
void test_Escape_data()
{
QTest::addColumn<QString>("through");
QTest::newRow("unix path") << "/abc/def/ghi/jkl";
QTest::newRow("windows path") << "C:\\Program files\\terrible\\name\\of something\\";
QTest::newRow("Plain text") << "Lorem ipsum dolor sit amet.";
QTest::newRow("Escape sequences") << "Lorem\n\t\n\\n\\tAAZ\nipsum dolor\n\nsit amet.";
QTest::newRow("Escape sequences 2") << "\"\n\n\"";
QTest::newRow("Hashtags") << "some data#something";
}
void test_Escape()
{
QFETCH(QString, through);
QString there = INIFile::escape(through);
QString back = INIFile::unescape(there);
QCOMPARE(back, through);
}
void test_SaveLoad()
{
QString a = "a";
QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\#thisIsNotAComment";
QString filename = "test_SaveLoad.ini";
// save
INIFile f;
f.set("a", a);
f.set("b", b);
f.saveFile(filename);
// load
INIFile f2;
f2.loadFile(filename);
QCOMPARE(a, f2.get("a","NOT SET").toString());
QCOMPARE(b, f2.get("b","NOT SET").toString());
}
};
QTEST_GUILESS_MAIN(IniFileTest)
#include "INIFile_test.moc"
| 23.609375 | 104 | 0.568498 | Spacc-Inc |
08c3d0fa4ab85ad2966db26ba479f8b6eb3dadb8 | 3,393 | cpp | C++ | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null |
#include "Texture.hpp"
#include <algorithm>
#include <utility>
#include <iostream>
#include <string>
#include <cassert>
#include <array>
#include <SFML/Graphics.hpp> // For sf::Image
#include "glm.hpp"
#include "GLHelpers.h"
using namespace en;
namespace {
int getNumMipmaps(Texture::Size size) {
int i = 1;
while (true) {
size.x = std::max(1, size.x / 2);
size.y = std::max(1, size.y / 2);
if (size.x == 1 && size.y == 1)
break;
++i;
}
return i;
}
}
Texture::Texture(const std::string& filename, GLint internalFormat) {
// Load from file using sf::Image, then put the data in an openGL buffer.
sf::Image image;
if (!image.loadFromFile(filename))
return;
auto temp = image.getSize();
m_size = {temp.x, temp.y};
// 0, 0 in sf::Image is top left, but openGL expects 0,0 to be bottom left, flip to compensate.
image.flipVertically();
glCheckError();
glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_2D, m_id);
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
}
glBindTexture(GL_TEXTURE_2D, 0);
m_kind = Kind::Texture2D;
}
Texture::Texture(const std::array<std::string, 6>& cubeSidePaths, GLint internalFormat) {
std::array<sf::Image, 6> images;
for (GLuint i = 0; i < images.size(); ++i)
if (!images[i].loadFromFile(cubeSidePaths[i]))
return;
glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_id);
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
for (GLuint i = 0; i < 6; ++i) {
const sf::Image& image = images[i];
auto temp = image.getSize();
m_size = {temp.x, temp.y};
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
m_kind = Kind::TextureCube;
}
Texture::Texture(Texture&& other) noexcept : m_id(std::exchange(other.m_id, 0)) {}
Texture& Texture::operator=(Texture&& other) noexcept {
m_id = std::exchange(other.m_id, 0);
return *this;
}
Texture::~Texture() {
glDeleteTextures(1, &m_id);
}
GLuint Texture::getId() const {
return m_id;
}
bool Texture::isValid() const {
return m_id != 0 && m_kind != Kind::None;
}
Texture::Kind Texture::getKind() const {
return m_kind;
}
Texture::Size Texture::getSize() const {
return m_size;
}
| 27.144 | 153 | 0.625995 | maksmaisak |
c09718d963b239802830ca2ce22bfbd41913313c | 13,342 | cpp | C++ | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <functional>
#include <math.h>
#include "cost_functions.hpp"
#include "vehicle.hpp"
#include "path.hpp"
#include "state_machine.hpp"
#include "collision_detector.hpp"
#include "utils.hpp"
double speedCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
double avg_speed = path.averageSpeed(CONTROLLER_UPDATE_RATE_SECONDS);
double epislon = 0.001;
if (avg_speed > MAX_SPEED_METERS_PER_SECOND + epislon)
{
return weight;
}
double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed) / MAX_SPEED_METERS_PER_SECOND;
// double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed);
// double diff = avg_speed / MAX_SPEED_METERS_PER_SECOND;
// cout << "**** Speed diff " << diff << endl;
return weight * (1 - exp(-abs(diff)));
}
double centerOfLaneDistCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
double final_d = path.m_d[path.m_d.size() - 1];
int lane = calculateLane(final_d, DEFAULT_LANE_SPACING, DEFAULT_LANE_INSIDE_OFFSET);
int lane_center = getLaneCenterFrenet(lane);
double diff = lane_center - final_d;
return weight * (1 - exp(-abs(diff)));
}
double laneChangeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
if (state.current_lane == state.future_lane)
{
// No penalty if staying on the same lane
return 0.0;
}
// Weight penalty if switching lane
return weight;
}
/**
* @brief Cost function that increases the penalty the closer the car ahead is from the
* ego vehicle
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double
*/
double distanceToClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// We are switching lanes and this is not a cancellable operation
// if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT)
// {
// return 0;
// }
// Find closest car ahead and get distance
if (!ego.m_isInLane)
{
return weight;
}
// Find all vehicles ahead on the current lane
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
// TODO We may also want to take speed into account
double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance) / VEHICLE_DISTANCE_THRESHOLD_METERS;
return weight * (1 - exp(-abs(diff)));
}
double longitudinalDistanceToClosestAdjacentCarFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// This cost function only applies to lane changes
if (state.current_lane == state.future_lane && state.current_lane == ego.m_lane)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : others)
{
if (v.m_isInLane && v.m_lane == state.future_lane)
{
// Other car is on different lane
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
}
// cout << "**************** DISTANCE ADJACENT LANE = " << min_distance << endl;
double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance);
return weight * (1 - exp(-abs(diff)));
}
double distanceToClosestCarAheadFutureLaneCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// Since we are not planning to switch lanes there is no cost in this case
if (state.d_state == LateralState::STAY_IN_LANE)
{
return 0.0;
// return distanceToClosestCarAheadCostFunction(ego, others, path, state, weight);
}
// Find closest car ahead and get distance
if (!ego.m_isInLane)
{
return weight;
}
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
double min_distance = LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
double diff_ahead = (LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS;
std::vector<Vehicle> behind = ego.behind(others, state.future_lane);
min_distance = LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : behind)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
double diff_behind = (LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS;
// cout << "*** DISTANCE RATIO AHEAD = " << diff_ahead << ", DISTANCE RATIO BEHIND = " << diff_behind << endl;
double diff = diff_behind + diff_ahead;
return weight * (1 - exp(-diff));
}
/**
* @brief Computes a cost function that penalises the future lane depending
* on the average speed of all vehicles ahead
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double
*/
double averageLaneSpeedDiffCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// We are switching lanes and this is not a cancellable operation
if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT)
{
return 0;
}
// Not in lane so doesn't count
if (!ego.m_isInLane)
{
return 0.0;
}
// Find all vehicles ahead
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double speed_avg = 0.0;
int count = 0;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
// Only look a bit ahead
if (dist <= VEHICLE_DISTANCE_THRESHOLD_METERS * 1.5)
{
speed_avg += v.getSpeed();
++count;
}
}
if (count == 0)
{
return 0.0;
}
speed_avg /= (double)count;
cout << "** Speed average of lane " << state.future_lane << ": " << speed_avg << endl;
// It's OK if the future lane is very fast... as long as ego itself keeps within the speed limits
if (speed_avg >= MAX_SPEED_METERS_PER_SECOND)
{
return 0.0;
}
// This time, let's get a ratio as it will produce a smoother result
double diff = (MAX_SPEED_METERS_PER_SECOND - speed_avg) / MAX_SPEED_METERS_PER_SECOND;
return weight * (1 - exp(-abs(diff)));
}
double speedDifferenceWithClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return 0.0;
}
std::vector<Vehicle> ahead = ego.ahead(others, state.current_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : ahead)
{
// Other car must be ahead in the same lane
if (v.m_s > ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
double v_speed = closest_vehicle.getSpeed();
// cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed
// << " other vehicle (lane=" << closest_vehicle.lane << ") : " << v_speed << endl;
// If ego is going faster than the vehicle ahead then we want to penalise it because it could lead to a collision
if (ego_speed > v_speed)
{
return weight;
}
// Otherwise we just want ego to match the speed of the vehicle ahead
double diff = v_speed - ego_speed;
return weight * (1 - exp(-abs(diff)));
}
// TODO Compute the average speed of lanes
double lanesAverageForwardSpeedCarsAhead(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return weight;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : others)
{
// Other car must be ahead in the same lane
if (v.m_isInLane && v.m_lane == state.future_lane && v.m_s > ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
double v_speed = closest_vehicle.getSpeed();
// cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed
// << " other vehicle (lane=" << closest_vehicle.lane << ") : " << closest_vehicle.getSpeed() << endl;
double diff = v_speed - ego_speed;
return weight * (1 - exp(-abs(diff)));
}
double collisionTimeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return weight;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : others)
{
if (v.m_isInLane && (v.m_lane == state.current_lane || v.m_lane == state.future_lane) && v.m_s >= ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
Collision collision = predictCollision(path, closest_vehicle, CONTROLLER_UPDATE_RATE_SECONDS);
if (!collision.willCollide)
{
// If no collision foreseen then don't penalize
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
// cout << "** Collision with vehicle at timestep = " << collision.collision_timestep << endl;
// Collision is far away so can be ignored for now
if (collision.collision_timestep > COLLISION_MAX_TIMESTEP_THRESHOLD)
{
return 0.0;
}
double speed_ratio = ego_speed / MAX_SPEED_METERS_PER_SECOND;
double timestep_ratio = (COLLISION_MAX_TIMESTEP_THRESHOLD - collision.collision_timestep) / COLLISION_MAX_TIMESTEP_THRESHOLD;
cout << "*** SPEED RATIO = " << speed_ratio << endl;
cout << "*** TIMESTEP RATIO = " << timestep_ratio << endl;
// double diff = 75 - (collision.collision_timestep + 5 * speed_ratio);
double diff = speed_ratio + timestep_ratio;
cout << "*** TIMESTEP + SPEED RATIO = " << diff << endl;
// Otherwise penalize as a factor of the time to collision - the further away in time the better
return weight * (1 - exp(-abs(diff)));
}
/**
* @brief Measures the distance to the goal at the end of our path
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double the distance to the goal at the end of our path
*/
double futureDistanceToGoalCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
int traj_size = path.size();
double diff = MAX_TRACK_S - path.m_s[traj_size - 1];
// cout << "** DISTANCE TO GOAL = " << diff << endl;
return weight * (1 - exp(-abs(diff / MAX_TRACK_S)));
} | 31.766667 | 150 | 0.625019 | codyreading |
c0976169ad487a34974c52771dc1de412c683277 | 1,043 | hpp | C++ | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | 4 | 2018-12-21T06:57:25.000Z | 2020-07-09T09:06:38.000Z | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | class Object0 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-4.32715,1.41943,0};dir=282.158;};
class Object1 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={4.41309,1.22168,0};dir=261.111;};
class Object2 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={5.28711,-4.24902,0};dir=261.111;};
class Object3 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-5.51807,-4.05078,0};dir=282.158;};
class Object4 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-2.09058,5.51855,0};dir=0.640371;};
class Object5 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-5.73682,2.41602,0};dir=283.253;};
class Object6 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={5.40674,5.48145,0};dir=79.4694;};
class Object7 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={2.37256,6.85742,0};dir=181.16;};
class Object8 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={6.73804,-2.20117,0};dir=79.4694;};
class Object9 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-7.64673,-5.54297,0};dir=283.253;}; | 104.3 | 105 | 0.714286 | Braincrushy |
c09a64bc764a0ee7b849dc5b95e85a29fcab89c3 | 2,760 | ipp | C++ | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 459 | 2016-03-16T04:11:37.000Z | 2022-03-31T08:05:21.000Z | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 2 | 2016-08-08T18:26:27.000Z | 2017-05-08T23:42:22.000Z | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 47 | 2016-05-31T15:55:52.000Z | 2022-03-28T14:49:40.000Z | // File implement/oglplus/enums/memory_barrier_bit_names.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/memory_barrier_bit.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 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
//
namespace enums {
OGLPLUS_LIB_FUNC StrCRef ValueName_(
MemoryBarrierBit*,
GLbitfield value
)
#if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \
!defined(OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT)
#define OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT
{
switch(value)
{
#if defined GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT
case GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT: return StrCRef("VERTEX_ATTRIB_ARRAY_BARRIER_BIT");
#endif
#if defined GL_ELEMENT_ARRAY_BARRIER_BIT
case GL_ELEMENT_ARRAY_BARRIER_BIT: return StrCRef("ELEMENT_ARRAY_BARRIER_BIT");
#endif
#if defined GL_UNIFORM_BARRIER_BIT
case GL_UNIFORM_BARRIER_BIT: return StrCRef("UNIFORM_BARRIER_BIT");
#endif
#if defined GL_TEXTURE_FETCH_BARRIER_BIT
case GL_TEXTURE_FETCH_BARRIER_BIT: return StrCRef("TEXTURE_FETCH_BARRIER_BIT");
#endif
#if defined GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
case GL_SHADER_IMAGE_ACCESS_BARRIER_BIT: return StrCRef("SHADER_IMAGE_ACCESS_BARRIER_BIT");
#endif
#if defined GL_COMMAND_BARRIER_BIT
case GL_COMMAND_BARRIER_BIT: return StrCRef("COMMAND_BARRIER_BIT");
#endif
#if defined GL_PIXEL_BUFFER_BARRIER_BIT
case GL_PIXEL_BUFFER_BARRIER_BIT: return StrCRef("PIXEL_BUFFER_BARRIER_BIT");
#endif
#if defined GL_TEXTURE_UPDATE_BARRIER_BIT
case GL_TEXTURE_UPDATE_BARRIER_BIT: return StrCRef("TEXTURE_UPDATE_BARRIER_BIT");
#endif
#if defined GL_BUFFER_UPDATE_BARRIER_BIT
case GL_BUFFER_UPDATE_BARRIER_BIT: return StrCRef("BUFFER_UPDATE_BARRIER_BIT");
#endif
#if defined GL_FRAMEBUFFER_BARRIER_BIT
case GL_FRAMEBUFFER_BARRIER_BIT: return StrCRef("FRAMEBUFFER_BARRIER_BIT");
#endif
#if defined GL_TRANSFORM_FEEDBACK_BARRIER_BIT
case GL_TRANSFORM_FEEDBACK_BARRIER_BIT: return StrCRef("TRANSFORM_FEEDBACK_BARRIER_BIT");
#endif
#if defined GL_ATOMIC_COUNTER_BARRIER_BIT
case GL_ATOMIC_COUNTER_BARRIER_BIT: return StrCRef("ATOMIC_COUNTER_BARRIER_BIT");
#endif
#if defined GL_SHADER_STORAGE_BARRIER_BIT
case GL_SHADER_STORAGE_BARRIER_BIT: return StrCRef("SHADER_STORAGE_BARRIER_BIT");
#endif
#if defined GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT
case GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT: return StrCRef("CLIENT_MAPPED_BUFFER_BARRIER_BIT");
#endif
#if defined GL_ALL_BARRIER_BITS
case GL_ALL_BARRIER_BITS: return StrCRef("ALL_BARRIER_BITS");
#endif
default:;
}
OGLPLUS_FAKE_USE(value);
return StrCRef();
}
#else
;
#endif
} // namespace enums
| 35.384615 | 94 | 0.838768 | Extrunder |
c09a93549fe66ee9fc78634d7a6ca089a788c931 | 31 | cpp | C++ | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 3 | 2016-01-15T20:17:21.000Z | 2021-01-21T02:32:15.000Z | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 11 | 2016-07-26T01:37:46.000Z | 2018-06-19T16:50:25.000Z | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 12 | 2016-02-09T04:31:41.000Z | 2021-12-03T01:04:04.000Z | #include "test_thrust_cuda.cu"
| 15.5 | 30 | 0.806452 | subhashis |
c0a45801b4089c575176675f343a93584898c772 | 1,046 | hpp | C++ | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | null | null | null | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 10 | 2018-02-06T14:46:36.000Z | 2018-03-20T13:37:20.000Z | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 1 | 2021-11-26T10:59:09.000Z | 2021-11-26T10:59:09.000Z | #pragma once
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/scope_exit.hpp>
#include <locale>
#include <string>
namespace bunsan::property_tree {
/*!
* \brief Read info from filename with relative path bug fix
*
* \warning This function is not safe,
* it should be used only from single thread.
*/
template <typename Ptree>
void read_info(const std::string &filename, Ptree &pt,
const std::locale &loc = std::locale()) {
boost::filesystem::initial_path(); // initialize for future use
BOOST_SCOPE_EXIT_ALL() {
boost::filesystem::current_path(boost::filesystem::initial_path());
};
boost::filesystem::current_path(
boost::filesystem::absolute(boost::filesystem::path(filename))
.parent_path());
boost::property_tree::info_parser::read_info(
boost::filesystem::path(filename).filename().string(), pt, loc);
}
} // namespace bunsan::property_tree
| 28.27027 | 71 | 0.713193 | bacsorg |
c0a55a4e17fe63b7d2278271b068ab7579edf0e1 | 1,095 | hh | C++ | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | 1 | 2020-01-06T09:43:56.000Z | 2020-01-06T09:43:56.000Z | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | #pragma once
#include <tuple>
#include <vector>
#include "Constants.hh"
#include "OPCode.hh"
#include "Operand.hh"
#include "Register.hh"
#include "QuadSource.hh"
#include "QuadDest.hh"
class Quad {
public:
Quad(OPCode op_code, QuadDest dest, QuadSource src_a, QuadSource src_b)
: m_op_code { op_code },
m_dest { dest },
m_src_a { src_a },
m_src_b { src_b } {}
std::string to_string() const;
std::tuple<std::string, std::string, std::string, std::string, std::string>
to_string_segments() const;
const std::vector<unsigned>& label_ids() const { return m_label_ids; }
bool has_label() const { return m_has_label; }
void add_label(unsigned label_id);
OPCode opcode() const { return m_op_code; };
QuadDest dest() const { return m_dest; }
QuadSource src_a() const { return m_src_a; }
QuadSource src_b() const { return m_src_b; }
private:
std::vector<unsigned> m_label_ids {};
bool m_has_label { false };
OPCode m_op_code;
QuadDest m_dest;
QuadSource m_src_a;
QuadSource m_src_b;
}; | 27.375 | 79 | 0.659361 | walecome |
c0acb905a2e128130982b721b209e67dc245db7f | 1,765 | cpp | C++ | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 32 | 2016-11-24T01:40:21.000Z | 2021-11-01T19:24:22.000Z | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 6 | 2016-10-15T05:57:00.000Z | 2021-08-13T12:29:24.000Z | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 49 | 2016-01-26T13:36:02.000Z | 2022-03-16T10:24:41.000Z | #include <iostream>
#include <assert.h>
#include <math.h>
#include "loopexpr.h"
#include "vars.h"
#include "constant.h"
using namespace std;
LoopExpr::LoopExpr (string _cv,
Expression *_frome,
Expression *_toe,
Expression *_stepe,
Expression *_bodye):frome(_frome),toe(_toe),stepe(_stepe),bodye(_bodye),controlVar(_cv){};
LoopExpr::~LoopExpr()
{
delete frome;
delete toe;
delete stepe;
delete bodye;
}
Value* LoopExpr::execute()
{
Value* garbage;
Value *control = frome->execute();
Value* to = toe->execute();
while(!control->equals(to))
{
setControlVariableTo(control);
executeBodyAndDeleteGarbage();
garbage = control;
control = makeStep(control);
delete garbage;
}
setControlVariableTo(control);
delete control;
delete to;
return bodye->execute();
}
void LoopExpr::setControlVariableTo(Value* value)
{
SetExpression *set = new SetExpression(controlVar, new Constant(value->clone()));
Value* garbage = set->execute();
delete garbage;
delete set;
}
void LoopExpr::executeBodyAndDeleteGarbage()
{
Value* garbage = bodye->execute();
delete garbage;
}
Value* LoopExpr::makeStep(Value* currentControlValue)
{
Value* stepValue = stepe->execute();
Value* newControlValue = currentControlValue->plus(stepValue);
delete stepValue;
return newControlValue;
}
void LoopExpr::print (ostream &out)
{
out << getID () << "[label=\"LOOP:" << controlVar << "\"];" << endl;
out << getID () << "->" << frome->getID() << ";" << endl;
out << getID () << "->" << toe->getID() << ";" << endl;
out << getID () << "->" << stepe->getID() << ";" << endl;
out << getID () << "->" << bodye->getID() << ";" << endl;
frome->print (out);
toe->print (out);
stepe->print (out);
bodye->print (out);
}
| 20.523256 | 99 | 0.645892 | code-hunger |
c0b08d0f8f46353005d205b81e5015b074873991 | 22,889 | cpp | C++ | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 516 | 2015-01-04T14:04:21.000Z | 2022-03-13T05:07:27.000Z | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 12 | 2018-08-04T22:37:46.000Z | 2021-02-17T00:37:56.000Z | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 99 | 2015-04-23T01:59:24.000Z | 2022-03-03T04:38:28.000Z | #include "pe/LdConfigDirWrapper.h"
// offset from the beginning of the structure
#define getStructFieldOffset(STRUCT, FIELD) ((ULONGLONG) &(STRUCT.FIELD) - (ULONGLONG)&STRUCT)
bufsize_t LdConfigDirWrapper::getLdConfigDirSize()
{
bufsize_t dirSize = 0;
if (m_Exe->getBitMode() == Executable::BITS_32) {
dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY32);
} else if (m_Exe->getBitMode() == Executable::BITS_64) {
dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY64);
}
return dirSize;
}
bufsize_t LdConfigDirWrapper::getHdrDefinedSize()
{
const offset_t rva = getDirEntryAddress();
offset_t raw = INVALID_ADDR;
try {
raw = m_Exe->rvaToRaw(rva);
} catch (CustomException &e) {
raw = INVALID_ADDR;
}
if (raw == INVALID_ADDR) return 0;
offset_t offset = INVALID_ADDR;
if (m_Exe->getBitMode() == Executable::BITS_32) {
pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld = { 0 };
offset = getStructFieldOffset(ld, Size);
} else if (m_Exe->getBitMode() == Executable::BITS_64) {
pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld = { 0 };
offset = getStructFieldOffset(ld, Size);
}
DWORD* sizePtr = (DWORD*) m_Exe->getContentAt((raw + offset), sizeof(DWORD));
if (!sizePtr) return 0;
return bufsize_t(*sizePtr);
}
void* LdConfigDirWrapper::getLdConfigDirPtr()
{
offset_t rva = getDirEntryAddress();
BYTE *ptr = m_Exe->getContentAt(rva, Executable::RVA, this->getSize());
return ptr;
}
bool LdConfigDirWrapper::wrapSubentriesTable(size_t parentFieldId, size_t counterFieldId)
{
bool isOk = false;
size_t count = this->getNumValue(counterFieldId, &isOk);
if (!isOk) {
return false;
}
for (size_t i = 0 ; i < count; i++) {
LdConfigEntryWrapper *entry = new LdConfigEntryWrapper(m_Exe, this, i, parentFieldId);
if (!entry || !entry->getPtr()) {
delete entry;
break;
}
this->entries.push_back(entry);
this->subEntriesMap[parentFieldId].push_back(entry);
}
return isOk;
}
bool LdConfigDirWrapper::wrap()
{
clear();
if (!getPtr()) return false;
//SEHandlerTable:
wrapSubentriesTable(SEH_TABLE, SEH_COUNT);
//GuardCFFunctionTable:
wrapSubentriesTable(GUARD_TABLE, GUARD_COUNT);
wrapSubentriesTable(GUARD_LONG_JUMP_TABLE, GUARD_LONG_JUMP_COUNT);
wrapSubentriesTable(GUARD_ADDR_IAT_ENTRY_TABLE, GUARD_ADDR_IAT_ENTRY_COUNT);
wrapSubentriesTable(GUARD_EH_CONT_TABLE, GUARD_EH_CONT_COUNT);
return true;
}
void* LdConfigDirWrapper::getPtr()
{
return getLdConfigDirPtr();
}
void LdConfigDirWrapper::clear()
{
std::map<uint32_t, std::vector<ExeNodeWrapper*> >::iterator mapItr;
for (mapItr = this->subEntriesMap.begin(); mapItr != this->subEntriesMap.end(); mapItr++) {
std::vector<ExeNodeWrapper*> &vec = mapItr->second;
vec.clear();
}
ExeNodeWrapper::clear();
}
void* LdConfigDirWrapper::firstSubEntryPtr(size_t parentId)
{
bool isOk = false;
offset_t offset = this->getNumValue(parentId, &isOk);
if (!isOk) return NULL;
Executable::addr_type aT = containsAddrType(parentId);
if (aT == Executable::NOT_ADDR) return NULL;
bufsize_t handlerSize = static_cast<bufsize_t>(this->firstSubEntrySize(parentId));
char *ptr = (char*) m_Exe->getContentAt(offset, aT, handlerSize);
if (!ptr) return NULL;
return ptr;
}
bufsize_t LdConfigDirWrapper::getSize()
{
//validate the offset
const offset_t rva = getDirEntryAddress();
if (!m_Exe->isValidAddr(rva, Executable::RVA)) {
return 0;
}
const bufsize_t hdrSize = this->getHdrDefinedSize();
const bufsize_t structSize = getLdConfigDirSize();
const bufsize_t totalSize = (hdrSize < structSize) ? hdrSize : structSize;
// is the size correct
const offset_t rvaEnd = rva + totalSize - 1;
if (!m_Exe->isValidAddr(rvaEnd, Executable::RVA)) {
return 0;
}
return totalSize;
}
offset_t LdConfigDirWrapper::_getFieldDelta(bool is32b, size_t fId)
{
static pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld32 = { 0 };
static pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld64 = { 0 };
//offset from the beginning of the IMAGE_LOAD_CONFIG_DIRECTORY_T strucure
offset_t fieldOffset = INVALID_ADDR;
switch (fId) {
case SIZE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Size) : getStructFieldOffset(ld64, Size);
break;
case TIMEST :
fieldOffset = (is32b) ? getStructFieldOffset(ld32,TimeDateStamp) : getStructFieldOffset(ld64, TimeDateStamp);
break;
case MAJOR_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32,MajorVersion) : getStructFieldOffset(ld64, MajorVersion);
break;
case MINOR_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, MinorVersion) : getStructFieldOffset(ld64, MinorVersion);
break;
case GLOBAL_FLAGS_CLEAR :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsClear) : getStructFieldOffset(ld64, GlobalFlagsClear);
break;
case GLOBAL_FLAGS_SET :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsSet) : getStructFieldOffset(ld64, GlobalFlagsSet);
break;
case CRITICAT_SEC_TIMEOUT :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CriticalSectionDefaultTimeout) : getStructFieldOffset(ld64, CriticalSectionDefaultTimeout);
break;
case DECOMMIT_FREE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitFreeBlockThreshold) : getStructFieldOffset(ld64, DeCommitFreeBlockThreshold);
break;
case DECOMMIT_TOTAL :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitTotalFreeThreshold) : getStructFieldOffset(ld64, DeCommitTotalFreeThreshold);
break;
case LOCK_PREFIX :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, LockPrefixTable) : getStructFieldOffset(ld64, LockPrefixTable);
break;
case MAX_ALLOC :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, MaximumAllocationSize) : getStructFieldOffset(ld64, MaximumAllocationSize);
break;
case VIRTUAL_MEM :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, VirtualMemoryThreshold) : getStructFieldOffset(ld64, VirtualMemoryThreshold);
break;
case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64
{
fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessHeapFlags) : getStructFieldOffset(ld64, ProcessAffinityMask);
break;
}
case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64
{
fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessAffinityMask) : getStructFieldOffset(ld64, ProcessHeapFlags);
break;
}
case CSD_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CSDVersion) : getStructFieldOffset(ld64, CSDVersion);
break;
case DEPENDENT_LOAD_FLAGS :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DependentLoadFlags) : getStructFieldOffset(ld64, DependentLoadFlags);
break;
case EDIT_LIST :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, EditList) : getStructFieldOffset(ld64, EditList);
break;
case SEC_COOKIE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SecurityCookie) : getStructFieldOffset(ld64, SecurityCookie);
break;
case SEH_TABLE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerTable) : getStructFieldOffset(ld64, SEHandlerTable);
break;
case SEH_COUNT :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerCount) : getStructFieldOffset(ld64, SEHandlerCount);
break;
// W8.1 part:
case GUARD_CHECK :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFCheckFunctionPointer) : getStructFieldOffset(ld64, GuardCFCheckFunctionPointer);
break;
case GUARD_DISPATCH :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFDispatchFunctionPointer) : getStructFieldOffset(ld64, GuardCFDispatchFunctionPointer);
break;
case GUARD_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionTable) : getStructFieldOffset(ld64, GuardCFFunctionTable);
break;
case GUARD_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionCount) : getStructFieldOffset(ld64, GuardCFFunctionCount);
break;
case GUARD_FLAGS:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardFlags) : getStructFieldOffset(ld64, GuardFlags);
break;
// W10 part:
case CODE_INTEGRITY_FLAGS:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Flags) : getStructFieldOffset(ld64, CodeIntegrity.Flags);
break;
case CODE_INTEGRITY_CATALOG:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Catalog) : getStructFieldOffset(ld64, CodeIntegrity.Catalog);
break;
case CODE_INTEGRITY_CATALOG_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.CatalogOffset) : getStructFieldOffset(ld64, CodeIntegrity.CatalogOffset);
break;
case CODE_INTEGRITY_RESERVED:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Reserved) : getStructFieldOffset(ld64, CodeIntegrity.Reserved);
break;
case GUARD_ADDR_IAT_ENTRY_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryTable) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryTable);
break;
case GUARD_ADDR_IAT_ENTRY_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryCount) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryCount);
break;
case GUARD_LONG_JUMP_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetTable) : getStructFieldOffset(ld64, GuardLongJumpTargetTable);
break;
case GUARD_LONG_JUMP_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetCount) : getStructFieldOffset(ld64, GuardLongJumpTargetCount);
break;
case DYNAMIC_VAL_RELOC:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTable) : getStructFieldOffset(ld64, DynamicValueRelocTable);
break;
case CHPE_METADATA_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CHPEMetadataPointer) : getStructFieldOffset(ld64, CHPEMetadataPointer);
break;
case GUARD_FAILURE_ROUTINE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutine) : getStructFieldOffset(ld64, GuardRFFailureRoutine);
break;
case GUARD_FAILURE_ROUTINE_FUNC_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutineFunctionPointer) : getStructFieldOffset(ld64, GuardRFFailureRoutineFunctionPointer);
break;
case DYNAMIC_VAL_RELOC_TABLE_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableOffset) : getStructFieldOffset(ld64, DynamicValueRelocTableOffset);
break;
case DYNAMIC_VAL_RELOC_TABLE_SECTION:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableSection) : getStructFieldOffset(ld64, DynamicValueRelocTableSection);
break;
case RESERVED2:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved2) : getStructFieldOffset(ld64, Reserved2);
break;
case GUARD_VERIFY_STACK_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFVerifyStackPointerFunctionPointer) : getStructFieldOffset(ld64, GuardRFVerifyStackPointerFunctionPointer);
break;
case HOT_PATCH_TABLE_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, HotPatchTableOffset) : getStructFieldOffset(ld64, HotPatchTableOffset);
break;
case RESERVED3:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved3) : getStructFieldOffset(ld64, Reserved3);
break;
case ENCLAVE_CONFIG_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, EnclaveConfigurationPointer) : getStructFieldOffset(ld64, EnclaveConfigurationPointer);
break;
case VOLATILE_METADATA_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, VolatileMetadataPointer) : getStructFieldOffset(ld64, VolatileMetadataPointer);
break;
case GUARD_EH_CONT_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationTable) : getStructFieldOffset(ld64, GuardEHContinuationTable);
break;
case GUARD_EH_CONT_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationCount) : getStructFieldOffset(ld64, GuardEHContinuationCount);
break;
}
return fieldOffset;
}
void* LdConfigDirWrapper::getFieldPtr(size_t fId, size_t subField)
{
const bool is32b = (m_Exe->getBitMode() == Executable::BITS_32) ? true : false;
offset_t fieldDelta = _getFieldDelta(is32b, fId);
if (fieldDelta != INVALID_ADDR) {
const offset_t hdrSize = this->getHdrDefinedSize();
if (fieldDelta >= hdrSize) {
return NULL;
}
return m_Exe->getContentAt(this->getOffset() + fieldDelta, 1);
}
return NULL;
}
QString LdConfigDirWrapper::getFieldName(size_t fieldId)
{
if (!m_Exe) return "";
const bool is32bit = (m_Exe->getBitMode() == Executable::BITS_32);
switch (fieldId) {
case SIZE : return "Size";
case TIMEST : return "TimeDateStamp";
case MAJOR_VER : return "MajorVersion";
case MINOR_VER : return "MinorVersion";
case GLOBAL_FLAGS_CLEAR : return "GlobalFlagsClear";
case GLOBAL_FLAGS_SET : return "GlobalFlagsSet";
case CRITICAT_SEC_TIMEOUT : return "CriticalSectionDefaultTimeout";
case DECOMMIT_FREE : return "DeCommitFreeBlockThreshold";
case DECOMMIT_TOTAL : return "DeCommitTotalFreeThreshold";
case LOCK_PREFIX : return "LockPrefixTable";
case MAX_ALLOC : return "MaximumAllocationSize";
case VIRTUAL_MEM : return "VirtualMemoryThreshold";
case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64
{
return (is32bit) ? "ProcessHeapFlags" : "ProcessAffinityMask";
}
case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64
{
return (is32bit) ? "ProcessAffinityMask" : "ProcessHeapFlags";
}
case CSD_VER : return "CSDVersion";
case DEPENDENT_LOAD_FLAGS : return "DependentLoadFlags";
case EDIT_LIST : return "EditList";
case SEC_COOKIE : return "SecurityCookie";
case SEH_TABLE : return "SEHandlerTable";
case SEH_COUNT : return "SEHandlerCount";
// W8.1 part :
case GUARD_CHECK : return "GuardCFCheckFunctionPtr";
case GUARD_DISPATCH : return "GuardCFDispatchFunctionPointer";
case GUARD_TABLE: return "GuardCFFunctionTable";
case GUARD_COUNT: return "GuardCFFunctionCount";
case GUARD_FLAGS: return "GuardFlags";
// W10 part:
case CODE_INTEGRITY_FLAGS: return "CodeIntegrity.Flags"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Flags
case CODE_INTEGRITY_CATALOG: return "CodeIntegrity.Catalog"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Catalog
case CODE_INTEGRITY_CATALOG_OFFSET: return "CodeIntegrity.CatalogOffset"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.CatalogOffset
case CODE_INTEGRITY_RESERVED: return "CodeIntegrity.Reserved"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Reserved
case GUARD_ADDR_IAT_ENTRY_TABLE: return "GuardAddressTakenIatEntryTable";
case GUARD_ADDR_IAT_ENTRY_COUNT: return "GuardAddressTakenIatEntryCount";
case GUARD_LONG_JUMP_TABLE: return "GuardLongJumpTargetTable";
case GUARD_LONG_JUMP_COUNT: return "GuardLongJumpTargetCount";
case DYNAMIC_VAL_RELOC: return "DynamicValueRelocTable";
case CHPE_METADATA_PTR: return "CHPEMetadataPointer";
case GUARD_FAILURE_ROUTINE: return "GuardRFFailureRoutine";
case GUARD_FAILURE_ROUTINE_FUNC_PTR: return "GuardRFFailureRoutineFunctionPointer";
case DYNAMIC_VAL_RELOC_TABLE_OFFSET: return "DynamicValueRelocTableOffset";
case DYNAMIC_VAL_RELOC_TABLE_SECTION: return "DynamicValueRelocTableSection";
case RESERVED2: return "Reserved2";
case GUARD_VERIFY_STACK_PTR: return "GuardRFVerifyStackPointerFunctionPointer";
case HOT_PATCH_TABLE_OFFSET: return "HotPatchTableOffset";
case RESERVED3: return "Reserved3";
case ENCLAVE_CONFIG_PTR: return "EnclaveConfigurationPointer";
case VOLATILE_METADATA_PTR: return "VolatileMetadataPointer";
case GUARD_EH_CONT_TABLE: return "GuardEHContinuationTable";
case GUARD_EH_CONT_COUNT: return "GuardEHContinuationCount";
}
return getName();
}
Executable::addr_type LdConfigDirWrapper::containsAddrType(size_t fieldId, size_t subField)
{
switch (fieldId) {
case LOCK_PREFIX :
case EDIT_LIST :
case SEC_COOKIE :
case SEH_TABLE :
case GUARD_CHECK :
case GUARD_DISPATCH :
case GUARD_TABLE :
case GUARD_ADDR_IAT_ENTRY_TABLE:
case GUARD_LONG_JUMP_TABLE:
case DYNAMIC_VAL_RELOC:
case GUARD_FAILURE_ROUTINE:
case GUARD_FAILURE_ROUTINE_FUNC_PTR:
case GUARD_VERIFY_STACK_PTR:
case ENCLAVE_CONFIG_PTR:
case VOLATILE_METADATA_PTR:
case GUARD_EH_CONT_TABLE:
return Executable::VA;
}
return Executable::NOT_ADDR;
}
std::set<DWORD> LdConfigDirWrapper::getGuardFlagsSet(DWORD flags)
{
const size_t guardFlagsCount = 13;
const DWORD guardFlags[guardFlagsCount] = {
IMAGE_GUARD_CF_INSTRUMENTED,
IMAGE_GUARD_CFW_INSTRUMENTED,
IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT,
IMAGE_GUARD_SECURITY_COOKIE_UNUSED,
IMAGE_GUARD_PROTECT_DELAYLOAD_IAT,
IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION,
IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT,
IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION,
IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT,
IMAGE_GUARD_RF_INSTRUMENTED,
IMAGE_GUARD_RF_ENABLE,
IMAGE_GUARD_RF_STRICT,
IMAGE_GUARD_RETPOLINE_PRESENT
};
std::set<DWORD> allFlags;
for (size_t i = 0; i < guardFlagsCount; ++i) {
const DWORD nextFlag = guardFlags[i];
if (flags & nextFlag) {
allFlags.insert(nextFlag);
}
}
return allFlags;
}
QString LdConfigDirWrapper::translateGuardFlag(DWORD flags)
{
if (flags & IMAGE_GUARD_CF_INSTRUMENTED) {
return ("CF_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_CFW_INSTRUMENTED) {
return ("CFW_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT) {
return ("CF_FUNCTION_TABLE_PRESENT");
}
if (flags & IMAGE_GUARD_SECURITY_COOKIE_UNUSED) {
return ("SECURITY_COOKIE_UNUSED");
}
if (flags & IMAGE_GUARD_PROTECT_DELAYLOAD_IAT) {
return ("PROTECT_DELAYLOAD_IAT");
}
if (flags & IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION) {
return ("DELAYLOAD_IAT_IN_ITS_OWN_SECTION");
}
if (flags & IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT) {
return ("CF_EXPORT_SUPPRESSION_INFO_PRESENT");
}
if (flags & IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION) {
return ("CF_ENABLE_EXPORT_SUPPRESSION");
}
if (flags & IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT) {
return ("CF_LONGJUMP_TABLE_PRESENT");
}
if (flags & IMAGE_GUARD_RF_INSTRUMENTED) {
return ("RF_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_RF_ENABLE) {
return ("RF_ENABLE");
}
if (flags & IMAGE_GUARD_RF_STRICT) {
return ("RF_STRICT");
}
if (flags & IMAGE_GUARD_RETPOLINE_PRESENT) {
return ("RETPOLINE_PRESENT");
}
return "";
}
QString LdConfigDirWrapper::translateGuardFlagsContent(const QString& delim)
{
bool isOk = false;
DWORD GuardFlags = this->getNumValue(GUARD_FLAGS, &isOk);
if (!isOk) {
return "-";
}
std::set<DWORD> flagsSet = LdConfigDirWrapper::getGuardFlagsSet(GuardFlags);
std::set<DWORD>::iterator itr;
QStringList list;
for (itr = flagsSet.begin() ; itr != flagsSet.end(); itr++) {
const DWORD nextFlag = *itr;
const QString flagInfo = LdConfigDirWrapper::translateGuardFlag(nextFlag);
if (flagInfo.length() == 0) continue;
list.append(flagInfo);
}
return list.join(delim);
}
QString LdConfigDirWrapper::translateFieldContent(size_t fieldId)
{
if (fieldId == GUARD_FLAGS) {
return translateGuardFlagsContent(";");;
}
return "";
}
//----------------
void* LdConfigEntryWrapper::getPtr()
{
if (this->parentDir == NULL) return NULL;
void* first = parentDir->firstSubEntryPtr(this->parentFieldId);
if (first == NULL) return NULL;
bufsize_t fieldSize = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId));
if (fieldSize == 0) return NULL;
offset_t offset = this->getOffset(first);
if (offset == INVALID_ADDR) return NULL;
//offset from the beginning:
offset_t fieldOffset = (this->entryNum * fieldSize);
offset += fieldOffset;
void *ptr = m_Exe->getContentAt(offset, Executable::RAW, fieldSize);
return ptr;
}
bufsize_t LdConfigEntryWrapper::getSize()
{
if (this->parentDir == NULL) return 0;
if (!getPtr()) return 0;
bufsize_t size = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId));
return size;
}
void* LdConfigEntryWrapper::getFieldPtr(size_t fieldId, size_t subField)
{
void* ptr = getPtr();
if (!ptr) return NULL;
if (fieldId == NONE) {
return ptr;
}
size_t counter = getFieldsCount();
if (fieldId >= counter) return NULL;
if (fieldId == HANDLER_ADDR) {
return ptr;
}
return (void*)((ULONGLONG)ptr + sizeof(DWORD));
}
bufsize_t LdConfigEntryWrapper::getFieldSize(size_t fieldId, size_t subField)
{
size_t count = this->getFieldsCount();
if (fieldId >= count) {
return 0;
}
if (fieldId == HANDLER_ADDR) {
return sizeof(DWORD);
}
return sizeof(BYTE);
}
| 41.093357 | 176 | 0.680676 | yjd |
c0b0c585b2bfa025ee88c817acf33c5a4a6e711c | 13,633 | cpp | C++ | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | // DataTable.cpp: implementation of the CDataTable class.
//
//////////////////////////////////////////////////////////////////////
#include "DataTable.h"
// Includes and external ptr for AssociateDLL scan
#include "DBPCompiler.h"
#include "direct.h"
extern CDBPCompiler* g_pDBPCompiler;
extern bool g_bExternaliseDLLS;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDataTable::CDataTable()
{
m_dwIndex=0;
m_dwType=0;
m_pNumeric=0;
m_pString=NULL;
m_pString2=NULL;
m_pNext=NULL;
m_bAddedToEXEData=false;
}
CDataTable::CDataTable(LPSTR pInitString)
{
m_dwIndex=0;
m_dwType=0;
m_pNumeric=0;
m_pString=new CStr(pInitString);
m_pString2=new CStr("");
m_pNext=NULL;
m_bAddedToEXEData=false;
}
CDataTable::~CDataTable()
{
SAFE_DELETE(m_pString);
SAFE_DELETE(m_pString2);
}
void CDataTable::Free(void)
{
CDataTable* pCurrent = this;
while(pCurrent)
{
CDataTable* pNext = pCurrent->GetNext();
delete pCurrent;
pCurrent = pNext;
}
}
void CDataTable::Add(CDataTable* pNew)
{
CDataTable* pCurrent = this;
while(pCurrent->m_pNext)
{
pCurrent=pCurrent->GetNext();
}
pCurrent->m_pNext=pNew;
}
bool CDataTable::AddNumeric(double dNum, DWORD dwIndex)
{
// Create new data item
CDataTable* pNewData = new CDataTable;
pNewData->SetNumeric(dNum);
// Set index
pNewData->SetIndex(dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddString(LPSTR pString, DWORD dwIndex)
{
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr = new CStr(pString);
pNewData->SetString(pStr);
pNewData->SetString2(NULL);
// Set index
pNewData->SetIndex(dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddTwoStrings(LPSTR pString, LPSTR pString2, DWORD* dwIndex)
{
// If string is NOT unique, fail
DWORD dwResult = FindString(pString);
if(dwResult>0)
{
*dwIndex=dwResult;
return false;
}
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr1 = new CStr(pString);
CStr* pStr2 = new CStr(pString2);
pNewData->SetString(pStr1);
pNewData->SetString2(pStr2);
// Set index
pNewData->SetIndex(*dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddUniqueString(LPSTR pString, DWORD* dwIndex)
{
// If string is NOT unique, fail
DWORD dwResult = FindString(pString);
if(dwResult>0)
{
*dwIndex=dwResult;
return false;
}
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr = new CStr(pString);
pNewData->SetString(pStr);
pNewData->SetString2(NULL);
// Set index
pNewData->SetIndex(*dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
DWORD CDataTable::FindString(LPSTR pFindString)
{
// Find String
CDataTable* pCurrent = this;
while(pCurrent)
{
// Match list item with search string
if(pCurrent->GetString())
if(stricmp(pCurrent->GetString()->GetStr(), pFindString)==NULL)
return pCurrent->GetIndex();
pCurrent=pCurrent->GetNext();
}
// Failed to find
return 0;
}
bool CDataTable::FindIndexStr(LPSTR pIndexAsString)
{
// Convert String to Index
DWORD dwFindIndex = atoi(pIndexAsString);
// Find String
CDataTable* pCurrent = this;
while(pCurrent)
{
// Match list item with search string
if(pCurrent->GetString())
if(pCurrent->GetIndex()==dwFindIndex)
return true;
pCurrent=pCurrent->GetNext();
}
// Soft Failed to find
return false;
}
bool CDataTable::NotExcluded ( LPSTR pFilename )
{
// false if excluded from compile
for ( DWORD i=1; i<g_pDBPCompiler->g_dwExcludeFilesCount; i++)
if ( g_pDBPCompiler->g_pExcludeFiles [ i ] )
if ( stricmp ( g_pDBPCompiler->g_pExcludeFiles [ i ], pFilename )==NULL )
return false;
// lee - 270308 - u67 - do not include DLL at all if flagged
if ( g_bExternaliseDLLS==true )
return false;
// complete, not excluded
return true;
}
int CDataTable::CompleteAnyLinkAssociates(void)
{
// Scan user plugins - check if associations require any DBPro DLLs
bool bAtLeastOneUserDLLNeeds3D = false;
bool bAtLeastOneUserDLLNeedsSOUND = false;
// reset index
DWORD dwIndex=0;
DWORD dwIndexBeforeAdds=0;
// First pass basic DLLs, second pass is dependence additions
for ( int iAddDependentsLoop=0; iAddDependentsLoop<2; iAddDependentsLoop++ )
{
for ( int iPass=0; iPass<2; iPass++ )
{
// Switch to PLUGINS-XXXX Folder
char pOldDir [ _MAX_PATH ];
getcwd ( pOldDir, _MAX_PATH );
// Depends on pass value
if ( iPass==0 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSUSERFOLDER));
if ( iPass==1 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSLICENSEDFOLDER));
// Go through DLLs from direct-command-list
CDataTable* pCurrent = this->GetNext();
while(pCurrent)
{
// Check if DLL is user-dll ( leefix - 011208 - u71 - gameFX needed to link to Basic3D! )
LPSTR pDLLName = pCurrent->GetString()->GetStr();
if ( strnicmp ( pDLLName, "dbpro", 5 )!=NULL || strnicmp ( pDLLName, "dbprogamefx", 11 )==NULL )
{
// must be user DLL (associated with main DLL)
int iAssociationCode = 0;
HMODULE hModule = LoadLibrary(pDLLName);
if(hModule)
{
// get associate dll value if any
if ( iAddDependentsLoop==0 )
{
typedef int ( *RETINTNOPARAM ) ( void );
RETINTNOPARAM GetAssociatedDLLs = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetAssociatedDLLs@@YAHXZ" );
if (!GetAssociatedDLLs)
GetAssociatedDLLs = (RETINTNOPARAM)GetProcAddress(hModule, "GetAssociatedDLLs");
if ( GetAssociatedDLLs ) iAssociationCode=GetAssociatedDLLs();
}
else
{
// get num of additional dependencies
int iNumDLLDependencies = 0;
typedef int ( *RETINTNOPARAM ) ( void );
RETINTNOPARAM GetNumDependencies = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetNumDependencies@@YAHXZ" );
if (!GetNumDependencies)
GetNumDependencies = (RETINTNOPARAM)GetProcAddress(hModule, "GetNumDependencies");
if ( GetNumDependencies ) iNumDLLDependencies=GetNumDependencies();
if ( iNumDLLDependencies > 0 )
{
typedef const char * ( *RETLPSTRNOPARAM ) ( int n );
RETLPSTRNOPARAM GetDependencyID = ( RETLPSTRNOPARAM ) GetProcAddress ( hModule, "?GetDependencyID@@YAPBDH@Z" );
if (!GetDependencyID)
GetDependencyID = (RETLPSTRNOPARAM)GetProcAddress(hModule, "GetDependencyID");
// store dependencies in list
for ( int iD=0; iD<iNumDLLDependencies; iD++ )
{
char pDependencyStr[256];
//LPSTR pDependencyStr = new char[256];
strcpy ( pDependencyStr, GetDependencyID(iD) );
DWORD dwTry=dwIndex+1;
if(AddUniqueString(pDependencyStr, &dwTry)) dwIndex=dwTry;
//SAFE_DELETE(pDependencyStr);
}
}
}
}
// free it if loaded
if(hModule)
{
FreeLibrary(hModule);
hModule=NULL;
}
// Association Codes (1=3d/2=sound/4-//)
if ( iAssociationCode & 1 ) bAtLeastOneUserDLLNeeds3D=true;
if ( iAssociationCode & 2 ) bAtLeastOneUserDLLNeedsSOUND=true;
}
// Next DLL
if ( iAddDependentsLoop==0 && iPass==0 ) dwIndex++;
pCurrent=pCurrent->GetNext();
}
// Restore dir before continue
_chdir(pOldDir);
}
// DLL index before adding any associations
if ( iAddDependentsLoop==0 ) dwIndexBeforeAdds=dwIndex;
}
// link Basic3D
if ( bAtLeastOneUserDLLNeeds3D )
{
DWORD dwTry=dwIndex+1;
if(AddUniqueString("DBProBasic3DDebug.dll", &dwTry)) dwIndex=dwTry;
}
// link Sound
if ( bAtLeastOneUserDLLNeedsSOUND )
{
DWORD dwTry=dwIndex+1;
if(AddUniqueString("DBProSoundDebug.dll", &dwTry)) dwIndex=dwTry;
}
// Scan all DLLS, and add any that are link-associated
CDataTable* pCurrent = this->GetNext();
while(pCurrent)
{
// If DLLTable Entry has string..
if(pCurrent->GetString())
{
// DLL Name contained in stringname
DWORD dwTry = 0;
LPSTR pDLL = NULL;
LPSTR pDLLName = pCurrent->GetString()->GetStr();
#define TRY_DLL(nm) dwTry=dwIndex+1;pDLL=nm;if(NotExcluded(pDLL))if(AddUniqueString(pDLL,&dwTry))dwIndex=dwTry
// Add other DLLs Associated With These..
if(stricmp(pDLLName, "DBProSetupDebug.dll")==NULL)
{
// Associate DLLs
TRY_DLL("DBProBasic2DDebug.dll");
TRY_DLL("DBProTextDebug.dll");
}
if(stricmp(pDLLName, "DBProTextDebug.dll")==NULL)
{
// Associate DLLs
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProInputDebug.dll")==NULL)
{
// Checklist Support
TRY_DLL("DBProSystemDebug.dll");
}
if(stricmp(pDLLName, "DBProSpritesDebug.dll")==NULL)
{
// Image Support
TRY_DLL("DBProImageDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL)
{
// Image Support
TRY_DLL("DBProImageDebug.dll");
// Transforms Support
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic2DDebug.dll")==NULL)
{
// Minimal DirectX
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProImageDebug.dll")==NULL
|| stricmp(pDLLName, "DBProAnimationDebug.dll")==NULL
|| stricmp(pDLLName, "DBProBitmapDebug.dll")==NULL)
{
// Sprite Support for pasting
TRY_DLL("DBProSpritesDebug.dll");
// Minimal DirectX
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProBasic2DDebug.dll");
TRY_DLL("DBProTextDebug.dll");
}
if(stricmp(pDLLName, "DBProMultiplayerDebug.dll")==NULL)
{
// Need access to memblock support
TRY_DLL("DBProMemblocksDebug.dll");
}
if(stricmp(pDLLName, "DBProMemblocksDebug.dll")==NULL)
{
// Memblocks Access to Bitmap, Image, Sound and Mesh
TRY_DLL("DBProBitmapDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProSoundDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
}
if(stricmp(pDLLName, "DBProCameraDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
}
if(stricmp(pDLLName, "DBProLightDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProMatrixDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL)
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProLightDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
// Secondary Support
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("ConvX.dll");
TRY_DLL("Conv3DS.dll");
TRY_DLL("ConvMDL.dll");
TRY_DLL("ConvMD2.dll");
TRY_DLL("ConvMD3.dll");
}
if(stricmp(pDLLName, "DBProWorld3DDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProLODTerrainDebug.dll");
TRY_DLL("DBProQ2BSPDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
TRY_DLL("DBProOwnBSPDebug.dll");
}
if(stricmp(pDLLName, "DBProLODTerrainDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProCSGDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProParticlesDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProParticlesDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProSystemDebug.dll")==NULL )
{
// for access to display mem
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProVectorsDebug.dll")==NULL )
{
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProTransformsDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
}
#undef TRY_DLL
}
// Next entry in DLL Table
pCurrent=pCurrent->GetNext();
}
// Complete
return (dwIndex-dwIndexBeforeAdds);
}
// WriteDBM
bool CDataTable::WriteDBMHeader(DWORD dwKindOfTable)
{
// Blank Line
CStr strDBMBlank(1);
if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false;
// header Line
CStr strDBMLine(256);
if(dwKindOfTable==1) strDBMLine.SetText("STRING:");
if(dwKindOfTable==2) strDBMLine.SetText("DATA:");
if(dwKindOfTable==3) strDBMLine.SetText("DLLS:");
if(dwKindOfTable==4) strDBMLine.SetText("COMMANDS:");
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
return true;
}
bool CDataTable::WriteDBM(void)
{
// Write out text
CStr strDBMLine(256);
strDBMLine.SetText(">>");
if(GetType()==1)
{
strDBMLine.AddNumericText(GetIndex());
strDBMLine.AddText("=");
strDBMLine.AddDoubleText(GetNumeric());
}
if(GetType()==2)
{
strDBMLine.AddNumericText(GetIndex());
strDBMLine.AddText("=");
strDBMLine.AddText(GetString());
}
// Output details
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
// Write next one
if(GetNext())
{
if((GetNext()->WriteDBM())==false) return false;
}
// Complete
return true;
}
| 25.434701 | 119 | 0.672559 | domydev |
c0b4f0c46557b3568a06437544cbfebd5c055175 | 1,631 | hpp | C++ | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 22 | 2018-08-27T15:28:10.000Z | 2022-02-13T08:18:00.000Z | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 3 | 2018-08-27T01:44:51.000Z | 2020-06-28T20:07:42.000Z | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 2 | 2018-08-26T18:55:47.000Z | 2018-09-29T01:04:36.000Z | #ifndef SNABL_FUNC_HPP
#define SNABL_FUNC_HPP
#include "snabl/def.hpp"
#include "snabl/fimp.hpp"
#include "snabl/ptrs.hpp"
#include "snabl/stack.hpp"
#include "snabl/std.hpp"
namespace snabl {
struct Lib;
struct Func: Def {
Lib &lib;
const I64 nargs;
unordered_map<Sym, unique_ptr<Fimp>> fimps;
Func(const Func &)=delete;
const Func &operator =(const Func &)=delete;
Func(Lib &lib, Sym id, I64 nargs): Def(id), lib(lib), nargs(nargs) { }
template <typename... ImpT>
Fimp &add_fimp(const Fimp::Args &args, ImpT &&... imp);
Fimp &get_fimp() const { return *fimps.begin()->second; }
Fimp *get_best_fimp(Stack::const_iterator begin,
Stack::const_iterator end) const {
I64 best_score(-1);
Fimp *best_fimp(nullptr);
for (auto &fp: fimps) {
auto &f(*fp.second);
auto fs(f.score(begin, end));
if (fs != -1) {
if (fs == 0) { return &f; }
if (best_score == -1 || fs < best_score) {
best_score = fs;
best_fimp = &f;
}
}
}
return best_fimp;
}
};
template <typename... ImpT>
Fimp &Func::add_fimp(const Fimp::Args &args, ImpT &&... imp) {
auto id(Fimp::get_id(*this, args));
auto found = fimps.find(id);
if (found == fimps.end()) {
return *fimps.emplace(id, make_unique<Fimp>(*this, args, forward<ImpT>(imp)...))
.first->second;
}
auto *fi(found->second.get());
fi->~Fimp();
new (fi) Fimp(*this, args, forward<ImpT>(imp)...);
return *fi;
}
}
#endif
| 23.637681 | 86 | 0.551196 | codr4life |
c0ba48d1e9f1c6011597c911dfced4c12a18267d | 17,749 | cpp | C++ | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | // GENERATED FILE - DO NOT EDIT.
// Generated by generate_tests.py
//
// Copyright (c) 2022 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "../diff_test_utils.h"
#include "gtest/gtest.h"
namespace spvtools {
namespace diff {
namespace {
// Test where src and dst have cases of a switch in different order.
constexpr char kSrc[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%22 = OpLabel
OpReturn
OpFunctionEnd)";
constexpr char kDst[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
TEST(DiffTest, ReorderedSwitchBlocks) {
constexpr char kDiff[] = R"( ; SPIR-V
; Version: 1.6
; Generator: Khronos SPIR-V Tools Assembler; 0
-; Bound: 58
+; Bound: 62
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
Options options;
DoStringDiffTest(kSrc, kDst, kDiff, options);
}
TEST(DiffTest, ReorderedSwitchBlocksNoDebug) {
constexpr char kSrcNoDebug[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
constexpr char kDstNoDebug[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
constexpr char kDiff[] = R"( ; SPIR-V
; Version: 1.6
; Generator: Khronos SPIR-V Tools Assembler; 0
-; Bound: 58
+; Bound: 62
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
Options options;
DoStringDiffTest(kSrcNoDebug, kDstNoDebug, kDiff, options);
}
} // namespace
} // namespace diff
} // namespace spvtools
| 30.444254 | 75 | 0.525607 | G-P-S |
c0bce06730b088981acc0b74199f6c44ef32337c | 16,185 | cpp | C++ | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | // lcd_test.cpp
#include "platform.h"
#include "lcd_test.h"
#include "hwpins.h"
#include "traces.h"
#include "hwlcdctrl.h"
#include "hwsdram.h"
#include "framebuffer16.h"
#include "clockcnt.h"
THwLcdCtrl lcdctrl;
TFrameBuffer16 disp;
#if defined(BOARD_DISCOVERY_F746)
void lcd_init()
{
uint32_t tmp;
uint32_t pinflags = 0;
// LCD CONTROLLER PINS
hwpinctrl.PinSetup(PORTNUM_E, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_12); //
hwpinctrl.PinSetup(PORTNUM_I, 9, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 10, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 14, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 15, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 0, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 1, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 2, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 3, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 5, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 6, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 7, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 8, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 9, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 10, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 11, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 13, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 14, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 15, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 0, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 1, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 2, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 5, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 6, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 7, pinflags | PINCFG_AF_14); //
// LCD GPIO PINS
hwpinctrl.PinSetup(PORTNUM_I, 12, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_DISP
hwpinctrl.PinSetup(PORTNUM_K, 3, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_BL_CTRL
// Configure the LCD clock
uint32_t lcd_pixel_clock = 8000000;
//lcdctrl.Init(480, 272, (void *)0x08000000); // give the rom start as the framebuffer
lcdctrl.Init(480, 272, (void *)hwsdram.address);
}
#endif
#if defined(BOARD_DISCOVERY_F429)
#include "hwspi.h"
TGpioPin pin_disp_cs(PORTNUM_C, 2, false);;
TGpioPin pin_disp_rs(PORTNUM_D, 13, false);
THwSpi disp_spi;
/* Level 1 Commands */
#define LCD_SWRESET 0x01 /* Software Reset */
#define LCD_READ_DISPLAY_ID 0x04 /* Read display identification information */
#define LCD_RDDST 0x09 /* Read Display Status */
#define LCD_RDDPM 0x0A /* Read Display Power Mode */
#define LCD_RDDMADCTL 0x0B /* Read Display MADCTL */
#define LCD_RDDCOLMOD 0x0C /* Read Display Pixel Format */
#define LCD_RDDIM 0x0D /* Read Display Image Format */
#define LCD_RDDSM 0x0E /* Read Display Signal Mode */
#define LCD_RDDSDR 0x0F /* Read Display Self-Diagnostic Result */
#define LCD_SPLIN 0x10 /* Enter Sleep Mode */
#define LCD_SLEEP_OUT 0x11 /* Sleep out register */
#define LCD_PTLON 0x12 /* Partial Mode ON */
#define LCD_NORMAL_MODE_ON 0x13 /* Normal Display Mode ON */
#define LCD_DINVOFF 0x20 /* Display Inversion OFF */
#define LCD_DINVON 0x21 /* Display Inversion ON */
#define LCD_GAMMA 0x26 /* Gamma register */
#define LCD_DISPLAY_OFF 0x28 /* Display off register */
#define LCD_DISPLAY_ON 0x29 /* Display on register */
#define LCD_COLUMN_ADDR 0x2A /* Colomn address register */
#define LCD_PAGE_ADDR 0x2B /* Page address register */
#define LCD_GRAM 0x2C /* GRAM register */
#define LCD_RGBSET 0x2D /* Color SET */
#define LCD_RAMRD 0x2E /* Memory Read */
#define LCD_PLTAR 0x30 /* Partial Area */
#define LCD_VSCRDEF 0x33 /* Vertical Scrolling Definition */
#define LCD_TEOFF 0x34 /* Tearing Effect Line OFF */
#define LCD_TEON 0x35 /* Tearing Effect Line ON */
#define LCD_MAC 0x36 /* Memory Access Control register*/
#define LCD_VSCRSADD 0x37 /* Vertical Scrolling Start Address */
#define LCD_IDMOFF 0x38 /* Idle Mode OFF */
#define LCD_IDMON 0x39 /* Idle Mode ON */
#define LCD_PIXEL_FORMAT 0x3A /* Pixel Format register */
#define LCD_WRITE_MEM_CONTINUE 0x3C /* Write Memory Continue */
#define LCD_READ_MEM_CONTINUE 0x3E /* Read Memory Continue */
#define LCD_SET_TEAR_SCANLINE 0x44 /* Set Tear Scanline */
#define LCD_GET_SCANLINE 0x45 /* Get Scanline */
#define LCD_WDB 0x51 /* Write Brightness Display register */
#define LCD_RDDISBV 0x52 /* Read Display Brightness */
#define LCD_WCD 0x53 /* Write Control Display register*/
#define LCD_RDCTRLD 0x54 /* Read CTRL Display */
#define LCD_WRCABC 0x55 /* Write Content Adaptive Brightness Control */
#define LCD_RDCABC 0x56 /* Read Content Adaptive Brightness Control */
#define LCD_WRITE_CABC 0x5E /* Write CABC Minimum Brightness */
#define LCD_READ_CABC 0x5F /* Read CABC Minimum Brightness */
#define LCD_READ_ID1 0xDA /* Read ID1 */
#define LCD_READ_ID2 0xDB /* Read ID2 */
#define LCD_READ_ID3 0xDC /* Read ID3 */
/* Level 2 Commands */
#define LCD_RGB_INTERFACE 0xB0 /* RGB Interface Signal Control */
#define LCD_FRMCTR1 0xB1 /* Frame Rate Control (In Normal Mode) */
#define LCD_FRMCTR2 0xB2 /* Frame Rate Control (In Idle Mode) */
#define LCD_FRMCTR3 0xB3 /* Frame Rate Control (In Partial Mode) */
#define LCD_INVTR 0xB4 /* Display Inversion Control */
#define LCD_BPC 0xB5 /* Blanking Porch Control register */
#define LCD_DFC 0xB6 /* Display Function Control register */
#define LCD_ETMOD 0xB7 /* Entry Mode Set */
#define LCD_BACKLIGHT1 0xB8 /* Backlight Control 1 */
#define LCD_BACKLIGHT2 0xB9 /* Backlight Control 2 */
#define LCD_BACKLIGHT3 0xBA /* Backlight Control 3 */
#define LCD_BACKLIGHT4 0xBB /* Backlight Control 4 */
#define LCD_BACKLIGHT5 0xBC /* Backlight Control 5 */
#define LCD_BACKLIGHT7 0xBE /* Backlight Control 7 */
#define LCD_BACKLIGHT8 0xBF /* Backlight Control 8 */
#define LCD_POWER1 0xC0 /* Power Control 1 register */
#define LCD_POWER2 0xC1 /* Power Control 2 register */
#define LCD_VCOM1 0xC5 /* VCOM Control 1 register */
#define LCD_VCOM2 0xC7 /* VCOM Control 2 register */
#define LCD_NVMWR 0xD0 /* NV Memory Write */
#define LCD_NVMPKEY 0xD1 /* NV Memory Protection Key */
#define LCD_RDNVM 0xD2 /* NV Memory Status Read */
#define LCD_READ_ID4 0xD3 /* Read ID4 */
#define LCD_PGAMMA 0xE0 /* Positive Gamma Correction register */
#define LCD_NGAMMA 0xE1 /* Negative Gamma Correction register */
#define LCD_DGAMCTRL1 0xE2 /* Digital Gamma Control 1 */
#define LCD_DGAMCTRL2 0xE3 /* Digital Gamma Control 2 */
#define LCD_INTERFACE 0xF6 /* Interface control register */
/* Extend register commands */
#define LCD_POWERA 0xCB /* Power control A register */
#define LCD_POWERB 0xCF /* Power control B register */
#define LCD_DTCA 0xE8 /* Driver timing control A */
#define LCD_DTCB 0xEA /* Driver timing control B */
#define LCD_POWER_SEQ 0xED /* Power on sequence register */
#define LCD_3GAMMA_EN 0xF2 /* 3 Gamma enable register */
#define LCD_PRC 0xF7 /* Pump ratio control register */
/* Size of read registers */
#define LCD_READ_ID4_SIZE 3 /* Size of Read ID4 */
void disp_write_data(uint16_t avalue)
{
pin_disp_rs.Set1(); // Set WRX to send data
pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data
disp_spi.SendData(avalue);
disp_spi.WaitSendFinish();
uint16_t d16;
while (disp_spi.TryRecvData(&d16))
{
//
}
pin_disp_cs.Set1(); // Deselect: Chip Select high
}
void disp_write_reg(uint8_t avalue)
{
pin_disp_rs.Set0(); // Reset WRX to send command
pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data
disp_spi.SendData(avalue);
disp_spi.WaitSendFinish();
uint16_t d16;
while (disp_spi.TryRecvData(&d16))
{
//
}
pin_disp_cs.Set1(); // Deselect: Chip Select high
}
void init_ili9341()
{
TRACE("Initializing ILI9341...\r\n");
pin_disp_cs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
pin_disp_rs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
//pin_disp_cs.Set0();
//pin_disp_cs.Set1();
// init SPI5
hwpinctrl.PinSetup(PORTNUM_F, 7, PINCFG_AF_5); // SPI5.SCK
hwpinctrl.PinSetup(PORTNUM_F, 8, PINCFG_AF_5 | PINCFG_PULLDOWN); // SPI5.MISO
hwpinctrl.PinSetup(PORTNUM_F, 9, PINCFG_AF_5); // SPI5.MOSI
disp_spi.idleclk_high = false;
disp_spi.speed = 4000000;
disp_spi.databits = 8;
disp_spi.Init(5);
delay_ms(100);
/* Configure LCD */
disp_write_reg(0xCA);
disp_write_data(0xC3);
disp_write_data(0x08);
disp_write_data(0x50);
disp_write_reg(LCD_POWERB);
disp_write_data(0x00);
disp_write_data(0xC1);
disp_write_data(0x30);
disp_write_reg(LCD_POWER_SEQ);
disp_write_data(0x64);
disp_write_data(0x03);
disp_write_data(0x12);
disp_write_data(0x81);
disp_write_reg(LCD_DTCA);
disp_write_data(0x85);
disp_write_data(0x00);
disp_write_data(0x78);
disp_write_reg(LCD_POWERA);
disp_write_data(0x39);
disp_write_data(0x2C);
disp_write_data(0x00);
disp_write_data(0x34);
disp_write_data(0x02);
disp_write_reg(LCD_PRC);
disp_write_data(0x20);
disp_write_reg(LCD_DTCB);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_reg(LCD_FRMCTR1);
disp_write_data(0x00);
disp_write_data(0x1B);
disp_write_reg(LCD_DFC);
disp_write_data(0x0A);
disp_write_data(0xA2);
disp_write_reg(LCD_POWER1);
disp_write_data(0x10);
disp_write_reg(LCD_POWER2);
disp_write_data(0x10);
disp_write_reg(LCD_VCOM1);
disp_write_data(0x45);
disp_write_data(0x15);
disp_write_reg(LCD_VCOM2);
disp_write_data(0x90);
disp_write_reg(LCD_MAC);
disp_write_data(0xC8);
disp_write_reg(LCD_3GAMMA_EN);
disp_write_data(0x00);
disp_write_reg(LCD_RGB_INTERFACE);
disp_write_data(0xC2);
disp_write_reg(LCD_DFC);
disp_write_data(0x0A);
disp_write_data(0xA7);
disp_write_data(0x27);
disp_write_data(0x04);
/* Colomn address set */
disp_write_reg(LCD_COLUMN_ADDR);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0xEF);
/* Page address set */
disp_write_reg(LCD_PAGE_ADDR);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0x01);
disp_write_data(0x3F);
disp_write_reg(LCD_INTERFACE);
disp_write_data(0x01);
disp_write_data(0x00);
disp_write_data(0x06);
disp_write_reg(LCD_GRAM);
delay_ms(200);
disp_write_reg(LCD_GAMMA);
disp_write_data(0x01);
disp_write_reg(LCD_PGAMMA);
disp_write_data(0x0F);
disp_write_data(0x29);
disp_write_data(0x24);
disp_write_data(0x0C);
disp_write_data(0x0E);
disp_write_data(0x09);
disp_write_data(0x4E);
disp_write_data(0x78);
disp_write_data(0x3C);
disp_write_data(0x09);
disp_write_data(0x13);
disp_write_data(0x05);
disp_write_data(0x17);
disp_write_data(0x11);
disp_write_data(0x00);
disp_write_reg(LCD_NGAMMA);
disp_write_data(0x00);
disp_write_data(0x16);
disp_write_data(0x1B);
disp_write_data(0x04);
disp_write_data(0x11);
disp_write_data(0x07);
disp_write_data(0x31);
disp_write_data(0x33);
disp_write_data(0x42);
disp_write_data(0x05);
disp_write_data(0x0C);
disp_write_data(0x0A);
disp_write_data(0x28);
disp_write_data(0x2F);
disp_write_data(0x0F);
disp_write_reg(LCD_SLEEP_OUT);
delay_ms(200);
disp_write_reg(LCD_DISPLAY_ON);
/* GRAM start writing */
disp_write_reg(LCD_GRAM);
}
void lcd_init()
{
uint32_t tmp;
uint32_t pinflags = PINCFG_SPEED_MEDIUM;
/*
+------------------------+-----------------------+----------------------------+
+ LCD pins assignment +
+------------------------+-----------------------+----------------------------+
| LCD_TFT R2 <-> PC.10 | LCD_TFT G2 <-> PA.06 | LCD_TFT B2 <-> PD.06 |
| LCD_TFT R3 <-> PB.00 | LCD_TFT G3 <-> PG.10 | LCD_TFT B3 <-> PG.11 |
| LCD_TFT R4 <-> PA.11 | LCD_TFT G4 <-> PB.10 | LCD_TFT B4 <-> PG.12 |
| LCD_TFT R5 <-> PA.12 | LCD_TFT G5 <-> PB.11 | LCD_TFT B5 <-> PA.03 |
| LCD_TFT R6 <-> PB.01 | LCD_TFT G6 <-> PC.07 | LCD_TFT B6 <-> PB.08 |
| LCD_TFT R7 <-> PG.06 | LCD_TFT G7 <-> PD.03 | LCD_TFT B7 <-> PB.09 |
-------------------------------------------------------------------------------
| LCD_TFT HSYNC <-> PC.06 | LCDTFT VSYNC <-> PA.04 |
| LCD_TFT CLK <-> PG.07 | LCD_TFT DE <-> PF.10 |
-----------------------------------------------------
*/
// LCD CONTROLLER PINS
hwpinctrl.PinSetup(PORTNUM_A, 3, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 4, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 12, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 0, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_B, 1, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_B, 8, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 9, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 7, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_D, 3, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_D, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_F, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 7, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 10, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_G, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_9);
// The ILI9341 must be initialized trough SPI
init_ili9341();
//--------------------------------------------------------------
// Configure the internal LCD controller
lcdctrl.hsync = 10;
lcdctrl.hbp = 20;
lcdctrl.hfp = 10;
lcdctrl.vsync = 2;
lcdctrl.vbp = 2;
lcdctrl.vfp = 5;
lcdctrl.Init(240, 320, (void *)hwsdram.address);
//lcdctrl.Init(240, 320, (void *)0x08000000);
}
#endif
void lcd_test()
{
TRACE("--- LCD TEST ---\r\n");
lcd_init();
uint16_t w = lcdctrl.hwwidth;
uint16_t h = lcdctrl.hwheight;
uint16_t * pp;
uint16_t color = 0x001F;
uint32_t cnt = w * 10;
uint32_t n;
pp = (uint16_t *)hwsdram.address;
for (n = 0; n < cnt; ++n)
{
*(pp++) = color;
}
#if 1
disp.Init(w, h, (void *)(hwsdram.address));
disp.FillScreen(0);
disp.color = RGB16(0, 255, 0);
disp.FillRect(10, 10, 100, 100, disp.color);
disp.color = RGB16(255, 0, 0);
disp.DrawRect(0, 0, disp.width, disp.height);
disp.color = 0xffff;
disp.SetCursor(50, 150);
disp.DrawString("Hello World!");
#endif
TRACE("LCD test finished.\r\n");
}
| 35.493421 | 88 | 0.658943 | nvitya |
c0bf52def1951745aca51f0d6cc56c2bc7c16281 | 330 | hpp | C++ | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | #pragma once
#include <cstdint>
#include <vector>
namespace ssmhasher {
class TestGen {
private:
uint32_t x;
uint32_t y;
uint32_t z;
uint32_t w;
void mix();
uint32_t randU32();
public:
TestGen();
explicit TestGen(uint32_t seed);
void gen(std::byte *blob, std::size_t size);
};
} // namespace ssmhasher | 12.692308 | 46 | 0.669697 | fleex-x |
c0ca2ef32f84e6385b70a2ec58b533a91acbc866 | 55,202 | cc | C++ | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2013-2019 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
#include <cstdint>
#include <node.h>
#include <node_buffer.h>
#if defined(_MSC_VER)
#include "io.h"
#include "fcntl.h"
#endif
extern "C" {
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_batch.h>
#include <aerospike/as_key.h>
#include <aerospike/as_record.h>
#include <aerospike/as_record_iterator.h>
#include <aerospike/aerospike_scan.h>
#include <aerospike/as_arraylist.h>
#include <aerospike/as_arraylist_iterator.h>
#include <aerospike/as_boolean.h>
#include <aerospike/as_geojson.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_hashmap_iterator.h>
#include <aerospike/as_pair.h>
#include <aerospike/as_scan.h>
#include <aerospike/as_map.h>
#include <aerospike/as_nil.h>
#include <aerospike/as_stringmap.h>
#include <aerospike/as_vector.h>
#include <citrusleaf/alloc.h>
}
#include "client.h"
#include "conversions.h"
#include "log.h"
#include "enums.h"
#include "string.h"
using namespace node;
using namespace v8;
const char * DoubleType = "Double";
const char * GeoJSONType = "GeoJSON";
/*******************************************************************************
* FUNCTIONS
******************************************************************************/
int get_string_property(char** strp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsString()) {
as_v8_error(log, "Type error: %s property should be string", prop);
return AS_NODE_PARAM_ERR;
}
(*strp) = strdup(*Nan::Utf8String(value));
as_v8_detail(log, "%s => \"%s\"", prop, *strp);
return AS_NODE_PARAM_OK;
}
int get_optional_string_property(char** strp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsString()) {
if (defined != NULL) (*defined) = true;
(*strp) = strdup(*Nan::Utf8String(value));
as_v8_detail(log, "%s => \"%s\"", prop, *strp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
} else {
as_v8_error(log, "Type error: %s property should be string", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_int_property(int* intp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsNumber()) {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
(*intp) = Nan::To<int>(value).FromJust();
as_v8_detail(log, "%s => (int) %d", prop, *intp);
return AS_NODE_PARAM_OK;
}
int get_optional_int_property(int* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int>(value).FromJust();
as_v8_detail(log, "%s => (int) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
} else {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_int64_property(int64_t* intp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsNumber()) {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
(*intp) = Nan::To<int64_t>(value).FromJust();
as_v8_detail(log, "%s => (int64) %d", prop, *intp);
return AS_NODE_PARAM_OK;
}
int get_uint32_property(uint32_t* uintp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
(*uintp) = Nan::To<uint32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *uintp);
} else {
as_v8_error(log, "Type error: %s property should be integer (uint32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_int64_property(int64_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int64_t>(value).FromJust();
as_v8_detail(log, "%s => (int64) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_int32_property(int32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer (int32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_uint32_property(uint32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<uint32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer (uint32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_bool_property(bool* boolp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsBoolean()) {
if (defined != NULL) (*defined) = true;
(*boolp) = Nan::To<bool>(value).FromJust();
as_v8_detail(log, "%s => (bool) %d", prop, *boolp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be boolean", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_bool_property(bool* boolp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsBoolean()) {
(*boolp) = Nan::To<bool>(value).FromJust();
as_v8_detail(log, "%s => (bool) %d", prop, *boolp);
} else {
as_v8_error(log, "Type error: %s property should be boolean", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_list_property(as_list** list, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsArray()) {
as_v8_error(log, "Type error: %s property should be array", prop);
return AS_NODE_PARAM_ERR;
}
return list_from_jsarray(list, Local<Array>::Cast(value), log);
}
int get_bytes_property(uint8_t** bytes, int* size, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!node::Buffer::HasInstance(value)) {
as_v8_error(log, "Type error: %s property should be Buffer", prop);
return AS_NODE_PARAM_ERR;
}
as_v8_debug(log, "Extracting bytes from JS Buffer");
if (extract_blob_from_jsobject(bytes, size, value.As<Object>(), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Extracting bytes from a JS Buffer failed");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_asval_property(as_val** value, Local<Object> obj, const char* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (v8value->IsUndefined()) {
as_v8_error(log, "Type error: %s property should not be undefined", prop);
return AS_NODE_PARAM_ERR;
}
return asval_from_jsvalue(value, v8value, log);
}
int get_optional_asval_property(as_val** value, bool* defined, Local<Object> obj, const char* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (v8value->IsUndefined() || v8value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
return AS_NODE_PARAM_OK;
}
if (defined != NULL) (*defined) = true;
return asval_from_jsvalue(value, v8value, log);
}
int host_from_jsobject(Local<Object> obj, char** addr, uint16_t* port, const LogInfo* log)
{
Local<Value> v8_addr = Nan::Get(obj, Nan::New("addr").ToLocalChecked()).ToLocalChecked();
Local<Value> v8_port = Nan::Get(obj, Nan::New("port").ToLocalChecked()).ToLocalChecked();
if (v8_addr->IsString()) {
*addr = (char*) malloc(HOST_ADDRESS_SIZE);
strcpy(*addr, *Nan::Utf8String(v8_addr.As<String>()));
as_v8_detail(log, "host addr : %s", (*addr));
} else {
return AS_NODE_PARAM_ERR;
}
if (v8_port->IsNumber()) {
*port = (uint16_t) Nan::To<uint32_t>(v8_port).FromJust();
} else {
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int log_from_jsobject(LogInfo* log, Local<Object> obj)
{
int rc = AS_NODE_PARAM_OK;
as_log_level level = log->level;
FILE* fd = log->fd;
if (obj->IsObject()) {
Local<Object> v8_log = obj.As<Object>();
Local<Value> v8_level = Nan::Get(v8_log, Nan::New("level").ToLocalChecked()).ToLocalChecked();
Local<Value> v8_file = Nan::Get(v8_log, Nan::New("file").ToLocalChecked()).ToLocalChecked();
// `level` is optional
if (v8_level->IsNumber()){
level = (as_log_level) Nan::To<int>(v8_level).FromJust();
} else if (v8_level->IsNull() || v8_level->IsUndefined()){
// `null` and `undefined` imply the value should not change.
} else {
// Any other value is a bad parameter
rc = AS_NODE_PARAM_ERR;
}
// `file` is optional
if (rc == AS_NODE_PARAM_OK) {
if (v8_file->IsNumber()) {
int fildes = Nan::To<int>(v8_file).FromJust();
#if !defined(_MSC_VER)
fd = fdopen(fildes, "a");
#else
intptr_t osfptr = _get_osfhandle(fildes);
int osfd = _open_osfhandle(osfptr, O_APPEND);
fd = _fdopen(osfd, "a");
#endif
if (fd == NULL) {
fprintf(stderr, "Could not open file descriptor for logging: %s\n", strerror(errno));
rc = AS_NODE_PARAM_ERR;
}
} else if (v8_file->IsNull() || v8_file->IsUndefined()){
// `null` and `undefined` imply the value should not change.
} else {
// Any other value is a bad parameter
rc = AS_NODE_PARAM_ERR;
}
}
} else {
// The value should be an object. Otherwise it should fail.
rc = AS_NODE_PARAM_ERR;
}
// Only if no error occurred do we set the log values.
if (rc == AS_NODE_PARAM_OK) {
log->level = level;
log->fd = fd;
}
return rc;
}
as_val* asval_clone(const as_val* val, const LogInfo* log)
{
as_val_t t = as_val_type( (as_val*)val);
as_val* clone_val = NULL;
switch(t) {
case AS_NIL: {
clone_val = (as_val*) &as_nil;
break;
}
case AS_BOOLEAN: {
as_boolean *bool_val = as_boolean_fromval(val);
as_boolean *clone_bool = as_boolean_new(bool_val->value);
if( clone_bool == NULL)
{
as_v8_error(log, "cloning a boolean value failed");
}
clone_val = as_boolean_toval(clone_bool);
break;
}
case AS_INTEGER: {
as_integer* int_val = as_integer_fromval( val );
int64_t ival = as_integer_get( int_val);
as_v8_detail(log, "Cloning Integer value %d", ival);
as_integer* clone_int = as_integer_new(ival);
if(clone_int == NULL)
{
as_v8_error(log, "Cloning integer failed");
}
clone_val = as_integer_toval(clone_int);
break;
}
case AS_STRING: {
as_string* str_val = as_string_fromval( val );
char* strval = as_string_get( str_val);
as_v8_detail(log, "Cloning String value %s", strval);
char* clone_str = (char*) cf_strdup( strval);
if(clone_str == NULL)
{
as_v8_error(log, "cloning string failed");
}
as_string* clone_as = as_string_new(clone_str, true);
if(clone_as == NULL)
{
as_v8_error(log, "cloning string failed");
}
clone_val = as_string_toval( clone_as);
break;
}
case AS_BYTES: {
as_bytes* bytes_val = as_bytes_fromval( val);
size_t size = as_bytes_size(bytes_val);
uint8_t *bytes = (uint8_t*) cf_malloc(size);
memcpy(bytes, as_bytes_get(bytes_val), size);
as_v8_detail(log, "Cloning Blob value %u ", bytes);
clone_val = as_bytes_toval(as_bytes_new_wrap( bytes, size, true));
break;
}
case AS_LIST: {
as_arraylist* list = (as_arraylist*) as_list_fromval((as_val*)val);
clone_val = as_list_toval( (as_list*)as_arraylist_new(as_arraylist_size(list), list->block_size));
as_arraylist_iterator it;
as_arraylist_iterator_init( &it, list);
int index = 0;
as_v8_detail(log, "Cloning a list value of size %d ", as_arraylist_size(list));
while( as_arraylist_iterator_has_next( &it)) {
as_val* arr_element = (as_val*) as_arraylist_iterator_next( &it);
as_val* clone_element = asval_clone( arr_element, log);
as_arraylist_set((as_arraylist*) clone_val, index++, clone_element);
}
as_v8_detail(log, "Cloning a list SUCCESS");
break;
}
case AS_MAP: {
as_hashmap* map = (as_hashmap*) as_map_fromval(val);
clone_val = as_map_toval( (as_map*)as_hashmap_new(as_hashmap_size(map)));
as_hashmap_iterator it;
as_hashmap_iterator_init( &it, map);
while( as_hashmap_iterator_has_next( &it )) {
as_pair* pair = (as_pair*) as_hashmap_iterator_next( &it);
as_val* orig_key = as_pair_1(pair);
as_val* orig_val = as_pair_2(pair);
as_val* clone_key = asval_clone( orig_key, log);
as_val* clone_mapval = asval_clone( orig_val, log);
as_hashmap_set( (as_hashmap*) clone_val, clone_key, clone_mapval);
}
as_v8_detail( log, "Cloning a map SUCCESS");
break;
}
case AS_DOUBLE: {
as_double * dbl_val = as_double_fromval(val);
double dval = as_double_get(dbl_val);
as_v8_detail(log, "Cloning double value %g", dval);
as_double * clone_dbl = as_double_new(dval);
if(clone_dbl == NULL)
{
as_v8_error(log, "Cloning double failed");
}
clone_val = as_double_toval(clone_dbl);
break;
}
case AS_GEOJSON: {
as_geojson * geo_val = as_geojson_fromval(val);
char* strval = as_geojson_get(geo_val);
as_v8_detail(log, "Cloning GeoJSON value %s", strval);
char* clone_str = (char*) cf_strdup(strval);
if(clone_str == NULL)
{
as_v8_error(log, "cloning GeoJSON failed");
}
as_geojson * clone_as = as_geojson_new(clone_str, true);
if(clone_as == NULL)
{
as_v8_error(log, "cloning GeoJSON failed");
}
clone_val = as_geojson_toval(clone_as);
break;
}
default:
as_v8_error( log, "as_val received is UNKNOWN type %d", (int)t);
break;
}
return clone_val;
}
bool key_clone(const as_key* src, as_key** dest, const LogInfo* log, bool alloc_key)
{
if (src == NULL || dest== NULL) {
as_v8_info(log, "Parameter error : NULL in source/destination");
return false;
}
as_v8_detail(log, "Cloning the key");
as_key_value* val = src->valuep;
if (src->digest.init == true) {
if (alloc_key) {
*dest = as_key_new_digest(src->ns, src->set, src->digest.value);
} else {
as_key_init_digest(*dest, src->ns, src->set, src->digest.value);
}
if (val != NULL) {
(*dest)->valuep = (as_key_value*) asval_clone((as_val*) val, log);
}
} else if (val != NULL) {
as_key_value* clone_val = (as_key_value*) asval_clone((as_val*) val, log);
if (alloc_key) {
*dest = as_key_new_value(src->ns, src->set, (as_key_value*) clone_val);
} else {
as_key_init_value(*dest, src->ns, src->set, (as_key_value*) clone_val);
}
} else {
as_v8_detail(log, "Key has neither value nor digest ");
}
return true;
}
bool record_clone(const as_record* src, as_record** dest, const LogInfo* log)
{
if(src == NULL || dest == NULL) {
return false;
}
as_v8_detail( log, "Cloning the record");
(*dest)->ttl = src->ttl;
(*dest)->gen = src->gen;
as_record_iterator it;
as_record_iterator_init(&it, src);
while (as_record_iterator_has_next(&it)) {
as_bin * bin = as_record_iterator_next(&it);
as_bin_value * val = as_bin_get_value(bin);
as_bin_value* clone_val = (as_bin_value*) asval_clone( (as_val*) val, log);
as_v8_detail(log, "Bin Name: %s", as_bin_get_name(bin));
as_record_set( *dest, as_bin_get_name(bin), clone_val);
}
as_key* src_key = (as_key*) &src->key;
as_key* dest_key = (as_key*) &(*dest)->key;
if(src_key != NULL) {
//clone the key but do not malloc the key structure,
// use the structure available inside record structure.
key_clone( src_key, &dest_key, log, false);
}
return true;
}
Local<Object> error_to_jsobject(as_error* error, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> err = Nan::New<Object>();
if (error == NULL) {
as_v8_info(log, "error(C structure) object is NULL, node.js error object cannot be constructed");
return scope.Escape(err);
}
// LDT error codes are populated as a string message.
// Parse the string and populate the error object appropriately
// so that application can look up the error codes and doesn't have
// to look at strings.
// Check if it's an UDF ERROR and message has string LDT in it
// then it implies it is an LDT error, so parse the error
// and populate the error object.
if(error->code == AEROSPIKE_ERR_UDF && strstr(error->message, "LDT") != NULL) {
char err_message[AS_ERROR_MESSAGE_MAX_LEN] = {"\0"};
as_strlcpy(err_message, error->message, AS_ERROR_MESSAGE_MAX_LEN);
char *ptr;
ptr = strtok(err_message, ":");
if(ptr != NULL) {
error->file = ptr;
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
error->line = atoi(ptr);
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
error->code = (as_status) atoi(ptr);
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
as_strlcpy(error->message, ptr, AS_ERROR_MESSAGE_MAX_LEN);
ptr = strtok(NULL, ":");
}
// LDT error does not populate function name as of now.
error->func = NULL;
}
Nan::Set(err, Nan::New("code").ToLocalChecked(), Nan::New(error->code));
Nan::Set(err, Nan::New("message").ToLocalChecked(), error->message[0] != '\0' ? Nan::New(error->message).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("func").ToLocalChecked(), error->func ? Nan::New(error->func).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("file").ToLocalChecked(), error->file ? Nan::New(error->file).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("line").ToLocalChecked(), error->line ? Nan::New(error->line) : Nan::New((uint32_t)0) );
Nan::Set(err, Nan::New("inDoubt").ToLocalChecked(), error->in_doubt ? Nan::True() : Nan::False());
return scope.Escape(err);
}
Local<Value> val_to_jsvalue(as_val* val, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
if ( val == NULL) {
as_v8_debug(log, "value = NULL");
return scope.Escape(Nan::Null());
}
switch ( as_val_type(val) ) {
case AS_NIL: {
as_v8_detail(log,"value is of type as_null");
return scope.Escape(Nan::Null());
}
case AS_INTEGER : {
as_integer * ival = as_integer_fromval(val);
if ( ival ) {
int64_t data = as_integer_getorelse(ival, -1);
as_v8_detail(log, "value = %lld ", data);
return scope.Escape(Nan::New((double)data));
}
break;
}
case AS_DOUBLE : {
as_double* dval = as_double_fromval(val);
if( dval ) {
double d = as_double_getorelse(dval, -1);
as_v8_detail(log, "value = %lf ",d);
return scope.Escape(Nan::New((double)d));
}
break;
}
case AS_STRING : {
as_string * sval = as_string_fromval(val);
if ( sval ) {
char * data = as_string_getorelse(sval, NULL);
as_v8_detail(log, "value = \"%s\"", data);
return scope.Escape(Nan::New(data).ToLocalChecked());
}
break;
}
case AS_BYTES : {
as_bytes * bval = as_bytes_fromval(val);
if ( bval ) {
uint8_t * data = as_bytes_getorelse(bval, NULL);
uint32_t size = as_bytes_size(bval);
as_v8_detail(log,
"value = <%x %x %x%s>",
size > 0 ? data[0] : 0,
size > 1 ? data[1] : 0,
size > 2 ? data[2] : 0,
size > 3 ? " ..." : ""
);
// this constructor actually copies data into the new Buffer
Local<Object> buff = Nan::CopyBuffer((char*) data, size).ToLocalChecked();
return scope.Escape(buff);
}
break;
}
case AS_LIST : {
as_arraylist* listval = (as_arraylist*) as_list_fromval((as_val*)val);
int size = as_arraylist_size(listval);
Local<Array> jsarray = Nan::New<Array>(size);
for ( int i = 0; i < size; i++ ) {
as_val * arr_val = as_arraylist_get(listval, i);
Local<Value> jsval = val_to_jsvalue(arr_val, log);
Nan::Set(jsarray, i, jsval);
}
return scope.Escape(jsarray);
}
case AS_MAP : {
Local<Object> jsobj = Nan::New<Object>();
as_hashmap* map = (as_hashmap*) as_map_fromval(val);
as_hashmap_iterator it;
as_hashmap_iterator_init(&it, map);
while ( as_hashmap_iterator_has_next(&it) ) {
as_pair *p = (as_pair*) as_hashmap_iterator_next(&it);
as_val* key = as_pair_1(p);
as_val* val = as_pair_2(p);
Nan::Set(jsobj, val_to_jsvalue(key, log), val_to_jsvalue(val, log));
}
return scope.Escape(jsobj);
}
case AS_GEOJSON : {
as_geojson * gval = as_geojson_fromval(val);
if ( gval ) {
char * data = as_geojson_getorelse(gval, NULL);
as_v8_detail(log, "geojson = \"%s\"", data);
return scope.Escape(Nan::New<String>(data).ToLocalChecked());
}
break;
}
default:
break;
}
return scope.Escape(Nan::Undefined());
}
Local<Object> recordbins_to_jsobject(const as_record* record, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> bins ;
if (record == NULL) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object");
return scope.Escape(bins);
}
bins = Nan::New<Object>();
as_record_iterator it;
as_record_iterator_init(&it, record);
while ( as_record_iterator_has_next(&it) ) {
as_bin * bin = as_record_iterator_next(&it);
char * name = as_bin_get_name(bin);
as_val * val = (as_val *) as_bin_get_value(bin);
Local<Value> obj = val_to_jsvalue(val, log );
Nan::Set(bins, Nan::New(name).ToLocalChecked(), obj);
as_v8_detail(log, "Setting binname %s ", name);
}
return scope.Escape(bins);
}
Local<Object> recordmeta_to_jsobject(const as_record* record, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> meta;
if(record == NULL) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js metadata object");
return scope.Escape(meta);
}
meta = Nan::New<Object>();
Local<Number> ttl;
switch(record->ttl) {
case AS_RECORD_NO_EXPIRE_TTL:
ttl = Nan::New<Number>(TTL_NEVER_EXPIRE);
break;
default:
ttl = Nan::New<Number>(record->ttl);
}
Nan::Set(meta, Nan::New("ttl").ToLocalChecked(), ttl);
as_v8_detail(log, "TTL of the record %d", record->ttl);
Nan::Set(meta, Nan::New("gen").ToLocalChecked(), Nan::New(record->gen));
as_v8_detail(log, "Gen of the record %d", record->gen);
return scope.Escape(meta);
}
Local<Object> record_to_jsobject(const as_record* record, const as_key* key, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> okey;
if ( record == NULL ) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object");
return scope.Escape(okey);
}
okey = key_to_jsobject(key ? key : &record->key, log);
Local<Object> bins = recordbins_to_jsobject(record, log );
Local<Object> meta = recordmeta_to_jsobject(record, log);
Local<Object> rec = Nan::New<Object>();
Nan::Set(rec, Nan::New("key").ToLocalChecked(), okey);
Nan::Set(rec, Nan::New("meta").ToLocalChecked(), meta);
Nan::Set(rec, Nan::New("bins").ToLocalChecked(), bins);
return scope.Escape(rec);
}
Local<Array> batch_records_to_jsarray(const as_batch_read_records* records, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
const as_vector* list = &records->list;
Local<Array> results = Nan::New<Array>(list->size);
for (uint32_t i = 0; i < list->size; i++) {
as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i);
as_status status = batch_record->result;
as_record* record = &batch_record->record;
as_key* key = &batch_record->key;
Local<Object> result = Nan::New<Object>();
Nan::Set(result, Nan::New("status").ToLocalChecked(), Nan::New(status));
Nan::Set(result, Nan::New("key").ToLocalChecked(), key_to_jsobject(key ? key : &record->key, log));
if (status == AEROSPIKE_OK) {
Nan::Set(result, Nan::New("meta").ToLocalChecked(), recordmeta_to_jsobject(record, log));
Nan::Set(result, Nan::New("bins").ToLocalChecked(), recordbins_to_jsobject(record, log));
}
Nan::Set(results, i, result);
}
return scope.Escape(results);
}
//Forward references;
int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log);
int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log);
bool instanceof(Local<Value> value, const char * type)
{
if (value->IsObject()) {
Local<String> ctor_name = value.As<Object>()->GetConstructorName();
Nan::Utf8String cn(ctor_name);
return 0 == strncmp(*cn, type, strlen(type));
} else {
return false;
}
}
/**
* Node.js stores all number values > 2^31 in the class Number and
* values < 2^31 are stored in the class SMI (Small Integers). To distinguish
* between a double and int64_t value in Node.js, retrieve the value as double
* and also as int64_t. If the values are same, then store it as int64_t. Else
* store it as double.
* The problem with this implementation is var 123.00 will be treated as int64_t.
* Applications can enforce double type by using the `Aerospike.Double` data type,
* e.g.
*
* const Double = Aerospike.Double
* var f = new Double(123)
**/
bool is_double_value(Local<Value> value)
{
if (value->IsNumber()) {
int64_t i = Nan::To<int64_t>(value).FromJust();
double d = Nan::To<double>(value).FromJust();
return d != (double)i;
}
return instanceof(value, DoubleType);
}
double double_value(Local<Value> value)
{
if (instanceof(value, DoubleType)) {
value = Nan::Get(value.As<Object>(), Nan::New<String>("Double").ToLocalChecked()).ToLocalChecked();
}
return Nan::To<double>(value).FromJust();
}
bool is_geojson_value(Local<Value> value)
{
return instanceof(value, GeoJSONType);
}
char* geojson_as_string(Local<Value> value)
{
Local<Value> strval = Nan::Get(value.As<Object>(), Nan::New("str").ToLocalChecked()).ToLocalChecked();
return strdup(*Nan::Utf8String(strval));
}
int list_from_jsarray(as_list** list, Local<Array> array, const LogInfo* log)
{
const uint32_t capacity = array->Length();
as_v8_detail(log, "Creating new as_arraylist with capacity %d", capacity);
as_arraylist* arraylist = as_arraylist_new(capacity, 0);
if (arraylist == NULL) {
as_v8_error(log, "List allocation failed");
Nan::ThrowError("List allocation failed");
return AS_NODE_PARAM_ERR;
}
*list = (as_list*) arraylist;
for (uint32_t i = 0; i < capacity; i++) {
as_val* val;
if (asval_from_jsvalue(&val, Nan::Get(array, i).ToLocalChecked(), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_list_append(*list, val);
}
return AS_NODE_PARAM_OK;
}
int map_from_jsobject(as_map** map, Local<Object> obj, const LogInfo* log)
{
const Local<Array> props = Nan::GetOwnPropertyNames(obj.As<Object>()).ToLocalChecked();
const uint32_t capacity = props->Length();
as_v8_detail(log, "Creating new as_hashmap with capacity %d", capacity);
as_hashmap* hashmap = as_hashmap_new(capacity);
if (hashmap == NULL) {
as_v8_error(log, "Map allocation failed");
Nan::ThrowError("Map allocation failed");
return AS_NODE_PARAM_ERR;
}
*map = (as_map*) hashmap;
for (uint32_t i = 0; i < capacity; i++) {
const Local<Value> name = Nan::Get(props, i).ToLocalChecked();
const Local<Value> value = Nan::Get(obj, name).ToLocalChecked();
as_val* val = NULL;
if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_stringmap_set(*map, *Nan::Utf8String(name), val);
}
return AS_NODE_PARAM_OK;
}
int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log)
{
if (v8value->IsNull()) {
as_v8_detail(log, "The as_val is NULL");
*value = (as_val*) &as_nil;
} else if (v8value->IsUndefined()) {
// asval_from_jsvalue is called recursively.
// If a bin value is undefined, it should be handled by the caller of
// this function gracefully.
// If an entry in a map/list is undefined the corresponding entry becomes null.
as_v8_detail(log, "Object passed is undefined");
*value = (as_val*) &as_nil;
} else if (v8value->IsBoolean()) {
*value = (as_val*) as_boolean_new(Nan::To<bool>(v8value).FromJust());
} else if (v8value->IsString()) {
*value = (as_val*) as_string_new(strdup(*Nan::Utf8String(v8value)), true);
} else if (v8value->IsInt32()) {
*value = (as_val*) as_integer_new(Nan::To<int32_t>(v8value).FromJust());
} else if (v8value->IsUint32()) {
*value = (as_val*) as_integer_new(Nan::To<uint32_t>(v8value).FromJust());
} else if (is_double_value(v8value)) {
*value = (as_val*) as_double_new(double_value(v8value));
} else if (v8value->IsNumber()) {
*value = (as_val*) as_integer_new(Nan::To<int64_t>(v8value).FromJust());
} else if (node::Buffer::HasInstance(v8value)) {
int size;
uint8_t* data;
if (extract_blob_from_jsobject(&data, &size, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Extractingb blob from a js object failed");
return AS_NODE_PARAM_ERR;
}
*value = (as_val*) as_bytes_new_wrap(data, size, true);
} else if (v8value->IsArray()) {
if (list_from_jsarray((as_list**) value, Local<Array>::Cast(v8value), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
} else if (is_geojson_value(v8value)) {
char* jsonstr = geojson_as_string(v8value);
*value = (as_val*) as_geojson_new(jsonstr, true);
} else { // generic object - treat as map
if (map_from_jsobject((as_map**) value, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
}
if (as_v8_detail_enabled(log)) {
auto val_type = as_val_type(*value);
char* val_str = as_val_tostring(*value);
as_v8_detail(log, "type: %d, string value: %s", val_type, val_str);
cf_free(val_str);
}
return AEROSPIKE_OK;
}
int recordbins_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log)
{
const Local<Array> props = Nan::GetOwnPropertyNames(obj).ToLocalChecked();
const uint32_t count = props->Length();
as_record_init(rec, count);
for ( uint32_t i = 0; i < count; i++ ) {
const Local<Value> name = Nan::Get(props, i).ToLocalChecked();
const Local<Value> value = Nan::Get(obj, name).ToLocalChecked();
// A bin can be undefined, or an entry inside a CDT(list, map)
// can be an undefined value.
// If a bin is undefined, it must error out at the earliest.
if( value->IsUndefined()) {
as_v8_error(log, "Bin value 'undefined' not supported: %s", *Nan::Utf8String(name));
return AS_NODE_PARAM_ERR;
}
Nan::Utf8String n(name);
if( strlen(*n) > AS_BIN_NAME_MAX_SIZE ) {
as_v8_error(log, "Bin name length exceeded (max. 14): %s", *n);
return AS_NODE_PARAM_ERR;
}
as_val* val = NULL;
if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
switch(as_val_type(val)) {
case AS_BOOLEAN:
as_val_destroy(val);
as_v8_error(log, "Boolean type not supported: %s", *n);
return AS_NODE_PARAM_ERR;
case AS_INTEGER:
as_record_set_integer(rec, *n, (as_integer*)val);
break;
case AS_DOUBLE:
as_record_set_as_double(rec, *n, (as_double*)val);
break;
case AS_STRING:
as_record_set_string(rec, *n, (as_string*)val);
break;
case AS_BYTES:
as_record_set_bytes(rec, *n, (as_bytes*) val);
break;
case AS_LIST:
as_record_set_list(rec, *n, (as_list*) val);
break;
case AS_MAP:
as_record_set_map(rec, *n, (as_map*) val);
break;
case AS_GEOJSON:
as_record_set_geojson(rec, *n, (as_geojson*) val);
break;
case AS_NIL:
as_record_set_nil(rec, *n);
break;
default:
as_v8_error(log,"Skipping unsupported as_val type %i: %s", as_val_type(val), *n);
break;
}
}
return AS_NODE_PARAM_OK;
}
int recordmeta_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log)
{
as_v8_detail(log, "Setting record meta from JS object");
if (setTTL(obj, &rec->ttl, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
};
if (setGeneration(obj, &rec->gen, log) != AS_NODE_PARAM_OK) {;
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log)
{
if (!node::Buffer::HasInstance(obj)) {
as_v8_error(log, "The binary data is not of the type UnsignedBytes");
return AS_NODE_PARAM_ERR;
}
(*len) = node::Buffer::Length(obj);
(*data) = (uint8_t*) cf_malloc(sizeof(uint8_t) * (*len));
memcpy((*data), node::Buffer::Data(obj), (*len));
return AS_NODE_PARAM_OK;
}
int setTTL(Local<Object> obj, uint32_t* ttl, const LogInfo* log)
{
Local<Value> v8_ttl = Nan::Get(obj, Nan::New("ttl").ToLocalChecked()).ToLocalChecked();
if (v8_ttl->IsNumber()) {
(*ttl) = Nan::To<uint32_t>(v8_ttl).FromJust();
as_v8_detail(log, "TTL: %d", (*ttl));
} else if (v8_ttl->IsNull() || v8_ttl->IsUndefined()) {
// noop - ttl may not be specified
} else {
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int setGeneration(Local<Object> obj, uint16_t* generation, const LogInfo* log)
{
Local<Value> v8_gen = Nan::Get(obj, Nan::New("gen").ToLocalChecked()).ToLocalChecked();
if (v8_gen->IsNumber()) {
(*generation) = (uint16_t) Nan::To<uint32_t>(v8_gen).FromJust();
as_v8_detail(log, "Generation: %d", (*generation));
} else if (v8_gen->IsNull() || v8_gen->IsUndefined()) {
// noop - gen may not be specified
} else {
as_v8_error(log, "Generation should be an integer");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
Local<Object> key_to_jsobject(const as_key* key, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> obj;
if (key == NULL) {
as_v8_debug(log, "Key (C structure) is NULL, cannot form node.js key object");
return scope.Escape(obj);
}
obj = Nan::New<Object>();
if (strlen(key->ns) > 0) {
as_v8_detail(log, "key.ns = \"%s\"", key->ns);
Nan::Set(obj, Nan::New("ns").ToLocalChecked(), Nan::New(key->ns).ToLocalChecked());
} else {
as_v8_debug(log, "Key namespace is NULL");
}
if (strlen(key->set) > 0) {
as_v8_detail(log, "key.set = \"%s\"", key->set);
Nan::Set(obj, Nan::New("set").ToLocalChecked(), Nan::New(key->set).ToLocalChecked());
} else {
as_v8_debug(log, "Key set is NULL");
}
if ( key->valuep ) {
as_val * val = (as_val *) key->valuep;
as_val_t type = as_val_type(val);
switch(type) {
case AS_INTEGER: {
as_integer * ival = as_integer_fromval(val);
as_v8_detail(log, "key.key = %d", as_integer_get(ival));
Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New((double)as_integer_get(ival)));
break;
}
case AS_STRING: {
as_string * sval = as_string_fromval(val);
as_v8_detail(log, "key.key = \"%s\"", as_string_get(sval));
Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New(as_string_get(sval)).ToLocalChecked());
break;
}
case AS_BYTES: {
as_bytes * bval = as_bytes_fromval(val);
if ( bval ) {
uint32_t size = as_bytes_size(bval);
as_v8_detail(log,"key.key = \"%u\"", bval->value);
Local<Object> buff = Nan::CopyBuffer((char*)bval->value, size).ToLocalChecked();
Nan::Set(obj, Nan::New("key").ToLocalChecked(), buff);
break;
}
}
default:
break;
}
} else {
as_v8_detail(log, "Key value is NULL");
}
if (key->digest.init == true) {
Local<Object> buff = Nan::CopyBuffer((char*)key->digest.value, AS_DIGEST_VALUE_SIZE).ToLocalChecked();
Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff);
}
return scope.Escape(obj);
}
Local<Object> jobinfo_to_jsobject(const as_job_info* info, const LogInfo* log)
{
Local<Object> jobinfo;
if (info == NULL) {
as_v8_debug(log, "Job Info ( C structure) is NULL, cannot form node.js jobInfo object");
return jobinfo;
}
jobinfo = Nan::New<Object>();
Nan::Set(jobinfo, Nan::New("progressPct").ToLocalChecked(), Nan::New(info->progress_pct));
as_v8_detail(log, "Progress pct of the job %d", info->progress_pct);
Local<Value> recordsRead = Nan::New((double)info->records_read);
Nan::Set(jobinfo, Nan::New("recordsRead").ToLocalChecked(), recordsRead);
as_v8_detail(log, "Number of records read so far %d", info->records_read);
Nan::Set(jobinfo, Nan::New("status").ToLocalChecked(), Nan::New(info->status));
return jobinfo;
}
int key_from_jsobject(as_key* key, Local<Object> obj, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
as_namespace ns = {'\0'};
as_set set = {'\0'};
if (obj->IsNull()) {
as_v8_error(log, "The key object passed is Null");
return AS_NODE_PARAM_ERR;
}
Local<Value> ns_obj = Nan::Get(obj, Nan::New("ns").ToLocalChecked()).ToLocalChecked();
if (ns_obj->IsString()) {
if (as_strlcpy(ns, *Nan::Utf8String(ns_obj), AS_NAMESPACE_MAX_SIZE) > AS_NAMESPACE_MAX_SIZE) {
as_v8_error(log, "The key namespace is too long (max. %d)", AS_NAMESPACE_MAX_SIZE);
return AS_NODE_PARAM_ERR;
}
if (strlen(ns) == 0) {
as_v8_error(log, "The key namespace must not be empty");
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "key.ns = \"%s\"", ns);
} else {
as_v8_error(log, "The key namespace must be a string");
return AS_NODE_PARAM_ERR;
}
Local<Value> set_obj = Nan::Get(obj, Nan::New("set").ToLocalChecked()).ToLocalChecked();
if (set_obj->IsString()) {
if (as_strlcpy(set, *Nan::Utf8String(set_obj), AS_SET_MAX_SIZE) > AS_SET_MAX_SIZE) {
as_v8_error(log, "The key set is too long (max. %d)", AS_SET_MAX_SIZE);
return AS_NODE_PARAM_ERR;
}
if (strlen(set) == 0) {
as_v8_debug(log, "Key set passed is empty string");
}
as_v8_detail(log,"key.set = \"%s\"", set);
} else if (set_obj->IsNull() || set_obj->IsUndefined()) {
// noop - set name may not be specified
} else {
as_v8_error(log, "The key set must be a string");
return AS_NODE_PARAM_ERR;
}
bool has_value = false;
Local<Value> val_obj = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked();
if (val_obj->IsString()) {
char* value = strdup(*Nan::Utf8String(val_obj));
as_key_init(key, ns, set, value);
as_v8_detail(log, "key.key = \"%s\"", value);
((as_string*) key->valuep)->free = true;
has_value = true;
} else if (is_double_value(val_obj)) {
as_v8_error(log, "Invalid key value: double - only string, integer and Buffer are supported");
return AS_NODE_PARAM_ERR;
} else if (val_obj->IsNumber()) {
int64_t value = Nan::To<int64_t>(val_obj).FromJust();
as_key_init_int64(key, ns, set, value);
as_v8_detail(log, "key.key = %d", value);
has_value = true;
} else if (val_obj->IsObject()) {
Local<Object> obj = val_obj.As<Object>();
int size ;
uint8_t* data ;
if (extract_blob_from_jsobject(&data, &size, obj, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_key_init_rawp(key, ns, set, data, size, true);
has_value = true;
as_v8_detail(log,
"key.key = <%x %x %x%s>",
size > 0 ? data[0] : 0,
size > 1 ? data[1] : 0,
size > 2 ? data[2] : 0,
size > 3 ? " ..." : ""
);
} else if (val_obj->IsNull() || val_obj->IsUndefined()) {
// noop - value can be omitted if digest is given
} else {
as_v8_error(log, "Invalid key value - only string, integer and Buffer are supported");
return AS_NODE_PARAM_ERR;
}
if (has_value) {
// Copy the digest back to the JS key object
as_digest* digest = as_key_digest(key);
uint8_t* bytes = digest->value;
Local<Object> buff = scope.Escape(Nan::CopyBuffer((char*) bytes, AS_DIGEST_VALUE_SIZE).ToLocalChecked());
Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff);
} else {
Local<Value> digest_value = Nan::Get(obj, Nan::New("digest").ToLocalChecked()).ToLocalChecked();
if (digest_value->IsObject()) {
Local<Object> digest_obj = digest_value.As<Object>();
int size;
uint8_t* data;
if (extract_blob_from_jsobject(&data, &size, digest_obj, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_digest_value digest;
memcpy(digest, data, AS_DIGEST_VALUE_SIZE);
as_v8_detail(log,
"key.digest = <%x %x %x%s>",
size > 0 ? digest[0] : 0,
size > 1 ? digest[1] : 0,
size > 2 ? digest[2] : 0,
size > 3 ? " ..." : ""
);
as_key_init_digest(key, ns, set, digest);
} else if (digest_value->IsNull() || digest_value->IsUndefined()) {
as_v8_error(log, "The key must have either a \"value\" or a \"digest\"");
return AS_NODE_PARAM_ERR;
} else {
as_v8_error(log, "Invalid digest value: \"digest\" must be a 20-byte Buffer");
return AS_NODE_PARAM_ERR;
}
}
return AS_NODE_PARAM_OK;
}
int batch_from_jsarray(as_batch* batch, Local<Array> arr, const LogInfo* log)
{
uint32_t len = arr->Length();
as_batch_init(batch, len);
for (uint32_t i = 0; i < len; i++) {
Local<Object> key = Nan::Get(arr, i).ToLocalChecked().As<Object>();
if (key_from_jsobject(as_batch_keyat(batch, i), key, log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch key [%d] failed", i);
return AS_NODE_PARAM_ERR;
}
}
return AS_NODE_PARAM_OK;
}
int batch_read_records_from_jsarray(as_batch_read_records** records, Local<Array> arr, const LogInfo* log)
{
uint32_t no_records = arr->Length();
*records = as_batch_read_create(no_records);
for (uint32_t i = 0; i < no_records; i++) {
as_batch_read_record* record = as_batch_read_reserve(*records);
Local<Object> obj = Nan::Get(arr, i).ToLocalChecked().As<Object>();
Local<Object> key = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked().As<Object>();
if (key_from_jsobject(&record->key, key, log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch keys failed");
return AS_NODE_PARAM_ERR;
}
Local<Value> v8_bins = Nan::Get(obj, Nan::New("bins").ToLocalChecked()).ToLocalChecked();
if (v8_bins->IsArray()) {
char** bin_names;
uint32_t n_bin_names;
if (bins_from_jsarray(&bin_names, &n_bin_names, Local<Array>::Cast(v8_bins), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch bin names failed");
return AS_NODE_PARAM_ERR;
}
record->bin_names = bin_names;
record->n_bin_names = n_bin_names;
}
Local<Value> v8_read_all_bins = Nan::Get(obj, Nan::New("read_all_bins").ToLocalChecked()).ToLocalChecked();
if (v8_read_all_bins->IsBoolean()) {
record->read_all_bins = Nan::To<bool>(v8_read_all_bins).FromJust();
}
}
return AS_NODE_PARAM_OK;
}
int bins_from_jsarray(char*** bins, uint32_t* num_bins, Local<Array> arr, const LogInfo* log)
{
int arr_length = arr->Length();
char** c_bins = (char**) cf_calloc(sizeof(char*), arr_length+1);
as_v8_debug(log, "Number of bins requested %d", arr_length);
for( int i = 0; i < arr_length; i++) {
Local<Value> bname = Nan::Get(arr, i).ToLocalChecked();
c_bins[i] = (char*)cf_malloc(AS_BIN_NAME_MAX_SIZE);
as_strlcpy(c_bins[i], *Nan::Utf8String(bname), AS_BIN_NAME_MAX_SIZE);
as_v8_detail(log, "name of the bin %s", c_bins[i]);
}
// The last entry should be NULL because we are passing to select API calls.
c_bins[arr_length] = NULL;
*bins = c_bins;
*num_bins = (uint32_t) arr_length;
return AS_NODE_PARAM_OK;
}
void
free_batch_records(as_batch_read_records* records)
{
const as_vector* list = &records->list;
for (uint32_t i = 0; i < list->size; i++) {
as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i);
if (batch_record->n_bin_names > 0) {
for (uint32_t j = 0; j < batch_record->n_bin_names; j++) {
cf_free(batch_record->bin_names[j]);
}
cf_free(batch_record->bin_names);
}
}
as_batch_read_destroy(records);
}
int udfargs_from_jsobject(char** filename, char** funcname, as_list** args, Local<Object> obj, const LogInfo* log)
{
if (obj->IsNull()) {
as_v8_error(log, "Object passed is NULL");
return AS_NODE_PARAM_ERR;
}
// Extract UDF module name
Local<Value> v8_module = Nan::Get(obj, Nan::New("module").ToLocalChecked()).ToLocalChecked();
if (v8_module->IsString()) {
size_t size = v8_module.As<String>()->Length() + 1;
if (*filename == NULL) {
*filename = (char*) cf_malloc(sizeof(char) * size);
}
if (as_strlcpy(*filename, *Nan::Utf8String(v8_module), size) > size) {
as_v8_error(log, "UDF module name is too long (> %d)", size);
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "Filename in the udf args is set to %s", *filename);
} else {
as_v8_error(log, "UDF module name should be string");
return AS_NODE_PARAM_ERR;
}
// Extract UDF function name
Local<Value> v8_funcname = Nan::Get(obj, Nan::New("funcname").ToLocalChecked()).ToLocalChecked();
if (v8_funcname->IsString()) {
size_t size = v8_funcname.As<String>()->Length() + 1;
if (*funcname == NULL) {
*funcname = (char*) cf_malloc(sizeof(char) * size);
}
if (as_strlcpy(*funcname, *Nan::Utf8String(v8_funcname), size) > size) {
as_v8_error(log, "UDF function name is too long (> %d)", size);
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "The function name in the UDF args set to %s", *funcname);
} else {
as_v8_error(log, "UDF function name should be string");
return AS_NODE_PARAM_ERR;
}
Local<Value> arglist = Nan::Get(obj, Nan::New("args").ToLocalChecked()).ToLocalChecked();
if (arglist->IsArray()) {
list_from_jsarray(args, Local<Array>::Cast(arglist), log);
as_v8_detail(log, "Parsing UDF args -- done !!!");
} else if (arglist->IsNull() || arglist->IsUndefined()) {
// No argument case: Initialize array with 0 elements.
*args = (as_list*) as_arraylist_new(0, 0);
} else {
as_v8_error(log, "UDF args should be an array");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
// Like strncpy but does not 0 fill the buffer and always null
// terminates. bufsize is the size of the destination buffer.
size_t as_strlcpy(char *d, const char *s, size_t bufsize)
{
size_t len = strlen(s);
size_t ret = len;
if (len >= bufsize) len = bufsize-1;
memcpy(d, s, len);
d[len] = 0;
return ret;
}
| 37.88744 | 162 | 0.591156 | jsa-research |
c0cbe96d938eef7ed67b4be296fed9f40e9c4ac1 | 15,112 | cpp | C++ | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <exception>
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
#include <string>
#include <functional>
#include <condition_variable>
#include <mutex>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <boost/network/protocol/http/server.hpp>
#include <boost/network/uri.hpp>
#include "dp/graph.h"
#include "dp/operators.h"
#include "dp/ingress/udp.h"
#include "dp/ingress/videocap.h"
#include "dp/util/error.h"
#include "mqtt/mqtt.h"
#include "movidius/ncs.h"
#include "movidius/ssd_mobilenet.h"
using namespace std;
using namespace dp;
static constexpr int http_port = 2052;
static constexpr int cast_port = 2053;
DEFINE_int32(port, in::udp::default_port, "listening port");
DEFINE_string(mqtt_host, "127.0.0.1", "MQTT server address");
DEFINE_int32(mqtt_port, mqtt::client::default_port, "MQTT server port");
DEFINE_string(mqtt_client_id, "", "MQTT client ID");
DEFINE_string(mqtt_topic, "", "MQTT topic");
DEFINE_string(model, "graph", "Model name");
DEFINE_string(http_addr, "", "image server listening address");
DEFINE_int32(http_port, http_port, "image server listening port");
DEFINE_int32(stream_port, cast_port, "TCP streaming port");
struct pub_op {
mqtt::client *client;
pub_op(mqtt::client* c) : client(c) { }
void operator() (graph::ctx ctx) {
const auto& str = ctx.in(0)->as<string>();
client->publish(FLAGS_mqtt_topic, str);
}
};
static string index_html(R"(<!DOCTYPE html>
<html>
<head>
<script language="javascript">
function refreshImage() {
document.getElementById('cam0').src = '/jpeg?ts='+Date.now();
setTimeout(refreshImage, 30);
}
document.addEventListener('DOMContentLoaded', refreshImage);
</script>
</head>
<body>
<img id="cam0">
</body>
</html>
)");
static string sz2str(size_t sz) {
char str[64];
sprintf(str, "%u", sz);
return str;
}
struct image_buffer {
vector<unsigned char> data;
size_t size;
image_id id;
static constexpr size_t max_buf_size = 0x10000;
image_buffer() : data(max_buf_size), size(0) { }
const unsigned char* ptr() const {
return &data[0];
}
void update(const void *buf, size_t _sz, const image_id& _id) {
if (_sz > max_buf_size) _sz = max_buf_size;
memcpy(&data[0], buf, _sz);
size = _sz;
id = _id;
}
};
class image_handler;
typedef ::boost::network::http::server<image_handler> http_server_t;
class image_handler {
public:
image_handler() : m_images(2), m_current_buf(0) { }
void set_image(const void *buf, size_t size, const image_id& id) {
int write_buf = 1 - m_current_buf.load();
m_images[write_buf].update(buf, size, id);
atomic_exchange(&m_current_buf, write_buf);
m_set_image_cv.notify_all();
}
const image_buffer* wait() const {
unique_lock<mutex> lock(m_set_image_mux);
m_set_image_cv.wait(lock);
return &m_images[m_current_buf.load()];
}
void operator() (http_server_t::request const& request, http_server_t::connection_ptr conn) {
VLOG(4) << request.method << " " << request.destination;
boost::network::uri::uri uri("http://localhost:80"+request.destination);
static http_server_t::response_header error_headers[] = {
{"Content-type", "text/plain"},
{"Connection", "close"},
};
if (request.method == "GET") {
if (uri.path() == "/") {
handle_index(conn);
return;
}
if (uri.path() == "/jpeg") {
handle_jpeg(conn);
return;
}
if (uri.path() == "/stream") {
handle_stream(conn);
return;
}
conn->set_status(http_server_t::connection::not_found);
conn->set_headers(boost::make_iterator_range(error_headers,
error_headers+sizeof(error_headers)/sizeof(error_headers[0])));
conn->write("Path not supported");
return;
}
conn->set_status(http_server_t::connection::not_supported);
conn->set_headers(boost::make_iterator_range(error_headers,
error_headers+sizeof(error_headers)/sizeof(error_headers[0])));
conn->write("Method not supported");
}
graph::op_func op() {
return [this](graph::ctx ctx) {
const buf_ref &buf = ctx.in(0)->as<buf_ref>();
const auto& id = ctx.in(1)->as<image_id>();
set_image(buf.ptr, buf.len, id);
};
}
private:
vector<image_buffer> m_images;
atomic_int m_current_buf;
mutable mutex m_set_image_mux;
mutable condition_variable m_set_image_cv;
void handle_index(http_server_t::connection_ptr conn) {
http_server_t::response_header common_headers[] = {
{"Content-type", "text/html"},
{"Content-length", sz2str(index_html.length())},
};
conn->set_status(http_server_t::connection::ok);
conn->set_headers(boost::make_iterator_range(common_headers,
common_headers+sizeof(common_headers)/sizeof(common_headers[0])));
conn->write(index_html);
}
void handle_jpeg(http_server_t::connection_ptr conn) {
const image_buffer& buf = m_images[m_current_buf.load()];
http_server_t::response_header common_headers[] = {
{"Content-type", "image/jpeg"},
{"Content-length", sz2str(buf.size)},
{"Cache-control", "max-age=0, no-cache"},
{"X-ImageId-Seq", sz2str(buf.id.seq)},
{"X-ImageId-Src", buf.id.src},
};
conn->set_status(http_server_t::connection::ok);
conn->set_headers(boost::make_iterator_range(common_headers,
common_headers+sizeof(common_headers)/sizeof(common_headers[0])));
conn->write(boost::asio::const_buffers_1(buf.ptr(), buf.size),
[](boost::system::error_code const&) {});
}
void handle_stream(http_server_t::connection_ptr conn) {
conn->set_status(http_server_t::connection::not_supported);
conn->write("Not implemented");
}
};
class socket_listener {
public:
socket_listener(int type, int port) : m_socket(-1) {
try {
m_socket = socket(PF_INET, type, 0);
if (m_socket < 0) {
throw runtime_error(errmsg("socket"));
}
long en = 1;
if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &en, sizeof(en)) < 0) {
throw runtime_error(errmsg("setsockopt"));
}
sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = PF_INET;
sa.sin_port = htons((u_short)port);
sa.sin_addr.s_addr = INADDR_ANY;
if (bind(m_socket, (sockaddr*)&sa, sizeof(sa)) < 0) {
throw runtime_error(errmsg("socket bind"));
}
if (type != SOCK_STREAM) return;
if (listen(m_socket, SOMAXCONN) < 0) {
throw runtime_error(errmsg("listen"));
}
} catch (runtime_error&) {
if (m_socket >= 0) {
close(m_socket);
}
throw;
}
}
virtual ~socket_listener() {
if (m_socket >= 0) {
close(m_socket);
}
}
int socket_fd() const { return m_socket; }
private:
int m_socket;
};
class streamer : public socket_listener {
public:
streamer(int port = cast_port)
: socket_listener(SOCK_STREAM, port) {
}
void run(const image_handler* images) {
while (true) {
sockaddr_in sa;
socklen_t salen = sizeof(sa);
int conn = accept(socket_fd(), (sockaddr*)&sa, &salen);
if (conn < 0) {
LOG(ERROR) << errmsg("accept");
break;
}
thread client([this, conn, images] { stream_to(conn, images); });
client.detach();
}
}
private:
void stream_to(int conn, const image_handler* images) {
const image_buffer* buf;
while ((buf = images->wait()) != nullptr) {
uint16_t sz = (uint16_t)buf->size;
int r = send(conn, &sz, sizeof(sz), MSG_NOSIGNAL);
if (r > 0) {
r = send(conn, buf->ptr(), buf->size, MSG_NOSIGNAL);
}
if (r < 0) {
LOG(ERROR) << errmsg("send");
break;
}
}
close(conn);
}
};
class udp_caster : public socket_listener {
public:
udp_caster(int port = cast_port)
: socket_listener(SOCK_DGRAM, port) {
}
void run(const image_handler* images) {
thread listener_thread([this] { run_listener(); });
run_caster(images);
listener_thread.join();
}
private:
struct subscriber {
sockaddr_in addr;
int failures;
subscriber(const sockaddr_in& sa) : failures(0) {
memcpy(&addr, &sa, sizeof(addr));
}
bool same(const sockaddr_in& sa) const {
return addr.sin_port == sa.sin_port && addr.sin_addr.s_addr == sa.sin_addr.s_addr;
}
string str() const {
string s(inet_ntoa(addr.sin_addr));
s += ":" + sz2str(ntohs(addr.sin_port));
return s;
}
static function<bool(const subscriber&)> if_same(sockaddr_in sa) {
return [sa] (const subscriber& sub) -> bool {
return sub.same(sa);
};
}
};
list<subscriber> m_subscribers;
mutex m_lock;
static constexpr int max_failures = 5;
void run_listener() {
char buf[4];
while (true) {
sockaddr_in sa;
socklen_t salen = sizeof(sa);
int r = recvfrom(socket_fd(), buf, sizeof(buf), 0, (sockaddr*)&sa, &salen);
if (r < 0) {
LOG(ERROR) << errmsg("recvfrom");
break;
}
if (r == 0) continue;
switch (buf[0]) {
case '+':
add_subscriber(sa);
break;
case '-':
del_subscriber(sa);
break;
}
}
}
void run_caster(const image_handler* images) {
const image_buffer* buf;
while ((buf = images->wait()) != nullptr) {
uint16_t sz = (uint16_t)buf->size;
cast(buf);
}
}
void cast(const image_buffer* buf) {
unique_lock<mutex> lock(m_lock);
list<subscriber>::iterator it = m_subscribers.begin();
while (it != m_subscribers.end()) {
auto cur = it;
it ++;
int r = sendto(socket_fd(), buf->ptr(), buf->size, MSG_NOSIGNAL,
(sockaddr*)&cur->addr, sizeof(cur->addr));
if (r < 0) {
LOG(ERROR) << cur->str() << ": " << errmsg("sendto");
cur->failures ++;
if (cur->failures > max_failures) {
LOG(WARNING) << "remove " << cur->str() << " due to too many failures";
m_subscribers.erase(cur);
}
}
}
}
void add_subscriber(const sockaddr_in& sa) {
unique_lock<mutex> lock(m_lock);
list<subscriber>::iterator it = find_if(m_subscribers.begin(), m_subscribers.end(), subscriber::if_same(sa));
if (it != m_subscribers.end()) {
it->failures = 0;
return;
}
m_subscribers.push_back(subscriber(sa));
}
void del_subscriber(const sockaddr_in& sa) {
unique_lock<mutex> lock(m_lock);
m_subscribers.remove_if(subscriber::if_same(sa));
}
};
class app {
public:
app() {
mqtt::initialize();
http_server_t::options options(m_imghandler);
options.reuse_address(true)
.thread_pool(make_shared<boost::network::utils::thread_pool>())
.port(sz2str(FLAGS_http_port));
if (!FLAGS_http_addr.empty()) {
options.address(FLAGS_http_addr);
}
m_httpsrv.reset(new http_server_t(options));
auto names = movidius::compute_stick::devices();
if (names.empty()) throw runtime_error("no Movidius NCS found");
LOG(INFO) << "MQTT Connect " << FLAGS_mqtt_host << ":" << FLAGS_mqtt_port;
m_mqtt_client.reset(new mqtt::client(FLAGS_mqtt_client_id));
m_mqtt_client->connect(FLAGS_mqtt_host, (unsigned short)FLAGS_mqtt_port).wait();
for (auto& name : names) {
LOG(INFO) << "Loading " << name << " with model " << FLAGS_model;
unique_ptr<movidius::compute_stick> stick(new movidius::compute_stick(name));
unique_ptr<movidius::compute_stick::graph> model(stick->alloc_graph_from_file(FLAGS_model));
unique_ptr<graph> g(new graph(name));
g->def_vars({"input", "id", "size", "pixels", "objects", "result"});
g->add_op("imgid", {"input"}, {"id"}, op::image_id());
g->add_op("decode", {"input"}, {"pixels", "size"}, op::decode_image());
g->add_op("detect", {"pixels"}, {"objects"}, movidius::op::ssd_mobilenet(model.get()));
g->add_op("json", {"size", "id", "objects"}, {"result"}, op::detect_boxes_json());
g->add_op("publish", {"result"}, {}, pub_op(m_mqtt_client.get()));
g->add_op("imagesrv", {"input", "id"}, {}, m_imghandler.op());
m_dispatcher.add_graph(g.get());
m_ncs.push_back(move(stick));
m_models.push_back(move(model));
m_graphs.push_back(move(g));
}
}
~app() {
mqtt::cleanup();
}
void run() {
LOG(INFO) << "Run!";
in::udp udp((uint16_t)FLAGS_port);
thread httpsrv_thread([this] { m_httpsrv->run(); });
thread streamer_thread([this] { run_streamer(); });
thread caster_thread([this] { run_caster(); });
udp.run(&m_dispatcher);
httpsrv_thread.join();
caster_thread.join();
streamer_thread.join();
}
private:
unique_ptr<mqtt::client> m_mqtt_client;
vector<unique_ptr<movidius::compute_stick>> m_ncs;
vector<unique_ptr<movidius::compute_stick::graph>> m_models;
vector<unique_ptr<graph>> m_graphs;
graph_dispatcher m_dispatcher;
image_handler m_imghandler;
unique_ptr<http_server_t> m_httpsrv;
void run_streamer() {
if (FLAGS_stream_port == 0) {
return;
}
streamer strm(FLAGS_stream_port);
strm.run(&m_imghandler);
}
void run_caster() {
if (FLAGS_stream_port == 0) {
return;
}
udp_caster caster(FLAGS_stream_port);
caster.run(&m_imghandler);
}
};
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
gflags::ParseCommandLineFlags(&argc, &argv, true);
app app;
app.run();
return 0;
}
| 31.287785 | 117 | 0.572128 | robotalks |
c0ccd87a26ac60b3c89e8dd5b45c154ffcf9aa51 | 1,512 | cpp | C++ | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | 2 | 2018-12-19T01:52:39.000Z | 2022-03-29T16:04:15.000Z | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | #include "../../include/core/Sprite.h"
#include "../../include/graphics/Graphics.h"
using namespace PhysicsEngine;
Sprite::Sprite(World *world) : Asset(world)
{
mCreated = false;
mChanged = false;
mPixelsPerUnit = 100;
}
Sprite::Sprite(World *world, Guid id) : Asset(world, id)
{
mCreated = false;
mChanged = false;
mPixelsPerUnit = 100;
}
Sprite::~Sprite()
{
}
void Sprite::serialize(YAML::Node &out) const
{
Asset::serialize(out);
out["textureId"] = mTextureId;
out["pixelsPerUnit"] = mPixelsPerUnit;
}
void Sprite::deserialize(const YAML::Node &in)
{
Asset::deserialize(in);
mTextureId = YAML::getValue<Guid>(in, "textureId");
mPixelsPerUnit = YAML::getValue<int>(in, "pixelsPerUnit");
}
int Sprite::getType() const
{
return PhysicsEngine::SPRITE_TYPE;
}
std::string Sprite::getObjectName() const
{
return PhysicsEngine::SPRITE_NAME;
}
bool Sprite::isCreated() const
{
return mCreated;
}
bool Sprite::isChanged() const
{
return mChanged;
}
GLuint Sprite::getNativeGraphicsVAO() const
{
return mVao;
}
Guid Sprite::getTextureId() const
{
return mTextureId;
}
void Sprite::setTextureId(Guid textureId)
{
mTextureId = textureId;
mChanged = true;
}
void Sprite::create()
{
if (mCreated)
{
return;
}
Graphics::createSprite(&mVao);
mCreated = true;
}
void Sprite::destroy()
{
if (!mCreated)
{
return;
}
Graphics::destroySprite(&mVao);
mCreated = false;
} | 14.823529 | 62 | 0.646164 | jsandham |
c0cd865b906fc7bbbbb5eaf3526f4af66d947300 | 1,650 | hpp | C++ | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | 4 | 2017-05-22T04:14:06.000Z | 2022-02-09T19:15:10.000Z | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include "../Drawable/Drawable3D.hpp"
#include "../Log.hpp"
class PhysicsMesh;
struct PhysicsElements;
class Program;
class btGeneric6DofSpringConstraint;
class btHingeConstraint;
class btTransform;
class Spider : public Drawable3D, public Logging::Log {
public:
struct Part {
Part();
Part(unsigned short group, unsigned short mask, float angle, bool active);
unsigned short collisionGroup;
unsigned short collisionMask;
float restAngle;
bool active;
Drawable3D* part;
btHingeConstraint* hinge;
btGeneric6DofSpringConstraint* dof;
};
Spider();
~Spider();
// Resets the positions, rotations and such for the whole spider
void reset();
void update(float deltaTime);
void draw(std::shared_ptr<Program>& program, bool bindTexture = false);
void draw(std::shared_ptr<Program>& program,
mmm::vec3 offset,
bool bindTexture = false);
void input(const Input::Event& event);
// Returns the child of spider if found by name
Drawable3D* child(const std::string& name);
std::map<std::string, Part>& parts();
// Upcasts a Drawable3D objet to a Spider object, if possible.
static Spider* upcast(Drawable3D* drawable);
static std::map<std::string, Part> SPIDER_PARTS;
private:
static std::map<std::string, btTransform> SPIDER_POSITIONS;
PhysicsElements* mElements;
std::shared_ptr<PhysicsMesh> mMesh;
std::map<std::string, Part> mParts;
};
| 25.78125 | 78 | 0.640606 | Reewr |
c0ce39bc7242daa28c2ced6a9563a9bf468294d6 | 1,532 | cc | C++ | src/server/Server.cc | kevinpolossat/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | 5 | 2018-01-23T18:13:08.000Z | 2018-01-28T21:10:38.000Z | src/server/Server.cc | kevinpolossat/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | 4 | 2018-01-10T15:56:30.000Z | 2018-01-28T16:08:57.000Z | src/server/Server.cc | polosskevin/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | null | null | null | //
// Created by Kรฉvin POLOSSAT on 14/01/2018.
//
#include <memory>
#include <iostream>
#include "Server.h"
#include "Resolver.h"
#include "Launcher.h"
Server::Server(): reactor_(), acceptor_(reactor_), gameManager_(std::make_unique<rtype::Launcher>()) {
lw_network::Reactor reactor;
lw_network::Resolver re;
re
.SetService("4242")
.SetFamily(AF_UNSPEC)
.SetSockType(SOCK_STREAM)
.SetFlags(AI_PASSIVE);
int yes = 1;
lw_network::error_code e = lw_network::no_error;
auto p = re.Resolve();
for (auto const & endPoint : p) {
e = lw_network::no_error;
acceptor_.open(endPoint.protocol(), e);
if (e) {
continue;
}
acceptor_.setOption(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int), e);
acceptor_.bind(endPoint, e);
if (e) {
acceptor_.close(e);
continue;
}
break;
}
if (!acceptor_.isOpen()) {
std::cerr << "FAIL" << std::endl;
return ;
}
acceptor_.listen(SOMAXCONN, e);
if (e) {
std::cerr << "FAIL listen" << std::endl;
return ;
}
doAccept_();
}
void Server::run() {
reactor_.handleEvents();
}
void Server::doAccept_() {
acceptor_.asyncAccept(
[this](lw_network::ReactiveSocket peer, lw_network::error_code ec) {
connectionManager_.start(std::make_shared<Connection>(std::move(peer), connectionManager_, gameManager_));
this->doAccept_();
}
);
}
| 25.533333 | 122 | 0.575718 | kevinpolossat |
c0d50317ce1222cc731771e9bfadf8da7a451eb8 | 22,104 | cpp | C++ | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | 1 | 2022-01-05T03:51:02.000Z | 2022-01-05T03:51:02.000Z | #include "DX11TestLayer.h"
#include "H2M/Renderer/TextureH2M.h"
#include "H2M/Scene/ComponentsH2M.h"
#include "DX11Context.h"
#include "DX11SwapChain.h"
#include "DX11Renderer.h"
#include "DX11Shader.h"
#include "DX11InputSystem.h"
#include "Core/Application.h"
#include "Core/ResourceManager.h"
#include "Platform/Windows/WindowsWindow.h"
std::shared_ptr<DX11CameraFP> DX11TestLayer::s_Camera;
glm::vec2 DX11TestLayer::s_StartMousePosition;
H2M::RefH2M<DX11Mesh> DX11TestLayer::s_Mesh;
H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_MeshLight;
H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_SkyboxSphere;
// Render meshes with materials
std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials;
std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials;
ImGuizmo::OPERATION DX11TestLayer::s_ImGuizmoType;
bool DX11TestLayer::s_LeftControlKeyPressed = false;
bool DX11TestLayer::s_ShowWindowSceneHierarchy = true;
bool DX11TestLayer::s_ShowWindowAssetManager = true;
bool DX11TestLayer::s_ShowWindowMaterialEditor = true;
H2M::RefH2M<H2M::SceneH2M> DX11TestLayer::s_Scene;
glm::mat4 DX11TestLayer::s_CurrentlySelectedTransform;
float DX11TestLayer::s_ViewportWidth = 0.0f;
float DX11TestLayer::s_ViewportHeight = 0.0f;
glm::vec2 DX11TestLayer::s_ViewportBounds[2];
bool DX11TestLayer::s_AllowViewportCameraEvents = true;
H2M::SceneHierarchyPanelH2M* DX11TestLayer::s_SceneHierarchyPanel;
H2M::ContentBrowserPanelH2M* DX11TestLayer::s_ContentBrowserPanel;
MaterialEditorPanel* DX11TestLayer::s_MaterialEditorPanel;
DX11TestLayer::DX11TestLayer()
{
s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f));
}
DX11TestLayer::DX11TestLayer(const std::string& name) : MoravaLayer(name)
{
s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f));
}
DX11TestLayer::~DX11TestLayer()
{
}
void DX11TestLayer::OnAttach()
{
DX11InputSystem::Get()->AddListener(this);
s_Scene = H2M::RefH2M<H2M::SceneH2M>::Create();
s_SceneHierarchyPanel = new H2M::SceneHierarchyPanelH2M(s_Scene);
s_ContentBrowserPanel = new H2M::ContentBrowserPanelH2M();
s_MaterialEditorPanel = new MaterialEditorPanel();
// Application::Get()->GetWindow()->SetInFocus(false);
DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true);
H2M::RefH2M<H2M::MeshH2M> meshSphere = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/sphere_hq.obj");
/*
RenderObject renderObjectGladiator;
renderObjectGladiator.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Gladiator/Gladiator.fbx");
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_BaseColor.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_Normal.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_BaseColor.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_Normal.jpg"));
renderObjectGladiator.Transform = glm::mat4(1.0f);
renderObjectGladiator.Transform = glm::translate(renderObjectGladiator.Transform, glm::vec3(0.0f, 0.0f, -2.0f));
renderObjectGladiator.Transform = glm::scale(renderObjectGladiator.Transform, glm::vec3(0.04f));
renderObjectGladiator.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectGladiator);
RenderObject renderObjectCerberus;
renderObjectCerberus.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Cerberus/CerberusMaterials.fbx");
renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(0));
renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(1));
renderObjectCerberus.Transform = glm::mat4(1.0f);
renderObjectCerberus.Transform = glm::translate(renderObjectCerberus.Transform, glm::vec3(0.0f, 4.0f, 14.0f));
renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f));
renderObjectCerberus.Transform = glm::scale(renderObjectCerberus.Transform, glm::vec3(4.0f));
renderObjectCerberus.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectCerberus);
RenderObject renderObjectSphereLeft;
renderObjectSphereLeft.Mesh = meshSphere;
renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg"));
renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg"));
renderObjectSphereLeft.Transform = glm::mat4(1.0f);
renderObjectSphereLeft.Transform = glm::translate(renderObjectSphereLeft.Transform, glm::vec3(-4.0f, 2.0f, 0.0f));
renderObjectSphereLeft.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectSphereLeft);
RenderObject renderObjectSphereRight;
renderObjectSphereRight.Mesh = meshSphere;
renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg"));
renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg"));
renderObjectSphereRight.Transform = glm::mat4(1.0f);
renderObjectSphereRight.Transform = glm::translate(renderObjectSphereRight.Transform, glm::vec3(4.0f, 2.0f, 0.0f));
renderObjectSphereRight.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectSphereRight);
*/
RenderObject renderObjectTerrain;
renderObjectTerrain.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/terrain.obj");
renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sand.jpg", true));
renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/normal_blank.png", false));
renderObjectTerrain.Transform = glm::mat4(1.0f);
renderObjectTerrain.Transform = glm::scale(renderObjectTerrain.Transform, glm::vec3(4.0f));
renderObjectTerrain.PipelineType = RenderObject::PipelineType::Unlit;
m_RenderObjects.push_back(renderObjectTerrain);
// ---- other assets ----
ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sky.jpg", true);
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/wood.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/default_material_albedo.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/umhlanga_sunrise_4k.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/gold.png");
// ResourceManager::LoadHazelTexture2D("Textures/container/container2.png");
// ResourceManager::LoadHazelTexture2D("Textures/container/container2_normal.png");
s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/teapot.obj");
// s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/spaceship.obj");
s_MeshLight = meshSphere;
s_SkyboxSphere = meshSphere;
/**** BEGIN Pipeline Unlit ****/
H2M::PipelineSpecificationH2M pipelineSpecUnlit;
pipelineSpecUnlit.DebugName = "Pipeline Unlit";
pipelineSpecUnlit.Layout = H2M::VertexBufferLayoutH2M{};
MoravaShaderSpecification moravaShaderSpecificationUnlit;
moravaShaderSpecificationUnlit.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader;
moravaShaderSpecificationUnlit.VertexShaderPath = "Shaders/HLSL/UnlitVertexShader.hlsl";
moravaShaderSpecificationUnlit.PixelShaderPath = "Shaders/HLSL/UnlitPixelShader.hlsl";
moravaShaderSpecificationUnlit.ForceCompile = false;
ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit);
pipelineSpecUnlit.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit);
H2M::RefH2M<DX11Pipeline> pipelineUnlit = DX11Pipeline::Create(pipelineSpecUnlit);
/**** END Pipeline Unlit ****/
/**** BEGIN Pipeline Illuminated ****/
H2M::PipelineSpecificationH2M pipelineSpecIlluminated;
pipelineSpecIlluminated.DebugName = "Pipeline Illuminated";
pipelineSpecIlluminated.Layout = H2M::VertexBufferLayoutH2M{};
MoravaShaderSpecification moravaShaderSpecificationIlluminated;
moravaShaderSpecificationIlluminated.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader;
moravaShaderSpecificationIlluminated.VertexShaderPath = "Shaders/HLSL/DirLightVertexShader.hlsl";
moravaShaderSpecificationIlluminated.PixelShaderPath = "Shaders/HLSL/DirLightPixelShader.hlsl";
moravaShaderSpecificationIlluminated.ForceCompile = false;
pipelineSpecIlluminated.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationIlluminated);
H2M::RefH2M<DX11Pipeline> pipelineIlluminated = DX11Pipeline::Create(pipelineSpecIlluminated);
/**** END Pipeline Illuminated ****/
/**** BEGIN Create meshes with materials ****
H2M::RefH2M<DX11Material> materialIlluminated = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Illuminated");
H2M::RefH2M<DX11Material> materialUnlit = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Unlit");
H2M::RefH2M<DX11Material> materialIlluminatedDerived = H2M::RefH2M<DX11Material>::Create(materialIlluminated, "Material Illuminated Derived");
H2M::RefH2M<DX11Material> materialUnlitDerived = H2M::RefH2M<DX11Material>::Create(materialUnlit, "Material Unlit Derived");
// BEGIN prepare data for rendering meshes with materials (render objects and the list of materials)
// std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials;
// std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials;
s_ListMaterials.reserve(32); // reserve 32 slots
H2M::RefH2M<Hazel::HazelTexture2D> textureBarrel = ResourceManager::LoadHazelTexture2D("Textures/PardCode/barrel.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseBrick = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_brick.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWindows = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_windows.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWood = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_wood.jpg");
H2M::RefH2M<DX11Material> materialBarrel = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material Barrel");
H2M::RefH2M<DX11Material> materialHouseBrick = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Brick");
H2M::RefH2M<DX11Material> materialHouseWindows = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Windows");
H2M::RefH2M<DX11Material> materialHouseWood = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Wood");
materialBarrel->AddTexture(textureBarrel.As<DX11Texture2D>());
materialHouseBrick->AddTexture(textureHouseBrick.As<DX11Texture2D>());
materialHouseWindows->AddTexture(textureHouseWindows.As<DX11Texture2D>());
materialHouseWood->AddTexture(textureHouseWood.As<DX11Texture2D>());
s_ListMaterials.push_back(materialBarrel);
s_ListMaterials.push_back(materialHouseBrick);
s_ListMaterials.push_back(materialHouseWindows);
s_ListMaterials.push_back(materialHouseWood);
RenderObject renderObjectHouse;
renderObjectHouse.MeshDX11 = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/house.obj");
renderObjectHouse.Transform = glm::mat4(1.0f);
renderObjectHouse.Transform = glm::translate(renderObjectHouse.Transform, glm::vec3(0.0f, 0.0f, -20.0f));
renderObjectHouse.Transform = glm::scale(renderObjectHouse.Transform, glm::vec3(6.0f));
renderObjectHouse.PipelineType = RenderObject::PipelineType::Light;
s_RenderObjectsWithMaterials.push_back(renderObjectHouse);
/**** END Create meshes with materials ****/
// END prepare data for rendering meshes with materials (render objects and the list of materials)
}
void DX11TestLayer::OnDetach()
{
}
void DX11TestLayer::OnUpdate(H2M::TimestepH2M ts)
{
bool windowInFocus = Application::Get()->GetWindow()->IsInFocus();
bool cameraEnabled = windowInFocus; // && !m_ShowMouseCursor;
s_Camera->SetEnabled(cameraEnabled);
// Log::GetLogger()->info("windowInFocus: {0}, m_ShowMouseCursor: {1}, cameraEnabled: {2}", windowInFocus, m_ShowMouseCursor, cameraEnabled);
DX11InputSystem::Get()->Update();
s_Camera->OnUpdate(ts);
s_Camera->SetProjectionMatrix(
glm::perspectiveFov(glm::radians(60.0f), (float)DX11Renderer::GetViewportWidth(), (float)DX11Renderer::GetViewportHeight(), 0.01f, 1000.0f));
glm::vec4 clearColor = { 0.1f, 0.1f, 0.1f, 1.0f };
Render(clearColor, s_Camera);
for (RenderObject renderObject : m_RenderObjects)
{
DX11Renderer::SubmitMesh(renderObject);
}
}
void DX11TestLayer::OnEvent(H2M::EventH2M& event)
{
s_Camera->OnEvent(event);
if (event.GetEventType() == H2M::EventTypeH2M::WindowResize)
{
H2M::WindowResizeEventH2M& e = (H2M::WindowResizeEventH2M&)event;
if (e.GetWidth() != 0 && e.GetHeight() != 0)
{
s_Camera->SetViewportSize((float)e.GetWidth(), (float)e.GetHeight());
s_Camera->SetProjectionMatrix(glm::perspectiveFov(glm::radians(60.0f), (float)e.GetWidth(), (float)e.GetHeight(), 0.1f, 1000.0f));
}
}
}
void DX11TestLayer::ShowExampleAppDockSpace(bool* p_open, Window* mainWindow)
{
}
void DX11TestLayer::OnRender(Window* mainWindow, Scene* scene)
{
DX11Renderer::Draw(scene->GetCamera());
}
void DX11TestLayer::OnImGuiRender(Window* mainWindow, Scene* scene)
{
}
void DX11TestLayer::Render(const glm::vec4& clearColor, std::shared_ptr<DX11CameraFP> camera)
{
}
void DX11TestLayer::OnKeyDown(int key)
{
if (key == VK_LCONTROL)
{
s_LeftControlKeyPressed = true;
}
}
void DX11TestLayer::OnKeyUp(int key)
{
if (key == VK_ESCAPE)
{
// Application::Get()->GetWindow()->SetInFocus(false);
DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true);
}
if (key == 'F')
{
m_FullscreenEnabled = !m_FullscreenEnabled;
WindowsWindow* windowsWindow = (WindowsWindow*)Application::Get()->GetWindow();
RECT windowRECT = windowsWindow->GetSizeScreen();
uint32_t width = windowRECT.right; // - windowRECT.left;
uint32_t height = windowRECT.bottom; // - windowRECT.top;
DX11Context::Get()->GetSwapChain()->SetFullScreen(m_FullscreenEnabled, width, height);
}
// ImGizmo switching modes
switch (key)
{
case '1':
s_ImGuizmoType = ImGuizmo::OPERATION::TRANSLATE;
break;
case '2':
s_ImGuizmoType = ImGuizmo::OPERATION::ROTATE;
break;
case '3':
s_ImGuizmoType = ImGuizmo::OPERATION::SCALE;
break;
case '4':
s_ImGuizmoType = (ImGuizmo::OPERATION)-1;
break;
}
if (key == VK_LCONTROL)
{
s_LeftControlKeyPressed = false;
}
if (s_LeftControlKeyPressed)
{
if (key == 'H')
{
s_ShowWindowSceneHierarchy = !s_ShowWindowSceneHierarchy;
Log::GetLogger()->info("s_ShowWindowSceneHierarchy: {0}", s_ShowWindowSceneHierarchy);
}
if (key == VK_SPACE)
{
s_ShowWindowAssetManager = !s_ShowWindowAssetManager;
Log::GetLogger()->info("s_ShowWindowAssetManager: {0}", s_ShowWindowAssetManager);
}
if (key == 'M')
{
s_ShowWindowMaterialEditor = !s_ShowWindowMaterialEditor;
Log::GetLogger()->info("s_ShowWindowMaterialEditor: {0}", s_ShowWindowMaterialEditor);
}
}
}
void DX11TestLayer::OnMouseMove(const glm::vec2& mousePosDelta, const glm::vec2& mousePosAbs)
{
}
void DX11TestLayer::OnLeftMouseDown(const glm::vec2& mousePos)
{
// MOUSE events
POINT currentMousePos = {};
::GetCursorPos(¤tMousePos);
s_StartMousePosition = glm::vec2(currentMousePos.x, currentMousePos.y);
if (DX11InputSystem::Get()->IsMouseCursorAboveViewport())
{
Application::Get()->GetWindow()->SetInFocus(true);
}
// DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = false);
// Log::GetLogger()->info("DX11TestLayer::OnLeftMouseDown {0}x{1}", mousePos.x, mousePos.y);
// bool windowInFocus = Application::Get()->GetWindow()->IsInFocus();
// Log::GetLogger()->info("Window::m_InFocus: {0}, m_ShowMouseCursor: {1}, m_Camera->IsEnabled: {2}",
// windowInFocus, m_ShowMouseCursor, DX11CameraFP::Get()->IsEnabled());
OnLeftMouseDownEventHandler(mousePos);
}
void DX11TestLayer::OnRightMouseDown(const glm::vec2& mousePos)
{
}
void DX11TestLayer::OnLeftMouseUp(const glm::vec2& mousePos)
{
}
void DX11TestLayer::OnRightMouseUp(const glm::vec2& mousePos)
{
}
bool DX11TestLayer::OnLeftMouseDownEventHandler(const glm::vec2& mousePos)
{
float mx = mousePos.x;
float my = mousePos.y;
Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler mousePos.x: {0}, mousePos.y: {1}", mousePos.x, mousePos.y);
if (!ImGuizmo::IsUsing() && !ImGuizmo::IsOver())
{
auto [mouseX, mouseY] = GetMouseViewportSpace();
Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler GetMouseViewportSpace mouseX: {0}, mouseY: {1}", mouseX, mouseY);
if (mouseX > -1.0f && mouseX < 1.0f && mouseY > -1.0f && mouseY < 1.0f)
{
auto [origin, direction] = CastRay(mouseX, mouseY);
EntitySelection::s_SelectionContext.clear();
auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>();
for (auto e : meshEntities)
{
H2M::EntityH2M entity = { e, s_Scene.Raw() };
auto mesh = entity.GetComponent<H2M::MeshComponentH2M>().Mesh;
if (!mesh) {
continue;
}
std::vector<H2M::RefH2M<H2M::SubmeshH2M>>& submeshes = mesh->GetSubmeshes();
float lastT = std::numeric_limits<float>::max(); // Distance between camera and intersection in CastRay
// for (Hazel::Submesh& submesh : submeshes)
for (uint32_t i = 0; i < submeshes.size(); i++)
{
H2M::RefH2M<H2M::SubmeshH2M> submesh = submeshes[i];
auto transform = entity.GetComponent<H2M::TransformComponentH2M>().GetTransform();
H2M::RayH2M ray = {
glm::inverse(transform * submesh->Transform) * glm::vec4(origin, 1.0f),
glm::inverse(glm::mat3(transform) * glm::mat3(submesh->Transform)) * direction
};
float t;
bool intersects = ray.IntersectsAABB(submesh->BoundingBox, t);
if (intersects)
{
const auto& triangleCache = ((H2M::MeshH2M*)mesh.Raw())->GetTriangleCache(i);
if (triangleCache.size())
{
for (const auto& triangle : triangleCache)
{
if (ray.IntersectsTriangle(triangle.V0.Position, triangle.V1.Position, triangle.V2.Position, t))
{
AddSubmeshToSelectionContext({ entity, submesh, t });
Log::GetLogger()->debug("Adding submesh to selection context. Submesh Name: '{0}', selection size: '{1}'",
submesh->MeshName, EntitySelection::s_SelectionContext.size());
break;
}
}
}
else {
AddSubmeshToSelectionContext({ entity, submesh, t });
}
}
}
}
std::sort(EntitySelection::s_SelectionContext.begin(), EntitySelection::s_SelectionContext.end(), [](auto& a, auto& b) { return a.Distance < b.Distance; });
// TODO: Handle mesh being deleted, etc
if (EntitySelection::s_SelectionContext.size()) {
s_CurrentlySelectedTransform = EntitySelection::s_SelectionContext[0].Mesh->Transform;
OnSelected(EntitySelection::s_SelectionContext[0]);
}
else {
RefH2M<H2M::EntityH2M> meshEntity = GetMeshEntity();
if (meshEntity) {
s_CurrentlySelectedTransform = meshEntity->Transform().GetTransform();
}
}
}
}
return false;
}
std::pair<float, float> DX11TestLayer::GetMouseViewportSpace()
{
auto [mx, my] = ImGui::GetMousePos(); // Input::GetMousePosition();
mx -= s_ViewportBounds[0].x;
my -= s_ViewportBounds[0].y;
s_ViewportWidth = s_ViewportBounds[1].x - s_ViewportBounds[0].x;
s_ViewportHeight = s_ViewportBounds[1].y - s_ViewportBounds[0].y;
return { (mx / s_ViewportWidth) * 2.0f - 1.0f, ((my / s_ViewportHeight) * 2.0f - 1.0f) * -1.0f };
}
std::pair<glm::vec3, glm::vec3> DX11TestLayer::CastRay(float mx, float my)
{
glm::vec4 mouseClipPos = { mx, my, -1.0f, 1.0f };
glm::mat4 projectionMatrix = s_Camera->GetProjectionMatrix();
glm::mat4 viewMatrix = s_Camera->GetViewMatrix();
auto inverseProj = glm::inverse(projectionMatrix);
auto inverseView = glm::inverse(glm::mat3(viewMatrix));
glm::vec4 ray = inverseProj * mouseClipPos;
glm::vec3 rayPos = s_Camera->GetPosition();
glm::vec3 rayDir = inverseView * glm::vec3(ray); // inverseView * glm::vec3(ray)
Log::GetLogger()->debug("DX11TestLayer::CastRay | MousePosition [ {0} {1} ]", mx, my);
Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[0] [ {0} {1} ]", s_ViewportBounds[0].x, s_ViewportBounds[0].y);
Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[1] [ {0} {1} ]", s_ViewportBounds[1].x, s_ViewportBounds[1].y);
Log::GetLogger()->debug("DX11TestLayer::CastRay | mouseClipPos [ {0} {1} ]", mouseClipPos.x, mouseClipPos.y);
return { rayPos, rayDir };
}
void DX11TestLayer::AddSubmeshToSelectionContext(SelectedSubmesh submesh)
{
EntitySelection::s_SelectionContext.push_back(submesh);
if (EntitySelection::s_SelectionContext.size() && EntitySelection::s_SelectionContext[0].Mesh) {
Log::GetLogger()->debug("SelectionContext[0].Mesh->MeshName: '{0}'", EntitySelection::s_SelectionContext[0].Mesh->MeshName);
}
}
void DX11TestLayer::OnSelected(const SelectedSubmesh& selectionContext)
{
// TODO: move to SceneHazelEnvMap
s_SceneHierarchyPanel->SetSelected(selectionContext.Entity);
s_Scene->SetSelectedEntity(selectionContext.Entity);
}
RefH2M<H2M::EntityH2M> DX11TestLayer::GetMeshEntity()
{
RefH2M<H2M::EntityH2M> meshEntity;
auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>();
if (meshEntities.size()) {
for (auto entt : meshEntities)
{
meshEntity = CreateRefH2M<H2M::EntityH2M>(entt, s_Scene.Raw());
}
return meshEntity;
}
return nullptr;
}
| 40.043478 | 159 | 0.76122 | imgui-works |
c0d85df88aee6e9cc6daa7c12f5ff143d26b589c | 7,096 | cpp | C++ | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | 2 | 2021-07-20T10:08:02.000Z | 2021-09-21T04:24:42.000Z | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | null | null | null | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | 2 | 2021-06-08T04:01:14.000Z | 2021-09-18T23:03:14.000Z | #include "FEMClothMesh.h"
#include <autodiff/forward.hpp>
#include <autodiff/forward/eigen.hpp>
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
namespace ClothSim
{
static std::vector<double> buildTriangleAreas(const TriMesh& mesh, const VecVec2d& restUVs)
{
std::vector<double> triangleAreas(mesh.triangleCount(), 0);
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = mesh.triangle(triIndex);
const Vec2d& v0 = restUVs[tri[0]];
const Vec2d& v1 = restUVs[tri[1]];
const Vec2d& v2 = restUVs[tri[2]];
triangleAreas[triIndex] = .5 * std::fabs(v0[0] * (v1[1] - v2[1]) + v1[0] * (v2[1] - v0[1]) + v2[0] * (v0[1] - v1[1]));
}
});
return triangleAreas;
}
static std::vector<double> buildVertexMasses(const TriMesh& mesh, const std::vector<double>& triangleAreas, double density)
{
std::vector<double> vertexMasses(mesh.vertexCount(), 0);
assert(mesh.vertexCount() == mesh.adjacentTriangles().size());
assert(triangleAreas.size() == mesh.triangleCount());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.vertexCount()), [&](tbb::blocked_range<int>& range)
{
for (int vertexIndex = range.begin(); vertexIndex != range.end(); ++vertexIndex)
{
for (int triIndex : mesh.adjacentTriangles()[vertexIndex])
vertexMasses[vertexIndex] += 1. / 3. * density * triangleAreas[triIndex];
}
});
return vertexMasses;
}
static VecMat2x2d buildDmInv(const TriMesh& mesh, const VecVec2d& restUVs)
{
assert(mesh.vertexCount() == restUVs.size());
VecMat2x2d dmInv(mesh.triangleCount());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
Mat2x2d localD;
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = mesh.triangle(triIndex);
localD.col(0) = restUVs[tri[1]] - restUVs[tri[0]];
localD.col(1) = restUVs[tri[2]] - restUVs[tri[0]];
dmInv[triIndex] = localD.inverse();
}
});
return dmInv;
}
template<typename Scalar>
Vec6t<Scalar> computeF(const Vec6t<Scalar>& D, const Vec4t<Scalar>& Dinv)
{
Mat3x2t<Scalar> Dmat;
Dmat.block(0, 0, 3, 1) = D.block(0, 0, 3, 1);
Dmat.block(0, 1, 3, 1) = D.block(3, 0, 3, 1);
Mat2x2t<Scalar> DinvMat;
DinvMat.block(0, 0, 2, 1) = Dinv.block(0, 0, 2, 1);
DinvMat.block(0, 1, 2, 1) = Dinv.block(2, 0, 2, 1);
Mat3x2t<Scalar> Fmat = Dmat * DinvMat;
Vec6t<Scalar> Fvec;
Fvec.block(0, 0, 3, 1) = Fmat.block(0, 0, 3, 1);
Fvec.block(3, 0, 3, 1) = Fmat.block(0, 1, 3, 1);
return Fvec;
}
static Mat3x2d computeF(const Vec3d& v0, const Vec3d& v1, const Vec3d& v2, const Mat2x2d& DmInv)
{
Mat3x2d Ds;
Ds.col(0) = v1 - v0;
Ds.col(1) = v2 - v0;
return Ds * DmInv;
}
template<typename Scalar>
static Vec6t<Scalar> computeFTemplated(const Vec3t<Scalar>& v0, const Vec3t<Scalar>& v1, const Vec3t<Scalar>& v2, const Mat2x2t<Scalar>& DmInv)
{
Mat3x2t<Scalar> Ds;
Ds.col(0) = v1 - v0;
Ds.col(1) = v2 - v0;
Mat3x2t<Scalar> Fmat = Ds * DmInv;
Vec6t<Scalar> Fvec;
Fvec.block(0, 0, 3, 1) = Fmat.col(0);
Fvec.block(3, 0, 3, 1) = Fmat.col(1);
return Fvec;
}
static Mat6x9d builddFdxAutodiff(const TriMesh& mesh, const VecMat2x2d& DmInv, int triIndex)
{
using autodiff::dual;
using autodiff::forward::jacobian;
using autodiff::forward::at;
using autodiff::forward::wrtpack;
const Vec3i& tri = mesh.triangle(triIndex);
const Vec3d& v0 = mesh.vertex(tri[0]);
const Vec3d& v1 = mesh.vertex(tri[1]);
const Vec3d& v2 = mesh.vertex(tri[2]);
Vec3t<dual> dualV0 = v0.cast<dual>();
Vec3t<dual> dualV1 = v1.cast<dual>();
Vec3t<dual> dualV2 = v2.cast<dual>();
Mat2x2t<dual> dualDmInv = DmInv[triIndex].cast<dual>();
Vec6t<dual> dualF;
Mat6x9d dFdx = jacobian(computeFTemplated<dual>, wrtpack(dualV0, dualV1, dualV2), at(dualV0, dualV1, dualV2, dualDmInv), dualF);
#if !defined(NDEBUG)
Mat3x2d F = computeF(v0, v1, v2, DmInv[triIndex]);
Mat3x2d Fautodiff;
Fautodiff.col(0) = dualF.block(0, 0, 3, 1).cast<double>();
Fautodiff.col(1) = dualF.block(3, 0, 3, 1).cast<double>();
assert((Fautodiff - F).lpNorm<Eigen::Infinity>() < 1e-10);
#endif
return dFdx;
}
static VecMat6x9d builddFdx(const TriMesh& mesh, const VecMat2x2d& DmInv)
{
VecMat6x9d dFdx(mesh.triangleCount(), Mat6x9d::Zero());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
double s0 = DmInv[triIndex].col(0).sum();
double s1 = DmInv[triIndex].col(1).sum();
double d0 = DmInv[triIndex](0, 0);
double d1 = DmInv[triIndex](1, 0);
double d2 = DmInv[triIndex](0, 1);
double d3 = DmInv[triIndex](1, 1);
// dF / dx0
dFdx[triIndex](0, 0) = -s0;
dFdx[triIndex](3, 0) = -s1;
// dF / dy0
dFdx[triIndex](1, 1) = -s0;
dFdx[triIndex](4, 1) = -s1;
// dF / dz0
dFdx[triIndex](2, 2) = -s0;
dFdx[triIndex](5, 2) = -s1;
// dF / dx1
dFdx[triIndex](0, 3) = d0;
dFdx[triIndex](3, 3) = d2;
// dF / dy1
dFdx[triIndex](1, 4) = d0;
dFdx[triIndex](4, 4) = d2;
// dF / dz1
dFdx[triIndex](2, 5) = d0;
dFdx[triIndex](5, 5) = d2;
// dF / dx2
dFdx[triIndex](0, 6) = d1;
dFdx[triIndex](3, 6) = d3;
// dF / dy2
dFdx[triIndex](1, 7) = d1;
dFdx[triIndex](4, 7) = d3;
// dF / dz2
dFdx[triIndex](2, 8) = d1;
dFdx[triIndex](5, 8) = d3;
#if !defined(NDEBUG)
// Autodiff verification
Mat6x9d dFdxAutodiff = builddFdxAutodiff(mesh, DmInv, triIndex);
assert((dFdx[triIndex] - dFdxAutodiff).lpNorm<Eigen::Infinity>() < 1e-10);
#endif
}
});
return dFdx;
}
FEMClothMesh::FEMClothMesh(const std::vector<int>& fixedVertices,
const double density,
const double stretchStiffness,
const double shearStiffness,
const VecVec2d& restUVs,
const TriMesh& inputMesh)
: TriMesh(inputMesh)
, myVertexVelocities(this->vertexCount(), Vec3d::Zero())
, myFixedVertices(this->vertexCount(), false)
, myDensity(density)
, myStretchStiffness(stretchStiffness)
, myShearStiffness(shearStiffness)
, myRestTriangleAreas(buildTriangleAreas(inputMesh, restUVs))
, myVertexMasses(buildVertexMasses(inputMesh, myRestTriangleAreas, myDensity))
, myDmInv(buildDmInv(inputMesh, restUVs))
, mydFdX(builddFdx(inputMesh, myDmInv))
, myF(this->triangleCount())
, myStateDirty(true)
{
for (int vertIndex : fixedVertices)
myFixedVertices[vertIndex] = true;
computeState();
}
void FEMClothMesh::buildF()
{
tbb::parallel_for(tbb::blocked_range<int>(0, this->triangleCount()), [&](const tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = this->triangle(triIndex);
const Vec3d& v0 = this->vertex(tri[0]);
const Vec3d& v1 = this->vertex(tri[1]);
const Vec3d& v2 = this->vertex(tri[2]);
myF[triIndex] = computeF(v0, v1, v2, myDmInv[triIndex]);
}
});
}
void FEMClothMesh::computeState()
{
if (myStateDirty)
{
buildF();
myStateDirty = false;
}
}
} | 27.292308 | 143 | 0.661922 | rgoldade |
c0daa70d55ebb60a9d065a6e0fe9c31f1dc1952b | 7,869 | hpp | C++ | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 56 | 2020-06-17T17:43:36.000Z | 2022-03-20T22:43:19.000Z | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 15 | 2020-06-24T16:34:44.000Z | 2021-04-08T22:00:57.000Z | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 18 | 2020-06-18T13:47:59.000Z | 2022-01-23T21:01:33.000Z | /**
* Copyright (c) 2020 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "activation.hpp"
namespace tinymind {
#if (defined(TINYMIND_USE_TANH_1_31))
struct TanhValuesTableQ1_31
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_1_31))
#if (defined(TINYMIND_USE_TANH_2_30))
struct TanhValuesTableQ2_30
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_2_30))
#if (defined(TINYMIND_USE_TANH_3_29))
struct TanhValuesTableQ3_29
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_3_29))
#if (defined(TINYMIND_USE_TANH_4_28))
struct TanhValuesTableQ4_28
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_4_28))
#if (defined(TINYMIND_USE_TANH_5_27))
struct TanhValuesTableQ5_27
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_5_27))
#if (defined(TINYMIND_USE_TANH_6_26))
struct TanhValuesTableQ6_26
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_6_26))
#if (defined(TINYMIND_USE_TANH_7_25))
struct TanhValuesTableQ7_25
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_7_25))
#if (defined(TINYMIND_USE_TANH_8_24))
struct TanhValuesTableQ8_24
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_8_24))
#if (defined(TINYMIND_USE_TANH_9_23))
struct TanhValuesTableQ9_23
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_9_23))
#if (defined(TINYMIND_USE_TANH_10_22))
struct TanhValuesTableQ10_22
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_10_22))
#if (defined(TINYMIND_USE_TANH_11_21))
struct TanhValuesTableQ11_21
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_11_21))
#if (defined(TINYMIND_USE_TANH_12_20))
struct TanhValuesTableQ12_20
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_12_20))
#if (defined(TINYMIND_USE_TANH_13_19))
struct TanhValuesTableQ13_19
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_13_19))
#if (defined(TINYMIND_USE_TANH_14_18))
struct TanhValuesTableQ14_18
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_14_18))
#if (defined(TINYMIND_USE_TANH_15_17))
struct TanhValuesTableQ15_17
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_15_17))
#if (defined(TINYMIND_USE_TANH_16_16))
struct TanhValuesTableQ16_16
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_16_16))
#if (defined(TINYMIND_USE_TANH_17_15))
struct TanhValuesTableQ17_15
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_17_15))
#if (defined(TINYMIND_USE_TANH_18_14))
struct TanhValuesTableQ18_14
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_18_14))
#if (defined(TINYMIND_USE_TANH_19_13))
struct TanhValuesTableQ19_13
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_19_13))
#if (defined(TINYMIND_USE_TANH_20_12))
struct TanhValuesTableQ20_12
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_20_12))
#if (defined(TINYMIND_USE_TANH_21_11))
struct TanhValuesTableQ21_11
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_21_11))
#if (defined(TINYMIND_USE_TANH_22_10))
struct TanhValuesTableQ22_10
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_22_10))
#if (defined(TINYMIND_USE_TANH_23_9))
struct TanhValuesTableQ23_9
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_23_9))
#if (defined(TINYMIND_USE_TANH_24_8))
struct TanhValuesTableQ24_8
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_24_8))
#if (defined(TINYMIND_USE_TANH_25_7))
struct TanhValuesTableQ25_7
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_25_7))
#if (defined(TINYMIND_USE_TANH_26_6))
struct TanhValuesTableQ26_6
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_26_6))
#if (defined(TINYMIND_USE_TANH_27_5))
struct TanhValuesTableQ27_5
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_27_5))
#if (defined(TINYMIND_USE_TANH_28_4))
struct TanhValuesTableQ28_4
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_28_4))
#if (defined(TINYMIND_USE_TANH_29_3))
struct TanhValuesTableQ29_3
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_29_3))
#if (defined(TINYMIND_USE_TANH_30_2))
struct TanhValuesTableQ30_2
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_30_2))
#if (defined(TINYMIND_USE_TANH_31_1))
struct TanhValuesTableQ31_1
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_31_1))
}
| 36.6 | 81 | 0.706697 | danmcleran |
c0dbed743787137efa2b5c4a4acfc82c0fefc37f | 3,914 | cpp | C++ | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "coherence/util/filter/InKeySetFilter.hpp"
#include "coherence/io/pof/SystemPofContext.hpp"
#include "coherence/util/filter/ExtractorFilter.hpp"
#include "coherence/util/HashSet.hpp"
#include "private/coherence/util/InvocableMapHelper.hpp"
COH_OPEN_NAMESPACE3(coherence,util,filter)
COH_REGISTER_PORTABLE_CLASS(72, InKeySetFilter);
// ----- constructors -------------------------------------------------------
InKeySetFilter::InKeySetFilter()
: f_vFilter(self()), m_vSetKeys(self(), NULL, /* mutable */ true), m_fConverted(false)
{
}
InKeySetFilter::InKeySetFilter(Filter::View vFilter, Set::View vSetKeys)
: f_vFilter(self(), vFilter), m_vSetKeys(self(), vSetKeys, /* mutable */ true),
m_fConverted(false)
{
}
// ----- EntryFilter interface ----------------------------------------------
bool InKeySetFilter::evaluateEntry(Map::Entry::View vEntry) const
{
if (!m_vSetKeys->contains(vEntry->getKey()))
{
return false;
}
return InvocableMapHelper::evaluateEntry(getFilter(), vEntry);
}
// ----- Filter interface ---------------------------------------------------
bool InKeySetFilter::evaluate(Object::View /* v */) const
{
COH_THROW (UnsupportedOperationException::create(
"InKeySetFilter::evaluate"));
}
// ----- IndexAwareFilter interface -----------------------------------------
size32_t InKeySetFilter::calculateEffectiveness(Map::View vMapIndexes,
Set::View vSetKeys) const
{
Filter::View vFilter = f_vFilter;
if (m_vSetKeys->size() < vSetKeys->size())
{
vSetKeys = m_vSetKeys;
}
return instanceof<IndexAwareFilter::View>(vFilter)
? (cast<IndexAwareFilter::View>(vFilter))->calculateEffectiveness(vMapIndexes, vSetKeys)
: vSetKeys->size()*ExtractorFilter::eval_cost;
}
Filter::View InKeySetFilter::applyIndex(Map::View vMapIndexes,
Set::Handle hSetKeys) const
{
hSetKeys->retainAll(m_vSetKeys);
Filter::View vFilter = f_vFilter;
return instanceof<IndexAwareFilter::View>(vFilter)
? (cast<IndexAwareFilter::View>(vFilter))->applyIndex(vMapIndexes, hSetKeys)
: NULL;
}
// ----- PortableObject interface -------------------------------------------
void InKeySetFilter::readExternal(PofReader::Handle hIn)
{
initialize(f_vFilter, cast<Filter::View>(hIn->readObject(0)));
m_vSetKeys = cast<Set::View>(hIn->readObject(1));
}
void InKeySetFilter:: writeExternal(PofWriter::Handle hOut) const
{
hOut->writeObject(0, getFilter());
hOut->writeObject(1, m_vSetKeys);
}
// ----- Object interface ---------------------------------------------------
TypedHandle<const String> InKeySetFilter::toString() const
{
return COH_TO_STRING("InKeySetFilter(" << getFilter() << ", keys=" << m_vSetKeys << ')');
}
// ----- data member accessors ----------------------------------------------
Filter::View InKeySetFilter::getFilter() const
{
return f_vFilter;
}
Set::View InKeySetFilter::getKeys() const
{
return m_vSetKeys;
}
// ----- helpers ------------------------------------------------------------
void InKeySetFilter::ensureConverted(Converter::View vConverter) const
{
COH_SYNCHRONIZED (this)
{
if (!m_fConverted)
{
HashSet::Handle hSetConv = HashSet::create();
for (Iterator::Handle iter = m_vSetKeys->iterator(); iter->hasNext();)
{
hSetConv->add(vConverter->convert(iter->next()));
}
m_vSetKeys = hSetConv;
m_fConverted = true;
}
}
}
COH_CLOSE_NAMESPACE3
| 28.362319 | 100 | 0.579969 | chpatel3 |
c0ded1ea466b2e8c2b64d8984c78eff2192c22d9 | 760 | cpp | C++ | bit/next_combination.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | bit/next_combination.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | bit/next_combination.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
/* next combination */
int next_combination(int sub) {
int x = sub & -sub, y = sub + x;
return (((sub & ~y) / x) >> 1) | y;
}
int main() {
int n = 5; // {0, 1, 2, 3, 4} ใฎ้จๅ้ๅใ่ใใ
int k = 3;
int bit = (1 << k) - 1; // bit = {0, 1, 2}
for (; bit < (1 << n); bit = next_combination(bit)) {
/* ใใใซๅฆ็ใๆธใ */
/* ใใกใใจใงใใฆใใใใจใ็ขบ่ชใใฆใฟใ */
// bit ใฎ่กจใ้ๅใๆฑใใ
vector<int> s;
rep(i, n) {
if (bit & (1 << i)) { // i ใ bit ใซๅ
ฅใใใฉใใ
s.push_back(i);
}
}
// bit ใฎ่กจใ้ๅใฎๅบๅ
cout << bit << ": {";
rep(i, s.size()) { cout << s[i] << " "; }
cout << "}" << endl;
}
} | 21.714286 | 55 | 0.465789 | Takumi1122 |
c0e3aced600bbef60ab4a4bb6635e233b10ffb74 | 1,181 | hpp | C++ | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 7 | 2019-06-02T12:04:22.000Z | 2019-10-15T18:01:21.000Z | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 26 | 2019-10-27T12:58:42.000Z | 2020-05-30T16:43:48.000Z | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 1 | 2019-10-03T13:36:36.000Z | 2019-10-03T13:36:36.000Z | #pragma once
#include <components/cursor/cursor.hpp>
#include <components/session/session.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include "forward.hpp"
namespace py = pybind11;
class PYBIND11_EXPORT wrapper_cursor final : public boost::intrusive_ref_counter<wrapper_cursor> {
public:
using type = components::cursor::cursor_t;
using pointer = type*;
wrapper_cursor(components::session::session_id_t session, pointer cursor);
void close();
bool has_next();
wrapper_cursor &next();
wrapper_cursor &iter();
std::size_t size();
py::object get(py::object key);
std::string print();
wrapper_cursor &sort(py::object sorter, py::object order);
//paginate();
//_order();
private:
std::atomic_bool close_;
duck_charmer::session_id_t session_;
pointer ptr_;
actor_zeta::address_t dispatcher_;
py::object get_(const std::string &key) const;
py::object get_(std::size_t index) const;
};
using wrapper_cursor_ptr = boost::intrusive_ptr<wrapper_cursor>;
| 25.12766 | 100 | 0.718882 | jinntechio |
c0ecbbe327cccc5da849b1ca21938e8b44f6900f | 974 | cpp | C++ | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: Application.cpp *
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Application.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
Application::Application() : GuiApplication()
{
// Set application title
SetTitle("<fill me>");
}
/**
* @brief
* Destructor
*/
Application::~Application()
{
}
| 25.631579 | 59 | 0.216632 | ktotheoz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.