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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bf91298e40c612d400b59a1ba3345244171e365e
| 1,293
|
hh
|
C++
|
code/language/family_prolog/language_prolog.hh
|
jmpcosta/loc
|
0efc9aadd4cc08a6c5c6841f494862b35f4533be
|
[
"MIT"
] | null | null | null |
code/language/family_prolog/language_prolog.hh
|
jmpcosta/loc
|
0efc9aadd4cc08a6c5c6841f494862b35f4533be
|
[
"MIT"
] | null | null | null |
code/language/family_prolog/language_prolog.hh
|
jmpcosta/loc
|
0efc9aadd4cc08a6c5c6841f494862b35f4533be
|
[
"MIT"
] | null | null | null |
// *****************************************************************************************
//
// File description:
//
// Author: Joao Costa
// Purpose: Provide the definitions/declarations for a programming language
//
// *****************************************************************************************
#ifndef LOC_LANGUAGE_PROLOG_HH_
#define LOC_LANGUAGE_PROLOG_HH_
// *****************************************************************************************
//
// Section: Import headers
//
// *****************************************************************************************
// Import C++ system headers
#include <string>
// Import application headers
#include "loc_defs.hh"
#include "trace_macros.hh"
#include "language/family_prolog/language_family_prolog.hh"
// *****************************************************************************************
//
// Section: Function declaration
//
// *****************************************************************************************
/// @brief Class responsible for implementing a C language
class language_prolog : public language_family_prolog
{
public:
/// @brief Class constructor
language_prolog ( void );
private:
TRACE_CLASSNAME_DECLARATION
};
#endif // LOC_LANGUAGE_PROLOG_HH_
| 23.944444
| 92
| 0.422274
|
jmpcosta
|
bf920eb264af20bd39516fb40da5ccaf9094ca7c
| 128
|
cpp
|
C++
|
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 27
|
2017-06-07T19:07:32.000Z
|
2020-10-15T10:09:12.000Z
|
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 3
|
2017-08-25T17:39:46.000Z
|
2017-11-18T03:40:55.000Z
|
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/MatrixBase_template_int_int_bottomLeftCorner_int_int.cpp
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 10
|
2017-06-16T18:04:45.000Z
|
2018-07-05T17:33:01.000Z
|
version https://git-lfs.github.com/spec/v1
oid sha256:ccbb36f2c90e75f1642d971bedefd05aa14d5ad26bf65ff7021499ec23df1725
size 301
| 32
| 75
| 0.882813
|
initialz
|
bf992618c15b414844100ec7522af7048ab0ce02
| 1,024
|
hpp
|
C++
|
include/boost/simd/function/definition/shuffle.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
include/boost/simd/function/definition/shuffle.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
include/boost/simd/function/definition/shuffle.hpp
|
yaeldarmon/boost.simd
|
561316cc54bdc6353ca78f3b6d7e9120acd11144
|
[
"BSL-1.0"
] | null | null | null |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
@copyright 2016 J.T.Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DEFINITION_SHUFFLE_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_DEFINITION_SHUFFLE_HPP_INCLUDED
#include <boost/simd/config.hpp>
#include <boost/dispatch/function/make_callable.hpp>
#include <boost/dispatch/hierarchy/functions.hpp>
#include <boost/simd/detail/dispatch.hpp>
namespace boost { namespace simd
{
namespace tag
{
BOOST_DISPATCH_MAKE_TAG(ext, shuffle_, boost::dispatch::elementwise_<shuffle_>);
}
namespace ext
{
BOOST_DISPATCH_FUNCTION_DECLARATION(tag, shuffle_);
}
BOOST_DISPATCH_CALLABLE_DEFINITION(tag::shuffle_,shuffle);
} }
#endif
| 26.947368
| 100
| 0.624023
|
yaeldarmon
|
bcce7e14c2292faff64de0cbe006700351469bcc
| 2,101
|
cpp
|
C++
|
src/SynchronizationPoint.cpp
|
omi-lab/tp_task_queue
|
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
|
[
"MIT"
] | null | null | null |
src/SynchronizationPoint.cpp
|
omi-lab/tp_task_queue
|
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
|
[
"MIT"
] | null | null | null |
src/SynchronizationPoint.cpp
|
omi-lab/tp_task_queue
|
e7b4e61cc87ad2ff3954782fb96d5e988c9fbc3f
|
[
"MIT"
] | 2
|
2018-08-30T10:00:25.000Z
|
2021-05-05T08:39:06.000Z
|
#include "tp_task_queue/SynchronizationPoint.h"
#include "tp_task_queue/Task.h"
#include "tp_utils/MutexUtils.h"
namespace tp_task_queue
{
//##################################################################################################
struct SynchronizationPoint::Private
{
TP_REF_COUNT_OBJECTS("tp_task_queue::SynchronizationPoint::Private");
TP_NONCOPYABLE(Private);
Private() = default;
std::vector<Task*> tasks;
TPMutex mutex{TPM};
TPWaitCondition waitCondition;
};
//##################################################################################################
SynchronizationPoint::SynchronizationPoint():
d(new Private())
{
}
//##################################################################################################
SynchronizationPoint::~SynchronizationPoint()
{
join();
delete d;
}
//##################################################################################################
void SynchronizationPoint::join()
{
TP_MUTEX_LOCKER(d->mutex);
while(!d->tasks.empty())
d->waitCondition.wait(TPMc d->mutex);
}
//##################################################################################################
void SynchronizationPoint::addTask(Task* task, size_t maxActive)
{
task->setSynchronizationPoint(this);
TP_MUTEX_LOCKER(d->mutex);
while(d->tasks.size()>=maxActive)
d->waitCondition.wait(TPMc d->mutex);
d->tasks.push_back(task);
}
//##################################################################################################
void SynchronizationPoint::cancelTasks()
{
TP_MUTEX_LOCKER(d->mutex);
for(auto task : d->tasks)
task->cancelTask();
}
//##################################################################################################
size_t SynchronizationPoint::activeTasks()
{
TP_MUTEX_LOCKER(d->mutex);
return d->tasks.size();
}
//##################################################################################################
void SynchronizationPoint::removeTask(Task* task)
{
TP_MUTEX_LOCKER(d->mutex);
tpRemoveOne(d->tasks, task);
d->waitCondition.wakeAll();
}
}
| 27.285714
| 100
| 0.447882
|
omi-lab
|
bccfd61828612b69f482e7a3c46f2248bdab8811
| 713
|
hpp
|
C++
|
include/SFRL/Direction.hpp
|
marukrap/SFRL
|
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
|
[
"MIT"
] | 4
|
2018-06-19T08:43:04.000Z
|
2021-03-15T08:37:57.000Z
|
include/SFRL/Direction.hpp
|
marukrap/SFRL
|
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
|
[
"MIT"
] | null | null | null |
include/SFRL/Direction.hpp
|
marukrap/SFRL
|
a241e09dae33eb6099b1ccb1eb1c741e0af589f0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <SFML/System/Vector2.hpp>
#include <array>
namespace rl
{
class Direction : public sf::Vector2i
{
public:
using sf::Vector2i::Vector2;
Direction operator-() const;
Direction left45() const;
Direction right45() const;
Direction left90() const;
Direction right90() const;
public:
static const Direction None;
static const Direction N;
static const Direction NE;
static const Direction E;
static const Direction SE;
static const Direction S;
static const Direction SW;
static const Direction W;
static const Direction NW;
static const std::array<Direction, 8> All;
static const std::array<Direction, 4> Cardinal;
static const std::array<Direction, 4> Diagonal;
};
}
| 17.825
| 48
| 0.743338
|
marukrap
|
bcd570392a18bf0acdd15273f3a9f1d4aa4eec15
| 1,396
|
cpp
|
C++
|
CSES/Tree Algorithms/Tree Diameter.cpp
|
s166harth/CC
|
b6c0fe58f03633fe2787a567a16909f1b2966e7b
|
[
"MIT"
] | 406
|
2020-05-28T13:35:08.000Z
|
2022-03-31T17:23:26.000Z
|
CSES/Tree Algorithms/Tree Diameter.cpp
|
shakeeb-droids/CC
|
2f49fcb52d748804aee9fc7f26abb3150bec69e5
|
[
"MIT"
] | 3
|
2021-01-01T17:50:34.000Z
|
2021-10-02T10:02:27.000Z
|
CSES/Tree Algorithms/Tree Diameter.cpp
|
shakeeb-droids/CC
|
2f49fcb52d748804aee9fc7f26abb3150bec69e5
|
[
"MIT"
] | 108
|
2020-07-21T13:02:33.000Z
|
2022-03-28T22:46:49.000Z
|
/**
🍪 thew6rst
🍪 11.02.2021 20:15:33
**/
#ifdef W
#include "k_II.h"
#else
#include <bits/stdc++.h>
using namespace std;
#endif
#define pb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) static_cast<int32_t>(x.size())
template<class T> class Y {
T f;
public:
template<class U> explicit Y(U&& f): f(forward<U>(f)) {}
template<class... Args> decltype(auto) operator()(Args&&... args) {
return f(ref(*this), forward<Args>(args)...);
}
}; template<class T> Y(T) -> Y<T>;
const int64_t DESPACITO = 2e18;
const int INF = 2e9, MOD = 1e9+7;
const int N = 2e5 + 5;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int i, n;
cin >> n;
vector<vector<int>> g(n);
for(i = 0; i < n-1; i++) {
int u, v; cin >> u >> v; u--, v--;
g[u].pb(v); g[v].pb(u);
}
auto bfs = [&] (int root) {
queue<int> q; q.push(root);
vector<int> d(n, -1); d[root] = 0;
while(!q.empty()) {
auto cur = q.front(); q.pop();
for(auto nxt : g[cur]) {
if(d[nxt] == -1) {
d[nxt] = d[cur] + 1;
q.push(nxt);
}
}
} auto it = max_element(all(d));
return make_pair(it-d.begin(), *it);
};
cout << bfs(bfs(0).first).second;
} // ~W
| 25.851852
| 72
| 0.465616
|
s166harth
|
bcde1e1fe21ce2194c1eaef09273b97749633db7
| 64
|
cpp
|
C++
|
test/wiztk/base/sigcxx/subject.cpp
|
wiztk/framework
|
179baf8a24406b19d3f4ea28e8405358b21f8446
|
[
"Apache-2.0"
] | 37
|
2017-11-22T14:15:33.000Z
|
2021-11-25T20:39:39.000Z
|
test/unit/core-sigcxx/subject.cpp
|
zhanggyb/skland
|
055d91a6830b95d248d407c37a8a2fa20b148efd
|
[
"Apache-2.0"
] | 3
|
2018-03-01T12:44:22.000Z
|
2021-01-04T23:14:41.000Z
|
test/wiztk/base/sigcxx/subject.cpp
|
wiztk/framework
|
179baf8a24406b19d3f4ea28e8405358b21f8446
|
[
"Apache-2.0"
] | 10
|
2017-11-25T19:09:11.000Z
|
2020-12-02T02:05:47.000Z
|
//
// Created by zhanggyb on 17-9-7.
//
#include "subject.hpp"
| 10.666667
| 33
| 0.625
|
wiztk
|
bce860a715f430c2d98ccef0ee18be5e34d29288
| 958
|
cpp
|
C++
|
EasyCppTest/OTP.cpp
|
Thalhammer/EasyCpp
|
6b9886fecf0aa363eaf03741426fd3462306c211
|
[
"MIT"
] | 3
|
2018-02-06T05:12:41.000Z
|
2020-05-12T20:57:32.000Z
|
EasyCppTest/OTP.cpp
|
Thalhammer/EasyCpp
|
6b9886fecf0aa363eaf03741426fd3462306c211
|
[
"MIT"
] | 41
|
2016-07-11T12:19:10.000Z
|
2017-08-08T07:43:12.000Z
|
EasyCppTest/OTP.cpp
|
Thalhammer/EasyCpp
|
6b9886fecf0aa363eaf03741426fd3462306c211
|
[
"MIT"
] | 2
|
2019-08-02T10:24:36.000Z
|
2020-09-11T01:45:12.000Z
|
#include <gtest/gtest.h>
#include <Hash/HOTP.h>
#include <Hash/TOTP.h>
#include <HexEncoding.h>
using namespace EasyCpp;
using namespace EasyCpp::Hash;
namespace EasyCppTest
{
TEST(OTP, HOTP)
{
std::string secret = "3132333435363738393031323334353637383930";
auto hotp = HOTP(HexEncoding::decode(secret));
std::string token6 = hotp.generate(0, 6);
std::string token8 = hotp.generate(0, 8);
ASSERT_EQ(std::string("755224"), token6);
ASSERT_EQ(std::string("84755224"), token8);
token6 = hotp.generate(1, 6);
token8 = hotp.generate(1, 8);
ASSERT_EQ(std::string("287082"), token6);
ASSERT_EQ(std::string("94287082"), token8);
}
TEST(OTP, TOTP)
{
std::string secret = "3132333435363738393031323334353637383930";
auto totp = TOTP(HexEncoding::decode(secret));
std::vector<std::string> keys;
for (int i = -5; i < 6; i++)
keys.push_back(totp.generate(i));
// Set a break point here and check using your TOTP device !
}
}
| 25.210526
| 66
| 0.692067
|
Thalhammer
|
bcedc443bbec46ce3220483cef3732cf95b74e68
| 1,533
|
hpp
|
C++
|
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/OVR/OpenVR/VRTextureDepthInfo_t.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:05 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Including type: OVR.OpenVR.HmdMatrix44_t
#include "OVR/OpenVR/HmdMatrix44_t.hpp"
// Including type: OVR.OpenVR.HmdVector2_t
#include "OVR/OpenVR/HmdVector2_t.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Autogenerated type: OVR.OpenVR.VRTextureDepthInfo_t
struct VRTextureDepthInfo_t : public System::ValueType {
public:
// public System.IntPtr handle
// Offset: 0x0
System::IntPtr handle;
// public OVR.OpenVR.HmdMatrix44_t mProjection
// Offset: 0x8
OVR::OpenVR::HmdMatrix44_t mProjection;
// public OVR.OpenVR.HmdVector2_t vRange
// Offset: 0x48
OVR::OpenVR::HmdVector2_t vRange;
// Creating value type constructor for type: VRTextureDepthInfo_t
VRTextureDepthInfo_t(System::IntPtr handle_ = {}, OVR::OpenVR::HmdMatrix44_t mProjection_ = {}, OVR::OpenVR::HmdVector2_t vRange_ = {}) : handle{handle_}, mProjection{mProjection_}, vRange{vRange_} {}
}; // OVR.OpenVR.VRTextureDepthInfo_t
}
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::VRTextureDepthInfo_t, "OVR.OpenVR", "VRTextureDepthInfo_t");
#pragma pack(pop)
| 39.307692
| 204
| 0.70972
|
Futuremappermydud
|
bcef795865b64ed8f4a5e4332ed5a48021129fd7
| 2,016
|
cpp
|
C++
|
src/entities/bretoniafighter.cpp
|
P-Sc/Pirateers
|
440e477d33bbbcd79d291700c369f74fd0a6cc7d
|
[
"MIT"
] | null | null | null |
src/entities/bretoniafighter.cpp
|
P-Sc/Pirateers
|
440e477d33bbbcd79d291700c369f74fd0a6cc7d
|
[
"MIT"
] | null | null | null |
src/entities/bretoniafighter.cpp
|
P-Sc/Pirateers
|
440e477d33bbbcd79d291700c369f74fd0a6cc7d
|
[
"MIT"
] | null | null | null |
#include "bretoniafighter.h"
#include "ship/shipsystem.h"
#include "gamelogic/aisystem.h"
BretoniaFighter::BretoniaFighter(ShipSystem& shipSystem, AISystem& aiSystem, ShipSettings shipSettings,
float multiplier)
: EnemyShip(shipSystem, aiSystem) {
EnergySettings energySettings;
energySettings.maxEnergy = 350;
energySettings.regenPerSecond = 70;
ShieldSettings shieldSettings;
shieldSettings.maxHull = 400;
shieldSettings.maxShield = 200;
shieldSettings.regenPerSecond = 100;
shieldSettings.maxRegenPause = 2;
shipSettings.energySettings = energySettings;
shipSettings.shieldSettings = shieldSettings;
shipSettings.shipname = "BretoniaFighter";
shipSettings.explosionDelay = 1;
shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(0, 1)));
shipSettings.weapons.back().damageMultiplier = 0.4f;
shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f);
shipSettings.weapons.back().scatterMultiplier = 0.5f;
shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(1, 0)));
shipSettings.weapons.back().damageMultiplier = 0.4f;
shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f);
shipSettings.weapons.back().scatterMultiplier = 0.5f;
shipSettings.weapons.push_back(Weapon("plasma", b2Vec2(-1, 0)));
shipSettings.weapons.back().damageMultiplier = 0.4f;
shipSettings.weapons.back().rateOfFireMultiplier = 1.5f * (0.5f + (rand() % 10) / 10.f);
shipSettings.weapons.back().scatterMultiplier = 0.5f;
//shipSettings.weapons.back().velocityMultiplier = 0.2f;
shipSettings.rewardCount = 2;
shipSettings.engineEffectSettings.offset.Set(0, -3);
shipSettings.engineEffectSettings.size = 4;
this->shipSettings = shipSettings;
aiSettings.type = AISettings::fighter;
aiSettings.weaponRange = 160;
aiSettings.combatRadius = 10 + rand() % 20;
aiSettings.sightRange = 300;
create(multiplier);
}
| 43.826087
| 103
| 0.713294
|
P-Sc
|
bcf3136b0161d63fcd188ddbac92dcb85a6f7e33
| 520
|
cpp
|
C++
|
tree/src/diameter.cpp
|
fumiphys/programming_contest
|
b9466e646045e1c64571af2a1e64813908e70841
|
[
"MIT"
] | 7
|
2019-04-30T14:25:40.000Z
|
2020-12-19T17:38:11.000Z
|
tree/src/diameter.cpp
|
fumiphys/programming_contest
|
b9466e646045e1c64571af2a1e64813908e70841
|
[
"MIT"
] | 46
|
2018-09-19T16:42:09.000Z
|
2020-05-07T09:05:08.000Z
|
tree/src/diameter.cpp
|
fumiphys/programming_contest
|
b9466e646045e1c64571af2a1e64813908e70841
|
[
"MIT"
] | null | null | null |
/*
* Library for Diameter
*/
#include <iostream>
#include <cassert>
#include "../diameter.hpp"
using namespace std;
int main(int argc, char const* argv[])
{
cout << "-- test for diameter start --" << endl;
Tree<int> t(6);
t.adde(0, 1, 1);
t.adde(0, 4, 1);
t.adde(1, 2, 1);
t.adde(1, 3, 1);
t.adde(4, 5, 1);
t.adde(1, 0, 1);
t.adde(4, 0, 1);
t.adde(2, 1, 1);
t.adde(3, 1, 1);
t.adde(5, 4, 1);
assert(t.diameter() == 4);
cout << "-- test for diameter end: Success --" << endl;
return 0;
}
| 19.259259
| 57
| 0.542308
|
fumiphys
|
bcf621d0d6f4d422359da11384b422b14a90c990
| 135,341
|
cpp
|
C++
|
retired/scalycpp/Parser.cpp
|
rschleitzer/scaly
|
7537cdf44f7a63ad1a560975017ee1c897c73787
|
[
"MIT"
] | 4
|
2019-09-08T15:20:11.000Z
|
2021-06-07T11:27:36.000Z
|
retired/scalycpp/Parser.cpp
|
rschleitzer/scaly
|
7537cdf44f7a63ad1a560975017ee1c897c73787
|
[
"MIT"
] | null | null | null |
retired/scalycpp/Parser.cpp
|
rschleitzer/scaly
|
7537cdf44f7a63ad1a560975017ee1c897c73787
|
[
"MIT"
] | 1
|
2017-07-20T21:12:33.000Z
|
2017-07-20T21:12:33.000Z
|
#include "scalycpp.h"
using namespace scaly;
namespace scalycpp {
Parser::Parser(string* theFileName, string* text) {
lexer = new(_getPage()->allocateExclusivePage()) Lexer(text);
fileName = theFileName;
classKeyword = new(_getPage()) string("class");
functionKeyword = new(_getPage()) string("function");
ifKeyword = new(_getPage()) string("if");
elseKeyword = new(_getPage()) string("else");
switchKeyword = new(_getPage()) string("switch");
caseKeyword = new(_getPage()) string("case");
defaultKeyword = new(_getPage()) string("default");
catchKeyword = new(_getPage()) string("catch");
forKeyword = new(_getPage()) string("for");
inKeyword = new(_getPage()) string("in");
whileKeyword = new(_getPage()) string("while");
doKeyword = new(_getPage()) string("do");
returnKeyword = new(_getPage()) string("return");
throwKeyword = new(_getPage()) string("throw");
breakKeyword = new(_getPage()) string("break");
throwsKeyword = new(_getPage()) string("throws");
staticKeyword = new(_getPage()) string("static");
letKeyword = new(_getPage()) string("let");
mutableKeyword = new(_getPage()) string("mutable");
isKeyword = new(_getPage()) string("is");
asKeyword = new(_getPage()) string("as");
constructorKeyword = new(_getPage()) string("constructor");
enumKeyword = new(_getPage()) string("enum");
thisKeyword = new(_getPage()) string("this");
nullKeyword = new(_getPage()) string("null");
newKeyword = new(_getPage()) string("new");
extendsKeyword = new(_getPage()) string("extends");
equal = new(_getPage()) string("=");
comma = new(_getPage()) string(",");
leftParen = new(_getPage()) string("(");
rightParen = new(_getPage()) string(")");
leftCurly = new(_getPage()) string("{");
rightCurly = new(_getPage()) string("}");
leftBracket = new(_getPage()) string("[");
rightBracket = new(_getPage()) string("]");
colon = new(_getPage()) string(":");
dot = new(_getPage()) string(".");
underscore = new(_getPage()) string("_");
circumflex = new(_getPage()) string("^");
dollar = new(_getPage()) string("$");
at = new(_getPage()) string("@");
hash = new(_getPage()) string("#");
ampersand = new(_getPage()) string("&");
}
_Result<Module, ParserError> Parser::parseModule(_Page* _rp, _Page* _ep) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
_Array<Statement>* statements = parseStatementList(_rp);
if (statements != nullptr) {
if (!isAtEnd()) {
_Region _region; _Page* _p = _region.get();
Position* errorPos = lexer->getPreviousPosition(_p);
return _Result<Module, ParserError>(new(_ep) ParserError(new(_ep) _ParserError_syntax(errorPos->line, errorPos->column)));
}
}
Position* end = lexer->getPosition(_p);
Module* ret = new(_rp) Module(statements, new(_rp) Position(start), new(_rp) Position(end));
if (statements != nullptr) {
Statement* item = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
item = *(*statements)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<Statement>* Parser::parseStatementList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<Statement>* ret = nullptr;
while (true) {
Statement* node = parseStatement(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<Statement>();
ret->push(node);
}
return ret ? new(_rp) _Array<Statement>(ret) : nullptr;
}
Statement* Parser::parseStatement(_Page* _rp) {
{
Declaration* node = parseDeclaration(_rp);
if (node != nullptr)
return node;
}
{
Expression* node = parseExpression(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
Declaration* Parser::parseDeclaration(_Page* _rp) {
{
ConstantDeclaration* node = parseConstantDeclaration(_rp);
if (node != nullptr)
return node;
}
{
MutableDeclaration* node = parseMutableDeclaration(_rp);
if (node != nullptr)
return node;
}
{
FunctionDeclaration* node = parseFunctionDeclaration(_rp);
if (node != nullptr)
return node;
}
{
EnumDeclaration* node = parseEnumDeclaration(_rp);
if (node != nullptr)
return node;
}
{
ClassDeclaration* node = parseClassDeclaration(_rp);
if (node != nullptr)
return node;
}
{
ConstructorDeclaration* node = parseConstructorDeclaration(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
ConstantDeclaration* Parser::parseConstantDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLet1 = lexer->parseKeyword(letKeyword);
if (successLet1)
lexer->advance();
else
return nullptr;
BindingInitializer* initializer = parseBindingInitializer(_rp);
if (initializer == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ConstantDeclaration* ret = new(_rp) ConstantDeclaration(initializer, new(_rp) Position(start), new(_rp) Position(end));
initializer->parent = ret;
return ret;
}
MutableDeclaration* Parser::parseMutableDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successMutable1 = lexer->parseKeyword(mutableKeyword);
if (successMutable1)
lexer->advance();
else
return nullptr;
BindingInitializer* initializer = parseBindingInitializer(_rp);
if (initializer == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
MutableDeclaration* ret = new(_rp) MutableDeclaration(initializer, new(_rp) Position(start), new(_rp) Position(end));
initializer->parent = ret;
return ret;
}
BindingInitializer* Parser::parseBindingInitializer(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
IdentifierInitializer* initializer = parseIdentifierInitializer(_rp);
if (initializer == nullptr)
return nullptr;
_Array<AdditionalInitializer>* additionalInitializers = parseAdditionalInitializerList(_rp);
Position* end = lexer->getPosition(_p);
BindingInitializer* ret = new(_rp) BindingInitializer(initializer, additionalInitializers, new(_rp) Position(start), new(_rp) Position(end));
initializer->parent = ret;
if (additionalInitializers != nullptr) {
AdditionalInitializer* item = nullptr;
size_t _additionalInitializers_length = additionalInitializers->length();
for (size_t _i = 0; _i < _additionalInitializers_length; _i++) {
item = *(*additionalInitializers)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<IdentifierInitializer>* Parser::parseIdentifierInitializerList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<IdentifierInitializer>* ret = nullptr;
while (true) {
IdentifierInitializer* node = parseIdentifierInitializer(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<IdentifierInitializer>();
ret->push(node);
}
return ret ? new(_rp) _Array<IdentifierInitializer>(ret) : nullptr;
}
IdentifierInitializer* Parser::parseIdentifierInitializer(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
IdentifierPattern* pattern = parseIdentifierPattern(_rp);
if (pattern == nullptr)
return nullptr;
Initializer* initializer = parseInitializer(_rp);
Position* end = lexer->getPosition(_p);
IdentifierInitializer* ret = new(_rp) IdentifierInitializer(pattern, initializer, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
if (initializer != nullptr)
initializer->parent = ret;
return ret;
}
Initializer* Parser::parseInitializer(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successEqual1 = lexer->parsePunctuation(equal);
if (successEqual1)
lexer->advance();
else
return nullptr;
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
Initializer* ret = new(_rp) Initializer(expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
_Array<AdditionalInitializer>* Parser::parseAdditionalInitializerList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<AdditionalInitializer>* ret = nullptr;
while (true) {
AdditionalInitializer* node = parseAdditionalInitializer(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<AdditionalInitializer>();
ret->push(node);
}
return ret ? new(_rp) _Array<AdditionalInitializer>(ret) : nullptr;
}
AdditionalInitializer* Parser::parseAdditionalInitializer(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successComma1 = lexer->parsePunctuation(comma);
if (successComma1)
lexer->advance();
else
return nullptr;
IdentifierInitializer* pattern = parseIdentifierInitializer(_rp);
if (pattern == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
AdditionalInitializer* ret = new(_rp) AdditionalInitializer(pattern, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
return ret;
}
Pattern* Parser::parsePattern(_Page* _rp) {
{
WildcardPattern* node = parseWildcardPattern(_rp);
if (node != nullptr)
return node;
}
{
IdentifierPattern* node = parseIdentifierPattern(_rp);
if (node != nullptr)
return node;
}
{
TuplePattern* node = parseTuplePattern(_rp);
if (node != nullptr)
return node;
}
{
ExpressionPattern* node = parseExpressionPattern(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
IdentifierPattern* Parser::parseIdentifierPattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* identifier = lexer->parseIdentifier(_rp);
if ((identifier != nullptr) && isIdentifier(identifier))
lexer->advance();
else
return nullptr;
TypeAnnotation* annotationForType = parseTypeAnnotation(_rp);
Position* end = lexer->getPosition(_p);
IdentifierPattern* ret = new(_rp) IdentifierPattern(identifier, annotationForType, new(_rp) Position(start), new(_rp) Position(end));
if (annotationForType != nullptr)
annotationForType->parent = ret;
return ret;
}
TypeAnnotation* Parser::parseTypeAnnotation(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successColon1 = lexer->parsePunctuation(colon);
if (successColon1)
lexer->advance();
else
return nullptr;
Type* annotationForType = parseType(_rp);
if (annotationForType == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
TypeAnnotation* ret = new(_rp) TypeAnnotation(annotationForType, new(_rp) Position(start), new(_rp) Position(end));
annotationForType->parent = ret;
return ret;
}
Type* Parser::parseType(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
_Array<TypePostfix>* postfixes = parseTypePostfixList(_rp);
LifeTime* lifeTime = parseLifeTime(_rp);
Position* end = lexer->getPosition(_p);
Type* ret = new(_rp) Type(name, postfixes, lifeTime, new(_rp) Position(start), new(_rp) Position(end));
if (postfixes != nullptr) {
TypePostfix* item = nullptr;
size_t _postfixes_length = postfixes->length();
for (size_t _i = 0; _i < _postfixes_length; _i++) {
item = *(*postfixes)[_i];
item->parent = ret;
}
}
if (lifeTime != nullptr)
lifeTime->parent = ret;
return ret;
}
_Array<TypePostfix>* Parser::parseTypePostfixList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<TypePostfix>* ret = nullptr;
while (true) {
TypePostfix* node = parseTypePostfix(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<TypePostfix>();
ret->push(node);
}
return ret ? new(_rp) _Array<TypePostfix>(ret) : nullptr;
}
TypePostfix* Parser::parseTypePostfix(_Page* _rp) {
{
IndexedType* node = parseIndexedType(_rp);
if (node != nullptr)
return node;
}
{
Pointer* node = parsePointer(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
IndexedType* Parser::parseIndexedType(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftBracket1 = lexer->parsePunctuation(leftBracket);
if (successLeftBracket1)
lexer->advance();
else
return nullptr;
Type* key = parseType(_rp);
bool successRightBracket3 = lexer->parsePunctuation(rightBracket);
if (successRightBracket3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
IndexedType* ret = new(_rp) IndexedType(key, new(_rp) Position(start), new(_rp) Position(end));
if (key != nullptr)
key->parent = ret;
return ret;
}
Pointer* Parser::parsePointer(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successCircumflex1 = lexer->parsePunctuation(circumflex);
if (successCircumflex1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
Pointer* ret = new(_rp) Pointer(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
LifeTime* Parser::parseLifeTime(_Page* _rp) {
{
Root* node = parseRoot(_rp);
if (node != nullptr)
return node;
}
{
Local* node = parseLocal(_rp);
if (node != nullptr)
return node;
}
{
Reference* node = parseReference(_rp);
if (node != nullptr)
return node;
}
{
Thrown* node = parseThrown(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
Root* Parser::parseRoot(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successDollar1 = lexer->parsePunctuation(dollar);
if (successDollar1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
Root* ret = new(_rp) Root(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
Local* Parser::parseLocal(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successAt1 = lexer->parsePunctuation(at);
if (successAt1)
lexer->advance();
else
return nullptr;
string* location = lexer->parseIdentifier(_rp);
if ((location != nullptr) && isIdentifier(location))
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
Local* ret = new(_rp) Local(location, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
Reference* Parser::parseReference(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successAmpersand1 = lexer->parsePunctuation(ampersand);
if (successAmpersand1)
lexer->advance();
else
return nullptr;
Literal* age = lexer->parseLiteral(_rp);
if (age != nullptr)
lexer->advance();
Position* end = lexer->getPosition(_p);
Reference* ret = new(_rp) Reference(age, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
Thrown* Parser::parseThrown(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successHash1 = lexer->parsePunctuation(hash);
if (successHash1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
Thrown* ret = new(_rp) Thrown(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
FunctionDeclaration* Parser::parseFunctionDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
_Array<Modifier>* modifiers = parseModifierList(_rp);
bool successFunction2 = lexer->parseKeyword(functionKeyword);
if (successFunction2)
lexer->advance();
else
return nullptr;
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
FunctionSignature* signature = parseFunctionSignature(_rp);
if (signature == nullptr)
return nullptr;
Expression* body = parseExpression(_rp);
Position* end = lexer->getPosition(_p);
FunctionDeclaration* ret = new(_rp) FunctionDeclaration(modifiers, name, signature, body, new(_rp) Position(start), new(_rp) Position(end));
if (modifiers != nullptr) {
Modifier* item = nullptr;
size_t _modifiers_length = modifiers->length();
for (size_t _i = 0; _i < _modifiers_length; _i++) {
item = *(*modifiers)[_i];
item->parent = ret;
}
}
signature->parent = ret;
if (body != nullptr)
body->parent = ret;
return ret;
}
_Array<Modifier>* Parser::parseModifierList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<Modifier>* ret = nullptr;
while (true) {
Modifier* node = parseModifier(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<Modifier>();
ret->push(node);
}
return ret ? new(_rp) _Array<Modifier>(ret) : nullptr;
}
Modifier* Parser::parseModifier(_Page* _rp) {
{
StaticWord* node = parseStaticWord(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
StaticWord* Parser::parseStaticWord(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successStatic1 = lexer->parseKeyword(staticKeyword);
if (successStatic1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
StaticWord* ret = new(_rp) StaticWord(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
FunctionSignature* Parser::parseFunctionSignature(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
ParameterClause* parameterClause = parseParameterClause(_rp);
if (parameterClause == nullptr)
return nullptr;
FunctionResult* result = parseFunctionResult(_rp);
ThrowsClause* throwsClause = parseThrowsClause(_rp);
Position* end = lexer->getPosition(_p);
FunctionSignature* ret = new(_rp) FunctionSignature(parameterClause, result, throwsClause, new(_rp) Position(start), new(_rp) Position(end));
parameterClause->parent = ret;
if (result != nullptr)
result->parent = ret;
if (throwsClause != nullptr)
throwsClause->parent = ret;
return ret;
}
_Array<ParameterClause>* Parser::parseParameterClauseList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<ParameterClause>* ret = nullptr;
while (true) {
ParameterClause* node = parseParameterClause(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<ParameterClause>();
ret->push(node);
}
return ret ? new(_rp) _Array<ParameterClause>(ret) : nullptr;
}
ParameterClause* Parser::parseParameterClause(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftParen1 = lexer->parsePunctuation(leftParen);
if (successLeftParen1)
lexer->advance();
else
return nullptr;
_Array<Parameter>* parameters = parseParameterList(_rp);
bool successRightParen3 = lexer->parsePunctuation(rightParen);
if (successRightParen3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
ParameterClause* ret = new(_rp) ParameterClause(parameters, new(_rp) Position(start), new(_rp) Position(end));
if (parameters != nullptr) {
Parameter* item = nullptr;
size_t _parameters_length = parameters->length();
for (size_t _i = 0; _i < _parameters_length; _i++) {
item = *(*parameters)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<Parameter>* Parser::parseParameterList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<Parameter>* ret = nullptr;
while (true) {
Parameter* node = parseParameter(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<Parameter>();
ret->push(node);
}
return ret ? new(_rp) _Array<Parameter>(ret) : nullptr;
}
Parameter* Parser::parseParameter(_Page* _rp) {
{
ConstParameter* node = parseConstParameter(_rp);
if (node != nullptr)
return node;
}
{
VarParameter* node = parseVarParameter(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
ConstParameter* Parser::parseConstParameter(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLet1 = lexer->parseKeyword(letKeyword);
if (successLet1)
lexer->advance();
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
bool successColon3 = lexer->parsePunctuation(colon);
if (successColon3)
lexer->advance();
else
return nullptr;
Type* parameterType = parseType(_rp);
if (parameterType == nullptr)
return nullptr;
bool successComma5 = lexer->parsePunctuation(comma);
if (successComma5)
lexer->advance();
Position* end = lexer->getPosition(_p);
ConstParameter* ret = new(_rp) ConstParameter(name, parameterType, new(_rp) Position(start), new(_rp) Position(end));
parameterType->parent = ret;
return ret;
}
VarParameter* Parser::parseVarParameter(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successMutable1 = lexer->parseKeyword(mutableKeyword);
if (successMutable1)
lexer->advance();
else
return nullptr;
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
bool successColon3 = lexer->parsePunctuation(colon);
if (successColon3)
lexer->advance();
else
return nullptr;
Type* parameterType = parseType(_rp);
if (parameterType == nullptr)
return nullptr;
bool successComma5 = lexer->parsePunctuation(comma);
if (successComma5)
lexer->advance();
Position* end = lexer->getPosition(_p);
VarParameter* ret = new(_rp) VarParameter(name, parameterType, new(_rp) Position(start), new(_rp) Position(end));
parameterType->parent = ret;
return ret;
}
FunctionResult* Parser::parseFunctionResult(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successColon1 = lexer->parsePunctuation(colon);
if (successColon1)
lexer->advance();
else
return nullptr;
Type* resultType = parseType(_rp);
if (resultType == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
FunctionResult* ret = new(_rp) FunctionResult(resultType, new(_rp) Position(start), new(_rp) Position(end));
resultType->parent = ret;
return ret;
}
ThrowsClause* Parser::parseThrowsClause(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successThrows1 = lexer->parseKeyword(throwsKeyword);
if (successThrows1)
lexer->advance();
else
return nullptr;
Type* throwsType = parseType(_rp);
if (throwsType == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ThrowsClause* ret = new(_rp) ThrowsClause(throwsType, new(_rp) Position(start), new(_rp) Position(end));
throwsType->parent = ret;
return ret;
}
EnumDeclaration* Parser::parseEnumDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successEnum1 = lexer->parseKeyword(enumKeyword);
if (successEnum1)
lexer->advance();
else
return nullptr;
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
bool successLeftCurly3 = lexer->parsePunctuation(leftCurly);
if (successLeftCurly3)
lexer->advance();
else
return nullptr;
_Array<EnumMember>* members = parseEnumMemberList(_rp);
bool successRightCurly5 = lexer->parsePunctuation(rightCurly);
if (successRightCurly5)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
EnumDeclaration* ret = new(_rp) EnumDeclaration(name, members, new(_rp) Position(start), new(_rp) Position(end));
if (members != nullptr) {
EnumMember* item = nullptr;
size_t _members_length = members->length();
for (size_t _i = 0; _i < _members_length; _i++) {
item = *(*members)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<EnumMember>* Parser::parseEnumMemberList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<EnumMember>* ret = nullptr;
while (true) {
EnumMember* node = parseEnumMember(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<EnumMember>();
ret->push(node);
}
return ret ? new(_rp) _Array<EnumMember>(ret) : nullptr;
}
EnumMember* Parser::parseEnumMember(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successCase1 = lexer->parseKeyword(caseKeyword);
if (successCase1)
lexer->advance();
else
return nullptr;
EnumCase* enumCase = parseEnumCase(_rp);
if (enumCase == nullptr)
return nullptr;
_Array<AdditionalCase>* additionalCases = parseAdditionalCaseList(_rp);
ParameterClause* parameterClause = parseParameterClause(_rp);
Position* end = lexer->getPosition(_p);
EnumMember* ret = new(_rp) EnumMember(enumCase, additionalCases, parameterClause, new(_rp) Position(start), new(_rp) Position(end));
enumCase->parent = ret;
if (additionalCases != nullptr) {
AdditionalCase* item = nullptr;
size_t _additionalCases_length = additionalCases->length();
for (size_t _i = 0; _i < _additionalCases_length; _i++) {
item = *(*additionalCases)[_i];
item->parent = ret;
}
}
if (parameterClause != nullptr)
parameterClause->parent = ret;
return ret;
}
EnumCase* Parser::parseEnumCase(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
EnumCase* ret = new(_rp) EnumCase(name, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
_Array<AdditionalCase>* Parser::parseAdditionalCaseList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<AdditionalCase>* ret = nullptr;
while (true) {
AdditionalCase* node = parseAdditionalCase(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<AdditionalCase>();
ret->push(node);
}
return ret ? new(_rp) _Array<AdditionalCase>(ret) : nullptr;
}
AdditionalCase* Parser::parseAdditionalCase(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successComma1 = lexer->parsePunctuation(comma);
if (successComma1)
lexer->advance();
else
return nullptr;
EnumCase* enumCase = parseEnumCase(_rp);
if (enumCase == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
AdditionalCase* ret = new(_rp) AdditionalCase(enumCase, new(_rp) Position(start), new(_rp) Position(end));
enumCase->parent = ret;
return ret;
}
ClassDeclaration* Parser::parseClassDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successClass1 = lexer->parseKeyword(classKeyword);
if (successClass1)
lexer->advance();
else
return nullptr;
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
TypeInheritanceClause* typeInheritanceClause = parseTypeInheritanceClause(_rp);
ClassBody* body = parseClassBody(_rp);
Position* end = lexer->getPosition(_p);
ClassDeclaration* ret = new(_rp) ClassDeclaration(name, typeInheritanceClause, body, new(_rp) Position(start), new(_rp) Position(end));
if (typeInheritanceClause != nullptr)
typeInheritanceClause->parent = ret;
if (body != nullptr)
body->parent = ret;
return ret;
}
TypeInheritanceClause* Parser::parseTypeInheritanceClause(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successExtends1 = lexer->parseKeyword(extendsKeyword);
if (successExtends1)
lexer->advance();
else
return nullptr;
_Array<Inheritance>* inheritances = parseInheritanceList(_rp);
Position* end = lexer->getPosition(_p);
TypeInheritanceClause* ret = new(_rp) TypeInheritanceClause(inheritances, new(_rp) Position(start), new(_rp) Position(end));
if (inheritances != nullptr) {
Inheritance* item = nullptr;
size_t _inheritances_length = inheritances->length();
for (size_t _i = 0; _i < _inheritances_length; _i++) {
item = *(*inheritances)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<Inheritance>* Parser::parseInheritanceList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<Inheritance>* ret = nullptr;
while (true) {
Inheritance* node = parseInheritance(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<Inheritance>();
ret->push(node);
}
return ret ? new(_rp) _Array<Inheritance>(ret) : nullptr;
}
Inheritance* Parser::parseInheritance(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Type* type = parseType(_rp);
if (type == nullptr)
return nullptr;
bool successComma2 = lexer->parsePunctuation(comma);
if (successComma2)
lexer->advance();
Position* end = lexer->getPosition(_p);
Inheritance* ret = new(_rp) Inheritance(type, new(_rp) Position(start), new(_rp) Position(end));
type->parent = ret;
return ret;
}
ClassBody* Parser::parseClassBody(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftCurly1 = lexer->parsePunctuation(leftCurly);
if (successLeftCurly1)
lexer->advance();
else
return nullptr;
_Array<ClassMember>* members = parseClassMemberList(_rp);
bool successRightCurly3 = lexer->parsePunctuation(rightCurly);
if (successRightCurly3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
ClassBody* ret = new(_rp) ClassBody(members, new(_rp) Position(start), new(_rp) Position(end));
if (members != nullptr) {
ClassMember* item = nullptr;
size_t _members_length = members->length();
for (size_t _i = 0; _i < _members_length; _i++) {
item = *(*members)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<ClassMember>* Parser::parseClassMemberList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<ClassMember>* ret = nullptr;
while (true) {
ClassMember* node = parseClassMember(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<ClassMember>();
ret->push(node);
}
return ret ? new(_rp) _Array<ClassMember>(ret) : nullptr;
}
ClassMember* Parser::parseClassMember(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Declaration* declaration = parseDeclaration(_rp);
if (declaration == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ClassMember* ret = new(_rp) ClassMember(declaration, new(_rp) Position(start), new(_rp) Position(end));
declaration->parent = ret;
return ret;
}
ConstructorDeclaration* Parser::parseConstructorDeclaration(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successConstructor1 = lexer->parseKeyword(constructorKeyword);
if (successConstructor1)
lexer->advance();
else
return nullptr;
ParameterClause* parameterClause = parseParameterClause(_rp);
if (parameterClause == nullptr)
return nullptr;
Expression* body = parseExpression(_rp);
if (body == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ConstructorDeclaration* ret = new(_rp) ConstructorDeclaration(parameterClause, body, new(_rp) Position(start), new(_rp) Position(end));
parameterClause->parent = ret;
body->parent = ret;
return ret;
}
Expression* Parser::parseExpression(_Page* _rp) {
{
CodeBlock* node = parseCodeBlock(_rp);
if (node != nullptr)
return node;
}
{
SimpleExpression* node = parseSimpleExpression(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
CodeBlock* Parser::parseCodeBlock(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftCurly1 = lexer->parsePunctuation(leftCurly);
if (successLeftCurly1)
lexer->advance();
else
return nullptr;
_Array<Statement>* statements = parseStatementList(_rp);
bool successRightCurly3 = lexer->parsePunctuation(rightCurly);
if (successRightCurly3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
CodeBlock* ret = new(_rp) CodeBlock(statements, new(_rp) Position(start), new(_rp) Position(end));
if (statements != nullptr) {
Statement* item = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
item = *(*statements)[_i];
item->parent = ret;
}
}
return ret;
}
SimpleExpression* Parser::parseSimpleExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
PrefixExpression* prefixExpression = parsePrefixExpression(_rp);
if (prefixExpression == nullptr)
return nullptr;
_Array<BinaryExpression>* binaryExpressions = parseBinaryExpressionList(_rp);
Position* end = lexer->getPosition(_p);
SimpleExpression* ret = new(_rp) SimpleExpression(prefixExpression, binaryExpressions, new(_rp) Position(start), new(_rp) Position(end));
prefixExpression->parent = ret;
if (binaryExpressions != nullptr) {
BinaryExpression* item = nullptr;
size_t _binaryExpressions_length = binaryExpressions->length();
for (size_t _i = 0; _i < _binaryExpressions_length; _i++) {
item = *(*binaryExpressions)[_i];
item->parent = ret;
}
}
return ret;
}
PrefixExpression* Parser::parsePrefixExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* prefixOperator = lexer->parsePrefixOperator(_rp);
if (prefixOperator != nullptr)
lexer->advance();
PostfixExpression* expression = parsePostfixExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
PrefixExpression* ret = new(_rp) PrefixExpression(prefixOperator, expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
PostfixExpression* Parser::parsePostfixExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
PrimaryExpression* primaryExpression = parsePrimaryExpression(_rp);
if (primaryExpression == nullptr)
return nullptr;
_Array<Postfix>* postfixes = parsePostfixList(_rp);
Position* end = lexer->getPosition(_p);
PostfixExpression* ret = new(_rp) PostfixExpression(primaryExpression, postfixes, new(_rp) Position(start), new(_rp) Position(end));
primaryExpression->parent = ret;
if (postfixes != nullptr) {
Postfix* item = nullptr;
size_t _postfixes_length = postfixes->length();
for (size_t _i = 0; _i < _postfixes_length; _i++) {
item = *(*postfixes)[_i];
item->parent = ret;
}
}
return ret;
}
PrimaryExpression* Parser::parsePrimaryExpression(_Page* _rp) {
{
IdentifierExpression* node = parseIdentifierExpression(_rp);
if (node != nullptr)
return node;
}
{
LiteralExpression* node = parseLiteralExpression(_rp);
if (node != nullptr)
return node;
}
{
IfExpression* node = parseIfExpression(_rp);
if (node != nullptr)
return node;
}
{
SwitchExpression* node = parseSwitchExpression(_rp);
if (node != nullptr)
return node;
}
{
ForExpression* node = parseForExpression(_rp);
if (node != nullptr)
return node;
}
{
WhileExpression* node = parseWhileExpression(_rp);
if (node != nullptr)
return node;
}
{
DoExpression* node = parseDoExpression(_rp);
if (node != nullptr)
return node;
}
{
ParenthesizedExpression* node = parseParenthesizedExpression(_rp);
if (node != nullptr)
return node;
}
{
ReturnExpression* node = parseReturnExpression(_rp);
if (node != nullptr)
return node;
}
{
ThrowExpression* node = parseThrowExpression(_rp);
if (node != nullptr)
return node;
}
{
BreakExpression* node = parseBreakExpression(_rp);
if (node != nullptr)
return node;
}
{
ConstructorCall* node = parseConstructorCall(_rp);
if (node != nullptr)
return node;
}
{
ThisExpression* node = parseThisExpression(_rp);
if (node != nullptr)
return node;
}
{
NullExpression* node = parseNullExpression(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
IdentifierExpression* Parser::parseIdentifierExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
IdentifierExpression* ret = new(_rp) IdentifierExpression(name, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
LiteralExpression* Parser::parseLiteralExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Literal* literal = lexer->parseLiteral(_rp);
if (literal != nullptr)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
LiteralExpression* ret = new(_rp) LiteralExpression(literal, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
IfExpression* Parser::parseIfExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successIf1 = lexer->parseKeyword(ifKeyword);
if (successIf1)
lexer->advance();
else
return nullptr;
Expression* condition = parseExpression(_rp);
if (condition == nullptr)
return nullptr;
Expression* consequent = parseExpression(_rp);
if (consequent == nullptr)
return nullptr;
ElseClause* elseClause = parseElseClause(_rp);
Position* end = lexer->getPosition(_p);
IfExpression* ret = new(_rp) IfExpression(condition, consequent, elseClause, new(_rp) Position(start), new(_rp) Position(end));
condition->parent = ret;
consequent->parent = ret;
if (elseClause != nullptr)
elseClause->parent = ret;
return ret;
}
ElseClause* Parser::parseElseClause(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successElse1 = lexer->parseKeyword(elseKeyword);
if (successElse1)
lexer->advance();
else
return nullptr;
Expression* alternative = parseExpression(_rp);
if (alternative == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ElseClause* ret = new(_rp) ElseClause(alternative, new(_rp) Position(start), new(_rp) Position(end));
alternative->parent = ret;
return ret;
}
SwitchExpression* Parser::parseSwitchExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successSwitch1 = lexer->parseKeyword(switchKeyword);
if (successSwitch1)
lexer->advance();
else
return nullptr;
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
SwitchBody* body = parseSwitchBody(_rp);
if (body == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
SwitchExpression* ret = new(_rp) SwitchExpression(expression, body, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
body->parent = ret;
return ret;
}
SwitchBody* Parser::parseSwitchBody(_Page* _rp) {
{
CurliedSwitchBody* node = parseCurliedSwitchBody(_rp);
if (node != nullptr)
return node;
}
{
NakedSwitchBody* node = parseNakedSwitchBody(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
CurliedSwitchBody* Parser::parseCurliedSwitchBody(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftCurly1 = lexer->parsePunctuation(leftCurly);
if (successLeftCurly1)
lexer->advance();
else
return nullptr;
_Array<SwitchCase>* cases = parseSwitchCaseList(_rp);
bool successRightCurly3 = lexer->parsePunctuation(rightCurly);
if (successRightCurly3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
CurliedSwitchBody* ret = new(_rp) CurliedSwitchBody(cases, new(_rp) Position(start), new(_rp) Position(end));
if (cases != nullptr) {
SwitchCase* item = nullptr;
size_t _cases_length = cases->length();
for (size_t _i = 0; _i < _cases_length; _i++) {
item = *(*cases)[_i];
item->parent = ret;
}
}
return ret;
}
NakedSwitchBody* Parser::parseNakedSwitchBody(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
_Array<SwitchCase>* cases = parseSwitchCaseList(_rp);
Position* end = lexer->getPosition(_p);
NakedSwitchBody* ret = new(_rp) NakedSwitchBody(cases, new(_rp) Position(start), new(_rp) Position(end));
if (cases != nullptr) {
SwitchCase* item = nullptr;
size_t _cases_length = cases->length();
for (size_t _i = 0; _i < _cases_length; _i++) {
item = *(*cases)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<SwitchCase>* Parser::parseSwitchCaseList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<SwitchCase>* ret = nullptr;
while (true) {
SwitchCase* node = parseSwitchCase(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<SwitchCase>();
ret->push(node);
}
return ret ? new(_rp) _Array<SwitchCase>(ret) : nullptr;
}
SwitchCase* Parser::parseSwitchCase(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
CaseLabel* label = parseCaseLabel(_rp);
if (label == nullptr)
return nullptr;
CaseContent* content = parseCaseContent(_rp);
if (content == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
SwitchCase* ret = new(_rp) SwitchCase(label, content, new(_rp) Position(start), new(_rp) Position(end));
label->parent = ret;
content->parent = ret;
return ret;
}
CaseLabel* Parser::parseCaseLabel(_Page* _rp) {
{
ItemCaseLabel* node = parseItemCaseLabel(_rp);
if (node != nullptr)
return node;
}
{
DefaultCaseLabel* node = parseDefaultCaseLabel(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
ItemCaseLabel* Parser::parseItemCaseLabel(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successCase1 = lexer->parseKeyword(caseKeyword);
if (successCase1)
lexer->advance();
else
return nullptr;
Pattern* pattern = parsePattern(_rp);
if (pattern == nullptr)
return nullptr;
_Array<CaseItem>* additionalPatterns = parseCaseItemList(_rp);
bool successColon4 = lexer->parsePunctuation(colon);
if (successColon4)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
ItemCaseLabel* ret = new(_rp) ItemCaseLabel(pattern, additionalPatterns, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
if (additionalPatterns != nullptr) {
CaseItem* item = nullptr;
size_t _additionalPatterns_length = additionalPatterns->length();
for (size_t _i = 0; _i < _additionalPatterns_length; _i++) {
item = *(*additionalPatterns)[_i];
item->parent = ret;
}
}
return ret;
}
DefaultCaseLabel* Parser::parseDefaultCaseLabel(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successDefault1 = lexer->parseKeyword(defaultKeyword);
if (successDefault1)
lexer->advance();
else
return nullptr;
bool successColon2 = lexer->parsePunctuation(colon);
if (successColon2)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
DefaultCaseLabel* ret = new(_rp) DefaultCaseLabel(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
_Array<CaseItem>* Parser::parseCaseItemList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<CaseItem>* ret = nullptr;
while (true) {
CaseItem* node = parseCaseItem(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<CaseItem>();
ret->push(node);
}
return ret ? new(_rp) _Array<CaseItem>(ret) : nullptr;
}
CaseItem* Parser::parseCaseItem(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successComma1 = lexer->parsePunctuation(comma);
if (successComma1)
lexer->advance();
else
return nullptr;
Pattern* pattern = parsePattern(_rp);
if (pattern == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
CaseItem* ret = new(_rp) CaseItem(pattern, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
return ret;
}
CaseContent* Parser::parseCaseContent(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
_Array<Statement>* statements = parseStatementList(_rp);
Position* end = lexer->getPosition(_p);
CaseContent* ret = new(_rp) CaseContent(statements, new(_rp) Position(start), new(_rp) Position(end));
if (statements != nullptr) {
Statement* item = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
item = *(*statements)[_i];
item->parent = ret;
}
}
return ret;
}
ForExpression* Parser::parseForExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successFor1 = lexer->parseKeyword(forKeyword);
if (successFor1)
lexer->advance();
else
return nullptr;
IdentifierPattern* pattern = parseIdentifierPattern(_rp);
if (pattern == nullptr)
return nullptr;
bool successIn3 = lexer->parseKeyword(inKeyword);
if (successIn3)
lexer->advance();
else
return nullptr;
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
Expression* code = parseExpression(_rp);
if (code == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ForExpression* ret = new(_rp) ForExpression(pattern, expression, code, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
expression->parent = ret;
code->parent = ret;
return ret;
}
WhileExpression* Parser::parseWhileExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successWhile1 = lexer->parseKeyword(whileKeyword);
if (successWhile1)
lexer->advance();
else
return nullptr;
Expression* condition = parseExpression(_rp);
if (condition == nullptr)
return nullptr;
Expression* code = parseExpression(_rp);
if (code == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
WhileExpression* ret = new(_rp) WhileExpression(condition, code, new(_rp) Position(start), new(_rp) Position(end));
condition->parent = ret;
code->parent = ret;
return ret;
}
DoExpression* Parser::parseDoExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successDo1 = lexer->parseKeyword(doKeyword);
if (successDo1)
lexer->advance();
else
return nullptr;
Expression* code = parseExpression(_rp);
if (code == nullptr)
return nullptr;
bool successWhile3 = lexer->parseKeyword(whileKeyword);
if (successWhile3)
lexer->advance();
else
return nullptr;
Expression* condition = parseExpression(_rp);
if (condition == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
DoExpression* ret = new(_rp) DoExpression(code, condition, new(_rp) Position(start), new(_rp) Position(end));
code->parent = ret;
condition->parent = ret;
return ret;
}
ParenthesizedExpression* Parser::parseParenthesizedExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftParen1 = lexer->parsePunctuation(leftParen);
if (successLeftParen1)
lexer->advance();
else
return nullptr;
_Array<ExpressionElement>* expressionElements = parseExpressionElementList(_rp);
bool successRightParen3 = lexer->parsePunctuation(rightParen);
if (successRightParen3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
ParenthesizedExpression* ret = new(_rp) ParenthesizedExpression(expressionElements, new(_rp) Position(start), new(_rp) Position(end));
if (expressionElements != nullptr) {
ExpressionElement* item = nullptr;
size_t _expressionElements_length = expressionElements->length();
for (size_t _i = 0; _i < _expressionElements_length; _i++) {
item = *(*expressionElements)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<ExpressionElement>* Parser::parseExpressionElementList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<ExpressionElement>* ret = nullptr;
while (true) {
ExpressionElement* node = parseExpressionElement(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<ExpressionElement>();
ret->push(node);
}
return ret ? new(_rp) _Array<ExpressionElement>(ret) : nullptr;
}
ExpressionElement* Parser::parseExpressionElement(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
bool successComma2 = lexer->parsePunctuation(comma);
if (successComma2)
lexer->advance();
Position* end = lexer->getPosition(_p);
ExpressionElement* ret = new(_rp) ExpressionElement(expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
ReturnExpression* Parser::parseReturnExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successReturn1 = lexer->parseKeyword(returnKeyword);
if (successReturn1)
lexer->advance();
else
return nullptr;
ParenthesizedExpression* expression = parseParenthesizedExpression(_rp);
Position* end = lexer->getPosition(_p);
ReturnExpression* ret = new(_rp) ReturnExpression(expression, new(_rp) Position(start), new(_rp) Position(end));
if (expression != nullptr)
expression->parent = ret;
return ret;
}
ThrowExpression* Parser::parseThrowExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successThrow1 = lexer->parseKeyword(throwKeyword);
if (successThrow1)
lexer->advance();
else
return nullptr;
IdentifierExpression* error = parseIdentifierExpression(_rp);
if (error == nullptr)
return nullptr;
ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp);
Position* end = lexer->getPosition(_p);
ThrowExpression* ret = new(_rp) ThrowExpression(error, arguments, new(_rp) Position(start), new(_rp) Position(end));
error->parent = ret;
if (arguments != nullptr)
arguments->parent = ret;
return ret;
}
BreakExpression* Parser::parseBreakExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successBreak1 = lexer->parseKeyword(breakKeyword);
if (successBreak1)
lexer->advance();
else
return nullptr;
ParenthesizedExpression* expression = parseParenthesizedExpression(_rp);
Position* end = lexer->getPosition(_p);
BreakExpression* ret = new(_rp) BreakExpression(expression, new(_rp) Position(start), new(_rp) Position(end));
if (expression != nullptr)
expression->parent = ret;
return ret;
}
ConstructorCall* Parser::parseConstructorCall(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successNew1 = lexer->parseKeyword(newKeyword);
if (successNew1)
lexer->advance();
else
return nullptr;
Type* typeToConstruct = parseType(_rp);
if (typeToConstruct == nullptr)
return nullptr;
ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp);
if (arguments == nullptr)
return nullptr;
_Array<CatchClause>* catchClauses = parseCatchClauseList(_rp);
Position* end = lexer->getPosition(_p);
ConstructorCall* ret = new(_rp) ConstructorCall(typeToConstruct, arguments, catchClauses, new(_rp) Position(start), new(_rp) Position(end));
typeToConstruct->parent = ret;
arguments->parent = ret;
if (catchClauses != nullptr) {
CatchClause* item = nullptr;
size_t _catchClauses_length = catchClauses->length();
for (size_t _i = 0; _i < _catchClauses_length; _i++) {
item = *(*catchClauses)[_i];
item->parent = ret;
}
}
return ret;
}
ThisExpression* Parser::parseThisExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successThis1 = lexer->parseKeyword(thisKeyword);
if (successThis1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
ThisExpression* ret = new(_rp) ThisExpression(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
NullExpression* Parser::parseNullExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successNull1 = lexer->parseKeyword(nullKeyword);
if (successNull1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
NullExpression* ret = new(_rp) NullExpression(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
_Array<Postfix>* Parser::parsePostfixList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<Postfix>* ret = nullptr;
while (true) {
Postfix* node = parsePostfix(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<Postfix>();
ret->push(node);
}
return ret ? new(_rp) _Array<Postfix>(ret) : nullptr;
}
Postfix* Parser::parsePostfix(_Page* _rp) {
{
OperatorPostfix* node = parseOperatorPostfix(_rp);
if (node != nullptr)
return node;
}
{
FunctionCall* node = parseFunctionCall(_rp);
if (node != nullptr)
return node;
}
{
MemberExpression* node = parseMemberExpression(_rp);
if (node != nullptr)
return node;
}
{
Subscript* node = parseSubscript(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
OperatorPostfix* Parser::parseOperatorPostfix(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* postfixOperator = lexer->parsePostfixOperator(_rp);
if (postfixOperator != nullptr)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
OperatorPostfix* ret = new(_rp) OperatorPostfix(postfixOperator, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
FunctionCall* Parser::parseFunctionCall(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
ParenthesizedExpression* arguments = parseParenthesizedExpression(_rp);
if (arguments == nullptr)
return nullptr;
_Array<CatchClause>* catchClauses = parseCatchClauseList(_rp);
Position* end = lexer->getPosition(_p);
FunctionCall* ret = new(_rp) FunctionCall(arguments, catchClauses, new(_rp) Position(start), new(_rp) Position(end));
arguments->parent = ret;
if (catchClauses != nullptr) {
CatchClause* item = nullptr;
size_t _catchClauses_length = catchClauses->length();
for (size_t _i = 0; _i < _catchClauses_length; _i++) {
item = *(*catchClauses)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<CatchClause>* Parser::parseCatchClauseList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<CatchClause>* ret = nullptr;
while (true) {
CatchClause* node = parseCatchClause(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<CatchClause>();
ret->push(node);
}
return ret ? new(_rp) _Array<CatchClause>(ret) : nullptr;
}
CatchClause* Parser::parseCatchClause(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successCatch1 = lexer->parseKeyword(catchKeyword);
if (successCatch1)
lexer->advance();
else
return nullptr;
CatchPattern* catchPattern = parseCatchPattern(_rp);
if (catchPattern == nullptr)
return nullptr;
TuplePattern* bindingPattern = parseTuplePattern(_rp);
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
CatchClause* ret = new(_rp) CatchClause(catchPattern, bindingPattern, expression, new(_rp) Position(start), new(_rp) Position(end));
catchPattern->parent = ret;
if (bindingPattern != nullptr)
bindingPattern->parent = ret;
expression->parent = ret;
return ret;
}
CatchPattern* Parser::parseCatchPattern(_Page* _rp) {
{
WildCardCatchPattern* node = parseWildCardCatchPattern(_rp);
if (node != nullptr)
return node;
}
{
IdentifierCatchPattern* node = parseIdentifierCatchPattern(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
WildCardCatchPattern* Parser::parseWildCardCatchPattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
WildcardPattern* pattern = parseWildcardPattern(_rp);
if (pattern == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
WildCardCatchPattern* ret = new(_rp) WildCardCatchPattern(pattern, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
return ret;
}
IdentifierCatchPattern* Parser::parseIdentifierCatchPattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* name = lexer->parseIdentifier(_rp);
if ((name != nullptr) && isIdentifier(name))
lexer->advance();
else
return nullptr;
MemberExpression* member = parseMemberExpression(_rp);
Position* end = lexer->getPosition(_p);
IdentifierCatchPattern* ret = new(_rp) IdentifierCatchPattern(name, member, new(_rp) Position(start), new(_rp) Position(end));
if (member != nullptr)
member->parent = ret;
return ret;
}
WildcardPattern* Parser::parseWildcardPattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successUnderscore1 = lexer->parsePunctuation(underscore);
if (successUnderscore1)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
WildcardPattern* ret = new(_rp) WildcardPattern(new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
TuplePattern* Parser::parseTuplePattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftParen1 = lexer->parsePunctuation(leftParen);
if (successLeftParen1)
lexer->advance();
else
return nullptr;
_Array<TuplePatternElement>* elements = parseTuplePatternElementList(_rp);
bool successRightParen3 = lexer->parsePunctuation(rightParen);
if (successRightParen3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
TuplePattern* ret = new(_rp) TuplePattern(elements, new(_rp) Position(start), new(_rp) Position(end));
if (elements != nullptr) {
TuplePatternElement* item = nullptr;
size_t _elements_length = elements->length();
for (size_t _i = 0; _i < _elements_length; _i++) {
item = *(*elements)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<TuplePatternElement>* Parser::parseTuplePatternElementList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<TuplePatternElement>* ret = nullptr;
while (true) {
TuplePatternElement* node = parseTuplePatternElement(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<TuplePatternElement>();
ret->push(node);
}
return ret ? new(_rp) _Array<TuplePatternElement>(ret) : nullptr;
}
TuplePatternElement* Parser::parseTuplePatternElement(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Pattern* pattern = parsePattern(_rp);
if (pattern == nullptr)
return nullptr;
bool successComma2 = lexer->parsePunctuation(comma);
if (successComma2)
lexer->advance();
Position* end = lexer->getPosition(_p);
TuplePatternElement* ret = new(_rp) TuplePatternElement(pattern, new(_rp) Position(start), new(_rp) Position(end));
pattern->parent = ret;
return ret;
}
ExpressionPattern* Parser::parseExpressionPattern(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
ExpressionPattern* ret = new(_rp) ExpressionPattern(expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
MemberExpression* Parser::parseMemberExpression(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successDot1 = lexer->parsePunctuation(dot);
if (successDot1)
lexer->advance();
else
return nullptr;
string* member = lexer->parseIdentifier(_rp);
if ((member != nullptr) && isIdentifier(member))
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
MemberExpression* ret = new(_rp) MemberExpression(member, new(_rp) Position(start), new(_rp) Position(end));
return ret;
}
Subscript* Parser::parseSubscript(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successLeftBracket1 = lexer->parsePunctuation(leftBracket);
if (successLeftBracket1)
lexer->advance();
else
return nullptr;
_Array<ExpressionElement>* expressions = parseExpressionElementList(_rp);
bool successRightBracket3 = lexer->parsePunctuation(rightBracket);
if (successRightBracket3)
lexer->advance();
else
return nullptr;
Position* end = lexer->getPosition(_p);
Subscript* ret = new(_rp) Subscript(expressions, new(_rp) Position(start), new(_rp) Position(end));
if (expressions != nullptr) {
ExpressionElement* item = nullptr;
size_t _expressions_length = expressions->length();
for (size_t _i = 0; _i < _expressions_length; _i++) {
item = *(*expressions)[_i];
item->parent = ret;
}
}
return ret;
}
_Array<BinaryExpression>* Parser::parseBinaryExpressionList(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
_Array<BinaryExpression>* ret = nullptr;
while (true) {
BinaryExpression* node = parseBinaryExpression(_rp);
if (node == nullptr)
break;
if (ret == nullptr)
ret = new(_p) _Array<BinaryExpression>();
ret->push(node);
}
return ret ? new(_rp) _Array<BinaryExpression>(ret) : nullptr;
}
BinaryExpression* Parser::parseBinaryExpression(_Page* _rp) {
{
BinaryOperation* node = parseBinaryOperation(_rp);
if (node != nullptr)
return node;
}
{
Assignment* node = parseAssignment(_rp);
if (node != nullptr)
return node;
}
{
TypeQuery* node = parseTypeQuery(_rp);
if (node != nullptr)
return node;
}
{
TypeCast* node = parseTypeCast(_rp);
if (node != nullptr)
return node;
}
return nullptr;
}
BinaryOperation* Parser::parseBinaryOperation(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
string* binaryOperator = lexer->parseBinaryOperator(_rp);
if (binaryOperator != nullptr)
lexer->advance();
else
return nullptr;
PrefixExpression* expression = parsePrefixExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
BinaryOperation* ret = new(_rp) BinaryOperation(binaryOperator, expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
Assignment* Parser::parseAssignment(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successEqual1 = lexer->parsePunctuation(equal);
if (successEqual1)
lexer->advance();
else
return nullptr;
Expression* expression = parseExpression(_rp);
if (expression == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
Assignment* ret = new(_rp) Assignment(expression, new(_rp) Position(start), new(_rp) Position(end));
expression->parent = ret;
return ret;
}
TypeQuery* Parser::parseTypeQuery(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successIs1 = lexer->parseKeyword(isKeyword);
if (successIs1)
lexer->advance();
else
return nullptr;
Type* objectType = parseType(_rp);
if (objectType == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
TypeQuery* ret = new(_rp) TypeQuery(objectType, new(_rp) Position(start), new(_rp) Position(end));
objectType->parent = ret;
return ret;
}
TypeCast* Parser::parseTypeCast(_Page* _rp) {
_Region _region; _Page* _p = _region.get();
Position* start = lexer->getPreviousPosition(_p);
bool successAs1 = lexer->parseKeyword(asKeyword);
if (successAs1)
lexer->advance();
else
return nullptr;
Type* objectType = parseType(_rp);
if (objectType == nullptr)
return nullptr;
Position* end = lexer->getPosition(_p);
TypeCast* ret = new(_rp) TypeCast(objectType, new(_rp) Position(start), new(_rp) Position(end));
objectType->parent = ret;
return ret;
}
bool Parser::isAtEnd() {
return lexer->isAtEnd();
}
bool Parser::isIdentifier(string* id) {
if (id->equals(classKeyword))
return false;
if (id->equals(functionKeyword))
return false;
if (id->equals(ifKeyword))
return false;
if (id->equals(elseKeyword))
return false;
if (id->equals(switchKeyword))
return false;
if (id->equals(caseKeyword))
return false;
if (id->equals(defaultKeyword))
return false;
if (id->equals(catchKeyword))
return false;
if (id->equals(forKeyword))
return false;
if (id->equals(inKeyword))
return false;
if (id->equals(whileKeyword))
return false;
if (id->equals(doKeyword))
return false;
if (id->equals(returnKeyword))
return false;
if (id->equals(throwKeyword))
return false;
if (id->equals(breakKeyword))
return false;
if (id->equals(throwsKeyword))
return false;
if (id->equals(staticKeyword))
return false;
if (id->equals(letKeyword))
return false;
if (id->equals(mutableKeyword))
return false;
if (id->equals(isKeyword))
return false;
if (id->equals(asKeyword))
return false;
if (id->equals(constructorKeyword))
return false;
if (id->equals(enumKeyword))
return false;
if (id->equals(thisKeyword))
return false;
if (id->equals(nullKeyword))
return false;
if (id->equals(newKeyword))
return false;
if (id->equals(extendsKeyword))
return false;
return true;
}
bool Visitor::openProgram(Program* program) {
return true;
}
void Visitor::closeProgram(Program* program) {
}
bool Visitor::openModule(Module* module) {
return true;
}
void Visitor::closeModule(Module* module) {
}
bool Visitor::openConstantDeclaration(ConstantDeclaration* constantDeclaration) {
return true;
}
void Visitor::closeConstantDeclaration(ConstantDeclaration* constantDeclaration) {
}
bool Visitor::openMutableDeclaration(MutableDeclaration* mutableDeclaration) {
return true;
}
void Visitor::closeMutableDeclaration(MutableDeclaration* mutableDeclaration) {
}
bool Visitor::openBindingInitializer(BindingInitializer* bindingInitializer) {
return true;
}
void Visitor::closeBindingInitializer(BindingInitializer* bindingInitializer) {
}
bool Visitor::openIdentifierInitializer(IdentifierInitializer* identifierInitializer) {
return true;
}
void Visitor::closeIdentifierInitializer(IdentifierInitializer* identifierInitializer) {
}
bool Visitor::openInitializer(Initializer* initializer) {
return true;
}
void Visitor::closeInitializer(Initializer* initializer) {
}
bool Visitor::openAdditionalInitializer(AdditionalInitializer* additionalInitializer) {
return true;
}
void Visitor::closeAdditionalInitializer(AdditionalInitializer* additionalInitializer) {
}
bool Visitor::openIdentifierPattern(IdentifierPattern* identifierPattern) {
return true;
}
void Visitor::closeIdentifierPattern(IdentifierPattern* identifierPattern) {
}
bool Visitor::openTypeAnnotation(TypeAnnotation* typeAnnotation) {
return true;
}
void Visitor::closeTypeAnnotation(TypeAnnotation* typeAnnotation) {
}
bool Visitor::openType(Type* type) {
return true;
}
void Visitor::closeType(Type* type) {
}
bool Visitor::openIndexedType(IndexedType* indexedType) {
return true;
}
void Visitor::closeIndexedType(IndexedType* indexedType) {
}
void Visitor::visitPointer(Pointer* pointer) {
}
void Visitor::visitRoot(Root* root) {
}
void Visitor::visitLocal(Local* local) {
}
void Visitor::visitReference(Reference* reference) {
}
void Visitor::visitThrown(Thrown* thrown) {
}
bool Visitor::openFunctionDeclaration(FunctionDeclaration* functionDeclaration) {
return true;
}
void Visitor::closeFunctionDeclaration(FunctionDeclaration* functionDeclaration) {
}
void Visitor::visitStaticWord(StaticWord* staticWord) {
}
bool Visitor::openFunctionSignature(FunctionSignature* functionSignature) {
return true;
}
void Visitor::closeFunctionSignature(FunctionSignature* functionSignature) {
}
bool Visitor::openParameterClause(ParameterClause* parameterClause) {
return true;
}
void Visitor::closeParameterClause(ParameterClause* parameterClause) {
}
bool Visitor::openConstParameter(ConstParameter* constParameter) {
return true;
}
void Visitor::closeConstParameter(ConstParameter* constParameter) {
}
bool Visitor::openVarParameter(VarParameter* varParameter) {
return true;
}
void Visitor::closeVarParameter(VarParameter* varParameter) {
}
bool Visitor::openFunctionResult(FunctionResult* functionResult) {
return true;
}
void Visitor::closeFunctionResult(FunctionResult* functionResult) {
}
bool Visitor::openThrowsClause(ThrowsClause* throwsClause) {
return true;
}
void Visitor::closeThrowsClause(ThrowsClause* throwsClause) {
}
bool Visitor::openEnumDeclaration(EnumDeclaration* enumDeclaration) {
return true;
}
void Visitor::closeEnumDeclaration(EnumDeclaration* enumDeclaration) {
}
bool Visitor::openEnumMember(EnumMember* enumMember) {
return true;
}
void Visitor::closeEnumMember(EnumMember* enumMember) {
}
void Visitor::visitEnumCase(EnumCase* enumCase) {
}
bool Visitor::openAdditionalCase(AdditionalCase* additionalCase) {
return true;
}
void Visitor::closeAdditionalCase(AdditionalCase* additionalCase) {
}
bool Visitor::openClassDeclaration(ClassDeclaration* classDeclaration) {
return true;
}
void Visitor::closeClassDeclaration(ClassDeclaration* classDeclaration) {
}
bool Visitor::openTypeInheritanceClause(TypeInheritanceClause* typeInheritanceClause) {
return true;
}
void Visitor::closeTypeInheritanceClause(TypeInheritanceClause* typeInheritanceClause) {
}
bool Visitor::openInheritance(Inheritance* inheritance) {
return true;
}
void Visitor::closeInheritance(Inheritance* inheritance) {
}
bool Visitor::openClassBody(ClassBody* classBody) {
return true;
}
void Visitor::closeClassBody(ClassBody* classBody) {
}
bool Visitor::openClassMember(ClassMember* classMember) {
return true;
}
void Visitor::closeClassMember(ClassMember* classMember) {
}
bool Visitor::openConstructorDeclaration(ConstructorDeclaration* constructorDeclaration) {
return true;
}
void Visitor::closeConstructorDeclaration(ConstructorDeclaration* constructorDeclaration) {
}
bool Visitor::openCodeBlock(CodeBlock* codeBlock) {
return true;
}
void Visitor::closeCodeBlock(CodeBlock* codeBlock) {
}
bool Visitor::openSimpleExpression(SimpleExpression* simpleExpression) {
return true;
}
void Visitor::closeSimpleExpression(SimpleExpression* simpleExpression) {
}
bool Visitor::openPrefixExpression(PrefixExpression* prefixExpression) {
return true;
}
void Visitor::closePrefixExpression(PrefixExpression* prefixExpression) {
}
bool Visitor::openPostfixExpression(PostfixExpression* postfixExpression) {
return true;
}
void Visitor::closePostfixExpression(PostfixExpression* postfixExpression) {
}
void Visitor::visitIdentifierExpression(IdentifierExpression* identifierExpression) {
}
void Visitor::visitLiteralExpression(LiteralExpression* literalExpression) {
}
bool Visitor::openIfExpression(IfExpression* ifExpression) {
return true;
}
void Visitor::closeIfExpression(IfExpression* ifExpression) {
}
bool Visitor::openElseClause(ElseClause* elseClause) {
return true;
}
void Visitor::closeElseClause(ElseClause* elseClause) {
}
bool Visitor::openSwitchExpression(SwitchExpression* switchExpression) {
return true;
}
void Visitor::closeSwitchExpression(SwitchExpression* switchExpression) {
}
bool Visitor::openCurliedSwitchBody(CurliedSwitchBody* curliedSwitchBody) {
return true;
}
void Visitor::closeCurliedSwitchBody(CurliedSwitchBody* curliedSwitchBody) {
}
bool Visitor::openNakedSwitchBody(NakedSwitchBody* nakedSwitchBody) {
return true;
}
void Visitor::closeNakedSwitchBody(NakedSwitchBody* nakedSwitchBody) {
}
bool Visitor::openSwitchCase(SwitchCase* switchCase) {
return true;
}
void Visitor::closeSwitchCase(SwitchCase* switchCase) {
}
bool Visitor::openItemCaseLabel(ItemCaseLabel* itemCaseLabel) {
return true;
}
void Visitor::closeItemCaseLabel(ItemCaseLabel* itemCaseLabel) {
}
void Visitor::visitDefaultCaseLabel(DefaultCaseLabel* defaultCaseLabel) {
}
bool Visitor::openCaseItem(CaseItem* caseItem) {
return true;
}
void Visitor::closeCaseItem(CaseItem* caseItem) {
}
bool Visitor::openCaseContent(CaseContent* caseContent) {
return true;
}
void Visitor::closeCaseContent(CaseContent* caseContent) {
}
bool Visitor::openForExpression(ForExpression* forExpression) {
return true;
}
void Visitor::closeForExpression(ForExpression* forExpression) {
}
bool Visitor::openWhileExpression(WhileExpression* whileExpression) {
return true;
}
void Visitor::closeWhileExpression(WhileExpression* whileExpression) {
}
bool Visitor::openDoExpression(DoExpression* doExpression) {
return true;
}
void Visitor::closeDoExpression(DoExpression* doExpression) {
}
bool Visitor::openParenthesizedExpression(ParenthesizedExpression* parenthesizedExpression) {
return true;
}
void Visitor::closeParenthesizedExpression(ParenthesizedExpression* parenthesizedExpression) {
}
bool Visitor::openExpressionElement(ExpressionElement* expressionElement) {
return true;
}
void Visitor::closeExpressionElement(ExpressionElement* expressionElement) {
}
bool Visitor::openReturnExpression(ReturnExpression* returnExpression) {
return true;
}
void Visitor::closeReturnExpression(ReturnExpression* returnExpression) {
}
bool Visitor::openThrowExpression(ThrowExpression* throwExpression) {
return true;
}
void Visitor::closeThrowExpression(ThrowExpression* throwExpression) {
}
bool Visitor::openBreakExpression(BreakExpression* breakExpression) {
return true;
}
void Visitor::closeBreakExpression(BreakExpression* breakExpression) {
}
bool Visitor::openConstructorCall(ConstructorCall* constructorCall) {
return true;
}
void Visitor::closeConstructorCall(ConstructorCall* constructorCall) {
}
void Visitor::visitThisExpression(ThisExpression* thisExpression) {
}
void Visitor::visitNullExpression(NullExpression* nullExpression) {
}
void Visitor::visitOperatorPostfix(OperatorPostfix* operatorPostfix) {
}
bool Visitor::openFunctionCall(FunctionCall* functionCall) {
return true;
}
void Visitor::closeFunctionCall(FunctionCall* functionCall) {
}
bool Visitor::openCatchClause(CatchClause* catchClause) {
return true;
}
void Visitor::closeCatchClause(CatchClause* catchClause) {
}
bool Visitor::openWildCardCatchPattern(WildCardCatchPattern* wildCardCatchPattern) {
return true;
}
void Visitor::closeWildCardCatchPattern(WildCardCatchPattern* wildCardCatchPattern) {
}
bool Visitor::openIdentifierCatchPattern(IdentifierCatchPattern* identifierCatchPattern) {
return true;
}
void Visitor::closeIdentifierCatchPattern(IdentifierCatchPattern* identifierCatchPattern) {
}
void Visitor::visitWildcardPattern(WildcardPattern* wildcardPattern) {
}
bool Visitor::openTuplePattern(TuplePattern* tuplePattern) {
return true;
}
void Visitor::closeTuplePattern(TuplePattern* tuplePattern) {
}
bool Visitor::openTuplePatternElement(TuplePatternElement* tuplePatternElement) {
return true;
}
void Visitor::closeTuplePatternElement(TuplePatternElement* tuplePatternElement) {
}
bool Visitor::openExpressionPattern(ExpressionPattern* expressionPattern) {
return true;
}
void Visitor::closeExpressionPattern(ExpressionPattern* expressionPattern) {
}
void Visitor::visitMemberExpression(MemberExpression* memberExpression) {
}
bool Visitor::openSubscript(Subscript* subscript) {
return true;
}
void Visitor::closeSubscript(Subscript* subscript) {
}
bool Visitor::openBinaryOperation(BinaryOperation* binaryOperation) {
return true;
}
void Visitor::closeBinaryOperation(BinaryOperation* binaryOperation) {
}
bool Visitor::openAssignment(Assignment* assignment) {
return true;
}
void Visitor::closeAssignment(Assignment* assignment) {
}
bool Visitor::openTypeQuery(TypeQuery* typeQuery) {
return true;
}
void Visitor::closeTypeQuery(TypeQuery* typeQuery) {
}
bool Visitor::openTypeCast(TypeCast* typeCast) {
return true;
}
void Visitor::closeTypeCast(TypeCast* typeCast) {
}
bool Visitor::_isCommonVisitor() { return (false); }
bool Visitor::_isCppVisitor() { return (false); }
bool Visitor::_isHeaderVisitor() { return (false); }
bool Visitor::_isSourceVisitor() { return (false); }
bool Visitor::_isModelVisitor() { return (false); }
bool SyntaxNode::_isProgram() { return (false); }
bool SyntaxNode::_isModule() { return (false); }
bool SyntaxNode::_isStatement() { return (false); }
bool SyntaxNode::_isDeclaration() { return (false); }
bool SyntaxNode::_isConstantDeclaration() { return (false); }
bool SyntaxNode::_isMutableDeclaration() { return (false); }
bool SyntaxNode::_isFunctionDeclaration() { return (false); }
bool SyntaxNode::_isEnumDeclaration() { return (false); }
bool SyntaxNode::_isClassDeclaration() { return (false); }
bool SyntaxNode::_isConstructorDeclaration() { return (false); }
bool SyntaxNode::_isExpression() { return (false); }
bool SyntaxNode::_isCodeBlock() { return (false); }
bool SyntaxNode::_isSimpleExpression() { return (false); }
bool SyntaxNode::_isBindingInitializer() { return (false); }
bool SyntaxNode::_isIdentifierInitializer() { return (false); }
bool SyntaxNode::_isInitializer() { return (false); }
bool SyntaxNode::_isAdditionalInitializer() { return (false); }
bool SyntaxNode::_isPattern() { return (false); }
bool SyntaxNode::_isIdentifierPattern() { return (false); }
bool SyntaxNode::_isWildcardPattern() { return (false); }
bool SyntaxNode::_isTuplePattern() { return (false); }
bool SyntaxNode::_isExpressionPattern() { return (false); }
bool SyntaxNode::_isTypeAnnotation() { return (false); }
bool SyntaxNode::_isType() { return (false); }
bool SyntaxNode::_isTypePostfix() { return (false); }
bool SyntaxNode::_isIndexedType() { return (false); }
bool SyntaxNode::_isPointer() { return (false); }
bool SyntaxNode::_isLifeTime() { return (false); }
bool SyntaxNode::_isRoot() { return (false); }
bool SyntaxNode::_isLocal() { return (false); }
bool SyntaxNode::_isReference() { return (false); }
bool SyntaxNode::_isThrown() { return (false); }
bool SyntaxNode::_isModifier() { return (false); }
bool SyntaxNode::_isStaticWord() { return (false); }
bool SyntaxNode::_isFunctionSignature() { return (false); }
bool SyntaxNode::_isParameterClause() { return (false); }
bool SyntaxNode::_isParameter() { return (false); }
bool SyntaxNode::_isConstParameter() { return (false); }
bool SyntaxNode::_isVarParameter() { return (false); }
bool SyntaxNode::_isFunctionResult() { return (false); }
bool SyntaxNode::_isThrowsClause() { return (false); }
bool SyntaxNode::_isEnumMember() { return (false); }
bool SyntaxNode::_isEnumCase() { return (false); }
bool SyntaxNode::_isAdditionalCase() { return (false); }
bool SyntaxNode::_isTypeInheritanceClause() { return (false); }
bool SyntaxNode::_isInheritance() { return (false); }
bool SyntaxNode::_isClassBody() { return (false); }
bool SyntaxNode::_isClassMember() { return (false); }
bool SyntaxNode::_isPrefixExpression() { return (false); }
bool SyntaxNode::_isPostfixExpression() { return (false); }
bool SyntaxNode::_isPrimaryExpression() { return (false); }
bool SyntaxNode::_isIdentifierExpression() { return (false); }
bool SyntaxNode::_isLiteralExpression() { return (false); }
bool SyntaxNode::_isIfExpression() { return (false); }
bool SyntaxNode::_isSwitchExpression() { return (false); }
bool SyntaxNode::_isForExpression() { return (false); }
bool SyntaxNode::_isWhileExpression() { return (false); }
bool SyntaxNode::_isDoExpression() { return (false); }
bool SyntaxNode::_isParenthesizedExpression() { return (false); }
bool SyntaxNode::_isReturnExpression() { return (false); }
bool SyntaxNode::_isThrowExpression() { return (false); }
bool SyntaxNode::_isBreakExpression() { return (false); }
bool SyntaxNode::_isConstructorCall() { return (false); }
bool SyntaxNode::_isThisExpression() { return (false); }
bool SyntaxNode::_isNullExpression() { return (false); }
bool SyntaxNode::_isElseClause() { return (false); }
bool SyntaxNode::_isSwitchBody() { return (false); }
bool SyntaxNode::_isCurliedSwitchBody() { return (false); }
bool SyntaxNode::_isNakedSwitchBody() { return (false); }
bool SyntaxNode::_isSwitchCase() { return (false); }
bool SyntaxNode::_isCaseLabel() { return (false); }
bool SyntaxNode::_isItemCaseLabel() { return (false); }
bool SyntaxNode::_isDefaultCaseLabel() { return (false); }
bool SyntaxNode::_isCaseItem() { return (false); }
bool SyntaxNode::_isCaseContent() { return (false); }
bool SyntaxNode::_isExpressionElement() { return (false); }
bool SyntaxNode::_isPostfix() { return (false); }
bool SyntaxNode::_isOperatorPostfix() { return (false); }
bool SyntaxNode::_isFunctionCall() { return (false); }
bool SyntaxNode::_isMemberExpression() { return (false); }
bool SyntaxNode::_isSubscript() { return (false); }
bool SyntaxNode::_isCatchClause() { return (false); }
bool SyntaxNode::_isCatchPattern() { return (false); }
bool SyntaxNode::_isWildCardCatchPattern() { return (false); }
bool SyntaxNode::_isIdentifierCatchPattern() { return (false); }
bool SyntaxNode::_isTuplePatternElement() { return (false); }
bool SyntaxNode::_isBinaryExpression() { return (false); }
bool SyntaxNode::_isBinaryOperation() { return (false); }
bool SyntaxNode::_isAssignment() { return (false); }
bool SyntaxNode::_isTypeQuery() { return (false); }
bool SyntaxNode::_isTypeCast() { return (false); }
Program::Program(string* name, _Array<Module>* modules) {
start = new(_getPage()) Position(0, 0);
end = new(_getPage()) Position(0, 0);
this->name = name;
this->modules = modules;
this->parent = nullptr;
}
void Program::accept(Visitor* visitor) {
if (!visitor->openProgram(this))
return;
if (modules != nullptr) {
Module* node = nullptr;
size_t _modules_length = modules->length();
for (size_t _i = 0; _i < _modules_length; _i++) {
node = *(*modules)[_i];
node->accept(visitor);
}
}
visitor->closeProgram(this);
}
bool Program::_isProgram() { return (true); }
Module::Module(_Array<Statement>* statements, Position* start, Position* end) {
this->start = start;
this->end = end;
this->statements = statements;
}
void Module::accept(Visitor* visitor) {
if (!visitor->openModule(this))
return;
if (statements != nullptr) {
Statement* node = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
node = *(*statements)[_i];
node->accept(visitor);
}
}
visitor->closeModule(this);
}
bool Module::_isModule() { return (true); }
void Statement::accept(Visitor* visitor) {
}
bool Statement::_isStatement() { return (true); }
bool Statement::_isDeclaration() { return (false); }
bool Statement::_isConstantDeclaration() { return (false); }
bool Statement::_isMutableDeclaration() { return (false); }
bool Statement::_isFunctionDeclaration() { return (false); }
bool Statement::_isEnumDeclaration() { return (false); }
bool Statement::_isClassDeclaration() { return (false); }
bool Statement::_isConstructorDeclaration() { return (false); }
bool Statement::_isExpression() { return (false); }
bool Statement::_isCodeBlock() { return (false); }
bool Statement::_isSimpleExpression() { return (false); }
void Declaration::accept(Visitor* visitor) {
}
bool Declaration::_isDeclaration() { return (true); }
bool Declaration::_isConstantDeclaration() { return (false); }
bool Declaration::_isMutableDeclaration() { return (false); }
bool Declaration::_isFunctionDeclaration() { return (false); }
bool Declaration::_isEnumDeclaration() { return (false); }
bool Declaration::_isClassDeclaration() { return (false); }
bool Declaration::_isConstructorDeclaration() { return (false); }
ConstantDeclaration::ConstantDeclaration(BindingInitializer* initializer, Position* start, Position* end) {
this->start = start;
this->end = end;
this->initializer = initializer;
}
void ConstantDeclaration::accept(Visitor* visitor) {
if (!visitor->openConstantDeclaration(this))
return;
initializer->accept(visitor);
visitor->closeConstantDeclaration(this);
}
bool ConstantDeclaration::_isConstantDeclaration() { return (true); }
MutableDeclaration::MutableDeclaration(BindingInitializer* initializer, Position* start, Position* end) {
this->start = start;
this->end = end;
this->initializer = initializer;
}
void MutableDeclaration::accept(Visitor* visitor) {
if (!visitor->openMutableDeclaration(this))
return;
initializer->accept(visitor);
visitor->closeMutableDeclaration(this);
}
bool MutableDeclaration::_isMutableDeclaration() { return (true); }
BindingInitializer::BindingInitializer(IdentifierInitializer* initializer, _Array<AdditionalInitializer>* additionalInitializers, Position* start, Position* end) {
this->start = start;
this->end = end;
this->initializer = initializer;
this->additionalInitializers = additionalInitializers;
}
void BindingInitializer::accept(Visitor* visitor) {
if (!visitor->openBindingInitializer(this))
return;
initializer->accept(visitor);
if (additionalInitializers != nullptr) {
AdditionalInitializer* node = nullptr;
size_t _additionalInitializers_length = additionalInitializers->length();
for (size_t _i = 0; _i < _additionalInitializers_length; _i++) {
node = *(*additionalInitializers)[_i];
node->accept(visitor);
}
}
visitor->closeBindingInitializer(this);
}
bool BindingInitializer::_isBindingInitializer() { return (true); }
IdentifierInitializer::IdentifierInitializer(IdentifierPattern* pattern, Initializer* initializer, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
this->initializer = initializer;
}
void IdentifierInitializer::accept(Visitor* visitor) {
if (!visitor->openIdentifierInitializer(this))
return;
pattern->accept(visitor);
if (initializer != nullptr)
initializer->accept(visitor);
visitor->closeIdentifierInitializer(this);
}
bool IdentifierInitializer::_isIdentifierInitializer() { return (true); }
Initializer::Initializer(Expression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void Initializer::accept(Visitor* visitor) {
if (!visitor->openInitializer(this))
return;
expression->accept(visitor);
visitor->closeInitializer(this);
}
bool Initializer::_isInitializer() { return (true); }
AdditionalInitializer::AdditionalInitializer(IdentifierInitializer* pattern, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
}
void AdditionalInitializer::accept(Visitor* visitor) {
if (!visitor->openAdditionalInitializer(this))
return;
pattern->accept(visitor);
visitor->closeAdditionalInitializer(this);
}
bool AdditionalInitializer::_isAdditionalInitializer() { return (true); }
void Pattern::accept(Visitor* visitor) {
}
bool Pattern::_isPattern() { return (true); }
bool Pattern::_isIdentifierPattern() { return (false); }
bool Pattern::_isWildcardPattern() { return (false); }
bool Pattern::_isTuplePattern() { return (false); }
bool Pattern::_isExpressionPattern() { return (false); }
IdentifierPattern::IdentifierPattern(string* identifier, TypeAnnotation* annotationForType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->identifier = identifier;
this->annotationForType = annotationForType;
}
void IdentifierPattern::accept(Visitor* visitor) {
if (!visitor->openIdentifierPattern(this))
return;
if (annotationForType != nullptr)
annotationForType->accept(visitor);
visitor->closeIdentifierPattern(this);
}
bool IdentifierPattern::_isIdentifierPattern() { return (true); }
TypeAnnotation::TypeAnnotation(Type* annotationForType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->annotationForType = annotationForType;
}
void TypeAnnotation::accept(Visitor* visitor) {
if (!visitor->openTypeAnnotation(this))
return;
annotationForType->accept(visitor);
visitor->closeTypeAnnotation(this);
}
bool TypeAnnotation::_isTypeAnnotation() { return (true); }
Type::Type(string* name, _Array<TypePostfix>* postfixes, LifeTime* lifeTime, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->postfixes = postfixes;
this->lifeTime = lifeTime;
}
void Type::accept(Visitor* visitor) {
if (!visitor->openType(this))
return;
if (postfixes != nullptr) {
TypePostfix* node = nullptr;
size_t _postfixes_length = postfixes->length();
for (size_t _i = 0; _i < _postfixes_length; _i++) {
node = *(*postfixes)[_i];
node->accept(visitor);
}
}
if (lifeTime != nullptr)
lifeTime->accept(visitor);
visitor->closeType(this);
}
bool Type::_isType() { return (true); }
void TypePostfix::accept(Visitor* visitor) {
}
bool TypePostfix::_isTypePostfix() { return (true); }
bool TypePostfix::_isIndexedType() { return (false); }
bool TypePostfix::_isPointer() { return (false); }
IndexedType::IndexedType(Type* key, Position* start, Position* end) {
this->start = start;
this->end = end;
this->key = key;
}
void IndexedType::accept(Visitor* visitor) {
if (!visitor->openIndexedType(this))
return;
if (key != nullptr)
key->accept(visitor);
visitor->closeIndexedType(this);
}
bool IndexedType::_isIndexedType() { return (true); }
Pointer::Pointer(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void Pointer::accept(Visitor* visitor) {
visitor->visitPointer(this);
}
bool Pointer::_isPointer() { return (true); }
void LifeTime::accept(Visitor* visitor) {
}
bool LifeTime::_isLifeTime() { return (true); }
bool LifeTime::_isRoot() { return (false); }
bool LifeTime::_isLocal() { return (false); }
bool LifeTime::_isReference() { return (false); }
bool LifeTime::_isThrown() { return (false); }
Root::Root(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void Root::accept(Visitor* visitor) {
visitor->visitRoot(this);
}
bool Root::_isRoot() { return (true); }
Local::Local(string* location, Position* start, Position* end) {
this->start = start;
this->end = end;
this->location = location;
}
void Local::accept(Visitor* visitor) {
visitor->visitLocal(this);
}
bool Local::_isLocal() { return (true); }
Reference::Reference(Literal* age, Position* start, Position* end) {
this->start = start;
this->end = end;
this->age = age;
}
void Reference::accept(Visitor* visitor) {
visitor->visitReference(this);
}
bool Reference::_isReference() { return (true); }
Thrown::Thrown(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void Thrown::accept(Visitor* visitor) {
visitor->visitThrown(this);
}
bool Thrown::_isThrown() { return (true); }
FunctionDeclaration::FunctionDeclaration(_Array<Modifier>* modifiers, string* name, FunctionSignature* signature, Expression* body, Position* start, Position* end) {
this->start = start;
this->end = end;
this->modifiers = modifiers;
this->name = name;
this->signature = signature;
this->body = body;
}
void FunctionDeclaration::accept(Visitor* visitor) {
if (!visitor->openFunctionDeclaration(this))
return;
if (modifiers != nullptr) {
Modifier* node = nullptr;
size_t _modifiers_length = modifiers->length();
for (size_t _i = 0; _i < _modifiers_length; _i++) {
node = *(*modifiers)[_i];
node->accept(visitor);
}
}
signature->accept(visitor);
if (body != nullptr)
body->accept(visitor);
visitor->closeFunctionDeclaration(this);
}
bool FunctionDeclaration::_isFunctionDeclaration() { return (true); }
void Modifier::accept(Visitor* visitor) {
}
bool Modifier::_isModifier() { return (true); }
bool Modifier::_isStaticWord() { return (false); }
StaticWord::StaticWord(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void StaticWord::accept(Visitor* visitor) {
visitor->visitStaticWord(this);
}
bool StaticWord::_isStaticWord() { return (true); }
FunctionSignature::FunctionSignature(ParameterClause* parameterClause, FunctionResult* result, ThrowsClause* throwsClause, Position* start, Position* end) {
this->start = start;
this->end = end;
this->parameterClause = parameterClause;
this->result = result;
this->throwsClause = throwsClause;
}
void FunctionSignature::accept(Visitor* visitor) {
if (!visitor->openFunctionSignature(this))
return;
parameterClause->accept(visitor);
if (result != nullptr)
result->accept(visitor);
if (throwsClause != nullptr)
throwsClause->accept(visitor);
visitor->closeFunctionSignature(this);
}
bool FunctionSignature::_isFunctionSignature() { return (true); }
ParameterClause::ParameterClause(_Array<Parameter>* parameters, Position* start, Position* end) {
this->start = start;
this->end = end;
this->parameters = parameters;
}
void ParameterClause::accept(Visitor* visitor) {
if (!visitor->openParameterClause(this))
return;
if (parameters != nullptr) {
Parameter* node = nullptr;
size_t _parameters_length = parameters->length();
for (size_t _i = 0; _i < _parameters_length; _i++) {
node = *(*parameters)[_i];
node->accept(visitor);
}
}
visitor->closeParameterClause(this);
}
bool ParameterClause::_isParameterClause() { return (true); }
void Parameter::accept(Visitor* visitor) {
}
bool Parameter::_isParameter() { return (true); }
bool Parameter::_isConstParameter() { return (false); }
bool Parameter::_isVarParameter() { return (false); }
ConstParameter::ConstParameter(string* name, Type* parameterType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->parameterType = parameterType;
}
void ConstParameter::accept(Visitor* visitor) {
if (!visitor->openConstParameter(this))
return;
parameterType->accept(visitor);
visitor->closeConstParameter(this);
}
bool ConstParameter::_isConstParameter() { return (true); }
VarParameter::VarParameter(string* name, Type* parameterType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->parameterType = parameterType;
}
void VarParameter::accept(Visitor* visitor) {
if (!visitor->openVarParameter(this))
return;
parameterType->accept(visitor);
visitor->closeVarParameter(this);
}
bool VarParameter::_isVarParameter() { return (true); }
FunctionResult::FunctionResult(Type* resultType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->resultType = resultType;
}
void FunctionResult::accept(Visitor* visitor) {
if (!visitor->openFunctionResult(this))
return;
resultType->accept(visitor);
visitor->closeFunctionResult(this);
}
bool FunctionResult::_isFunctionResult() { return (true); }
ThrowsClause::ThrowsClause(Type* throwsType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->throwsType = throwsType;
}
void ThrowsClause::accept(Visitor* visitor) {
if (!visitor->openThrowsClause(this))
return;
throwsType->accept(visitor);
visitor->closeThrowsClause(this);
}
bool ThrowsClause::_isThrowsClause() { return (true); }
EnumDeclaration::EnumDeclaration(string* name, _Array<EnumMember>* members, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->members = members;
}
void EnumDeclaration::accept(Visitor* visitor) {
if (!visitor->openEnumDeclaration(this))
return;
if (members != nullptr) {
EnumMember* node = nullptr;
size_t _members_length = members->length();
for (size_t _i = 0; _i < _members_length; _i++) {
node = *(*members)[_i];
node->accept(visitor);
}
}
visitor->closeEnumDeclaration(this);
}
bool EnumDeclaration::_isEnumDeclaration() { return (true); }
EnumMember::EnumMember(EnumCase* enumCase, _Array<AdditionalCase>* additionalCases, ParameterClause* parameterClause, Position* start, Position* end) {
this->start = start;
this->end = end;
this->enumCase = enumCase;
this->additionalCases = additionalCases;
this->parameterClause = parameterClause;
}
void EnumMember::accept(Visitor* visitor) {
if (!visitor->openEnumMember(this))
return;
enumCase->accept(visitor);
if (additionalCases != nullptr) {
AdditionalCase* node = nullptr;
size_t _additionalCases_length = additionalCases->length();
for (size_t _i = 0; _i < _additionalCases_length; _i++) {
node = *(*additionalCases)[_i];
node->accept(visitor);
}
}
if (parameterClause != nullptr)
parameterClause->accept(visitor);
visitor->closeEnumMember(this);
}
bool EnumMember::_isEnumMember() { return (true); }
EnumCase::EnumCase(string* name, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
}
void EnumCase::accept(Visitor* visitor) {
visitor->visitEnumCase(this);
}
bool EnumCase::_isEnumCase() { return (true); }
AdditionalCase::AdditionalCase(EnumCase* enumCase, Position* start, Position* end) {
this->start = start;
this->end = end;
this->enumCase = enumCase;
}
void AdditionalCase::accept(Visitor* visitor) {
if (!visitor->openAdditionalCase(this))
return;
enumCase->accept(visitor);
visitor->closeAdditionalCase(this);
}
bool AdditionalCase::_isAdditionalCase() { return (true); }
ClassDeclaration::ClassDeclaration(string* name, TypeInheritanceClause* typeInheritanceClause, ClassBody* body, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->typeInheritanceClause = typeInheritanceClause;
this->body = body;
}
void ClassDeclaration::accept(Visitor* visitor) {
if (!visitor->openClassDeclaration(this))
return;
if (typeInheritanceClause != nullptr)
typeInheritanceClause->accept(visitor);
if (body != nullptr)
body->accept(visitor);
visitor->closeClassDeclaration(this);
}
bool ClassDeclaration::_isClassDeclaration() { return (true); }
TypeInheritanceClause::TypeInheritanceClause(_Array<Inheritance>* inheritances, Position* start, Position* end) {
this->start = start;
this->end = end;
this->inheritances = inheritances;
}
void TypeInheritanceClause::accept(Visitor* visitor) {
if (!visitor->openTypeInheritanceClause(this))
return;
if (inheritances != nullptr) {
Inheritance* node = nullptr;
size_t _inheritances_length = inheritances->length();
for (size_t _i = 0; _i < _inheritances_length; _i++) {
node = *(*inheritances)[_i];
node->accept(visitor);
}
}
visitor->closeTypeInheritanceClause(this);
}
bool TypeInheritanceClause::_isTypeInheritanceClause() { return (true); }
Inheritance::Inheritance(Type* type, Position* start, Position* end) {
this->start = start;
this->end = end;
this->type = type;
}
void Inheritance::accept(Visitor* visitor) {
if (!visitor->openInheritance(this))
return;
type->accept(visitor);
visitor->closeInheritance(this);
}
bool Inheritance::_isInheritance() { return (true); }
ClassBody::ClassBody(_Array<ClassMember>* members, Position* start, Position* end) {
this->start = start;
this->end = end;
this->members = members;
}
void ClassBody::accept(Visitor* visitor) {
if (!visitor->openClassBody(this))
return;
if (members != nullptr) {
ClassMember* node = nullptr;
size_t _members_length = members->length();
for (size_t _i = 0; _i < _members_length; _i++) {
node = *(*members)[_i];
node->accept(visitor);
}
}
visitor->closeClassBody(this);
}
bool ClassBody::_isClassBody() { return (true); }
ClassMember::ClassMember(Declaration* declaration, Position* start, Position* end) {
this->start = start;
this->end = end;
this->declaration = declaration;
}
void ClassMember::accept(Visitor* visitor) {
if (!visitor->openClassMember(this))
return;
declaration->accept(visitor);
visitor->closeClassMember(this);
}
bool ClassMember::_isClassMember() { return (true); }
ConstructorDeclaration::ConstructorDeclaration(ParameterClause* parameterClause, Expression* body, Position* start, Position* end) {
this->start = start;
this->end = end;
this->parameterClause = parameterClause;
this->body = body;
}
void ConstructorDeclaration::accept(Visitor* visitor) {
if (!visitor->openConstructorDeclaration(this))
return;
parameterClause->accept(visitor);
body->accept(visitor);
visitor->closeConstructorDeclaration(this);
}
bool ConstructorDeclaration::_isConstructorDeclaration() { return (true); }
void Expression::accept(Visitor* visitor) {
}
bool Expression::_isExpression() { return (true); }
bool Expression::_isCodeBlock() { return (false); }
bool Expression::_isSimpleExpression() { return (false); }
CodeBlock::CodeBlock(_Array<Statement>* statements, Position* start, Position* end) {
this->start = start;
this->end = end;
this->statements = statements;
}
void CodeBlock::accept(Visitor* visitor) {
if (!visitor->openCodeBlock(this))
return;
if (statements != nullptr) {
Statement* node = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
node = *(*statements)[_i];
node->accept(visitor);
}
}
visitor->closeCodeBlock(this);
}
bool CodeBlock::_isCodeBlock() { return (true); }
SimpleExpression::SimpleExpression(PrefixExpression* prefixExpression, _Array<BinaryExpression>* binaryExpressions, Position* start, Position* end) {
this->start = start;
this->end = end;
this->prefixExpression = prefixExpression;
this->binaryExpressions = binaryExpressions;
}
void SimpleExpression::accept(Visitor* visitor) {
if (!visitor->openSimpleExpression(this))
return;
prefixExpression->accept(visitor);
if (binaryExpressions != nullptr) {
BinaryExpression* node = nullptr;
size_t _binaryExpressions_length = binaryExpressions->length();
for (size_t _i = 0; _i < _binaryExpressions_length; _i++) {
node = *(*binaryExpressions)[_i];
node->accept(visitor);
}
}
visitor->closeSimpleExpression(this);
}
bool SimpleExpression::_isSimpleExpression() { return (true); }
PrefixExpression::PrefixExpression(string* prefixOperator, PostfixExpression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->prefixOperator = prefixOperator;
this->expression = expression;
}
void PrefixExpression::accept(Visitor* visitor) {
if (!visitor->openPrefixExpression(this))
return;
expression->accept(visitor);
visitor->closePrefixExpression(this);
}
bool PrefixExpression::_isPrefixExpression() { return (true); }
PostfixExpression::PostfixExpression(PrimaryExpression* primaryExpression, _Array<Postfix>* postfixes, Position* start, Position* end) {
this->start = start;
this->end = end;
this->primaryExpression = primaryExpression;
this->postfixes = postfixes;
}
void PostfixExpression::accept(Visitor* visitor) {
if (!visitor->openPostfixExpression(this))
return;
primaryExpression->accept(visitor);
if (postfixes != nullptr) {
Postfix* node = nullptr;
size_t _postfixes_length = postfixes->length();
for (size_t _i = 0; _i < _postfixes_length; _i++) {
node = *(*postfixes)[_i];
node->accept(visitor);
}
}
visitor->closePostfixExpression(this);
}
bool PostfixExpression::_isPostfixExpression() { return (true); }
void PrimaryExpression::accept(Visitor* visitor) {
}
bool PrimaryExpression::_isPrimaryExpression() { return (true); }
bool PrimaryExpression::_isIdentifierExpression() { return (false); }
bool PrimaryExpression::_isLiteralExpression() { return (false); }
bool PrimaryExpression::_isIfExpression() { return (false); }
bool PrimaryExpression::_isSwitchExpression() { return (false); }
bool PrimaryExpression::_isForExpression() { return (false); }
bool PrimaryExpression::_isWhileExpression() { return (false); }
bool PrimaryExpression::_isDoExpression() { return (false); }
bool PrimaryExpression::_isParenthesizedExpression() { return (false); }
bool PrimaryExpression::_isReturnExpression() { return (false); }
bool PrimaryExpression::_isThrowExpression() { return (false); }
bool PrimaryExpression::_isBreakExpression() { return (false); }
bool PrimaryExpression::_isConstructorCall() { return (false); }
bool PrimaryExpression::_isThisExpression() { return (false); }
bool PrimaryExpression::_isNullExpression() { return (false); }
IdentifierExpression::IdentifierExpression(string* name, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
}
void IdentifierExpression::accept(Visitor* visitor) {
visitor->visitIdentifierExpression(this);
}
bool IdentifierExpression::_isIdentifierExpression() { return (true); }
LiteralExpression::LiteralExpression(Literal* literal, Position* start, Position* end) {
this->start = start;
this->end = end;
this->literal = literal;
}
void LiteralExpression::accept(Visitor* visitor) {
visitor->visitLiteralExpression(this);
}
bool LiteralExpression::_isLiteralExpression() { return (true); }
IfExpression::IfExpression(Expression* condition, Expression* consequent, ElseClause* elseClause, Position* start, Position* end) {
this->start = start;
this->end = end;
this->condition = condition;
this->consequent = consequent;
this->elseClause = elseClause;
}
void IfExpression::accept(Visitor* visitor) {
if (!visitor->openIfExpression(this))
return;
condition->accept(visitor);
consequent->accept(visitor);
if (elseClause != nullptr)
elseClause->accept(visitor);
visitor->closeIfExpression(this);
}
bool IfExpression::_isIfExpression() { return (true); }
ElseClause::ElseClause(Expression* alternative, Position* start, Position* end) {
this->start = start;
this->end = end;
this->alternative = alternative;
}
void ElseClause::accept(Visitor* visitor) {
if (!visitor->openElseClause(this))
return;
alternative->accept(visitor);
visitor->closeElseClause(this);
}
bool ElseClause::_isElseClause() { return (true); }
SwitchExpression::SwitchExpression(Expression* expression, SwitchBody* body, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
this->body = body;
}
void SwitchExpression::accept(Visitor* visitor) {
if (!visitor->openSwitchExpression(this))
return;
expression->accept(visitor);
body->accept(visitor);
visitor->closeSwitchExpression(this);
}
bool SwitchExpression::_isSwitchExpression() { return (true); }
void SwitchBody::accept(Visitor* visitor) {
}
bool SwitchBody::_isSwitchBody() { return (true); }
bool SwitchBody::_isCurliedSwitchBody() { return (false); }
bool SwitchBody::_isNakedSwitchBody() { return (false); }
CurliedSwitchBody::CurliedSwitchBody(_Array<SwitchCase>* cases, Position* start, Position* end) {
this->start = start;
this->end = end;
this->cases = cases;
}
void CurliedSwitchBody::accept(Visitor* visitor) {
if (!visitor->openCurliedSwitchBody(this))
return;
if (cases != nullptr) {
SwitchCase* node = nullptr;
size_t _cases_length = cases->length();
for (size_t _i = 0; _i < _cases_length; _i++) {
node = *(*cases)[_i];
node->accept(visitor);
}
}
visitor->closeCurliedSwitchBody(this);
}
bool CurliedSwitchBody::_isCurliedSwitchBody() { return (true); }
NakedSwitchBody::NakedSwitchBody(_Array<SwitchCase>* cases, Position* start, Position* end) {
this->start = start;
this->end = end;
this->cases = cases;
}
void NakedSwitchBody::accept(Visitor* visitor) {
if (!visitor->openNakedSwitchBody(this))
return;
if (cases != nullptr) {
SwitchCase* node = nullptr;
size_t _cases_length = cases->length();
for (size_t _i = 0; _i < _cases_length; _i++) {
node = *(*cases)[_i];
node->accept(visitor);
}
}
visitor->closeNakedSwitchBody(this);
}
bool NakedSwitchBody::_isNakedSwitchBody() { return (true); }
SwitchCase::SwitchCase(CaseLabel* label, CaseContent* content, Position* start, Position* end) {
this->start = start;
this->end = end;
this->label = label;
this->content = content;
}
void SwitchCase::accept(Visitor* visitor) {
if (!visitor->openSwitchCase(this))
return;
label->accept(visitor);
content->accept(visitor);
visitor->closeSwitchCase(this);
}
bool SwitchCase::_isSwitchCase() { return (true); }
void CaseLabel::accept(Visitor* visitor) {
}
bool CaseLabel::_isCaseLabel() { return (true); }
bool CaseLabel::_isItemCaseLabel() { return (false); }
bool CaseLabel::_isDefaultCaseLabel() { return (false); }
ItemCaseLabel::ItemCaseLabel(Pattern* pattern, _Array<CaseItem>* additionalPatterns, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
this->additionalPatterns = additionalPatterns;
}
void ItemCaseLabel::accept(Visitor* visitor) {
if (!visitor->openItemCaseLabel(this))
return;
pattern->accept(visitor);
if (additionalPatterns != nullptr) {
CaseItem* node = nullptr;
size_t _additionalPatterns_length = additionalPatterns->length();
for (size_t _i = 0; _i < _additionalPatterns_length; _i++) {
node = *(*additionalPatterns)[_i];
node->accept(visitor);
}
}
visitor->closeItemCaseLabel(this);
}
bool ItemCaseLabel::_isItemCaseLabel() { return (true); }
DefaultCaseLabel::DefaultCaseLabel(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void DefaultCaseLabel::accept(Visitor* visitor) {
visitor->visitDefaultCaseLabel(this);
}
bool DefaultCaseLabel::_isDefaultCaseLabel() { return (true); }
CaseItem::CaseItem(Pattern* pattern, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
}
void CaseItem::accept(Visitor* visitor) {
if (!visitor->openCaseItem(this))
return;
pattern->accept(visitor);
visitor->closeCaseItem(this);
}
bool CaseItem::_isCaseItem() { return (true); }
CaseContent::CaseContent(_Array<Statement>* statements, Position* start, Position* end) {
this->start = start;
this->end = end;
this->statements = statements;
}
void CaseContent::accept(Visitor* visitor) {
if (!visitor->openCaseContent(this))
return;
if (statements != nullptr) {
Statement* node = nullptr;
size_t _statements_length = statements->length();
for (size_t _i = 0; _i < _statements_length; _i++) {
node = *(*statements)[_i];
node->accept(visitor);
}
}
visitor->closeCaseContent(this);
}
bool CaseContent::_isCaseContent() { return (true); }
ForExpression::ForExpression(IdentifierPattern* pattern, Expression* expression, Expression* code, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
this->expression = expression;
this->code = code;
}
void ForExpression::accept(Visitor* visitor) {
if (!visitor->openForExpression(this))
return;
pattern->accept(visitor);
expression->accept(visitor);
code->accept(visitor);
visitor->closeForExpression(this);
}
bool ForExpression::_isForExpression() { return (true); }
WhileExpression::WhileExpression(Expression* condition, Expression* code, Position* start, Position* end) {
this->start = start;
this->end = end;
this->condition = condition;
this->code = code;
}
void WhileExpression::accept(Visitor* visitor) {
if (!visitor->openWhileExpression(this))
return;
condition->accept(visitor);
code->accept(visitor);
visitor->closeWhileExpression(this);
}
bool WhileExpression::_isWhileExpression() { return (true); }
DoExpression::DoExpression(Expression* code, Expression* condition, Position* start, Position* end) {
this->start = start;
this->end = end;
this->code = code;
this->condition = condition;
}
void DoExpression::accept(Visitor* visitor) {
if (!visitor->openDoExpression(this))
return;
code->accept(visitor);
condition->accept(visitor);
visitor->closeDoExpression(this);
}
bool DoExpression::_isDoExpression() { return (true); }
ParenthesizedExpression::ParenthesizedExpression(_Array<ExpressionElement>* expressionElements, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expressionElements = expressionElements;
}
void ParenthesizedExpression::accept(Visitor* visitor) {
if (!visitor->openParenthesizedExpression(this))
return;
if (expressionElements != nullptr) {
ExpressionElement* node = nullptr;
size_t _expressionElements_length = expressionElements->length();
for (size_t _i = 0; _i < _expressionElements_length; _i++) {
node = *(*expressionElements)[_i];
node->accept(visitor);
}
}
visitor->closeParenthesizedExpression(this);
}
bool ParenthesizedExpression::_isParenthesizedExpression() { return (true); }
ExpressionElement::ExpressionElement(Expression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void ExpressionElement::accept(Visitor* visitor) {
if (!visitor->openExpressionElement(this))
return;
expression->accept(visitor);
visitor->closeExpressionElement(this);
}
bool ExpressionElement::_isExpressionElement() { return (true); }
ReturnExpression::ReturnExpression(ParenthesizedExpression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void ReturnExpression::accept(Visitor* visitor) {
if (!visitor->openReturnExpression(this))
return;
if (expression != nullptr)
expression->accept(visitor);
visitor->closeReturnExpression(this);
}
bool ReturnExpression::_isReturnExpression() { return (true); }
ThrowExpression::ThrowExpression(IdentifierExpression* error, ParenthesizedExpression* arguments, Position* start, Position* end) {
this->start = start;
this->end = end;
this->error = error;
this->arguments = arguments;
}
void ThrowExpression::accept(Visitor* visitor) {
if (!visitor->openThrowExpression(this))
return;
error->accept(visitor);
if (arguments != nullptr)
arguments->accept(visitor);
visitor->closeThrowExpression(this);
}
bool ThrowExpression::_isThrowExpression() { return (true); }
BreakExpression::BreakExpression(ParenthesizedExpression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void BreakExpression::accept(Visitor* visitor) {
if (!visitor->openBreakExpression(this))
return;
if (expression != nullptr)
expression->accept(visitor);
visitor->closeBreakExpression(this);
}
bool BreakExpression::_isBreakExpression() { return (true); }
ConstructorCall::ConstructorCall(Type* typeToConstruct, ParenthesizedExpression* arguments, _Array<CatchClause>* catchClauses, Position* start, Position* end) {
this->start = start;
this->end = end;
this->typeToConstruct = typeToConstruct;
this->arguments = arguments;
this->catchClauses = catchClauses;
}
void ConstructorCall::accept(Visitor* visitor) {
if (!visitor->openConstructorCall(this))
return;
typeToConstruct->accept(visitor);
arguments->accept(visitor);
if (catchClauses != nullptr) {
CatchClause* node = nullptr;
size_t _catchClauses_length = catchClauses->length();
for (size_t _i = 0; _i < _catchClauses_length; _i++) {
node = *(*catchClauses)[_i];
node->accept(visitor);
}
}
visitor->closeConstructorCall(this);
}
bool ConstructorCall::_isConstructorCall() { return (true); }
ThisExpression::ThisExpression(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void ThisExpression::accept(Visitor* visitor) {
visitor->visitThisExpression(this);
}
bool ThisExpression::_isThisExpression() { return (true); }
NullExpression::NullExpression(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void NullExpression::accept(Visitor* visitor) {
visitor->visitNullExpression(this);
}
bool NullExpression::_isNullExpression() { return (true); }
void Postfix::accept(Visitor* visitor) {
}
bool Postfix::_isPostfix() { return (true); }
bool Postfix::_isOperatorPostfix() { return (false); }
bool Postfix::_isFunctionCall() { return (false); }
bool Postfix::_isMemberExpression() { return (false); }
bool Postfix::_isSubscript() { return (false); }
OperatorPostfix::OperatorPostfix(string* postfixOperator, Position* start, Position* end) {
this->start = start;
this->end = end;
this->postfixOperator = postfixOperator;
}
void OperatorPostfix::accept(Visitor* visitor) {
visitor->visitOperatorPostfix(this);
}
bool OperatorPostfix::_isOperatorPostfix() { return (true); }
FunctionCall::FunctionCall(ParenthesizedExpression* arguments, _Array<CatchClause>* catchClauses, Position* start, Position* end) {
this->start = start;
this->end = end;
this->arguments = arguments;
this->catchClauses = catchClauses;
}
void FunctionCall::accept(Visitor* visitor) {
if (!visitor->openFunctionCall(this))
return;
arguments->accept(visitor);
if (catchClauses != nullptr) {
CatchClause* node = nullptr;
size_t _catchClauses_length = catchClauses->length();
for (size_t _i = 0; _i < _catchClauses_length; _i++) {
node = *(*catchClauses)[_i];
node->accept(visitor);
}
}
visitor->closeFunctionCall(this);
}
bool FunctionCall::_isFunctionCall() { return (true); }
CatchClause::CatchClause(CatchPattern* catchPattern, TuplePattern* bindingPattern, Expression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->catchPattern = catchPattern;
this->bindingPattern = bindingPattern;
this->expression = expression;
}
void CatchClause::accept(Visitor* visitor) {
if (!visitor->openCatchClause(this))
return;
catchPattern->accept(visitor);
if (bindingPattern != nullptr)
bindingPattern->accept(visitor);
expression->accept(visitor);
visitor->closeCatchClause(this);
}
bool CatchClause::_isCatchClause() { return (true); }
void CatchPattern::accept(Visitor* visitor) {
}
bool CatchPattern::_isCatchPattern() { return (true); }
bool CatchPattern::_isWildCardCatchPattern() { return (false); }
bool CatchPattern::_isIdentifierCatchPattern() { return (false); }
WildCardCatchPattern::WildCardCatchPattern(WildcardPattern* pattern, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
}
void WildCardCatchPattern::accept(Visitor* visitor) {
if (!visitor->openWildCardCatchPattern(this))
return;
pattern->accept(visitor);
visitor->closeWildCardCatchPattern(this);
}
bool WildCardCatchPattern::_isWildCardCatchPattern() { return (true); }
IdentifierCatchPattern::IdentifierCatchPattern(string* name, MemberExpression* member, Position* start, Position* end) {
this->start = start;
this->end = end;
this->name = name;
this->member = member;
}
void IdentifierCatchPattern::accept(Visitor* visitor) {
if (!visitor->openIdentifierCatchPattern(this))
return;
if (member != nullptr)
member->accept(visitor);
visitor->closeIdentifierCatchPattern(this);
}
bool IdentifierCatchPattern::_isIdentifierCatchPattern() { return (true); }
WildcardPattern::WildcardPattern(Position* start, Position* end) {
this->start = start;
this->end = end;
}
void WildcardPattern::accept(Visitor* visitor) {
visitor->visitWildcardPattern(this);
}
bool WildcardPattern::_isWildcardPattern() { return (true); }
TuplePattern::TuplePattern(_Array<TuplePatternElement>* elements, Position* start, Position* end) {
this->start = start;
this->end = end;
this->elements = elements;
}
void TuplePattern::accept(Visitor* visitor) {
if (!visitor->openTuplePattern(this))
return;
if (elements != nullptr) {
TuplePatternElement* node = nullptr;
size_t _elements_length = elements->length();
for (size_t _i = 0; _i < _elements_length; _i++) {
node = *(*elements)[_i];
node->accept(visitor);
}
}
visitor->closeTuplePattern(this);
}
bool TuplePattern::_isTuplePattern() { return (true); }
TuplePatternElement::TuplePatternElement(Pattern* pattern, Position* start, Position* end) {
this->start = start;
this->end = end;
this->pattern = pattern;
}
void TuplePatternElement::accept(Visitor* visitor) {
if (!visitor->openTuplePatternElement(this))
return;
pattern->accept(visitor);
visitor->closeTuplePatternElement(this);
}
bool TuplePatternElement::_isTuplePatternElement() { return (true); }
ExpressionPattern::ExpressionPattern(Expression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void ExpressionPattern::accept(Visitor* visitor) {
if (!visitor->openExpressionPattern(this))
return;
expression->accept(visitor);
visitor->closeExpressionPattern(this);
}
bool ExpressionPattern::_isExpressionPattern() { return (true); }
MemberExpression::MemberExpression(string* member, Position* start, Position* end) {
this->start = start;
this->end = end;
this->member = member;
}
void MemberExpression::accept(Visitor* visitor) {
visitor->visitMemberExpression(this);
}
bool MemberExpression::_isMemberExpression() { return (true); }
Subscript::Subscript(_Array<ExpressionElement>* expressions, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expressions = expressions;
}
void Subscript::accept(Visitor* visitor) {
if (!visitor->openSubscript(this))
return;
if (expressions != nullptr) {
ExpressionElement* node = nullptr;
size_t _expressions_length = expressions->length();
for (size_t _i = 0; _i < _expressions_length; _i++) {
node = *(*expressions)[_i];
node->accept(visitor);
}
}
visitor->closeSubscript(this);
}
bool Subscript::_isSubscript() { return (true); }
void BinaryExpression::accept(Visitor* visitor) {
}
bool BinaryExpression::_isBinaryExpression() { return (true); }
bool BinaryExpression::_isBinaryOperation() { return (false); }
bool BinaryExpression::_isAssignment() { return (false); }
bool BinaryExpression::_isTypeQuery() { return (false); }
bool BinaryExpression::_isTypeCast() { return (false); }
BinaryOperation::BinaryOperation(string* binaryOperator, PrefixExpression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->binaryOperator = binaryOperator;
this->expression = expression;
}
void BinaryOperation::accept(Visitor* visitor) {
if (!visitor->openBinaryOperation(this))
return;
expression->accept(visitor);
visitor->closeBinaryOperation(this);
}
bool BinaryOperation::_isBinaryOperation() { return (true); }
Assignment::Assignment(Expression* expression, Position* start, Position* end) {
this->start = start;
this->end = end;
this->expression = expression;
}
void Assignment::accept(Visitor* visitor) {
if (!visitor->openAssignment(this))
return;
expression->accept(visitor);
visitor->closeAssignment(this);
}
bool Assignment::_isAssignment() { return (true); }
TypeQuery::TypeQuery(Type* objectType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->objectType = objectType;
}
void TypeQuery::accept(Visitor* visitor) {
if (!visitor->openTypeQuery(this))
return;
objectType->accept(visitor);
visitor->closeTypeQuery(this);
}
bool TypeQuery::_isTypeQuery() { return (true); }
TypeCast::TypeCast(Type* objectType, Position* start, Position* end) {
this->start = start;
this->end = end;
this->objectType = objectType;
}
void TypeCast::accept(Visitor* visitor) {
if (!visitor->openTypeCast(this))
return;
objectType->accept(visitor);
visitor->closeTypeCast(this);
}
bool TypeCast::_isTypeCast() { return (true); }
}
| 32.003074
| 165
| 0.671171
|
rschleitzer
|
bcfb26f1b23ecdb6fb1d8ca72d4cf914751b0995
| 8,418
|
cpp
|
C++
|
code/wxWidgets/src/mac/classic/dirmac.cpp
|
Bloodknight/NeuTorsion
|
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
|
[
"MIT"
] | 38
|
2016-02-20T02:46:28.000Z
|
2021-11-17T11:39:57.000Z
|
code/wxWidgets/src/mac/classic/dirmac.cpp
|
Dwarf-King/TorsionEditor
|
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
|
[
"MIT"
] | 17
|
2016-02-20T02:19:55.000Z
|
2021-02-08T15:15:17.000Z
|
code/wxWidgets/src/mac/classic/dirmac.cpp
|
Dwarf-King/TorsionEditor
|
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
|
[
"MIT"
] | 46
|
2016-02-20T02:47:33.000Z
|
2021-01-31T15:46:05.000Z
|
/////////////////////////////////////////////////////////////////////////////
// Name: msw/dir.cpp
// Purpose: wxDir implementation for Mac
// Author: Stefan Csomor
// Modified by:
// Created: 08.12.99
// RCS-ID: $Id: dirmac.cpp,v 1.4 2005/04/05 16:10:06 ABX Exp $
// Copyright: (c) 1999 Stefan Csomor <csomor@advanced.ch>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#ifdef __GNUG__
#pragma implementation "dir.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/intl.h"
#include "wx/log.h"
#endif // PCH
#include "wx/dir.h"
#include "wx/filefn.h" // for wxDirExists()
#ifndef __DARWIN__
#include <windows.h>
#endif
#include "wx/mac/private.h"
#ifdef __DARWIN__
# include "MoreFilesX.h"
#else
# include "MoreFiles.h"
# include "MoreFilesExtras.h"
#endif
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
#ifndef MAX_PATH
#define MAX_PATH 260 // from VC++ headers
#endif
// ----------------------------------------------------------------------------
// macros
// ----------------------------------------------------------------------------
#define M_DIR ((wxDirData *)m_data)
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
// this class stores everything we need to enumerate the files
class wxDirData
{
public:
wxDirData(const wxString& dirname);
~wxDirData();
void SetFileSpec(const wxString& filespec) { m_filespec = filespec; }
void SetFlags(int flags) { m_flags = flags; }
bool Read(wxString *filename); // reads the next
void Rewind() ;
const wxString& GetName() const { return m_dirname; }
bool Ok() const { return m_ok; }
private:
CInfoPBRec m_CPB ;
wxInt16 m_index ;
long m_dirId ;
Str255 m_name ;
Boolean m_isDir ;
wxString m_dirname;
wxString m_filespec;
int m_flags;
bool m_ok;
};
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxDirData
// ----------------------------------------------------------------------------
wxDirData::wxDirData(const wxString& dirname)
: m_dirname(dirname)
{
m_ok = false;
OSErr err;
// throw away the trailing slashes
size_t n = m_dirname.length();
wxCHECK_RET( n, _T("empty dir name in wxDir") );
while ( n > 0 && wxIsPathSeparator(m_dirname[--n]) )
;
m_dirname.Truncate(n + 1);
#ifdef __DARWIN__
FSRef theRef;
// get the FSRef associated with the POSIX path
err = FSPathMakeRef((const UInt8 *) m_dirname.c_str(), &theRef, NULL);
FSGetVRefNum(&theRef, &(m_CPB.hFileInfo.ioVRefNum));
err = FSGetNodeID( &theRef , &m_dirId , &m_isDir ) ;
#else
FSSpec fsspec ;
wxMacFilename2FSSpec( m_dirname , &fsspec ) ;
m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ;
err = FSpGetDirectoryID( &fsspec , &m_dirId , &m_isDir ) ;
#endif
//wxASSERT_MSG( (err == noErr) || (err == nsvErr) , wxT("Error accessing directory " + m_dirname)) ;
if ( (err == noErr) || (err == nsvErr))
m_ok = true;
else
wxLogError(wxString(wxT("Error accessing directory ")) + m_dirname);
m_CPB.hFileInfo.ioNamePtr = m_name ;
m_index = 0 ;
}
wxDirData::~wxDirData()
{
}
void wxDirData::Rewind()
{
m_index = 0 ;
}
bool wxDirData::Read(wxString *filename)
{
if ( !m_isDir )
return false ;
wxString result;
short err = noErr ;
while ( err == noErr )
{
m_index++ ;
m_CPB.dirInfo.ioFDirIndex = m_index;
m_CPB.dirInfo.ioDrDirID = m_dirId; /* we need to do this every time */
err = PBGetCatInfoSync((CInfoPBPtr)&m_CPB);
if ( err != noErr )
break ;
// its hidden but we don't want it
if ( ( m_CPB.hFileInfo.ioFlFndrInfo.fdFlags & kIsInvisible ) && !(m_flags & wxDIR_HIDDEN) )
continue ;
#ifdef __DARWIN__
// under X, names that start with '.' are hidden
if ( ( m_name[1] == '.' ) && !(m_flags & wxDIR_HIDDEN) )
continue;
#endif
#if TARGET_CARBON
// under X thats the way the mounting points look like
if ( ( m_CPB.dirInfo.ioDrDirID == 0 ) && ( m_flags & wxDIR_DIRS) )
break ;
#endif
// we have a directory
if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (m_flags & wxDIR_DIRS) )
break ;
// its a file but we don't want it
if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(m_flags & wxDIR_FILES ) )
continue ;
wxString file = wxMacMakeStringFromPascal( m_name ) ;
if ( m_filespec.empty() || m_filespec == wxT("*.*") || m_filespec == wxT("*") )
{
}
else if ( m_filespec.Length() > 1 && m_filespec.Left(1) == wxT("*") )
{
if ( file.Right( m_filespec.Length() - 1 ).Upper() != m_filespec.Mid(1).Upper() )
{
continue ;
}
}
else if ( m_filespec.Length() > 1 && m_filespec.Right(1) == wxT("*") )
{
if ( file.Left( m_filespec.Length() - 1 ).Upper() != m_filespec.Left( m_filespec.Length() - 1 ).Upper() )
{
continue ;
}
}
else if ( file.Upper() != m_filespec.Upper() )
{
continue ;
}
break ;
}
if ( err != noErr )
{
return false ;
}
*filename = wxMacMakeStringFromPascal( m_name ) ;
return true;
}
// ----------------------------------------------------------------------------
// wxDir helpers
// ----------------------------------------------------------------------------
/* static */
bool wxDir::Exists(const wxString& dir)
{
return wxDirExists(dir);
}
// ----------------------------------------------------------------------------
// wxDir construction/destruction
// ----------------------------------------------------------------------------
wxDir::wxDir(const wxString& dirname)
{
m_data = NULL;
(void)Open(dirname);
}
bool wxDir::Open(const wxString& dirname)
{
delete M_DIR;
m_data = new wxDirData(dirname);
if (m_data->Ok())
return true;
else
{
delete m_data;
m_data = NULL;
return false;
}
}
bool wxDir::IsOpened() const
{
return m_data != NULL;
}
wxString wxDir::GetName() const
{
wxString name;
if ( m_data )
{
name = M_DIR->GetName();
if ( !name.empty() && (name.Last() == _T('/')) )
{
// chop off the last (back)slash
name.Truncate(name.length() - 1);
}
}
return name;
}
wxDir::~wxDir()
{
if (M_DIR != NULL) {
delete M_DIR;
m_data = NULL;
}
}
// ----------------------------------------------------------------------------
// wxDir enumerating
// ----------------------------------------------------------------------------
bool wxDir::GetFirst(wxString *filename,
const wxString& filespec,
int flags) const
{
wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") );
M_DIR->Rewind();
M_DIR->SetFileSpec(filespec);
M_DIR->SetFlags(flags);
return GetNext(filename);
}
bool wxDir::GetNext(wxString *filename) const
{
wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") );
wxCHECK_MSG( filename, false, _T("bad pointer in wxDir::GetNext()") );
return M_DIR->Read(filename);
}
| 26.06192
| 117
| 0.456284
|
Bloodknight
|
4c01be17a7ee931aab224362627f5ded43f4288c
| 2,047
|
hpp
|
C++
|
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/HoudiniEngineUnity/HEU_TestHelpers_RequireClass_1.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: HoudiniEngineUnity.HEU_TestHelpers
#include "HoudiniEngineUnity/HEU_TestHelpers.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::HoudiniEngineUnity::HEU_TestHelpers::RequireClass_1, "HoudiniEngineUnity", "HEU_TestHelpers/RequireClass`1");
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// WARNING Size may be invalid!
// Autogenerated type: HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1
// [TokenAttribute] Offset: FFFFFFFF
template<typename T>
class HEU_TestHelpers::RequireClass_1 : public ::Il2CppObject {
public:
// public System.Void .ctor()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HEU_TestHelpers::RequireClass_1<T>* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::HoudiniEngineUnity::HEU_TestHelpers::RequireClass_1::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HEU_TestHelpers::RequireClass_1<T>*, creationType>()));
}
}; // HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1
// Could not write size check! Type: HoudiniEngineUnity.HEU_TestHelpers/HoudiniEngineUnity.RequireClass`1 is generic, or has no fields that are valid for size checks!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 53.868421
| 168
| 0.753786
|
RedBrumbler
|
4c05bd2e801efe4d94d466660e3639a588d0b640
| 528
|
cpp
|
C++
|
application/source/geometry_node.cpp
|
luigielbambino/CG_Lab_Titz120003Alvarez119446
|
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
|
[
"MIT"
] | null | null | null |
application/source/geometry_node.cpp
|
luigielbambino/CG_Lab_Titz120003Alvarez119446
|
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
|
[
"MIT"
] | null | null | null |
application/source/geometry_node.cpp
|
luigielbambino/CG_Lab_Titz120003Alvarez119446
|
e494b9d7695dcee5d1e466a3b8bbef1f13cb96bc
|
[
"MIT"
] | null | null | null |
// Geometry Node function definitions
#include "node.hpp"
#include "window_handler.hpp"
#include "utils.hpp"
#include <glbinding/gl/gl.h>
// use gl definitions from glbinding
using namespace gl;
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <iostream>
//Geometry Node constructor
GeometryNode::GeometryNode(){
//geometry = newgeometry;
}
// getters and setters definitios
model GeometryNode::getGeometry(){
return geometry;
}
void GeometryNode::setGeometry(model newgeometry){
geometry = newgeometry;
}
| 19.555556
| 50
| 0.761364
|
luigielbambino
|
4c07d9c899552b022ad3629f2b0f776769c1fa46
| 2,277
|
cpp
|
C++
|
test/error.cpp
|
madmongo1/url
|
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
|
[
"BSL-1.0"
] | null | null | null |
test/error.cpp
|
madmongo1/url
|
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
|
[
"BSL-1.0"
] | null | null | null |
test/error.cpp
|
madmongo1/url
|
e7c9b0c860abd5fba3b7a20c3b29552a326de7b5
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/url
//
// Test that header file is self-contained.
#include <boost/url/error.hpp>
#include "test_suite.hpp"
#include <memory>
namespace boost {
namespace urls {
class error_test
{
public:
void check(error e)
{
auto const ec = make_error_code(e);
BOOST_TEST(ec.category().name() != nullptr);
BOOST_TEST(! ec.message().empty());
BOOST_TEST(ec.category().default_error_condition(
static_cast<int>(e)).category() == ec.category());
}
void check(condition c, error e)
{
{
auto const ec = make_error_code(e);
BOOST_TEST(ec.category().name() != nullptr);
BOOST_TEST(! ec.message().empty());
BOOST_TEST(ec == c);
}
{
auto ec = make_error_condition(c);
BOOST_TEST(ec.category().name() != nullptr);
BOOST_TEST(! ec.message().empty());
BOOST_TEST(ec == c);
}
}
void
run()
{
check(condition::parse_error, error::no_match);
check(condition::parse_error, error::syntax);
check(condition::parse_error, error::invalid);
check(condition::parse_error, error::missing_scheme);
check(condition::parse_error, error::bad_scheme_start_char);
check(condition::parse_error, error::bad_scheme_char);
check(condition::parse_error, error::bad_username_char);
check(condition::parse_error, error::bad_userinfo_char);
check(condition::parse_error, error::bad_port_char);
check(condition::parse_error, error::port_overflow);
check(condition::parse_error, error::missing_hostname);
check(condition::parse_error, error::missing_port);
check(condition::parse_error, error::bad_pct_encoding_digit);
check(condition::parse_error, error::incomplete_pct_encoding);
check(condition::parse_error, error::illegal_reserved_char);
}
};
TEST_SUITE(error_test, "boost.url.error");
} // urls
} // boost
| 30.36
| 79
| 0.639877
|
madmongo1
|
4c0a4a878fea72ad83ca002391f785bed505d4e9
| 6,635
|
cc
|
C++
|
src/student_dataSK.cc
|
rmolin88/corba
|
b23fe31e084b0946211ee8df6346f9042f4f5bac
|
[
"MIT"
] | null | null | null |
src/student_dataSK.cc
|
rmolin88/corba
|
b23fe31e084b0946211ee8df6346f9042f4f5bac
|
[
"MIT"
] | null | null | null |
src/student_dataSK.cc
|
rmolin88/corba
|
b23fe31e084b0946211ee8df6346f9042f4f5bac
|
[
"MIT"
] | 1
|
2020-04-29T23:43:55.000Z
|
2020-04-29T23:43:55.000Z
|
// This file is generated by omniidl (C++ backend)- omniORB_4_2. Do not edit.
#include "student_data.hh"
#include <omniORB4/IOP_S.h>
#include <omniORB4/IOP_C.h>
#include <omniORB4/callDescriptor.h>
#include <omniORB4/callHandle.h>
#include <omniORB4/objTracker.h>
OMNI_USING_NAMESPACE(omni)
static const char* _0RL_library_version = omniORB_4_2;
StudentInfo_ptr StudentInfo_Helper::_nil() {
return ::StudentInfo::_nil();
}
::CORBA::Boolean StudentInfo_Helper::is_nil(::StudentInfo_ptr p) {
return ::CORBA::is_nil(p);
}
void StudentInfo_Helper::release(::StudentInfo_ptr p) {
::CORBA::release(p);
}
void StudentInfo_Helper::marshalObjRef(::StudentInfo_ptr obj, cdrStream& s) {
::StudentInfo::_marshalObjRef(obj, s);
}
StudentInfo_ptr StudentInfo_Helper::unmarshalObjRef(cdrStream& s) {
return ::StudentInfo::_unmarshalObjRef(s);
}
void StudentInfo_Helper::duplicate(::StudentInfo_ptr obj) {
if (obj && !obj->_NP_is_nil()) omni::duplicateObjRef(obj);
}
StudentInfo_ptr
StudentInfo::_duplicate(::StudentInfo_ptr obj)
{
if (obj && !obj->_NP_is_nil()) omni::duplicateObjRef(obj);
return obj;
}
StudentInfo_ptr
StudentInfo::_narrow(::CORBA::Object_ptr obj)
{
if (!obj || obj->_NP_is_nil() || obj->_NP_is_pseudo()) return _nil();
_ptr_type e = (_ptr_type) obj->_PR_getobj()->_realNarrow(_PD_repoId);
return e ? e : _nil();
}
StudentInfo_ptr
StudentInfo::_unchecked_narrow(::CORBA::Object_ptr obj)
{
if (!obj || obj->_NP_is_nil() || obj->_NP_is_pseudo()) return _nil();
_ptr_type e = (_ptr_type) obj->_PR_getobj()->_uncheckedNarrow(_PD_repoId);
return e ? e : _nil();
}
StudentInfo_ptr
StudentInfo::_nil()
{
#ifdef OMNI_UNLOADABLE_STUBS
static _objref_StudentInfo _the_nil_obj;
return &_the_nil_obj;
#else
static _objref_StudentInfo* _the_nil_ptr = 0;
if (!_the_nil_ptr) {
omni::nilRefLock().lock();
if (!_the_nil_ptr) {
_the_nil_ptr = new _objref_StudentInfo;
registerNilCorbaObject(_the_nil_ptr);
}
omni::nilRefLock().unlock();
}
return _the_nil_ptr;
#endif
}
const char* StudentInfo::_PD_repoId = "IDL:StudentInfo:1.0";
_objref_StudentInfo::~_objref_StudentInfo() {
}
_objref_StudentInfo::_objref_StudentInfo(omniIOR* ior, omniIdentity* id) :
omniObjRef(::StudentInfo::_PD_repoId, ior, id, 1)
{
_PR_setobj(this);
}
void*
_objref_StudentInfo::_ptrToObjRef(const char* id)
{
if (id == ::StudentInfo::_PD_repoId)
return (::StudentInfo_ptr) this;
if (id == ::CORBA::Object::_PD_repoId)
return (::CORBA::Object_ptr) this;
if (omni::strMatch(id, ::StudentInfo::_PD_repoId))
return (::StudentInfo_ptr) this;
if (omni::strMatch(id, ::CORBA::Object::_PD_repoId))
return (::CORBA::Object_ptr) this;
return 0;
}
//
// Code for StudentInfo::SetStudentData
// Proxy call descriptor class. Mangled signature:
// _clong
class _0RL_cd_80d5c52d0a7a1b14_00000000
: public omniCallDescriptor
{
public:
inline _0RL_cd_80d5c52d0a7a1b14_00000000(LocalCallFn lcfn, const char* op_, size_t oplen, _CORBA_Boolean upcall=0)
: omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 0, upcall)
{
}
void unmarshalReturnedValues(cdrStream&);
void marshalReturnedValues(cdrStream&);
static const char* const _user_exns[];
::CORBA::Long result;
};
void _0RL_cd_80d5c52d0a7a1b14_00000000::marshalReturnedValues(cdrStream& _n)
{
result >>= _n;
}
void _0RL_cd_80d5c52d0a7a1b14_00000000::unmarshalReturnedValues(cdrStream& _n)
{
(::CORBA::Long&)result <<= _n;
}
const char* const _0RL_cd_80d5c52d0a7a1b14_00000000::_user_exns[] = {
0
};
// Local call call-back function.
static void
_0RL_lcfn_80d5c52d0a7a1b14_10000000(omniCallDescriptor* cd, omniServant* svnt)
{
_0RL_cd_80d5c52d0a7a1b14_00000000* tcd = (_0RL_cd_80d5c52d0a7a1b14_00000000*)cd;
_impl_StudentInfo* impl = (_impl_StudentInfo*) svnt->_ptrToInterface(StudentInfo::_PD_repoId);
tcd->result = impl->SetStudentData();
}
::CORBA::Long _objref_StudentInfo::SetStudentData()
{
_0RL_cd_80d5c52d0a7a1b14_00000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_10000000, "SetStudentData", 15);
_invoke(_call_desc);
return _call_desc.result;
}
//
// Code for StudentInfo::GetStudentData
// Proxy call descriptor class. Mangled signature:
// void
class _0RL_cd_80d5c52d0a7a1b14_20000000
: public omniCallDescriptor
{
public:
inline _0RL_cd_80d5c52d0a7a1b14_20000000(LocalCallFn lcfn, const char* op_, size_t oplen, _CORBA_Boolean upcall=0)
: omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 0, upcall)
{
}
static const char* const _user_exns[];
};
const char* const _0RL_cd_80d5c52d0a7a1b14_20000000::_user_exns[] = {
0
};
// Local call call-back function.
static void
_0RL_lcfn_80d5c52d0a7a1b14_30000000(omniCallDescriptor*, omniServant* svnt)
{
_impl_StudentInfo* impl = (_impl_StudentInfo*) svnt->_ptrToInterface(StudentInfo::_PD_repoId);
impl->GetStudentData();
}
void _objref_StudentInfo::GetStudentData()
{
_0RL_cd_80d5c52d0a7a1b14_20000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_30000000, "GetStudentData", 15);
_invoke(_call_desc);
}
_pof_StudentInfo::~_pof_StudentInfo() {}
omniObjRef*
_pof_StudentInfo::newObjRef(omniIOR* ior, omniIdentity* id)
{
return new ::_objref_StudentInfo(ior, id);
}
::CORBA::Boolean
_pof_StudentInfo::is_a(const char* id) const
{
if (omni::ptrStrMatch(id, ::StudentInfo::_PD_repoId))
return 1;
return 0;
}
const _pof_StudentInfo _the_pof_StudentInfo;
_impl_StudentInfo::~_impl_StudentInfo() {}
::CORBA::Boolean
_impl_StudentInfo::_dispatch(omniCallHandle& _handle)
{
const char* op = _handle.operation_name();
if (omni::strMatch(op, "SetStudentData")) {
_0RL_cd_80d5c52d0a7a1b14_00000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_10000000, "SetStudentData", 15, 1);
_handle.upcall(this,_call_desc);
return 1;
}
if (omni::strMatch(op, "GetStudentData")) {
_0RL_cd_80d5c52d0a7a1b14_20000000 _call_desc(_0RL_lcfn_80d5c52d0a7a1b14_30000000, "GetStudentData", 15, 1);
_handle.upcall(this,_call_desc);
return 1;
}
return 0;
}
void*
_impl_StudentInfo::_ptrToInterface(const char* id)
{
if (id == ::StudentInfo::_PD_repoId)
return (::_impl_StudentInfo*) this;
if (id == ::CORBA::Object::_PD_repoId)
return (void*) 1;
if (omni::strMatch(id, ::StudentInfo::_PD_repoId))
return (::_impl_StudentInfo*) this;
if (omni::strMatch(id, ::CORBA::Object::_PD_repoId))
return (void*) 1;
return 0;
}
const char*
_impl_StudentInfo::_mostDerivedRepoId()
{
return ::StudentInfo::_PD_repoId;
}
POA_StudentInfo::~POA_StudentInfo() {}
| 21.542208
| 116
| 0.728711
|
rmolin88
|
4c0ca970261e746930efb887b363d742f6ed5d0b
| 42
|
hpp
|
C++
|
src/boost_mpl_map_aux__at_impl.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_mpl_map_aux__at_impl.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_mpl_map_aux__at_impl.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/mpl/map/aux_/at_impl.hpp>
| 21
| 41
| 0.761905
|
miathedev
|
4c0f49126be8045054e8bbb5fbc2b341af61d729
| 13,082
|
cpp
|
C++
|
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
|
jagilley/MrsWatson
|
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
|
[
"BSD-2-Clause"
] | 2
|
2019-06-14T10:20:30.000Z
|
2020-02-19T17:53:42.000Z
|
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
|
jagilley/MrsWatson
|
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
|
[
"BSD-2-Clause"
] | null | null | null |
VST3 SDK/vstgui4/vstgui/lib/controls/csegmentbutton.cpp
|
jagilley/MrsWatson
|
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
|
[
"BSD-2-Clause"
] | 1
|
2021-03-16T13:02:17.000Z
|
2021-03-16T13:02:17.000Z
|
//-----------------------------------------------------------------------------
// VST Plug-Ins SDK
// VSTGUI: Graphical User Interface Framework not only for VST plugins
//
// Version 4.3
//
//-----------------------------------------------------------------------------
// VSTGUI LICENSE
// (c) 2015, Steinberg Media Technologies, 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 Steinberg Media Technologies nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "csegmentbutton.h"
#include "../cdrawcontext.h"
#include "../cframe.h"
#include "../cgraphicspath.h"
#include <algorithm>
namespace VSTGUI {
typedef std::numeric_limits<uint32_t> UInt32Limit;
uint32_t CSegmentButton::kPushBack = UInt32Limit::max ();
//-----------------------------------------------------------------------------
CSegmentButton::CSegmentButton (const CRect& size, IControlListener* listener, int32_t tag)
: CControl (size, listener, tag)
, textColor (kBlackCColor)
, textColorHighlighted (kWhiteCColor)
, frameColor (kBlackCColor)
, textAlignment (kCenterText)
, textMargin (0)
, font (kNormalFont)
, roundRadius (5)
, frameWidth (1)
, style (kHorizontal)
, textTruncateMode (CDrawMethods::kTextTruncateNone)
{
setWantsFocus (true);
}
//-----------------------------------------------------------------------------
void CSegmentButton::addSegment (Segment segment, uint32_t index)
{
if (index == kPushBack && segments.size () < kPushBack)
segments.push_back (segment);
else if (index < segments.size ())
{
Segments::iterator it = segments.begin ();
std::advance (it, index);
segments.insert (it, segment);
}
updateSegmentSizes ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::removeSegment (uint32_t index)
{
if (index < segments.size ())
{
Segments::iterator it = segments.begin ();
std::advance (it, index);
segments.erase (it);
}
updateSegmentSizes ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::removeAllSegments ()
{
segments.clear ();
invalid ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::setSelectedSegment (uint32_t index)
{
setValueNormalized (static_cast<float> (index) / static_cast<float> (segments.size () - 1));
invalid ();
}
//-----------------------------------------------------------------------------
uint32_t CSegmentButton::getSelectedSegment () const
{
return getSegmentIndex (getValueNormalized ());
}
//-----------------------------------------------------------------------------
void CSegmentButton::setStyle (Style newStyle)
{
if (style != newStyle)
{
style = newStyle;
updateSegmentSizes ();
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextTruncateMode (CDrawMethods::TextTruncateMode mode)
{
if (textTruncateMode != mode)
{
textTruncateMode = mode;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setGradient (CGradient* newGradient)
{
if (gradient != newGradient)
{
gradient = newGradient;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setGradientHighlighted (CGradient* newGradient)
{
if (gradientHighlighted != newGradient)
{
gradientHighlighted = newGradient;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setRoundRadius (CCoord newRoundRadius)
{
if (roundRadius != newRoundRadius)
{
roundRadius = newRoundRadius;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFont (CFontRef newFont)
{
if (font != newFont)
{
font = newFont;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextAlignment (CHoriTxtAlign newAlignment)
{
if (textAlignment != newAlignment)
{
textAlignment = newAlignment;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextMargin (CCoord newMargin)
{
if (textMargin != newMargin)
{
textMargin = newMargin;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextColor (CColor newColor)
{
if (textColor != newColor)
{
textColor = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextColorHighlighted (CColor newColor)
{
if (textColorHighlighted != newColor)
{
textColorHighlighted = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFrameColor (CColor newColor)
{
if (frameColor != newColor)
{
frameColor = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFrameWidth (CCoord newWidth)
{
if (frameWidth != newWidth)
{
frameWidth = newWidth;
invalid ();
}
}
//-----------------------------------------------------------------------------
bool CSegmentButton::attached (CView *parent)
{
if (CControl::attached (parent))
{
updateSegmentSizes ();
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CSegmentButton::setViewSize (const CRect& rect, bool invalid)
{
CControl::setViewSize (rect, invalid);
updateSegmentSizes ();
}
//-----------------------------------------------------------------------------
CMouseEventResult CSegmentButton::onMouseDown (CPoint& where, const CButtonState& buttons)
{
if (buttons.isLeftButton ())
{
float newValue = 0;
float valueOffset = 1.f / (segments.size () - 1);
uint32_t currentIndex = getSegmentIndex (getValueNormalized ());
for (Segments::const_iterator it = segments.begin (), end = segments.end (); it != end; ++it, newValue += valueOffset)
{
if ((*it).rect.pointInside (where))
{
uint32_t newIndex = getSegmentIndex (newValue);
if (newIndex != currentIndex)
{
beginEdit ();
setSelectedSegment (newIndex);
valueChanged ();
endEdit ();
invalid ();
}
break;
}
}
}
return kMouseDownEventHandledButDontNeedMovedOrUpEvents;
}
//-----------------------------------------------------------------------------
int32_t CSegmentButton::onKeyDown (VstKeyCode& keyCode)
{
int32_t result = -1;
if (keyCode.modifier == 0 && keyCode.character == 0)
{
uint32_t newIndex = getSegmentIndex (getValueNormalized ());
uint32_t oldIndex = newIndex;
switch (keyCode.virt)
{
case VKEY_LEFT:
{
if (style == kHorizontal && newIndex > 0)
newIndex--;
result = 1;
break;
}
case VKEY_RIGHT:
{
if (style == kHorizontal && newIndex < segments.size () - 1)
newIndex++;
result = 1;
break;
}
case VKEY_UP:
{
if (style == kVertical && newIndex > 0)
newIndex--;
result = 1;
break;
}
case VKEY_DOWN:
{
if (style == kVertical && newIndex < segments.size () - 1)
newIndex++;
result = 1;
break;
}
}
if (newIndex != oldIndex)
{
beginEdit ();
setSelectedSegment (newIndex);
valueChanged ();
endEdit ();
invalid ();
}
}
return result;
}
//-----------------------------------------------------------------------------
void CSegmentButton::draw (CDrawContext* pContext)
{
CView::draw (pContext);
}
//-----------------------------------------------------------------------------
void CSegmentButton::drawRect (CDrawContext* pContext, const CRect& dirtyRect)
{
bool isHorizontal = style == kHorizontal;
SharedPointer<CGraphicsPath> path;
if (gradient || gradientHighlighted || (getFrameWidth () > 0. && getFrameColor ().alpha != 0))
{
CRect r (getViewSize ());
r.inset (getFrameWidth () / 2., getFrameWidth () / 2.);
path = owned (pContext->createGraphicsPath ());
path->addRoundRect (r, getRoundRadius ());
}
pContext->setDrawMode (kAntiAliasing);
bool drawLines = getFrameWidth () > 0. && getFrameColor ().alpha != 0;
if (drawLines)
{
pContext->setLineStyle (kLineSolid);
pContext->setLineWidth (getFrameWidth ());
pContext->setFrameColor (getFrameColor ());
}
if (gradient)
{
pContext->fillLinearGradient (path, *gradient, getViewSize ().getTopLeft (), getViewSize ().getBottomLeft ());
}
uint32_t selectedIndex = getSelectedSegment ();
for (uint32_t index = 0; index < segments.size (); ++index)
{
Segment& segment = segments[index];
if (!dirtyRect.rectOverlap (segment.rect))
continue;
CRect oldClip;
pContext->getClipRect (oldClip);
CRect clipRect (segment.rect);
clipRect.bound (oldClip);
pContext->setClipRect (clipRect);
bool selected = selectedIndex == index;
if (selected && gradientHighlighted)
pContext->fillLinearGradient (path, *gradientHighlighted, segment.rect.getTopLeft (), segment.rect.getBottomLeft ());
if (selected && segment.backgroundHighlighted)
segment.backgroundHighlighted->draw (pContext, segment.rect);
else if (segment.background)
segment.background->draw (pContext, segment.rect);
CDrawMethods::drawIconAndText (pContext, selected ? segment.iconHighlighted : segment.icon, segment.iconPosition, textAlignment, textMargin, segment.rect, segment.name, font, selected ? textColorHighlighted : textColor, textTruncateMode);
pContext->setClipRect (oldClip);
if (drawLines && index > 0 && index < segments.size ())
{
path->beginSubpath (segment.rect.getTopLeft ());
path->addLine (isHorizontal ? segment.rect.getBottomLeft () : segment.rect.getTopRight ());
}
}
if (drawLines)
pContext->drawGraphicsPath (path, CDrawContext::kPathStroked);
setDirty (false);
}
//-----------------------------------------------------------------------------
uint32_t CSegmentButton::getSegmentIndex (float value) const
{
if (value < 0.f || value > 1.f)
return kPushBack;
return static_cast<uint32_t> (static_cast<float> (segments.size () - 1) * value);
}
//-----------------------------------------------------------------------------
void CSegmentButton::updateSegmentSizes ()
{
if (isAttached () && !segments.empty ())
{
if (style == kHorizontal)
{
CCoord width = getWidth () / segments.size ();
CRect r (getViewSize ());
r.setWidth (width);
for (Segments::iterator it = segments.begin (), end = segments.end (); it != end; ++it)
{
(*it).rect = r;
r.offset (width, 0);
}
}
else
{
CCoord height = getHeight () / segments.size ();
CRect r (getViewSize ());
r.setHeight (height);
for (Segments::iterator it = segments.begin (), end = segments.end (); it != end; ++it)
{
(*it).rect = r;
r.offset (0, height);
}
}
}
}
//-----------------------------------------------------------------------------
bool CSegmentButton::drawFocusOnTop ()
{
return false;
}
//-----------------------------------------------------------------------------
bool CSegmentButton::getFocusPath (CGraphicsPath& outPath)
{
CRect r (getViewSize ());
r.inset (getFrameWidth () / 2., getFrameWidth () / 2.);
outPath.addRoundRect (r, getRoundRadius ());
CCoord focusWidth = getFrame ()->getFocusWidth ();
r.extend (focusWidth, focusWidth);
outPath.addRoundRect (r, getRoundRadius ());
return true;
}
} // namespace
| 29.397753
| 240
| 0.561764
|
jagilley
|
4c167a98f982f4c381e95bf4a1ecf121b323b20c
| 26,089
|
cpp
|
C++
|
build/source/rotatelogsw.cpp
|
g-stefan/vendor-httpd
|
14c434fc0932dd888a620442016c7a52cfe34e14
|
[
"MIT",
"Apache-2.0",
"Unlicense"
] | null | null | null |
build/source/rotatelogsw.cpp
|
g-stefan/vendor-httpd
|
14c434fc0932dd888a620442016c7a52cfe34e14
|
[
"MIT",
"Apache-2.0",
"Unlicense"
] | null | null | null |
build/source/rotatelogsw.cpp
|
g-stefan/vendor-httpd
|
14c434fc0932dd888a620442016c7a52cfe34e14
|
[
"MIT",
"Apache-2.0",
"Unlicense"
] | null | null | null |
/* 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.
*/
#include "apr.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_errno.h"
#include "apr_file_io.h"
#include "apr_file_info.h"
#include "apr_general.h"
#include "apr_time.h"
#include "apr_getopt.h"
#include "apr_thread_proc.h"
#include "apr_signal.h"
#if APR_FILES_AS_SOCKETS
#include "apr_poll.h"
#endif
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#define APR_WANT_STRFUNC
#include "apr_want.h"
#define BUFSIZE 65536
#define ROTATE_NONE 0
#define ROTATE_NEW 1
#define ROTATE_TIME 2
#define ROTATE_SIZE 3
#define ROTATE_FORCE 4
static const char *const ROTATE_REASONS[] = {
"None",
"Open a new file",
"Time interval expired",
"Maximum size reached",
"Forced rotation",
NULL
};
typedef struct rotate_config rotate_config_t;
struct rotate_config {
unsigned int sRotation;
int tRotation;
int utc_offset;
int use_localtime;
int use_strftime;
int force_open;
int verbose;
int echo;
char *szLogRoot;
int truncate;
const char *linkfile;
const char *postrotate_prog;
#if APR_FILES_AS_SOCKETS
int create_empty;
#endif
int num_files;
int create_path;
};
typedef struct rotate_status rotate_status_t;
/* "adjusted_time_t" is used to store Unix time (seconds since epoch)
* which has been adjusted for some timezone fudge factor. It should
* be used for storing the return values from get_now(). A typedef is
* used since this type is similar to time_t, but different. */
typedef long adjusted_time_t;
/* Structure to contain relevant logfile state: fd, pool and
* filename. */
struct logfile {
apr_pool_t *pool;
apr_file_t *fd;
char name[APR_PATH_MAX];
};
struct rotate_status {
struct logfile current; /* current logfile. */
apr_pool_t *pool; /* top-level pool */
int rotateReason;
adjusted_time_t tLogEnd;
int nMessCount;
int fileNum;
};
static rotate_config_t config;
static rotate_status_t status;
static void usage(const char *argv0, const char *reason)
{
if (reason) {
fprintf(stderr, "%s\n", reason);
}
fprintf(stderr,
#if APR_FILES_AS_SOCKETS
"Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-c] [-n number] <logfile> "
#else
"Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-n number] <logfile> "
#endif
"{<rotation time in seconds>|<rotation size>(B|K|M|G)} "
"[offset minutes from UTC]\n\n",
argv0);
#ifdef OS2
fprintf(stderr,
"Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n",
argv0);
#else
fprintf(stderr,
"Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n",
argv0);
fprintf(stderr,
"or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
#endif
fprintf(stderr,
"to httpd.conf. By default, the generated name will be\n"
"<logfile>.nnnn where nnnn is the system time at which the log\n"
"nominally starts (N.B. if using a rotation time, the time will\n"
"always be a multiple of the rotation time, so you can synchronize\n"
"cron scripts with it). If <logfile> contains strftime conversion\n"
"specifications, those will be used instead. At the end of each\n"
"rotation time or when the file size is reached a new log is\n"
"started.\n"
"\n"
"Options:\n"
" -v Verbose operation. Messages are written to stderr.\n"
" -l Base rotation on local time instead of UTC.\n"
" -L path Create hard link from current log to specified path.\n"
" -p prog Run specified program after opening a new log file. See below.\n"
" -f Force opening of log on program start.\n"
" -D Create parent directories of log file.\n"
" -t Truncate logfile instead of rotating, tail friendly.\n"
" -e Echo log to stdout for further processing.\n"
#if APR_FILES_AS_SOCKETS
" -c Create log even if it is empty.\n"
#endif
" -n num Rotate file by adding suffixes '.1', '.2', ..., '.num'.\n"
"\n"
"The program for '-p' is invoked as \"[prog] <curfile> [<prevfile>]\"\n"
"where <curfile> is the filename of the newly opened logfile, and\n"
"<prevfile>, if given, is the filename of the previously used logfile.\n"
"\n");
exit(1);
}
/* This function returns the current Unix time (time_t) adjusted for
* any configured or derived local time offset. The offset applied is
* returned via *offset. */
static adjusted_time_t get_now(rotate_config_t *config, apr_int32_t *offset)
{
apr_time_t tNow = apr_time_now();
apr_int32_t utc_offset;
if (config->use_localtime) {
/* Check for our UTC offset before using it, since it might
* change if there's a switch between standard and daylight
* savings time.
*/
apr_time_exp_t lt;
apr_time_exp_lt(<, tNow);
utc_offset = lt.tm_gmtoff;
}
else {
utc_offset = config->utc_offset;
}
if (offset)
*offset = utc_offset;
return apr_time_sec(tNow) + utc_offset;
}
/*
* Close a file and destroy the associated pool.
*/
static void close_logfile(rotate_config_t *config, struct logfile *logfile)
{
if (config->verbose) {
fprintf(stderr, "Closing file %s\n", logfile->name);
}
apr_file_close(logfile->fd);
apr_pool_destroy(logfile->pool);
}
/*
* Dump the configuration parsing result to STDERR.
*/
static void dumpConfig (rotate_config_t *config)
{
fprintf(stderr, "Rotation time interval: %12d\n", config->tRotation);
fprintf(stderr, "Rotation size interval: %12d\n", config->sRotation);
fprintf(stderr, "Rotation time UTC offset: %12d\n", config->utc_offset);
fprintf(stderr, "Rotation based on localtime: %12s\n", config->use_localtime ? "yes" : "no");
fprintf(stderr, "Rotation file date pattern: %12s\n", config->use_strftime ? "yes" : "no");
fprintf(stderr, "Rotation file forced open: %12s\n", config->force_open ? "yes" : "no");
fprintf(stderr, "Create parent directories: %12s\n", config->create_path ? "yes" : "no");
fprintf(stderr, "Rotation verbose: %12s\n", config->verbose ? "yes" : "no");
#if APR_FILES_AS_SOCKETS
fprintf(stderr, "Rotation create empty logs: %12s\n", config->create_empty ? "yes" : "no");
#endif
fprintf(stderr, "Rotation file name: %21s\n", config->szLogRoot);
fprintf(stderr, "Post-rotation prog: %21s\n", config->postrotate_prog ? config->postrotate_prog : "not used");
}
/*
* Check whether we need to rotate.
* Possible reasons are:
* - No log file open (ROTATE_NEW)
* - User forces us to rotate (ROTATE_FORCE)
* - Our log file size is already bigger than the
* allowed maximum (ROTATE_SIZE)
* - The next log time interval expired (ROTATE_TIME)
*
* When size and time constraints are both given,
* it suffices that one of them is fulfilled.
*/
static void checkRotate(rotate_config_t *config, rotate_status_t *status)
{
if (status->current.fd == NULL) {
status->rotateReason = ROTATE_NEW;
}
else if (config->sRotation) {
apr_finfo_t finfo;
apr_off_t current_size = -1;
if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->current.fd) == APR_SUCCESS) {
current_size = finfo.size;
}
if (current_size > config->sRotation) {
status->rotateReason = ROTATE_SIZE;
}
else if (config->tRotation) {
if (get_now(config, NULL) >= status->tLogEnd) {
status->rotateReason = ROTATE_TIME;
}
}
}
else if (config->tRotation) {
if (get_now(config, NULL) >= status->tLogEnd) {
status->rotateReason = ROTATE_TIME;
}
}
else {
fprintf(stderr, "No rotation time or size specified\n");
exit(2);
}
if (status->rotateReason != ROTATE_NONE && config->verbose) {
fprintf(stderr, "File rotation needed, reason: %s\n", ROTATE_REASONS[status->rotateReason]);
}
}
/*
* Handle post-rotate processing.
*/
static void post_rotate(apr_pool_t *pool, struct logfile *newlog,
rotate_config_t *config, rotate_status_t *status)
{
apr_status_t rv;
char error[120];
apr_procattr_t *pattr;
const char *argv[4];
apr_proc_t proc;
/* Handle link file, if configured. */
if (config->linkfile) {
apr_file_remove(config->linkfile, newlog->pool);
if (config->verbose) {
fprintf(stderr, "Linking %s to %s\n", newlog->name, config->linkfile);
}
rv = apr_file_link(newlog->name, config->linkfile);
if (rv != APR_SUCCESS) {
apr_strerror(rv, error, sizeof error);
fprintf(stderr, "Error linking file %s to %s (%s)\n",
newlog->name, config->linkfile, error);
exit(2);
}
}
if (!config->postrotate_prog) {
/* Nothing more to do. */
return;
}
/* Collect any zombies from a previous run, but don't wait. */
while (apr_proc_wait_all_procs(&proc, NULL, NULL, APR_NOWAIT, pool) == APR_CHILD_DONE)
/* noop */;
if ((rv = apr_procattr_create(&pattr, pool)) != APR_SUCCESS) {
fprintf(stderr,
"post_rotate: apr_procattr_create failed for '%s': %s\n",
config->postrotate_prog,
apr_strerror(rv, error, sizeof(error)));
return;
}
rv = apr_procattr_error_check_set(pattr, 1);
if (rv == APR_SUCCESS)
rv = apr_procattr_cmdtype_set(pattr, APR_PROGRAM_ENV);
if (rv != APR_SUCCESS) {
fprintf(stderr,
"post_rotate: could not set up process attributes for '%s': %s\n",
config->postrotate_prog,
apr_strerror(rv, error, sizeof(error)));
return;
}
argv[0] = config->postrotate_prog;
argv[1] = newlog->name;
if (status->current.fd) {
argv[2] = status->current.name;
argv[3] = NULL;
}
else {
argv[2] = NULL;
}
if (config->verbose)
fprintf(stderr, "Calling post-rotate program: %s\n", argv[0]);
rv = apr_proc_create(&proc, argv[0], argv, NULL, pattr, pool);
if (rv != APR_SUCCESS) {
fprintf(stderr, "Could not spawn post-rotate process '%s': %s\n",
config->postrotate_prog,
apr_strerror(rv, error, sizeof(error)));
return;
}
}
/* After a error, truncate the current file and write out an error
* message, which must be contained in message. The process is
* terminated on failure. */
static void truncate_and_write_error(rotate_status_t *status, const char *message)
{
apr_size_t buflen = strlen(message);
if (apr_file_trunc(status->current.fd, 0) != APR_SUCCESS) {
fprintf(stderr, "Error truncating the file %s\n", status->current.name);
exit(2);
}
if (apr_file_write_full(status->current.fd, message, buflen, NULL) != APR_SUCCESS) {
fprintf(stderr, "Error writing error (%s) to the file %s\n",
message, status->current.name);
exit(2);
}
}
/*
* Open a new log file, and if successful
* also close the old one.
*
* The timestamp for the calculation of the file
* name of the new log file will be the actual millisecond
* timestamp, except when a regular rotation based on a time
* interval is configured and the previous interval
* is over. Then the timestamp is the starting time
* of the actual interval.
*/
static void doRotate(rotate_config_t *config, rotate_status_t *status)
{
apr_int32_t offset;
adjusted_time_t now, tLogStart;
apr_status_t rv;
struct logfile newlog;
int thisLogNum = -1;
/* Retrieve local-time-adjusted-Unix-time. */
now = get_now(config, &offset);
status->rotateReason = ROTATE_NONE;
if (config->tRotation) {
adjusted_time_t tLogEnd;
tLogStart = (now / config->tRotation) * config->tRotation;
tLogEnd = tLogStart + config->tRotation;
/*
* Check if rotation was forced and the last rotation
* interval is not yet over. Use the value of now instead
* of the time interval boundary for the file name then.
*/
if (tLogStart < status->tLogEnd) {
tLogStart = now;
}
status->tLogEnd = tLogEnd;
}
else {
tLogStart = now;
}
if (config->use_strftime) {
apr_time_t tNow = apr_time_from_sec(tLogStart);
apr_time_exp_t e;
apr_size_t rs;
/* Explode the local-time-adjusted-Unix-time into a struct tm,
* first *reversing* local-time-adjustment applied by
* get_now() if we are using localtime. */
if (config->use_localtime)
apr_time_exp_lt(&e, tNow - apr_time_from_sec(offset));
else
apr_time_exp_gmt(&e, tNow);
apr_strftime(newlog.name, &rs, sizeof(newlog.name), config->szLogRoot, &e);
}
else {
if (config->truncate) {
apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
}
else if (config->num_files > 0) {
if (status->fileNum == -1 || status->fileNum == (config->num_files - 1)) {
thisLogNum = 0;
apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
}
else {
thisLogNum = status->fileNum + 1;
apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%d", config->szLogRoot, thisLogNum);
}
}
else {
apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%010ld", config->szLogRoot,
tLogStart);
}
}
apr_pool_create(&newlog.pool, status->pool);
if (config->create_path) {
char *ptr = strrchr(newlog.name, '/');
if (ptr && ptr > newlog.name) {
char *path = apr_pstrmemdup(newlog.pool, newlog.name, ptr - newlog.name);
if (config->verbose) {
fprintf(stderr, "Creating directory tree %s\n", path);
}
rv = apr_dir_make_recursive(path, APR_FPROT_OS_DEFAULT, newlog.pool);
if (rv != APR_SUCCESS) {
char error[120];
apr_strerror(rv, error, sizeof error);
fprintf(stderr, "Could not create directory '%s' (%s)\n", path, error);
exit(2);
}
}
}
if (config->verbose) {
fprintf(stderr, "Opening file %s\n", newlog.name);
}
rv = apr_file_open(&newlog.fd, newlog.name, APR_WRITE | APR_CREATE | APR_APPEND
| (config->truncate || (config->num_files > 0 && status->current.fd) ? APR_TRUNCATE : 0),
APR_OS_DEFAULT, newlog.pool);
if (rv == APR_SUCCESS) {
/* Handle post-rotate processing. */
post_rotate(newlog.pool, &newlog, config, status);
status->fileNum = thisLogNum;
/* Close out old (previously 'current') logfile, if any. */
if (status->current.fd) {
close_logfile(config, &status->current);
}
/* New log file is now 'current'. */
status->current = newlog;
}
else {
char *error = apr_psprintf(newlog.pool, "%pm", &rv);
char *message;
/* Uh-oh. Failed to open the new log file. Try to clear
* the previous log file, note the lost log entries,
* and keep on truckin'. */
if (status->current.fd == NULL) {
fprintf(stderr, "Could not open log file '%s' (%s)\n", newlog.name, error);
exit(2);
}
/* Try to keep this error message constant length
* in case it occurs several times. */
message = apr_psprintf(newlog.pool,
"Resetting log file due to error opening "
"new log file, %10d messages lost: %-25.25s\n",
status->nMessCount, error);
truncate_and_write_error(status, message);
/* Throw away new state; it isn't going to be used. */
apr_pool_destroy(newlog.pool);
}
status->nMessCount = 0;
}
/*
* Get a size or time param from a string.
* Parameter 'last' indicates, whether the
* argument is the last commadnline argument.
* UTC offset is only allowed as a last argument
* in order to make is distinguishable from the
* rotation interval time.
*/
static const char *get_time_or_size(rotate_config_t *config,
const char *arg, int last) {
const char *ptr = NULL;
/* Byte multiplier */
unsigned int mult = 1;
if ((ptr = strchr(arg, 'B')) != NULL) { /* Found KB size */
mult = 1;
}
else if ((ptr = strchr(arg, 'K')) != NULL) { /* Found KB size */
mult = 1024;
}
else if ((ptr = strchr(arg, 'M')) != NULL) { /* Found MB size */
mult = 1024 * 1024;
}
else if ((ptr = strchr(arg, 'G')) != NULL) { /* Found GB size */
mult = 1024 * 1024 * 1024;
}
if (ptr) { /* rotation based on file size */
if (config->sRotation > 0) {
return "Rotation size parameter allowed only once";
}
if (*(ptr+1) == '\0') {
config->sRotation = atoi(arg) * mult;
}
if (config->sRotation == 0) {
return "Invalid rotation size parameter";
}
}
else if ((config->sRotation > 0 || config->tRotation > 0) && last) {
/* rotation based on elapsed time */
if (config->use_localtime) {
return "UTC offset parameter is not valid with -l";
}
config->utc_offset = atoi(arg) * 60;
}
else { /* rotation based on elapsed time */
if (config->tRotation > 0) {
return "Rotation time parameter allowed only once";
}
config->tRotation = atoi(arg);
if (config->tRotation <= 0) {
return "Invalid rotation time parameter";
}
}
return NULL;
}
//
// 2019.07.03 - modified by Grigore Stefan <g_stefan@yahoo.com>
//
int applicationMain (int argc, const char * const argv[])
{
char buf[BUFSIZE];
apr_size_t nRead, nWrite;
apr_file_t *f_stdin;
apr_file_t *f_stdout;
apr_getopt_t *opt;
apr_status_t rv;
char c;
const char *opt_arg;
const char *err = NULL;
#if APR_FILES_AS_SOCKETS
apr_pollfd_t pollfd = { 0 };
apr_status_t pollret = APR_SUCCESS;
long polltimeout;
#endif
apr_app_initialize(&argc, &argv, NULL);
atexit(apr_terminate);
memset(&config, 0, sizeof config);
memset(&status, 0, sizeof status);
status.rotateReason = ROTATE_NONE;
apr_pool_create(&status.pool, NULL);
apr_getopt_init(&opt, status.pool, argc, argv);
#if APR_FILES_AS_SOCKETS
while ((rv = apr_getopt(opt, "lL:p:fDtvecn:", &c, &opt_arg)) == APR_SUCCESS) {
#else
while ((rv = apr_getopt(opt, "lL:p:fDtven:", &c, &opt_arg)) == APR_SUCCESS) {
#endif
switch (c) {
case 'l':
config.use_localtime = 1;
break;
case 'L':
config.linkfile = opt_arg;
break;
case 'p':
config.postrotate_prog = opt_arg;
#ifdef SIGCHLD
/* Prevent creation of zombies (on modern Unix systems). */
apr_signal(SIGCHLD, SIG_IGN);
#endif
break;
case 'f':
config.force_open = 1;
break;
case 'D':
config.create_path = 1;
break;
case 't':
config.truncate = 1;
break;
case 'v':
config.verbose = 1;
break;
case 'e':
config.echo = 1;
break;
#if APR_FILES_AS_SOCKETS
case 'c':
config.create_empty = 1;
break;
#endif
case 'n':
config.num_files = atoi(opt_arg);
status.fileNum = -1;
break;
}
}
if (rv != APR_EOF) {
usage(argv[0], NULL /* specific error message already issued */ );
}
/*
* After the initial flags we need 2 to 4 arguments,
* the file name, either the rotation interval time or size
* or both of them, and optionally the UTC offset.
*/
if ((argc - opt->ind < 2) || (argc - opt->ind > 4) ) {
usage(argv[0], "Incorrect number of arguments");
}
rv = apr_filepath_merge(&config.szLogRoot, "", argv[opt->ind++],
APR_FILEPATH_TRUENAME, status.pool);
if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
usage(argv[0], "Invalid filename given");
}
/* Read in the remaining flags, namely time, size and UTC offset. */
for(; opt->ind < argc; opt->ind++) {
if ((err = get_time_or_size(&config, argv[opt->ind],
opt->ind < argc - 1 ? 0 : 1)) != NULL) {
usage(argv[0], err);
}
}
config.use_strftime = (strchr(config.szLogRoot, '%') != NULL);
if (config.use_strftime && config.num_files > 0) {
fprintf(stderr, "Cannot use -n with %% in filename\n");
exit(1);
}
if (status.fileNum == -1 && config.num_files < 1) {
fprintf(stderr, "Invalid -n argument\n");
exit(1);
}
if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) {
fprintf(stderr, "Unable to open stdin\n");
exit(1);
}
if (apr_file_open_stdout(&f_stdout, status.pool) != APR_SUCCESS) {
fprintf(stderr, "Unable to open stdout\n");
exit(1);
}
/*
* Write out result of config parsing if verbose is set.
*/
if (config.verbose) {
dumpConfig(&config);
}
#if APR_FILES_AS_SOCKETS
if (config.create_empty && config.tRotation) {
pollfd.p = status.pool;
pollfd.desc_type = APR_POLL_FILE;
pollfd.reqevents = APR_POLLIN;
pollfd.desc.f = f_stdin;
}
#endif
/*
* Immediately open the logfile as we start, if we were forced
* to do so via '-f'.
*/
if (config.force_open) {
doRotate(&config, &status);
}
for (;;) {
nRead = sizeof(buf);
#if APR_FILES_AS_SOCKETS
if (config.create_empty && config.tRotation) {
polltimeout = status.tLogEnd ? status.tLogEnd - get_now(&config, NULL) : config.tRotation;
if (polltimeout <= 0) {
pollret = APR_TIMEUP;
}
else {
pollret = apr_poll(&pollfd, 1, &pollret, apr_time_from_sec(polltimeout));
}
}
if (pollret == APR_SUCCESS) {
rv = apr_file_read(f_stdin, buf, &nRead);
if (APR_STATUS_IS_EOF(rv)) {
break;
}
else if (rv != APR_SUCCESS) {
exit(3);
}
}
else if (pollret == APR_TIMEUP) {
*buf = 0;
nRead = 0;
}
else {
fprintf(stderr, "Unable to poll stdin\n");
exit(5);
}
#else /* APR_FILES_AS_SOCKETS */
rv = apr_file_read(f_stdin, buf, &nRead);
if (APR_STATUS_IS_EOF(rv)) {
break;
}
else if (rv != APR_SUCCESS) {
exit(3);
}
#endif /* APR_FILES_AS_SOCKETS */
checkRotate(&config, &status);
if (status.rotateReason != ROTATE_NONE) {
doRotate(&config, &status);
}
nWrite = nRead;
rv = apr_file_write_full(status.current.fd, buf, nWrite, &nWrite);
if (nWrite != nRead) {
apr_off_t cur_offset;
apr_pool_t *pool;
char *error;
cur_offset = 0;
if (apr_file_seek(status.current.fd, APR_CUR, &cur_offset) != APR_SUCCESS) {
cur_offset = -1;
}
status.nMessCount++;
apr_pool_create(&pool, status.pool);
error = apr_psprintf(pool, "Error %d writing to log file at offset %"
APR_OFF_T_FMT ". %10d messages lost (%pm)\n",
rv, cur_offset, status.nMessCount, &rv);
truncate_and_write_error(&status, error);
apr_pool_destroy(pool);
}
else {
status.nMessCount++;
}
if (config.echo) {
if (apr_file_write_full(f_stdout, buf, nRead, &nWrite)) {
fprintf(stderr, "Unable to write to stdout\n");
exit(4);
}
}
}
return 0; /* reached only at stdin EOF. */
}
//
// 2019.07.03 - modified by Grigore Stefan <g_stefan@yahoo.com>
// - suport subsytem windows [no console window]
//
#include "xyo.hpp"
int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR cmdLine,int cmdShow)
{
char exeName[MAX_PATH];
int cmdN;
char** cmdS;
int retV;
GetModuleFileName(nullptr,exeName,MAX_PATH);
XYO::Shell::mainArgsSet(exeName,GetCommandLineA(),cmdN,cmdS);
retV=applicationMain(cmdN,cmdS);
XYO::Shell::mainArgsDelete(cmdN,cmdS);
return retV;
}
| 32.288366
| 114
| 0.584423
|
g-stefan
|
4c1714d40ec701830907793939149d0f492a9e12
| 6,015
|
cpp
|
C++
|
arm9/source/level.cpp
|
RocketRobz/Konotsu-Gunner-DS
|
7e8f3d6594c4a02ab431662008f10614a3b6987e
|
[
"MIT"
] | 1
|
2020-02-26T14:39:43.000Z
|
2020-02-26T14:39:43.000Z
|
arm9/source/level.cpp
|
RocketRobz/Konotsu-Gunner-DS
|
7e8f3d6594c4a02ab431662008f10614a3b6987e
|
[
"MIT"
] | null | null | null |
arm9/source/level.cpp
|
RocketRobz/Konotsu-Gunner-DS
|
7e8f3d6594c4a02ab431662008f10614a3b6987e
|
[
"MIT"
] | 1
|
2020-03-04T18:44:02.000Z
|
2020-03-04T18:44:02.000Z
|
#include <nds.h>
#include "gl2d.h"
#include "graphics/fontHandler.h"
#include "graphics/graphics.h"
#include "tonccpy.h"
#include "sound.h"
#include "player.h"
#include "bottomImage.h"
#include "spr_aimbutton.h"
#include "tiles.h"
#include "tilenum.h"
#define bgTile 11
#define grayBlockTile 17
extern bool wideScreen;
extern bool fadeType;
static bool inited = false;
int mapHsize = 32;
int mapVsize = 24;
int cameraXpos = 0;
int cameraYpos = 0;
u8 mapData[32*27] = {7};
extern int playerX[2], playerY[2];
static int tileTexID;
glImage tileImage[(128 / 16) * (128 / 16)];
void levelGraphicLoad(void) {
tileTexID = glLoadTileSet(tileImage, // pointer to glImage array
16, // sprite width
16, // sprite height
128, // bitmap width
128, // bitmap height
GL_RGB256, // texture type for glTexImage2D() in videoGL.h
TEXTURE_SIZE_128, // sizeX for glTexImage2D() in videoGL.h
TEXTURE_SIZE_128, // sizeY for glTexImage2D() in videoGL.h
GL_TEXTURE_WRAP_S | GL_TEXTURE_WRAP_T | TEXGEN_OFF | GL_TEXTURE_COLOR0_TRANSPARENT, // param for glTexImage2D() in videoGL.h
256, // Length of the palette to use (16 colors)
(u16*) tilesPal, // Load our 16 color tiles palette
(u8*) tilesBitmap // image data generated by GRIT
);
}
bool isSolidTile(u8 tile) {
switch (tile) {
case 4:
case 5:
case 6:
case 7:
case 8:
case 13:
case 16:
case 17:
case 20:
case 21:
case 24:
case 25:
case 28:
case 29:
case 33:
case 34:
case 35:
case 36:
case 37:
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
return true;
default:
break;
}
return false;
}
void loadLevel(const char* filename) {
mapHsize = -1;
mapVsize = -1;
toncset(mapData, 0, sizeof(mapData));
off_t klvFileSize = 0;
FILE* klvFile = fopen(filename, "rb");
fseek(klvFile, 0, SEEK_END);
klvFileSize = ftell(klvFile); // Get source file's size
fseek(klvFile, 0, SEEK_SET);
if (klvFileSize == 0) {
return;
}
u8* orgMapData = new u8[klvFileSize];
fread(orgMapData, 1, klvFileSize, klvFile);
fclose(klvFile);
bool mapHsizeSet = false;
bool processTile = false;
int generatedPlayerX = -16;
int i1 = -1; // Position in generated map
int i2 = -1; // Position in kglf file
while (1) {
if (orgMapData[i2] == 'E' && orgMapData[i2+1] == 'N' && orgMapData[i2+2] == 'D') {
break;
} else if ((orgMapData[i2] == 0x0D && orgMapData[i2+1] == 0x0A) || (orgMapData[i2] == 0x0A)) {
if (orgMapData[i2] == 0x0D && orgMapData[i2+1] == 0x0A) {
i2++;
}
mapVsize++;
generatedPlayerX = -16;
mapHsizeSet = true;
} else {
i1++;
processTile = true;
}
generatedPlayerX += 16;
i2++;
if (!mapHsizeSet) {
mapHsize++;
}
if (orgMapData[i2] == '1' || orgMapData[i2] == '2') {
setPlayerPosition((orgMapData[i2] == '2' ? 1 : 0), generatedPlayerX, (mapVsize*16)-16);
} else
if (processTile) {
for (int i3 = 0; i3 < (int)sizeof(textTiles); i3++) {
if (textTiles[i3] == orgMapData[i2]) {
mapData[i1] = i3;
break;
}
}
processTile = false;
}
}
delete[] orgMapData;
}
void levelMode(void) {
if (!inited) {
loadLevel("nitro:/klv/level.klv");
playerGraphicLoad();
decompress(bottomImageBitmap, bgGetGfxPtr(bg3), LZ77Vram);
bgSetScroll(bg3, 0, 0);
bgScroll(bg3, 0, 0);
oamClear(&oamSub, 0, 2);
gfxSub = oamAllocateGfx(&oamSub, SpriteSize_32x64, SpriteColorFormat_16Color);
tonccpy(gfxSub, spr_aimbuttonTiles, spr_aimbuttonTilesLen);
for (int i = 0; i < 16; i++) {
SPRITE_PALETTE_SUB[i] = spr_aimbuttonPal[i];
}
oamSet(&oamSub,
0,
80, 48,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(32*8),
-1,
false,
false,
false, false,
false
);
oamSet(&oamSub,
1,
112, 48,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub,
-1,
false,
false,
false, false,
false
);
oamSet(&oamSub,
2,
144, 48,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(32*8),
-1,
false,
false,
true, false,
false
);
oamSet(&oamSub,
3,
80, 80,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(64*8),
-1,
false,
false,
false, false,
false
);
oamSet(&oamSub,
4,
144, 80,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(64*8),
-1,
false,
false,
true, false,
false
);
oamSet(&oamSub,
5,
80, 112,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(32*8),
-1,
false,
false,
false, true,
false
);
oamSet(&oamSub,
6,
144, 112,
0,
0,
SpriteSize_32x32,
SpriteColorFormat_16Color,
gfxSub+(32*8),
-1,
false,
false,
true, true,
false
);
fadeType = true;
snd().loadStream("nitro:/music/tense.wav", true);
snd().beginStream();
inited = true;
}
scanKeys();
int pressed = keysDown();
int held = keysHeld();
playerLoop(pressed, held);
}
void levelGraphicDisplay(void) {
glBoxFilled(0, 0, (wideScreen ? 308 : 256), 192, RGB15(85/8, 85/8, 255/8));
/*for (int x = 0; x < 256; x += 16) {
for (int y = 0; y < 192; y += 16) {
glSprite(x, y, GL_FLIP_NONE, &tileImage[bgTile]);
}
}*/
//if (mapHsize>16 && playerX>(256/2)) {
cameraXpos = playerX[0]-((wideScreen ? 308 : 256)/2);
/* if (cameraXpos > (mapHsize*16)-256) {
cameraXpos = (mapHsize*16)-256;
}
} else {
cameraXpos = 0;
}*/
//if (mapVsize>12 && playerY>192/2) {
cameraYpos = playerY[0]-(192/2);
/* if (cameraYpos > (mapVsize*16)-192) {
cameraYpos = (mapVsize*16)-192;
}
} else {
cameraYpos = 0;
}*/
for (int x = 0; x < mapHsize; x++) {
for (int y = 0; y < mapVsize; y++) {
if (mapData[(y*mapHsize)+x] != 0) {
glSprite((x*16)-cameraXpos, (y*16)-cameraYpos, GL_FLIP_NONE, &tileImage[mapData[(y*mapHsize)+x]]);
}
}
}
renderPlayer();
}
| 18.974763
| 131
| 0.599501
|
RocketRobz
|
4c1abc47ce27fd4ac8805bda0b50bfb8b2b3a6bc
| 665
|
cpp
|
C++
|
Miracle/src/Miracle/MiracleAppBuilder.cpp
|
McFlyboy/Miracle
|
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
|
[
"MIT"
] | null | null | null |
Miracle/src/Miracle/MiracleAppBuilder.cpp
|
McFlyboy/Miracle
|
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
|
[
"MIT"
] | 3
|
2021-12-10T23:19:29.000Z
|
2022-03-27T05:04:14.000Z
|
Miracle/src/Miracle/MiracleAppBuilder.cpp
|
McFlyboy/Miracle
|
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
|
[
"MIT"
] | null | null | null |
#include <Miracle/components/Miracle/MiracleAppBuilder.hpp>
namespace Miracle {
MiracleAppBuilder& MiracleAppBuilder::configureWindow(std::function<void (View::WindowProps&)> configurer) {
configurer(m_windowProps);
return *this;
}
MiracleAppBuilder& MiracleAppBuilder::setStartScript(std::function<void ()> startScript) {
m_startScript = startScript;
return *this;
}
MiracleAppBuilder& MiracleAppBuilder::setUpdateScript(std::function<void ()> updateScript) {
m_updateScript = updateScript;
return *this;
}
MiracleApp MiracleAppBuilder::build() const {
return MiracleApp(
m_windowProps,
m_startScript,
m_updateScript
);
}
}
| 22.166667
| 109
| 0.754887
|
McFlyboy
|
4c2500db72cf536f5754aceeb1c412e75ade4455
| 1,412
|
cpp
|
C++
|
aoj/1195/main.cpp
|
acm-icpc-training/acm-icpc-training
|
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
|
[
"MIT"
] | null | null | null |
aoj/1195/main.cpp
|
acm-icpc-training/acm-icpc-training
|
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
|
[
"MIT"
] | null | null | null |
aoj/1195/main.cpp
|
acm-icpc-training/acm-icpc-training
|
a4ee0f81a89cfe95b94c3de8521a11d61290bba3
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <unordered_set>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool ProcessCase() {
string encoded;
cin >> encoded;
if (encoded == "#") return false;
unordered_set<string> curr_set;
curr_set.insert(encoded);
unordered_set<string> next_set;
for (int step = 24; step >= 0; step--) {
char after = 'a' + step;
char before = 'a' + step + 1;
for (const string& curr : curr_set) {
bool end = false;
for (int i = 0; i < curr.size(); i++) {
if (curr[i] == before) {
end = true;
break;
}
if (curr[i] == after) {
string next = curr;
next[i] = before;
next_set.insert(next);
}
}
if (!end) {
next_set.insert(curr);
}
}
curr_set.swap(next_set);
next_set.clear();
}
vector<string> answers;
answers.assign(curr_set.begin(), curr_set.end());
sort(answers.begin(), answers.end());
cout << answers.size() << endl;
if (answers.size() <= 10) {
for (int i = 0; i < answers.size(); ++i) {
cout << answers[i] << endl;
}
} else {
for (int i = 0; i < 5; i++) {
cout << answers[i] << endl;
}
for (int i = answers.size() - 5; i < answers.size(); ++i) {
cout << answers[i] << endl;
}
}
return true;
}
int main() {
while (ProcessCase()) {}
return 0;
}
| 21.074627
| 63
| 0.525496
|
acm-icpc-training
|
4c2710bc5685a5c748ce3c4505b334a480be6ce6
| 1,128
|
cpp
|
C++
|
src/Engine.cpp
|
nsierra-/DotEngine
|
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
|
[
"MIT"
] | null | null | null |
src/Engine.cpp
|
nsierra-/DotEngine
|
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
|
[
"MIT"
] | null | null | null |
src/Engine.cpp
|
nsierra-/DotEngine
|
07d0d9bc6cf5238d9e94e6f538298b89d51832e5
|
[
"MIT"
] | null | null | null |
#include "Engine.hpp"
#include "Logger.hpp"
namespace Dot
{
Engine::Engine() :
_running(true),
_window(sf::VideoMode(800, 600), "DotEngine")
{
}
void Engine::handleEvents(void)
{
Logger::debug("Engine - handleEvents()");
_retrieveEvents();
_statesManager.handleEvents(this);
}
void Engine::update(void)
{
Logger::debug("Engine - update()");
_statesManager.update(this);
}
void Engine::draw(void)
{
Logger::debug("Engine - draw()");
_statesManager.draw(this);
}
void Engine::_retrieveEvents(void)
{
sf::Event * tmp = new sf::Event;
_events.clear();
while (_window.pollEvent(*tmp))
{
if (tmp->type == sf::Event::Closed)
{
_running = false;
delete tmp;
return ;
}
_events.push_back(std::unique_ptr<sf::Event>(tmp));
tmp = new sf::Event;
}
delete tmp;
}
void Engine::loop(void)
{
while (_running)
{
handleEvents();
update();
draw();
}
}
void Engine::pushState(AGameState * state) { _statesManager.pushState(state); }
void Engine::popState(void) { _statesManager.popState(); }
bool Engine::isRunning() const { return _running; }
}
| 17.353846
| 80
| 0.640071
|
nsierra-
|
4c276fd69fe70021e55ab4059c738da69f267136
| 2,521
|
cpp
|
C++
|
test_json.cpp
|
6502/jsoncpp
|
934481de03c373ee5299b8f880e0179a9d3a0030
|
[
"MIT"
] | 2
|
2016-10-25T09:31:08.000Z
|
2018-11-10T07:42:29.000Z
|
test_json.cpp
|
6502/jsoncpp
|
934481de03c373ee5299b8f880e0179a9d3a0030
|
[
"MIT"
] | null | null | null |
test_json.cpp
|
6502/jsoncpp
|
934481de03c373ee5299b8f880e0179a9d3a0030
|
[
"MIT"
] | null | null | null |
#include "json.h"
using JSON::Value;
int main() {
Value v;
v["x"][2]["y"] = "Test";
v["a"] = false;
v["b"] = 3.141592654;
Value& vv = v["c"];
vv[0] = 42;
vv[2] = "Foo";
vv[4]["x"] = 10;
vv[4]["y"] = 20;
std::vector< std::vector<int> > vvi(2);
vvi[0].push_back(1);
vvi[0].push_back(2);
vvi[0].push_back(3);
vvi[1].push_back(4);
vvi[1].push_back(5);
vvi[1].push_back(6);
v["c"][5] = vvi;
std::vector< std::vector<int> > vvi_b = v["c"][5];
v["c"][6] = vvi_b;
v["c"][6][0][0] = std::string(v["c"][2]) + "\n";
std::string s = JSON::json(v);
printf("%s\n", s.c_str());
const char *p = s.c_str();
Value v2 = JSON::parse(p);
printf("%s\n", JSON::json(v2).c_str());
Value& path = v["path"];
for (int i=0; i<1000; i++) {
path[i]["x"] = 10.0 / (i+1);
path[i]["y"] = 20.0 / (i+1);
}
{
clock_t start = clock();
for (int i=0; i<1000; i++) {
v["path2"] = v["path"];
}
clock_t stop = clock();
printf("Assignment = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC);
}
{
clock_t start = clock();
for (int i=0; i<1000; i++) {
std::string s = JSON::json(v["path"]);
}
clock_t stop = clock();
printf("obj -> JSON = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC);
}
{
std::string s = JSON::json(v["path"]);
clock_t start = clock();
for (int i=0; i<1000; i++) {
const char *p = s.c_str();
v["path"] = JSON::parse(p);
}
clock_t stop = clock();
printf("JSON -> obj = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC);
printf("data = %i bytes\n", int(s.size()));
}
{
clock_t start = clock();
for (int i=0; i<1000; i++) {
std::vector<unsigned char> buf;
JSON::save(v["path"], buf);
}
clock_t stop = clock();
printf("obj -> buf = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC);
}
{
clock_t start = clock();
std::vector<unsigned char> buf;
JSON::save(v["path"], buf);
for (int i=0; i<1000; i++) {
Value x;
const unsigned char *p = &buf[0];
JSON::load(x, p);
}
clock_t stop = clock();
printf("buf -> obj = %0.3fms\n", double(stop-start) / CLOCKS_PER_SEC);
printf("data = %i bytes\n", int(buf.size()));
}
return 0;
}
| 25.72449
| 79
| 0.455375
|
6502
|
4c295f55b985099b580bdbc8686857ddc049022b
| 189
|
cpp
|
C++
|
258-add-digits/258-add-digits.cpp
|
ComputerScientist-01/SDE-Sheet
|
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
|
[
"MIT"
] | null | null | null |
258-add-digits/258-add-digits.cpp
|
ComputerScientist-01/SDE-Sheet
|
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
|
[
"MIT"
] | null | null | null |
258-add-digits/258-add-digits.cpp
|
ComputerScientist-01/SDE-Sheet
|
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int addDigits(int num) {
// we use the property of 9
if(num == 0) return 0;
if(num % 9 == 0 ) return 9;
return (num%9);
}
};
| 21
| 35
| 0.492063
|
ComputerScientist-01
|
4c2e5c096d5deddf10ce1cb14fc8826ed0c5e871
| 579
|
cpp
|
C++
|
src/env.cpp
|
ibradypod/bradypod
|
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
|
[
"BSD-3-Clause"
] | 3
|
2018-03-05T15:29:42.000Z
|
2018-03-07T01:54:11.000Z
|
src/env.cpp
|
ibradypod/bradypod
|
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
|
[
"BSD-3-Clause"
] | null | null | null |
src/env.cpp
|
ibradypod/bradypod
|
cd3b0bc156d7fccb1b8efb2b02163dca46c366d7
|
[
"BSD-3-Clause"
] | null | null | null |
#include "env.h"
#include <QCoreApplication>
#include <QString>
#include <QVariantMap>
#include <QProcessEnvironment>
static Env* env_instance = NULL;
Env* Env::instance()
{
if (NULL == env_instance) {
env_instance = new Env();
}
return env_instance;
}
Env::Env()
: QObject(QCoreApplication::instance())
{
const QProcessEnvironment& env = QProcessEnvironment::systemEnvironment();
foreach(const QString & key, env.keys()) {
m_map[key] = env.value(key);
}
}
// public:
QVariantMap Env::asVariantMap() const
{
return m_map;
}
| 17.029412
| 78
| 0.658031
|
ibradypod
|
4c32df3f96185150890e6b58f2b995ed6470d32e
| 463
|
cpp
|
C++
|
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | 2
|
2021-03-05T22:32:23.000Z
|
2021-03-05T22:32:29.000Z
|
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | null | null | null |
Questions Level-Wise/Medium/count-nice-pairs-in-an-array.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int rev(int num)
{
int t=0;
while(num>0)
t=(t*10)+(num%10),num/=10;
return t;
}
int countNicePairs(vector<int>& nums)
{
int c=0;
unordered_map<int,int> x;
for(int i=0;i<nums.size();i++)
x[nums[i]-rev(nums[i])]++;
for(auto e: x)
c=(c+((((long)e.second*(long)(e.second-1))/2)%1000000007))%1000000007;
return c;
}
};
| 23.15
| 82
| 0.464363
|
PrakharPipersania
|
4c3370c1c627b7857e4423d1aeaf009ac6d23811
| 2,219
|
cpp
|
C++
|
projects/acommandline/test/repeated_test.cpp
|
agnesoft/adev-alt
|
3df0329939e3048bbf5db252efb5f74de9c0f061
|
[
"Apache-2.0"
] | null | null | null |
projects/acommandline/test/repeated_test.cpp
|
agnesoft/adev-alt
|
3df0329939e3048bbf5db252efb5f74de9c0f061
|
[
"Apache-2.0"
] | 136
|
2020-03-29T11:15:38.000Z
|
2020-10-14T06:21:23.000Z
|
projects/acommandline/test/repeated_test.cpp
|
agnesoft/adev-alt
|
3df0329939e3048bbf5db252efb5f74de9c0f061
|
[
"Apache-2.0"
] | 1
|
2020-08-04T09:56:53.000Z
|
2020-08-04T09:56:53.000Z
|
import atest;
import acommandline;
using ::atest::expect;
using ::atest::suite;
using ::atest::test;
static const auto S = suite("repeated", [] { // NOLINT(cert-err58-cpp)
test("single named", [] {
std::stringstream stream;
::acommandline::CommandLine commandLine{stream};
std::vector<std::string> values;
commandLine.option().long_name("name1").description("").bind_to(&values);
expect(commandLine.parse(2, std::array<const char *, 2>{"./app", "--name1=val"}.data())).to_be(true);
expect(values).to_be(std::vector<std::string>{"val"});
});
test("named", [] {
std::stringstream stream;
::acommandline::CommandLine commandLine{stream};
std::vector<double> values;
static constexpr int argc = 7;
commandLine.option().long_name("value").short_name('v').description("").bind_to(&values);
expect(commandLine.parse(argc, std::array<const char *, argc>{"./app", "-v", "33.3", "--value=51.61234", "-v=9.999", "-v", "19.19"}.data())).to_be(true);
expect(values).to_be(std::vector{33.3, 51.61234, 9.999, 19.19}); // NOLINT(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)
});
test("single positional", [] {
std::stringstream stream;
::acommandline::CommandLine commandLine{stream};
std::vector<std::int64_t> values;
commandLine.option().positional().description("").bind_to(&values);
expect(commandLine.parse(2, std::array<const char *, 2>{"./app", "1350"}.data())).to_be(true);
expect(values).to_be(std::vector<std::int64_t>{1350}); // NOLINT(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)
});
test("positional", [] {
std::stringstream stream;
::acommandline::CommandLine commandLine{stream};
std::vector<std::string> values;
commandLine.option().positional().default_value(std::vector<std::string>{"input"}).description("").bind_to(&values);
expect(commandLine.parse(4, std::array<const char *, 4>{"./app", "input1", "input2", "input3"}.data())).to_be(true);
expect(values).to_be(std::vector<std::string>{"input1", "input2", "input3"});
});
});
| 38.929825
| 161
| 0.626408
|
agnesoft
|
4c3984bc3005960c087f0b4d701a9d4caba60fda
| 1,057
|
cc
|
C++
|
cpp/leetcode/451.sort-characters-by-frequency.cc
|
liubang/laboratory
|
747f239a123cd0c2e5eeba893b9a4d1536555b1e
|
[
"MIT"
] | 3
|
2021-03-03T13:18:23.000Z
|
2022-02-09T07:49:24.000Z
|
cpp/leetcode/451.sort-characters-by-frequency.cc
|
liubang/laboratory
|
747f239a123cd0c2e5eeba893b9a4d1536555b1e
|
[
"MIT"
] | null | null | null |
cpp/leetcode/451.sort-characters-by-frequency.cc
|
liubang/laboratory
|
747f239a123cd0c2e5eeba893b9a4d1536555b1e
|
[
"MIT"
] | 1
|
2021-03-29T15:21:42.000Z
|
2021-03-29T15:21:42.000Z
|
#include <gtest/gtest.h>
#include <algorithm>
#include <string>
#include <unordered_map>
namespace {
class Solution {
public:
std::string frequencySort(const std::string& s) {
std::unordered_map<char, int> charcount;
for (auto& ch : s) {
charcount[ch]++;
}
std::vector<std::pair<char, int>> v(charcount.begin(), charcount.end());
std::sort(v.begin(), v.end(), [](const auto& lhs, const auto& rhs) {
return lhs.second > rhs.second;
});
std::string ret;
for (auto& p : v) {
ret.append(p.second, p.first);
}
return ret;
}
};
} // namespace
TEST(Leetcode, sort_characters_by_frequency) {
Solution s;
{
std::string input = "tree";
auto ret = s.frequencySort(input);
EXPECT_TRUE(ret == "eetr" || ret == "eert");
}
{
std::string input = "cccaaa";
auto ret = s.frequencySort(input);
EXPECT_TRUE(ret == "cccaaa" || ret == "aaaccc");
}
{
std::string input = "Aabb";
auto ret = s.frequencySort(input);
EXPECT_TRUE(ret == "bbaA" || ret == "bbAa");
}
}
| 22.978261
| 76
| 0.589404
|
liubang
|
4c3be975324d4c979442a56019d9e3ddc8edb0c8
| 567
|
cpp
|
C++
|
src/cells/src/lib/logic/effect/buff/Slow.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | null | null | null |
src/cells/src/lib/logic/effect/buff/Slow.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | 15
|
2021-05-18T14:16:03.000Z
|
2021-06-17T19:36:32.000Z
|
src/cells/src/lib/logic/effect/buff/Slow.cpp
|
SimonPiCarter/GameEngine
|
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
|
[
"Apache-2.0"
] | null | null | null |
#include "Slow.h"
#include <cassert>
#include "logic/entity/MobEntity.h"
Slow::Slow(MobEntity * target_p, std::string id_p, double spawntime_p, double duration_p, double slow_p, unsigned long maxStack_p)
: BuffTimer(target_p, id_p, spawntime_p, duration_p, maxStack_p)
, _slow(slow_p)
{
assert(_slow > 1e-5);
assert(_slow < 1.-1e-5);
}
void Slow::applyBuff()
{
_mobTarget->setSpeed(_mobTarget->getSpeed() * (1.-std::min(0.99,(_slow*_stack))));
}
void Slow::revertBuff()
{
_mobTarget->setSpeed(_mobTarget->getSpeed() * (1.-std::min(0.99,(_slow*_stack))));
}
| 24.652174
| 130
| 0.705467
|
SimonPiCarter
|
4c410d1d29d3a9598e009809b2aca084df0c1b48
| 893
|
cpp
|
C++
|
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 108
|
2021-03-29T05:04:16.000Z
|
2022-03-19T15:11:52.000Z
|
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | null | null | null |
Problem Solving/Data Structures/Linked Lists/Find Merge Point of Two Lists/find merge point of two lists.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 32
|
2021-03-30T03:56:54.000Z
|
2022-03-27T14:41:32.000Z
|
/* Author: Isaac Asante
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem
* Original video explanation: https://www.youtube.com/watch?v=PUMCc5GPn1Q
* Last verified on: March 28, 2021
*/
/* IMPORTANT:
* This code is meant to be used as a solution on HackerRank (link above).
* It is not meant to be executed as a standalone program.
*/
// Complete the findMergeNode function below.
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode* first = head1;
SinglyLinkedListNode* second = head2;
while (first != second) {
first = first->next;
second = second->next;
// Restart when necessary
if (!first) first = head1;
if (!second) second = head2;
}
return first->data; // first and second are the same
}
| 34.346154
| 130
| 0.693169
|
IsaacAsante
|
4c417224f883b73130aba6d98bc4b1db7c73d838
| 4,501
|
hpp
|
C++
|
src/read_set.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 33
|
2015-07-13T03:00:01.000Z
|
2021-03-20T08:49:07.000Z
|
src/read_set.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 9
|
2016-11-29T00:04:30.000Z
|
2020-02-10T17:46:01.000Z
|
src/read_set.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 6
|
2015-09-10T15:49:34.000Z
|
2017-03-09T05:14:06.000Z
|
#ifndef ISOLATOR_READ_SET_HPP
#define ISOLATOR_READ_SET_HPP
#include <boost/iterator/iterator_facade.hpp>
#include <boost/unordered_map.hpp>
#include <vector>
#include "common.hpp"
#include "hat-trie/hat-trie.h"
#include "samtools/sam.h"
#include "samtools/samtools_extra.h"
#include "transcripts.hpp"
/* A representation of an aligned sequence. */
struct Alignment
{
Alignment();
Alignment(const Alignment& other);
Alignment(const bam1_t* other);
~Alignment();
bool operator == (const bam1_t* b) const;
bool operator != (const bam1_t* b) const;
bool operator == (const Alignment& other) const;
bool operator < (const Alignment& other) const;
pos_t start;
pos_t end;
bool paired;
uint16_t cigar_len;
uint32_t* cigar;
uint8_t strand;
uint16_t alnnum;
float misaligned_pr;
};
struct AlignmentPtrCmp
{
bool operator () (const Alignment* a, const Alignment* b) const
{
return *a < *b;
}
};
/* A single cigar operation. */
struct Cigar
{
uint8_t op;
pos_t start;
pos_t end;
};
/* Iterate through cigar operations in an alignment.. */
class CigarIterator :
public boost::iterator_facade<CigarIterator,
const Cigar,
boost::forward_traversal_tag>
{
public:
CigarIterator();
CigarIterator(const Alignment&);
private:
friend class boost::iterator_core_access;
void increment();
bool equal(const CigarIterator& other) const;
const Cigar& dereference() const;
const Alignment* owner;
size_t i;
Cigar c;
};
/* A read with some number of alignments. */
struct AlignedRead
{
AlignedRead();
~AlignedRead();
bool operator < (const AlignedRead& other) const;
pos_t start, end;
bool paired;
std::vector<Alignment*> mate1;
std::vector<Alignment*> mate2;
};
/* A pair of alignments. (One for each mate.) */
struct AlignmentPair
{
AlignmentPair();
AlignmentPair(const AlignmentPair& other);
bool operator == (const AlignmentPair& other) const;
bool operator < (const AlignmentPair& other) const;
bool valid_frag() const;
/* Fragment length, assuming the read-pair originated from the given
* transcript.
*
* Returns 0 if the pair lacks a mate so that so not no estimate can be
* made.
*
* Return <0 if the pair is incompatible with the trascript. */
pos_t frag_len(const Transcript& t) const;
/* The fragment length of a paired-end read, ignoring the effects of
* splicing. */
pos_t naive_frag_len() const;
/* Orientation of the read. */
strand_t strand() const;
const Alignment* mate1;
const Alignment* mate2;
// Return the amount of soft-clipping on the ends of the fragment
std::pair<pos_t, pos_t> flanks_soft_clipping() const;
};
/* Iterate of the cartesian product of mate alignment. */
class AlignedReadIterator :
public boost::iterator_facade<AlignedReadIterator,
const AlignmentPair,
boost::forward_traversal_tag>
{
public:
AlignedReadIterator();
AlignedReadIterator(const AlignedRead&);
~AlignedReadIterator();
private:
friend class boost::iterator_core_access;
void increment();
bool equal(const AlignedReadIterator& other) const;
bool finished() const;
const AlignmentPair& dereference() const;
const AlignedRead* r;
size_t i, j;
AlignmentPair p;
};
/* A container for a set of reads indexed by id. */
class ReadSet
{
public:
ReadSet();
~ReadSet();
/* Add an alignment to the read set. */
void add_alignment(long idx, const bam1_t* b);
/* Make the set empty. Free memory. */
void clear();
size_t size() const;
/* Map aligned reads to number of occurances. */
struct UniqueReadCountsCmp
{
bool operator () (AlignedRead* const& a, AlignedRead* const& b) const
{
return *a < *b;
}
};
typedef std::map<AlignedRead*, unsigned int, UniqueReadCountsCmp>
UniqueReadCounts;
/* Make a unique read count from the read set. */
void make_unique_read_counts(UniqueReadCounts& counts);
boost::unordered_map<long, AlignedRead*> rs;
};
#endif
| 23.321244
| 81
| 0.623639
|
dcjones
|
4c436c434537e6a9b906a1a0c48187e7b294f98f
| 20,984
|
cpp
|
C++
|
src/main.cpp
|
MarkZH/Genetic_Chess
|
1e07cf0b3bbe87936820844edb322a3fd85f8155
|
[
"MIT"
] | 9
|
2019-08-01T14:42:38.000Z
|
2021-09-03T17:49:37.000Z
|
src/main.cpp
|
MarkZH/Genetic_Chess
|
1e07cf0b3bbe87936820844edb322a3fd85f8155
|
[
"MIT"
] | 107
|
2016-05-22T14:28:08.000Z
|
2022-03-31T08:27:27.000Z
|
src/main.cpp
|
MarkZH/Genetic_Chess
|
1e07cf0b3bbe87936820844edb322a3fd85f8155
|
[
"MIT"
] | 3
|
2017-12-13T04:15:42.000Z
|
2021-07-17T20:59:00.000Z
|
#include <iostream>
#include <memory>
#include <fstream>
#include <cctype>
#include <algorithm>
#include <string>
#include <stdexcept>
#include <utility>
#include "Game/Game.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Players/Minimax_AI.h"
#include "Players/Iterative_Deepening_AI.h"
#include "Players/Random_AI.h"
#include "Genes/Gene_Pool.h"
#include "Utility/Exceptions.h"
#include "Utility/String.h"
#include "Testing.h"
//! \file
namespace
{
//! \brief Print the command-line options for this program.
void print_help();
//! \brief Confirm that all moves in a PGN game record are legal moves.
//!
//! \param file_name The name of the file with the PGN game records. All games will be examined.
bool confirm_game_record(const std::string& file_name);
//! \brief Starts a single game according to command line options.
//!
//! \param argc The number of command line options (same as for main(int argc, char *argv[])).
//! \param argv The command line options (same as for main(int argc, char *argv[])).
void start_game(int argc, char* argv[]);
//! \brief Reads a genome file and rewrites it in the latest style.
//!
//! \param file_name The name of the file to update.
//! \exception Genetic_AI_Creation_Error or derivative if the genome file is invalid.
void update_genome_file(const std::string& file_name);
//! \brief Throws std::invalid_argument if assertion fails
//!
//! \param condition A condition that must be true to continue.
//! \param failure_message A message to display if the assertion fails.
void argument_assert(bool condition, const std::string& failure_message);
}
//! \brief The starting point for the whole program.
//!
//! \param argc The number of command-line arguments.
//! \param argv The command-line arguments. See print_help() (or run the program
//! with no arguments) for a listing of all the options.
//! \returns EXIT_SUCCESS or EXIT_FAILURE.
int main(int argc, char *argv[])
{
if(argc <= 1)
{
print_help();
return EXIT_SUCCESS;
}
try
{
const std::string option = argv[1];
if(option == "-gene-pool")
{
argument_assert(argc > 2, "Specify a configuration file to run a gene pool.");
gene_pool(argv[2]);
}
else if(option == "-confirm")
{
argument_assert(argc > 2, "Provide a file containing a game to confirm has all legal moves.");
return confirm_game_record(argv[2]) ? EXIT_SUCCESS : EXIT_FAILURE;
}
else if(option == "-test")
{
return run_tests() ? EXIT_SUCCESS : EXIT_FAILURE;
}
else if(option == "-speed")
{
run_speed_tests();
}
else if(option == "-perft")
{
return run_perft_tests() ? EXIT_SUCCESS : EXIT_FAILURE;
}
else if(option == "-update")
{
argument_assert(argc > 2, "Provide a file containing Genetic AI data.");
update_genome_file(argv[2]);
}
else
{
start_game(argc, argv);
}
}
catch(const std::exception& e)
{
std::cerr << "\nERROR: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
namespace
{
void print_help()
{
std::cout << "\n\nGenetic Chess\n"
<< "=============\n\n"
<< "Standalone functions (only first is run if multiple are specified):\n\n"
<< "\t-gene-pool [file name]\n"
<< "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name.\n\n"
<< "\t-confirm [filename]\n"
<< "\t\tCheck a file containing PGN game records for any illegal moves\n\t\tor mismarked checks or checkmates.\n\n"
<< "\t-test\n"
<< "\t\tRun tests to ensure various parts of the program function\n\t\tcorrectly.\n\n"
<< "\t-speed\n"
<< "\t\tRun a speed test for gene scoring and boad move submission.\n\n"
<< "\t-perft\n"
<< "\t\tRun a legal move generation test.\n\n"
<< "\t-update [filename]\n"
<< "\t\tIf genetic_chess has changed how genomes are written, use\n\t\tthis option to update the file to the latest format.\n\n"
<< "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP/xboard or UCI command from a GUI\nto start playing.\n\n"
<< "\t-genetic-minimax [filename [number]]\n"
<< "\t\tSelect a minimaxing genetic AI player for a game. Optional file name\n\t\tand ID number to load an AI from a file.\n\n"
<< "\t-genetic-iterative [filename [number]]\n"
<< "\t\tSelect an iteratively deepening minimax genetic AI player for the game.\n\t\tOptional file name and ID number to\n\t\tload an AI from a file.\n\n"
<< "\t-random\n"
<< "\t\tSelect a player that makes random moves for a game.\n\n"
<< "Other game options:\n\n"
<< "\t-time [number]\n"
<< "\t\tSpecify the time (in seconds) each player has to play the game\n\t\tor to make a set number of moves (see -reset_moves option).\n\n"
<< "\t-reset-moves [number]\n"
<< "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock adds the initial time every time this\n\t\tnumber of moves is made.\n\n"
<< "\t-increment-time [number]\n"
<< "\t\tSpecify seconds to add to time after each move.\n\n"
<< "\t-board [FEN string]\n"
<< "\t\tSpecify the starting board state using FEN notation. The entire\n\t\tstring should be quoted.\n\n"
<< "\t-event [name]\n"
<< "\t\tAn optional name for the game to be played. This name will be\n\t\twritten to the PGN game record.\n\n"
<< "\t-location [name]\n"
<< "\t\tAn optional location for the game to be played. This will be\n\t\twritten to the PGN game record.\n\n"
<< "\t-game-file [file name]\n"
<< "\t\tSpecify the name of the file where the game record should be\n\t\twritten. If none, record is printed to stdout.\n\n"
<< "All game options in this section can be overriden by GUI commands except\n-short-post, -event, -location, and -game-file.\n\n";
}
bool confirm_game_record(const std::string& file_name)
{
auto input = std::ifstream(file_name);
if( ! input)
{
throw std::runtime_error("Could not open file " + file_name + " for reading.");
}
auto line_number = 0;
auto last_move_line_number = 0;
auto expected_winner = Winner_Color::NONE;
auto expect_checkmate = true;
auto expect_fifty_move_draw = false;
auto expect_threefold_draw = false;
auto in_game = false;
Board board;
Game_Result result;
for(std::string line; std::getline(input, line);)
{
++line_number;
line = String::remove_pgn_comments(line);
if(line.empty())
{
continue;
}
// Start header of new game
if(in_game && String::starts_with(line, "["))
{
if(expect_fifty_move_draw != String::contains(result.ending_reason(), "50"))
{
std::cerr << "Header indicates 50-move draw, but last move did not trigger rule (line: " << last_move_line_number << ")." << std::endl;
return false;
}
if(expect_threefold_draw != String::contains(result.ending_reason(), "fold"))
{
std::cerr << "Header indicates threefold draw, but last move did not trigger rule (line: " << last_move_line_number << ")." << std::endl;
return false;
}
expected_winner = Winner_Color::NONE;
expect_checkmate = true;
expect_fifty_move_draw = false;
expect_threefold_draw = false;
in_game = false;
board = Board();
result = {};
}
if(String::starts_with(line, "[Result"))
{
if(String::contains(line, "1-0"))
{
expected_winner = Winner_Color::WHITE;
}
else if(String::contains(line, "0-1"))
{
expected_winner = Winner_Color::BLACK;
}
else if(String::contains(line, "1/2-1/2"))
{
expect_checkmate = false;
}
else if(String::contains(line, '*'))
{
expect_checkmate = false;
}
else
{
std::cerr << "Malformed Result: " << line << " (line: " << line_number << ")" << std::endl;
return false;
}
}
else if(String::starts_with(line, "[Termination"))
{
expect_checkmate = false;
if(String::contains(line, "fold"))
{
expect_threefold_draw = true;
}
else if(String::contains(line, "50"))
{
expect_fifty_move_draw = true;
}
}
else if(String::starts_with(line, "[FEN"))
{
board = Board(String::split(line, "\"").at(1));
}
else if(String::starts_with(line, "["))
{
continue;
}
else // Line contains game moves
{
in_game = true;
std::string move_number;
for(const auto& move : String::split(line))
{
if(move.back() == '.')
{
move_number = move + ' ';
continue;
}
if(board.whose_turn() == Piece_Color::BLACK)
{
move_number += "... ";
}
if((move == "1/2-1/2" && expected_winner != Winner_Color::NONE) ||
(move == "1-0" && expected_winner != Winner_Color::WHITE) ||
(move == "0-1" && expected_winner != Winner_Color::BLACK) ||
(move == "*" && expected_winner != Winner_Color::NONE))
{
std::cerr << "Final result mark (" << move << ") does not match game result. (line: " << line_number << ")" << std::endl;
return false;
}
if(move == "1/2-1/2" || move == "1-0" || move == "0-1" || move == "*")
{
continue;
}
try
{
const auto move_checkmates = move.back() == '#';
const auto move_checks = move_checkmates || move.back() == '+';
const auto& move_to_play = board.interpret_move(move);
last_move_line_number = line_number;
if(String::contains(move, 'x')) // check that move captures
{
if( ! std::as_const(board).piece_on_square(move_to_play.end()) && ! move_to_play.is_en_passant())
{
std::cerr << "Move: " << move_number << move << " indicates capture but does not capture. (line: " << line_number << ")" << std::endl;
return false;
}
}
result = board.play_move(move_to_play);
if(move_checks)
{
if( ! board.king_is_in_check())
{
std::cerr << "Move (" << move_number << move << ") indicates check but does not check. (line: " << line_number << ")" << std::endl;
return false;
}
}
else
{
if(board.king_is_in_check())
{
std::cerr << "Move (" << move_number << move << ") indicates no check but does check. (line: " << line_number << ")" << std::endl;
return false;
}
}
if(move_checkmates)
{
if(result.winner() != static_cast<Winner_Color>(opposite(board.whose_turn())))
{
std::cerr << "Move (" << move_number << move << ") indicates checkmate, but move does not checkmate. (line: " << line_number << ")" << std::endl;
return false;
}
if( ! expect_checkmate)
{
std::cerr << "Game ends in checkmate, but this is not indicated in headers. (line: " << line_number << ")" << std::endl;
return false;
}
}
else
{
if(result.winner() != Winner_Color::NONE)
{
std::cerr << "Move (" << move_number << move << ") does not indicate checkmate, but move does checkmate. (line: " << line_number << ")" << std::endl;
return false;
}
}
}
catch(const Illegal_Move& error)
{
std::cerr << "Move (" << move_number << move << ") is illegal: "
<< error.what()
<< ". (line: " << line_number << ")" << std::endl;
std::cerr << "Legal moves: ";
for(const auto legal_move : board.legal_moves())
{
std::cerr << legal_move->algebraic(board) << " ";
}
std::cerr << std::endl;
std::cerr << board.fen() << std::endl;
return false;
}
}
}
}
return true;
}
void start_game(int argc, char* argv[])
{
// Use pointers since each player could be Genetic, Random, etc.
std::unique_ptr<Player> white;
std::unique_ptr<Player> black;
std::unique_ptr<Player> latest;
Clock::seconds game_time{};
size_t moves_per_reset = 0;
Clock::seconds increment_time{};
Board board;
std::string game_file_name;
std::string event_name;
std::string location;
auto thinking_output = Thinking_Output_Type::NO_THINKING;
for(int i = 1; i < argc; ++i)
{
const std::string opt = argv[i];
if(opt == "-random")
{
latest = std::make_unique<Random_AI>();
}
else if(opt == "-genetic-minimax")
{
argument_assert(i + 1 < argc, "Genome file needed for Genetic AI player");
std::string filename = argv[++i];
try
{
const auto id = i + 1 < argc ? argv[i + 1] : std::string{};
latest = std::make_unique<Minimax_AI>(filename, String::to_number<int>(id));
++i;
}
catch(const std::invalid_argument&) // Could not convert id to an int.
{
latest = std::make_unique<Minimax_AI>(filename, find_last_id(filename));
}
}
else if(opt == "-genetic-iterative")
{
argument_assert(i + 1 < argc, "Genome file needed for Genetic AI player");
std::string filename = argv[++i];
try
{
const auto id = i + 1 < argc ? argv[i + 1] : std::string{};
latest = std::make_unique<Iterative_Deepening_AI>(filename, String::to_number<int>(id));
++i;
}
catch(const std::invalid_argument&) // Could not convert id to an int.
{
latest = std::make_unique<Iterative_Deepening_AI>(filename, find_last_id(filename));
}
}
else if(opt == "-time" && i + 1 < argc)
{
game_time = String::to_duration<Clock::seconds>(argv[++i]);
}
else if(opt == "-reset-moves" && i + 1 < argc)
{
moves_per_reset = String::to_number<size_t>(argv[++i]);
}
else if(opt == "-increment-time" && i + 1 < argc)
{
increment_time = String::to_duration<Clock::seconds>(argv[++i]);
}
else if(opt == "-board" && i + 1 < argc)
{
board = Board(argv[++i]);
}
else if(opt == "-game-file" && i + 1 < argc)
{
game_file_name = argv[++i];
}
else if(opt == "-event" && i + 1 < argc)
{
event_name = argv[++i];
}
else if(opt == "-location" && i + 1 < argc)
{
location = argv[++i];
}
else if(opt == "-xboard")
{
thinking_output = Thinking_Output_Type::CECP;
}
else if(opt == "-uci")
{
thinking_output = Thinking_Output_Type::UCI;
}
else
{
throw std::invalid_argument("Invalid or incomplete game option: " + opt);
}
if(latest)
{
if( ! white)
{
white = std::move(latest);
}
else if( ! black)
{
black = std::move(latest);
}
else
{
throw std::invalid_argument("More than two players specified.");
}
}
}
if( ! white)
{
throw std::invalid_argument("At least one player must be specified.");
}
if( ! black)
{
play_game_with_outsider(*white, event_name, location, game_file_name);
}
else
{
board.set_thinking_mode(thinking_output);
play_game(board,
Clock(game_time, moves_per_reset, increment_time, Time_Reset_Method::ADDITION, board.whose_turn()),
*white, *black,
event_name,
location,
game_file_name);
}
}
void update_genome_file(const std::string& file_name)
{
auto input = std::ifstream(file_name);
std::vector<int> id_list;
for(std::string line; std::getline(input, line);)
{
if(String::starts_with(line, "ID:"))
{
id_list.push_back(String::to_number<int>(String::split(line, ":", 1).back()));
}
}
input = std::ifstream(file_name);
const auto output_file_name = String::add_to_file_name(file_name, "-updated");
auto output = std::ofstream(output_file_name);
std::cout << "Writing to: " << output_file_name << std::endl;
for(auto id : id_list)
{
try
{
Genetic_AI(input, id).print(output);
}
catch(const Genetic_AI_Creation_Error& e)
{
std::cerr << e.what() << '\n';
}
}
}
void argument_assert(const bool condition, const std::string& failure_message)
{
if( ! condition)
{
throw std::invalid_argument(failure_message);
}
}
}
| 39.22243
| 275
| 0.468643
|
MarkZH
|
4c477a5cf79b4be9d463acfb54ce565b4d909723
| 959
|
cc
|
C++
|
tests/proto_worker.cc
|
acs-network/MCC
|
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
|
[
"BSD-3-Clause"
] | 5
|
2022-03-04T06:57:43.000Z
|
2022-03-30T08:45:42.000Z
|
tests/proto_worker.cc
|
acs-network/MCC
|
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
|
[
"BSD-3-Clause"
] | null | null | null |
tests/proto_worker.cc
|
acs-network/MCC
|
808e8f27a5a875331f2d54b99c83d4720f2c9bb9
|
[
"BSD-3-Clause"
] | 2
|
2022-03-04T07:19:13.000Z
|
2022-03-04T07:23:58.000Z
|
#include "proto/mcc.pb.h"
#include "application.h"
#include "reactor.h"
#include "tcp_server.h"
using namespace infgen;
namespace bpo = boost::program_options;
int main(int argc, char* argv[]) {
application app;
app.add_options()
("client-id,n", bpo::value<unsigned>()->default_value(0), "client id");
app.run(argc, argv, [&app]() {
// worker node
auto &config = app.configuration();
auto id = config["client-id"].as<unsigned>();
ipv4_addr addr("10.30.10.233", 2222);
pin_this_thread(1);
auto conn = engine().connect(make_ipv4_address(addr));
conn->when_ready([&](const connptr& conn) {
report r;
r.set_client_id(id);
report::notice* n = r.mutable_note();
n->set_online(true);
std::string packet;
if (!r.SerializeToString(&packet)) {
app_logger.error("serialize message failed");
exit(-1);
}
conn->send_packet(packet);
});
engine().run();
});
}
| 27.4
| 75
| 0.618352
|
acs-network
|
4c47ffd057e8d17bf3da03f0f9e399a9055e9775
| 229
|
cpp
|
C++
|
native_libs/src/ValueHolder.cpp
|
mwu-tow/Dataframes
|
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
|
[
"MIT"
] | 4
|
2019-05-09T17:25:29.000Z
|
2019-10-30T21:22:14.000Z
|
native_libs/src/ValueHolder.cpp
|
mwu-tow/Dataframes
|
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
|
[
"MIT"
] | 94
|
2018-07-09T19:02:56.000Z
|
2019-03-29T13:30:39.000Z
|
native_libs/src/ValueHolder.cpp
|
mwu-tow/Dataframes
|
fd82802fe9b490cee9ac7be9aee0f5cc2e1fba28
|
[
"MIT"
] | 3
|
2019-05-16T21:05:39.000Z
|
2020-06-19T14:36:33.000Z
|
#include "ValueHolder.h"
#include <utility>
const char * ValueHolder::store(std::string s)
{
buffer = std::move(s);
return buffer.c_str();
}
void ValueHolder::clear()
{
buffer.clear();
buffer.shrink_to_fit();
}
| 15.266667
| 46
| 0.650655
|
mwu-tow
|
4c4ef384bb0ab01432660c8f155c5409c543a8f3
| 1,631
|
cpp
|
C++
|
src/Crypt.cpp
|
thomaseolsen/SpaceMonopoly
|
96eb22111f3584b972e71b3880ee91314d9fd0cd
|
[
"MIT"
] | null | null | null |
src/Crypt.cpp
|
thomaseolsen/SpaceMonopoly
|
96eb22111f3584b972e71b3880ee91314d9fd0cd
|
[
"MIT"
] | null | null | null |
src/Crypt.cpp
|
thomaseolsen/SpaceMonopoly
|
96eb22111f3584b972e71b3880ee91314d9fd0cd
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
#include <vcl\vcl.h>
#pragma hdrstop
#include "crypt.h"
//---------------------------------------------------------------------------
/*****************************************************************************
* crypt -- encrypt and decrypt functions used to encrypt and decrypt arrays *
* of characters using arrays of characters! *
* *
* Author: David Vivash *
* Created: 6-Jul-1998 *
*****************************************************************************/
//-----------------------------------------------
void encrypt(unsigned char *buffer, unsigned char *passbuf,int size1, int size2)
{
int j=0; /* Counter for passbuf */
for (int i=0; i<(size1); ++i)
{
//if((buffer[i] += passbuf[j])>255) buffer[i] -= 256;
if ((256-passbuf[j])<=buffer[i])
buffer[i]-=(256-passbuf[j]);
else buffer[i]+=passbuf[j];
//buffer[i] += passbuf[j];
++j;
if (j==size2) j=0;
}
}
//------------------------------------------
void decrypt(unsigned char *buffer, unsigned char *passbuf,int size1, int size2)
{
int j=0;
for (int i=0; i<(size1); ++i)
{
//if((buffer[i] -= passbuf[j])<0) buffer[i] += 256;
if (buffer[i]>passbuf[j])
buffer[i] -= passbuf[j];
else buffer[i]+=(256-passbuf[j]);
//buffer[i] -= passbuf[j];
++j;
if (j==size2) j=0;
}
}
//---------------
| 33.979167
| 81
| 0.351318
|
thomaseolsen
|
4c570b3d079bc038581b4359cbf08f4267f96251
| 7,901
|
cpp
|
C++
|
src/native/Utils.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | 2
|
2020-09-04T07:19:24.000Z
|
2020-10-08T11:36:58.000Z
|
src/native/Utils.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | null | null | null |
src/native/Utils.cpp
|
sx-aurora-test/rv
|
5d546958b155d7349b20a8cbbeff1b4c65589fd7
|
[
"Apache-2.0"
] | 1
|
2022-01-25T07:01:35.000Z
|
2022-01-25T07:01:35.000Z
|
//===- Utils.cpp -----------------------------===//
//
// The Region Vectorizer
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// @author montada
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Constants.h>
#include <utils/rvTools.h>
#include "Utils.h"
#include "NatBuilder.h"
using namespace llvm;
using namespace rv;
Type *getVectorType(Type *type, unsigned width) {
if (type->isVoidTy())
return type;
else
return FixedVectorType::get(type, width);
}
Value *createContiguousVector(unsigned width, Type *type, int start, int stride) {
std::vector<Constant*> constants(width, nullptr);
for (unsigned i = 0; i < width; ++i) {
unsigned int val = i*stride + start;
Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, val) : ConstantInt::get(type, val);
constants[i] = constant;
}
return ConstantVector::get(constants);
}
llvm::Value *getConstantVector(unsigned width, Type *type, unsigned value) {
Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, value)
: ConstantInt::get(type, value);
return getConstantVector(width, constant);
}
llvm::Value *getConstantVector(unsigned width, Constant *constant) {
std::vector<Constant *> constants;
constants.reserve(width);
for (unsigned i = 0; i < width; ++i) {
constants.push_back(constant);
}
return ConstantVector::get(constants);
}
Value *getConstantVectorPadded(unsigned width, Type *type, std::vector<unsigned> &values, bool padWithZero) {
std::vector<Constant *> constants(width, nullptr);
unsigned i = 0;
for (; i < values.size(); ++i) {
Constant *constant = type->isFloatingPointTy() ? ConstantFP::get(type, values[i])
: ConstantInt::get(type, values[i]);
constants[i] = constant;
}
Constant *zeroConst = type->isFloatingPointTy() ? ConstantFP::get(type, 0) : ConstantInt::get(type, 0);
Constant *padding = padWithZero ? zeroConst : UndefValue::get(type);
for (; i < width; ++i) {
constants[i] = padding;
}
return ConstantVector::get(constants);
}
Value *getPointerOperand(Instruction *instr) {
LoadInst *load = dyn_cast<LoadInst>(instr);
StoreInst *store = dyn_cast<StoreInst>(instr);
if (load) return load->getPointerOperand();
else if (store) return store->getPointerOperand();
else return nullptr;
}
Value *getBasePointer(Value *addr) {
GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(addr);
BitCastInst *bc = dyn_cast<BitCastInst>(addr);
if (gep)
return getBasePointer(gep->getPointerOperand());
if (bc)
return getBasePointer(bc->getOperand(0));
return addr;
}
BasicBlock *createCascadeBlocks(Function *insertInto, unsigned vectorWidth,
std::vector<BasicBlock *> &condBlocks,
std::vector<BasicBlock *> &maskedBlocks) {
BasicBlock *cond, *mask;
for (unsigned lane = 0; lane < vectorWidth; ++lane) {
cond = BasicBlock::Create(insertInto->getContext(), "cascade_cond_" + std::to_string(lane),
insertInto);
mask = BasicBlock::Create(insertInto->getContext(), "cascade_masked_" + std::to_string(lane),
insertInto);
condBlocks.push_back(cond);
maskedBlocks.push_back(mask);
}
return BasicBlock::Create(insertInto->getContext(), "cascade_end", insertInto);
}
bool isSupportedOperation(Instruction *const inst) {
// binary operations (normal & bitwise), load / stores, conversion operations, returns, and other operations
// exception: calls with vector or struct return type are not supported
CallInst *call = dyn_cast<CallInst>(inst);
if (call) {
Type *retType = call->getFunctionType()->getReturnType();
if (retType->isStructTy() || retType->isVectorTy())
return false;
}
return inst->isUnaryOp() || inst->isBinaryOp() || isa<LoadInst>(inst) || isa<StoreInst>(inst) || inst->isCast() || isa<ReturnInst>(inst) ||
(!isa<ExtractElementInst>(inst) && !isa<ExtractValueInst>(inst) && !isa<InsertElementInst>(inst) &&
!isa<InsertValueInst>(inst) && !isa<ShuffleVectorInst>(inst) &&
(inst->getOpcode() >= Instruction::OtherOpsBegin && inst->getOpcode() <= Instruction::OtherOpsEnd));
}
bool isHomogeneousStruct(StructType *const type, DataLayout &layout) {
assert(type->getStructNumElements() > 0 && "emptry struct!");
Type *prevElTy = nullptr;
for (Type *elTy : type->elements()) {
if (!elTy->isStructTy() && !(elTy->isIntegerTy() || elTy->isFloatingPointTy()))
return false;
else if (elTy->isStructTy() && !isHomogeneousStruct(cast<StructType>(elTy), layout))
return false;
if (prevElTy && layout.getTypeStoreSize(prevElTy) != layout.getTypeStoreSize(elTy))
return false;
prevElTy = elTy;
}
return true;
}
StructType *isStructAccess(Value *const address) {
assert(address->getType()->isPointerTy() && "not a pointer");
if (isa<BitCastInst>(address))
return isStructAccess(cast<BitCastInst>(address)->getOperand(0));
Type *type;
if (isa<GetElementPtrInst>(address))
type = cast<GetElementPtrInst>(address)->getSourceElementType();
else
type = address->getType();
return containsStruct(type);
}
StructType *containsStruct(Type *const type) {
if (type->isStructTy())
return cast<StructType>(type);
if (type->isPointerTy())
return containsStruct(cast<PointerType>(type)->getPointerElementType());
else
return nullptr;
}
unsigned getNumLeafElements(Type *const type, Type *const leafType, DataLayout &layout) {
return (unsigned) (layout.getTypeStoreSize(type) / layout.getTypeStoreSize(leafType));
#if 0
std::deque<std::pair<Type *const, unsigned>> queue;
queue.push_back(std::pair<Type *const, unsigned>(type, 0));
unsigned nodes = 0;
unsigned lastDistance = 0;
bool lastTrip = false;
while (!queue.empty()) {
Type *const ty = queue.front().first;
unsigned distance = queue.front().second;
queue.pop_front();
if (distance == lastDistance)
++nodes;
else if (!lastTrip) {
nodes = 1;
lastDistance = distance;
} else
break;
if (ty->getNumContainedTypes() == 0)
lastTrip = true;
if (!lastTrip)
for (unsigned i = 0; i < ty->getNumContainedTypes(); ++i) {
Type *const elTy = ty->getContainedType(i);
queue.push_back(std::pair<Type *const, unsigned>(elTy, distance + 1));
}
}
return nodes;
#endif
}
unsigned getStructOffset(GetElementPtrInst *const gep) {
Type *srcPtrType = gep->getSourceElementType();
std::vector<Value *> indices;
for (unsigned i = 0; i < gep->getNumIndices(); ++i) {
Value *idx = gep->getOperand(i + 1);
indices.push_back(idx);
Type *indexedType = GetElementPtrInst::getIndexedType(srcPtrType, indices);
if (indexedType->isStructTy()) {
unsigned structOffset = 0;
for (++i; i < gep->getNumIndices(); ++i) {
idx = gep->getOperand(i + 1);
assert(isa<ConstantInt>(idx) && "element access with non-constant!");
unsigned idxValue = (unsigned) cast<ConstantInt>(idx)->getLimitedValue();
structOffset += idxValue;
}
return structOffset;
}
}
return 0;
}
void setInsertionToDomBlockEnd(IRBuilder<> &builder, std::vector<llvm::BasicBlock *> &blocks) {
BasicBlock *domBlock = nullptr;
for (BasicBlock *block : blocks) {
if (block->getName().count("cascade_masked"))
continue;
domBlock = block;
if (block->empty())
break;
if (!block->getTerminator())
break;
}
assert(domBlock && "no block found!");
Instruction *term;
if ((term = domBlock->getTerminator()))
builder.SetInsertPoint(term);
else
builder.SetInsertPoint(domBlock);
}
| 32.24898
| 141
| 0.654727
|
sx-aurora-test
|
4c59fe702fd49d18898f89598a63ac96541d1ac3
| 13,407
|
cpp
|
C++
|
tests/sm/test_btree_basic.cpp
|
lslersch/zero
|
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
|
[
"Spencer-94"
] | 27
|
2015-04-21T08:52:37.000Z
|
2022-03-18T03:38:58.000Z
|
tests/sm/test_btree_basic.cpp
|
lslersch/zero
|
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
|
[
"Spencer-94"
] | 24
|
2015-07-04T10:45:41.000Z
|
2018-05-03T08:52:36.000Z
|
tests/sm/test_btree_basic.cpp
|
lslersch/zero
|
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
|
[
"Spencer-94"
] | 15
|
2015-03-31T09:57:10.000Z
|
2021-06-09T13:44:58.000Z
|
#include "btree_test_env.h"
#include "gtest/gtest.h"
#include "sm_vas.h"
#include "btree.h"
#include "btcursor.h"
btree_test_env *test_env;
/**
* Unit test for basic Insert/Select/Delete features of BTree.
*/
w_rc_t insert_simple(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert(stid, "a1", "data1"));
W_DO(test_env->btree_insert(stid, "aa2", "data2"));
W_DO(test_env->btree_insert(stid, "aaaa3", "data3"));
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("a1"), s.minkey);
EXPECT_EQ (std::string("aaaa3"), s.maxkey);
return RCOK;
}
TEST (BtreeBasicTest, InsertSimple) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_simple), 0);
}
TEST (BtreeBasicTest, InsertSimpleLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_simple, true), 0);
}
w_rc_t insert_toolong_fail(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "a1", "data1lkjdflgjldfjgkldfjg1"));
W_DO(test_env->btree_insert (stid, "ab2", "data1lkjdflgjldfjgkldfjg2"));
W_DO(test_env->btree_insert (stid, "abc3", "data1lkjdflgjldfjgkldfjg3"));
W_DO(test_env->btree_insert (stid, "abcd4", "data1lkjdflgjldfjgkldfjg4"));
// this one is fine. though the key is longer than the definition, we actually don't care the schema.
W_DO(test_env->btree_insert (stid, "abcde5", "data1lkjdflgjldfjgkldfjg5"));
// should fail here because one page can't hold this record
char long_data[SM_PAGESIZE + 1] = "";
memset (long_data, 'a', SM_PAGESIZE);
long_data[SM_PAGESIZE] = '\0';
cout << "We should see too-long error here:" << endl;
w_rc_t rc = test_env->btree_insert (stid, "abcdef6", long_data);
EXPECT_EQ (rc.err_num(), (w_error_codes) eRECWONTFIT);
if (rc.err_num() == eRECWONTFIT) {
cout << "yep, we did. the following message is NOT an error." << endl;
} else {
cerr << "wtf" << endl;
}
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (5, s.rownum);
EXPECT_EQ (std::string("a1"), s.minkey);
EXPECT_EQ (std::string("abcde5"), s.maxkey);
return rc;
}
TEST (BtreeBasicTest, InsertTooLongfail) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_toolong_fail), 0);
}
TEST (BtreeBasicTest, InsertTooLongfailLock) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_toolong_fail, true), 0);
}
w_rc_t insert_dup_fail(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
// should fail here
cout << "We should see a duplicate error here:" << endl;
w_rc_t rc = test_env->btree_insert (stid, "key006", "data7");
EXPECT_EQ (rc.err_num(), (w_error_codes) eDUPLICATE);
if (rc.err_num() == eDUPLICATE) {
cout << "yep, we did. the following message is NOT an error." << endl;
} else {
cerr << "wtf: no duplicate?" << endl;
}
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
return rc;
}
TEST (BtreeBasicTest, InsertDupFail) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_dup_fail), 0);
}
TEST (BtreeBasicTest, InsertDupFailLock) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_dup_fail, true), 0);
}
w_rc_t insert_remove(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
W_DO(test_env->btree_remove (stid, "key006"));
W_DO(test_env->btree_insert (stid, "key006", "data7"));
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
return RCOK;
}
TEST (BtreeBasicTest, InsertRemove) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_remove), 0);
}
TEST (BtreeBasicTest, InsertRemoveLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_remove, true), 0);
}
w_rc_t insert_remove_fail(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
// should fail here
cout << "We should see a NOTFOUND error here:" << endl;
w_rc_t rc = test_env->btree_remove (stid, "key003");
EXPECT_EQ (rc.err_num(), eNOTFOUND);
if (rc.err_num() == eNOTFOUND) {
cout << "yep, we did. the following message is NOT an error." << endl;
} else {
cerr << "wtf?" << endl;
}
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
return rc;
}
TEST (BtreeBasicTest, InsertRemoveFail) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_remove_fail), 0);
}
TEST (BtreeBasicTest, InsertRemoveFailLock) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_remove_fail, true), 0);
}
w_rc_t insert_remove_fail_repeat(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
W_DO(test_env->btree_remove (stid, "key005"));
// should fail here
cout << "We should see a NOTFOUND error here:" << endl;
w_rc_t rc = test_env->btree_remove (stid, "key005");
EXPECT_EQ (rc.err_num(), (w_error_codes) eNOTFOUND);
if (rc.err_num() == eNOTFOUND) {
cout << "yep, we did. the following message is NOT an error." << endl;
} else {
cerr << "wtf?" << endl;
}
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (2, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
return rc;
}
TEST (BtreeBasicTest, InsertRemoveFailRepeat) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_remove_fail_repeat), 0);
}
TEST (BtreeBasicTest, InsertRemoveFailRepeatLock) {
test_env->empty_logdata_dir();
EXPECT_NE(test_env->runBtreeTest(insert_remove_fail_repeat, true), 0);
}
w_rc_t insert_update(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
W_DO(test_env->btree_update (stid, "key006", "data7"));
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
W_DO(x_btree_verify(ssm, stid));
W_DO(test_env->begin_xct());
std::string data;
test_env->btree_lookup(stid, "key006", data);
EXPECT_EQ (std::string("data7"), data);
W_DO(test_env->btree_update (stid, "key006", "d"));
test_env->btree_lookup(stid, "key006", data);
EXPECT_EQ (std::string("d"), data);
W_DO(test_env->btree_update (stid, "key006", "dksjdfljslkdfjskldjf"));
test_env->btree_lookup(stid, "key006", data);
EXPECT_EQ (std::string("dksjdfljslkdfjskldjf"), data);
W_DO(test_env->commit_xct());
W_DO(x_btree_verify(ssm, stid));
return RCOK;
}
TEST (BtreeBasicTest, InsertUpdate) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_update), 0);
}
TEST (BtreeBasicTest, InsertUpdateLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_update, true), 0);
}
w_rc_t insert_overwrite(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
W_DO(test_env->btree_overwrite (stid, "key006", "b", 2));
W_DO(test_env->commit_xct());
x_btree_scan_result s;
W_DO(test_env->btree_scan(stid, s));
EXPECT_EQ (3, s.rownum);
EXPECT_EQ (std::string("key004"), s.minkey);
EXPECT_EQ (std::string("key006"), s.maxkey);
W_DO(x_btree_verify(ssm, stid));
std::string data;
test_env->btree_lookup_and_commit(stid, "key006", data);
EXPECT_EQ (std::string("daba6"), data);
return RCOK;
}
TEST (BtreeBasicTest, InsertOverwrite) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_overwrite), 0);
}
TEST (BtreeBasicTest, InsertOverwriteLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_overwrite, true), 0);
}
w_rc_t insert_overwrite_fail(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(test_env->begin_xct());
W_DO(test_env->btree_insert (stid, "key005", "data5"));
W_DO(test_env->btree_insert (stid, "key004", "data4"));
W_DO(test_env->btree_insert (stid, "key006", "data6"));
W_DO(test_env->btree_overwrite (stid, "key006", "b", 4));
rc_t rc1 = test_env->btree_overwrite (stid, "key006", "b", 5);
EXPECT_EQ (eRECWONTFIT, rc1.err_num());
rc_t rc2 = test_env->btree_overwrite (stid, "key006", "b", 6);
EXPECT_EQ (eRECWONTFIT, rc2.err_num());
W_DO(test_env->commit_xct());
return RCOK;
}
TEST (BtreeBasicTest, InsertOverwriteFail) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_overwrite_fail), 0);
}
TEST (BtreeBasicTest, InsertOverwriteFailLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_overwrite_fail, true), 0);
}
w_rc_t insert_many(ss_m* ssm, test_volume_t *test_volume) {
StoreID stid;
PageID root_pid;
W_DO(x_btree_create_index(ssm, test_volume, stid, root_pid));
W_DO(ssm->begin_xct());
test_env->set_xct_query_lock();
w_keystr_t key;
vec_t data;
char keystr[6] = "";
char datastr[50] = "";
memset(keystr, '\0', 6);
memset(datastr, '\0', 50);
keystr[0] = 'k';
keystr[1] = 'e';
keystr[2] = 'y';
datastr[0] = 'd';
datastr[1] = 'a';
datastr[2] = 't';
cout << "Inserting 200 records into BTree..." << endl;
for (int i = 0; i < 200; ++i) {
datastr[3] = keystr[3] = ('0' + ((i / 100) % 10));
datastr[4] = keystr[4] = ('0' + ((i / 10) % 10));
datastr[5] = keystr[5] = ('0' + ((i / 1) % 10));
for (int j = 6; j < 50; ++j) {
++datastr[j];
if (datastr[j] > '9') datastr[j] = '0';
}
key.construct_regularkey(keystr, 6);
data.set(datastr, 50);
W_DO(ssm->create_assoc(stid, key, data));
}
W_DO(ssm->commit_xct());
cout << "Inserted." << endl;
x_btree_scan_result s;
W_DO(x_btree_scan(ssm, stid, s, test_env->get_use_locks()));
EXPECT_EQ (200, s.rownum);
EXPECT_EQ (std::string("key000"), s.minkey);
EXPECT_EQ (std::string("key199"), s.maxkey);
return RCOK;
}
TEST (BtreeBasicTest, InsertMany) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_many), 0);
}
TEST (BtreeBasicTest, InsertManyLock) {
test_env->empty_logdata_dir();
EXPECT_EQ(test_env->runBtreeTest(insert_many, true), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
test_env = new btree_test_env();
::testing::AddGlobalTestEnvironment(test_env);
return RUN_ALL_TESTS();
}
| 33.68593
| 105
| 0.664877
|
lslersch
|
4c5a826ebefb81e6e0062c3ce90b8057aaba4c06
| 37,943
|
cpp
|
C++
|
SPOUTSDK/SpoutGL/SpoutControls.cpp
|
initialfx/Spout2
|
0f88e631d5328d5e5aedef287a7f8f3076b99be3
|
[
"BSD-2-Clause"
] | null | null | null |
SPOUTSDK/SpoutGL/SpoutControls.cpp
|
initialfx/Spout2
|
0f88e631d5328d5e5aedef287a7f8f3076b99be3
|
[
"BSD-2-Clause"
] | null | null | null |
SPOUTSDK/SpoutGL/SpoutControls.cpp
|
initialfx/Spout2
|
0f88e631d5328d5e5aedef287a7f8f3076b99be3
|
[
"BSD-2-Clause"
] | null | null | null |
//
// SpoutControls
//
// Allows an application to control a Spout sender
//
// ====================================================================================
// Revisions :
//
// 21.06.15 - project start
// 08.07.15 - project Version 1
// 16.07.15 - changed CheckControls to return the control index that was changed
// int SpoutControls::CheckControls(vector<control> &controls)
// 17.07.15 - introduced two versions of CheckControls
// introduced Lesser GPL licence
// 22.07.15 - included CreateControl
// - removed clear control file path from the registry
// so that it remains for controllers to find the last sender started
// 27.07.15 - Added "OpenSpoutController"
// 18.08.15 - Cleanup for 1.002 release
// 24.09.15 - re-ordering in cleanup
// 24.12.15 - added executable path to registry "ControlPath"
// 30.12.15 - restored CopyControlFile
// - Moved GetControls public
// 13.01.16 - Changed OpenSpoutController to look for executable host path
// as well as SpoutControls installation path.
// 15.01.16 - Added fixed "NoClose" argument for opening SpoutController from an application
// so that the Close button is hidden.
// 17.01.16 - Added commandline argument to the OpenController function
// "NoClose" is now a key word
// - CloseControls - look for the SpoutController window and close it
// 18.01.16 - added getcwd to OpenSpoutController
// - cleanup on exit confirmed for Processing
// - Instead of closecontrols, close the controller in CleanUp if it has been opened
// 26.01.16 - added default empty string for OpenSpoutController - then needs SpoutControls installation
// 27.01.16 - brought SpoutController.exe topmost before close to prevent freeze if hidden
// 19.02.16 - fixed command line for OpenSpoutController
// 08.05.16 - fixed OpenSpoutController function to detect SpoutController.exe
// 11.05.16 - 1.007
// 02.09.16 - safety checks for mailslot handle. Code cleanup.
// 17.01.17 - 1.008 release for Spout 2.006 - no code changes
// 27.01.17 - Changes to OpenSpoutController to find a SpoutControls installation
// 02.06.17 - Registry functions called from SpoutUtils
// 13.12.17 - OpenControls - returns false if no controls - no registry write
// 28.12.17 - Added GetFileControls
// 04.12.18 - corrected return value for GetFileControls
// 03.01.19 - Changed to revised registry functions in SpoutUtils
// 28.04.19 - Rebuild VS2017 - 2.007 - /MT
// 27.12.20 - Remove from Spout SDK and use for Processing library
// Rebuild Win32/x64 - /MT : VS2017 - 2.007
//
//
// ====================================================================================
//
// Copyright (C) 2015-2021. Lynn Jarvis, Leading Edge. Pty. Ltd.
//
// This program 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You will receive a copy of the GNU Lesser General Public License along
// with this program. If not, see http://www.gnu.org/licenses/.
//
#include "SpoutControls.h"
SpoutControls::SpoutControls()
{
m_sharedMemoryName = ""; // Memory map name sring
m_hSharedMemory = NULL; // Memory map handle
m_pBuffer = NULL; // Shared memory pointer
m_hAccessMutex = NULL; // Map access mutex
m_hSlot = NULL; // Handle to the mailslot
m_dwSize = 0; // Size of the memory map
}
//---------------------------------------------------------
SpoutControls::~SpoutControls()
{
Cleanup();
}
// ======================================================================
// Public
// ======================================================================
// ===================================================================== //
// CONTROLLER //
// ===================================================================== //
//---------------------------------------------------------
// Find a control map name in the registry
// This will only exist if the sender has created it and is running
// It is erased when the sender closes.
bool SpoutControls::FindControls(std::string &mapname)
{
char path[MAX_PATH];
// Find the if controller map name exists the registry
if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap", path) ) {
if(path[0] > 0) {
mapname = path;
return true;
}
}
return false;
}
//---------------------------------------------------------
// Create a controls memory map, existence mutex and access mutex
// and fill the memory map with the control vector
bool SpoutControls::CreateControls(std::string mapname, std::vector<control> controls)
{
std::string mutexName;
std::string sharedMemoryName;
// Create a mutex to control the write / read
mutexName = mapname;
mutexName += "ControlsAccess";
mutexName += "_mutex";
m_hAccessMutex = CreateMutexA(NULL, true, mutexName.c_str()); // initial ownership
if (!m_hAccessMutex) {
printf("CreateControls : Mutex creation failed\n");
return false;
}
// Create a memory map that will contain the updated control information
m_sharedMemoryName = mapname; // Global shared memory name used throughout
sharedMemoryName = mapname;
sharedMemoryName += "Controls";
sharedMemoryName += "_map";
// Calculate the size required for the memory map
// First 4 bytes on the first line are the size of the control array
// Next the information for each control
// Type DWORD (4 bytes) Name (16 bytes) Data (256 bytes) - total 276 bytes per control
// Total : 276 + size *(276)
m_dwSize = 276 + (DWORD)(controls.size()*276);
// Create or open the shared memory map
m_hSharedMemory = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, m_dwSize, (LPCSTR)sharedMemoryName.c_str());
if (m_hSharedMemory == NULL || m_hSharedMemory == INVALID_HANDLE_VALUE) {
printf("CreateControls : error occured while creating file mapping object : %d\n", GetLastError() );
CloseHandle(m_hAccessMutex);
return false;
}
// Map a view to get a pointer to write to
m_pBuffer = (LPTSTR)MapViewOfFile(m_hSharedMemory, FILE_MAP_ALL_ACCESS, 0, 0, m_dwSize);
if (m_pBuffer == NULL) {
printf("CreateControls : error occured while mapping view of the file : %d\n", GetLastError() );
CloseHandle(m_hSharedMemory);
CloseHandle(m_hAccessMutex);
return false;
}
WriteControls(m_pBuffer, controls);
UnmapViewOfFile(m_pBuffer);
// End of creation so unlock the access mutex
// If the reader tries to access the memory there will be nothing in it
ReleaseMutex(m_hAccessMutex);
return true;
}
//---------------------------------------------------------
// Set the changed controls to the memory map and inform the sender
bool SpoutControls::SetControls(std::vector<control> controls)
{
if(UpdateControls(controls)) {
// Inform the sender that new control data is ready
WriteMail(m_sharedMemoryName, "Ready");
return true;
}
return false;
}
//---------------------------------------------------------
// Find a control map and update it with the controls
bool SpoutControls::UpdateControls(std::vector<control> controls)
{
std::string mutexName;
std::string memoryMapName; // local name of the shared memory
HANDLE hMemory = NULL; // local handle to shared memory
LPTSTR pBuf = NULL; // local shared memory pointer
HANDLE hAccessMutex = NULL;
DWORD dwWaitResult;
DWORD dwMapSize = 0;
char *buf = NULL;
char temp[256];
//
// Controller writes to the memory map to update control data
//
// Check the access mutex
mutexName = m_sharedMemoryName; // mapname;
mutexName += "ControlsAccess";
mutexName += "_mutex";
hAccessMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, mutexName.c_str());
if(!hAccessMutex) {
printf("UpdateControls - access mutex does not exist\n");
CloseHandle(hAccessMutex);
return false;
}
dwWaitResult = WaitForSingleObject(m_hAccessMutex, 67);
if (dwWaitResult != WAIT_OBJECT_0) { // reader is accessing it
CloseHandle(hAccessMutex);
return false;
}
// The mutex is now locked so that the reader does not read while writing
// The memory map name is defined by the global mapname
memoryMapName = m_sharedMemoryName; // local name;
memoryMapName += "Controls";
memoryMapName += "_map";
// ====================================
// At this stage the map size is not known, but it's size
// is the first 4 bytes of the map, so read that first to get the size
hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4, (LPCSTR)memoryMapName.c_str());
if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) {
printf("UpdateControls : Error occured while opening file mapping object : %d\n", GetLastError() );
CloseHandle(hAccessMutex);
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 4); // only 4 bytes to read
if (pBuf == NULL || pBuf[0] == 0) {
printf("UpdateControls : Error 1 occured while mapping view of the file : %d\n", GetLastError() );
if(pBuf) UnmapViewOfFile(pBuf);
CloseHandle(hMemory);
CloseHandle(hAccessMutex);
return false;
}
// Retrieve the map size - the first 4 bytes
buf = (char *)pBuf; // moveable pointer
for(int i = 0; i<4; i++)
temp[i] = *buf++;
temp[4] = 0;
dwMapSize = (DWORD)atoi(temp);
// Now close the map and re-open it with the known size
UnmapViewOfFile(pBuf);
CloseHandle(hMemory);
// First check that the map size is correct for the control vector passed
// First 4 bytes on the first line are the size of the control array
// Next the information for each control
// Type DWORD (4 bytes) Name (16 bytes) Data (256 bytes) - total 276 bytes per control
// Total : 276 + size *(276)
if(dwMapSize != (276 + (DWORD)(controls.size()*276)) ) {
CloseHandle(hAccessMutex);
return false;
}
// Now open the full map and write the control data to it
hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwMapSize, (LPCSTR)memoryMapName.c_str());
if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) {
CloseHandle(hAccessMutex);
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, dwMapSize);
if (pBuf == NULL) {
printf("UpdateControls : Error 2 occured while mapping view of the file : %d\n", GetLastError() );
CloseHandle(hMemory);
CloseHandle(hAccessMutex);
return false;
}
//
// Write the controls to the memory map
//
WriteControls(pBuf, controls);
UnmapViewOfFile(pBuf); // Finished with the buffer
CloseHandle(hMemory); // Closes the memory map
ReleaseMutex(hAccessMutex); // Unlock the access mutex so that the reader can read from the memory map
CloseHandle(hAccessMutex);// Close the local handle
return true;
}
//---------------------------------------------------------
// Get controls from an existing map
bool SpoutControls::GetControls(std::vector<control> &controls)
{
std::string mutexName;
std::string memoryMapName; // local name of the shared memory
HANDLE hMemory = NULL; // local handle to shared memory
LPTSTR pBuf = NULL; // local shared memory pointer
HANDLE hAccessMutex = NULL;
DWORD dwWaitResult;
DWORD dwMapSize = 0;
// int nControls = 0;
// int ControlType = 0;
// float ControlValue = 0; // Float value of a control
std::string ControlText; // Text data of a control
char *buf = NULL;
char temp[256];
//
// Reader reads the memory map to retrieve control data
//
// Check the access mutex
mutexName = m_sharedMemoryName; // mapname;
mutexName += "ControlsAccess";
mutexName += "_mutex";
hAccessMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, mutexName.c_str());
if(!hAccessMutex) {
printf("GetControls : No access mutex\n");
CloseHandle(hAccessMutex);
return false;
}
dwWaitResult = WaitForSingleObject(hAccessMutex, 67);
if (dwWaitResult != WAIT_OBJECT_0) { // writer is accessing it
CloseHandle(hAccessMutex);
return false;
}
// The mutex is now locked so that the writer does not write while reading
// The memory map name is defined by the global mapname
memoryMapName = m_sharedMemoryName;
memoryMapName += "Controls";
memoryMapName += "_map";
// ====================================
// At this stage the map size is not known, but it's size is the
// first 4 bytes of the map so read that first to get the size
hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4, (LPCSTR)memoryMapName.c_str());
if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) {
printf("GetControls - Error occured opening file mapping object : %d\n", GetLastError() );
ReleaseMutex(hAccessMutex);
CloseHandle(hAccessMutex);
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, 4); // only 4 bytes to read
// Did the mapping fail or is there nothing in the map
if (pBuf == NULL || pBuf[0] == 0) {
printf("GetControls - Error 1 occured while mapping view of the file : %d\n", GetLastError() );
if(pBuf) UnmapViewOfFile(pBuf);
CloseHandle(hMemory);
ReleaseMutex(hAccessMutex);
CloseHandle(hAccessMutex);
return false;
}
// Retrieve the map size - the first 4 bytes
buf = (char *)pBuf; // moveable pointer
for(int i = 0; i<4; i++)
temp[i] = *buf++;
temp[4] = 0;
dwMapSize = (DWORD)atoi(temp);
// Now close the map and re-open it with the known size
UnmapViewOfFile(pBuf);
CloseHandle(hMemory);
hMemory = CreateFileMappingA ( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwMapSize, (LPCSTR)memoryMapName.c_str());
if (hMemory == NULL || hMemory == INVALID_HANDLE_VALUE) {
printf("GetControls - CreateFileMapping failed\n");
ReleaseMutex(hAccessMutex);
CloseHandle(hAccessMutex);
return false;
}
pBuf = (LPTSTR)MapViewOfFile(hMemory, FILE_MAP_ALL_ACCESS, 0, 0, dwMapSize);
if (pBuf == NULL) {
printf("GetControls - Error 2 occured while mapping view of the file : %d\n", GetLastError() );
CloseHandle(hMemory);
ReleaseMutex(hAccessMutex);
CloseHandle(hAccessMutex);
return false;
}
//
// Get the controls from the memory map
//
ReadControls(pBuf, controls);
// Finished with the buffer
UnmapViewOfFile(pBuf);
// Reader closes the memory map
CloseHandle(hMemory);
// Unlock the access mutex so that the writer can write to the memory map
ReleaseMutex(hAccessMutex);
// Close the local mutex handle
// All handles must be closed before the writer finally closes with the creation handle
CloseHandle(hAccessMutex);
return true;
}
//---------------------------------------------------------
// OpenControls
// A sender creates the controls and then calls OpenControls with a control name
// so that the controller can set up a memory map ans share data with the sender as it changes the controls
// The sender provides the map name, creates the mailslot and writes the map name to the registry
bool SpoutControls::OpenControls(std::string mapname)
{
char Path[MAX_PATH];
HRESULT hr;
Path[0] = 0;
// 13.12.17 - return if no controls
// TODO remove size check below
// printf("SpoutControls::OpenControls(%s) - controls size = %d\n", mapname.c_str(), filecontrols.size());
if (filecontrols.size() == 0) {
// printf("No controls\n");
return false;
}
// Set the global map name
m_sharedMemoryName = mapname;
// Create the mailslot
// m_hSlot is intitialized to NULL in constructor
CreateMail(m_sharedMemoryName, m_hSlot);
// printf("Created mailslot handle [%x]\n", m_hSlot);
// Write the executable path to the registry
GetModuleFileNameA(NULL, Path, sizeof(Path));
// printf("ControlPath(%s)\n", Path);
if (WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlPath", Path)) {
// printf("registry write OK\n");
}
// Write the name path to the registry to identify the memory map
strcpy_s(Path, MAX_PATH, m_sharedMemoryName.c_str());
PathStripPathA(Path);
PathRemoveExtensionA(Path);
// printf("ControlMap(%s)\n", Path);
if (WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap", Path)) {
// printf("registry write 2 OK\n");
}
// If the user has created controls, find the programdata or executable path and write the control file
m_ControlFilePath[0] = 0;
if(filecontrols.size() > 0) {
// Find or create the Spout programdata folder
// Look for "ProgramData" if it exists
hr = SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA, NULL, 0, Path);
if (SUCCEEDED(hr)) {
sprintf_s(m_ControlFilePath, MAX_PATH, "%s\\Spout", Path);
CreateDirectoryA((LPCSTR)m_ControlFilePath, NULL); // Will create if it does not exist
// RemoveDirectoryA((LPCSTR)SpoutPath);
strcat_s(m_ControlFilePath, MAX_PATH, "\\");
strcat_s(m_ControlFilePath, mapname.c_str());
strcat_s(m_ControlFilePath, ".txt"); // The control file name
}
// If that failed use the executable path
if(!m_ControlFilePath[0]) {
GetModuleFileNameA(NULL, Path, sizeof(Path));
PathRemoveFileSpecA(Path);
strcat_s(Path, MAX_PATH, "\\");
strcat_s(Path, mapname.c_str());
strcat_s(Path, ".txt"); // The control file name
strcpy_s(m_ControlFilePath, MAX_PATH, Path);
}
CreateControlFile(m_ControlFilePath);
// Write the control file path to the registry
// printf("writing control file [%s]\n", m_ControlFilePath);
WritePathToRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlFile", m_ControlFilePath);
return true;
}
return false;
}
//---------------------------------------------------------
bool SpoutControls::CloseControls()
{
// Release all handles etc
Cleanup();
return true;
}
//---------------------------------------------------------
// Open the SpoutController executable to allow controls to be changed
// Requires SpoutController.exe to be in the path passed
// or in the folder of a host executable
// or a SpoutControls installation
bool SpoutControls::OpenSpoutController(std::string CommandLine)
{
char Path[MAX_PATH];
char InstallPath[MAX_PATH];
// HRESULT hr;
Path[0] = 0;
InstallPath[0] = 0;
// Look for the SpoutControls installation path in the registry
// This contains the full path including "SpoutController.exe"
if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\SpoutControls", "InstallPath", InstallPath)) {
strcpy_s(Path, MAX_PATH, InstallPath);
}
else if(!CommandLine.empty()) {
// A path been passed - add the executable name
strcpy_s(Path, MAX_PATH, CommandLine.c_str());
strcat_s(Path, MAX_PATH, "\\SpoutController.exe");
}
else {
// No path can be found
return false;
}
if(PathFileExistsA(Path) ) {
// Launch SpoutController
SHELLEXECUTEINFOA ShExecInfo;
ZeroMemory(&ShExecInfo, sizeof(ShExecInfo));
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = (LPCSTR)Path;
// If opening the controller from an application, give it an argument
// "NoClose" to remove the Close button
// WinSpoutController is now changed to show/hide or exit on Escape key
if(!CommandLine.empty() && CommandLine.c_str()[0] != 0) {
if(InstallPath[0] == 0) {
// No SpoutContols installation, so use the path passed
ShExecInfo.lpParameters = (LPCSTR)CommandLine.c_str(); // "";
}
else {
// SpoutContols installation as well as a command line, so use "NOCLOSE"
strcpy_s(InstallPath, MAX_PATH, "NOCLOSE");
ShExecInfo.lpParameters = InstallPath;
}
}
else {
ShExecInfo.lpParameters = "";
}
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
ShellExecuteExA(&ShExecInfo);
Sleep(125); // alow time to open
return true;
}
return false;
}
//---------------------------------------------------------
// Check the mailslot and return all controls
bool SpoutControls::CheckControls(std::vector<control> &controls)
{
// if intialized already, check for a message from the controller
if(CheckMail(m_sharedMemoryName, m_hSlot)) {
// Get the new controls
GetControls(controls);
return true;
}
return false;
}
// ======================================================================
// Sender functions to create a control file
// ======================================================================
bool SpoutControls::CreateControl(std::string name, std::string type)
{
return CreateFileControl(name, type, 0.0f, 1.0f, 1.0, "");
}
bool SpoutControls::CreateControl(std::string name, std::string type, float value)
{
return CreateFileControl(name, type, 0.0f, value, value, ""); // Min. max, default
}
bool SpoutControls::CreateControl(std::string name, std::string type, std::string text)
{
return CreateFileControl(name, type, 0.0f, 1.0f, 1.0, text);
}
bool SpoutControls::CreateControl(std::string name, std::string type, float minimum, float maximum, float value)
{
return CreateFileControl(name, type, minimum, maximum, value, "");
}
//---------------------------------------------------------
// Used by the controller to find the control file path
// and find the control map name in the registry
bool SpoutControls::FindControlFile(std::string &filepath)
{
char path[MAX_PATH];
// Find if the controller map file name exists the registry
if(ReadPathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlFile", path) ) {
if(path[0] > 0) {
// 24.08.15 - add existence check
if(_access(path, 0) == -1) // Mode 0 - existence check
return false;
// File found
filepath = path;
return true;
}
}
return false;
}
//---------------------------------------------------------
// Used by a multiple controlled senders to copy the control
// file from ProgramData to the local dll directory
bool SpoutControls::CopyControlFile (std::string &filepath, std::string &destpath)
{
// copy from source to destination
if(CopyFileA((LPCSTR)filepath.c_str(), (LPCSTR)destpath.c_str(), false)) {
return true;
}
return false;
}
bool SpoutControls::GetFileControls(std::vector<filecontrol> &controls)
{
if (filecontrols.size() > 0) {
controls.clear();
for (unsigned int i = 0; i < filecontrols.size(); i++) {
controls.push_back(filecontrols.at(i));
}
return true;
}
return false;
}
// ======================================================================
// Private
// ======================================================================
//---------------------------------------------------------
// Create a file control and add to the sender's filecontrol vector
bool SpoutControls::CreateFileControl(std::string name, std::string type, float minimum, float maximum, float value, std::string text)
{
filecontrol fc;
if(name.empty() || type.empty()) {
return false;
}
fc.name = name;
fc.desc = type;
fc.min = minimum;
fc.max = maximum;
fc.def = value;
fc.value = value;
fc.text = text.c_str();
if(type == "bool")
fc.fftype = 0; // checkbox
if(type == "event")
fc.fftype = 1; // button
if(type == "float")
fc.fftype = 10; // float slider
if(type == "text")
fc.fftype = 100; // text
filecontrols.push_back(fc);
return true;
}
//---------------------------------------------------------
// Create a JSON control file from the filecontrols vector
bool SpoutControls::CreateControlFile(const char *filepath)
{
std::string linestring;
char path[MAX_PATH];
char temp[256];
if(!filepath[0] || filecontrols.empty())
return false;
strcpy_s(path, MAX_PATH, filepath);
//
// Write the contents of the parameter list
//
// Example
//
/*{
"CREDIT": "by Lynn Jarvis - spout.zeal.co",
"DESCRIPTION": "SpoutControls",
"CATEGORIES": [
"Parameter adjustment"
],
"INPUTS": [
{
"NAME": "User text",
"TYPE": "text",
"DEFAULT": 0
},
{
"NAME": "Rotate",
"TYPE": "bool",
"DEFAULT": 1
},
{
"NAME": "Speed",
"TYPE": "float",
"MIN": 0.0,
"MAX": 4.0,
"DEFAULT": 0.5
},
]
}*/
// Create the file
std::ofstream sourceFile(path);
// Source file created OK ?
if(sourceFile.is_open()) {
// Create the JSON header
linestring = "/*{\n";
sourceFile.write(linestring.c_str(), linestring.length());
sprintf_s(temp, 256, " \"CREDIT\": \"SpoutControls - spout.zeal.co\",\n");
sourceFile.write(temp, strlen(temp));
PathStripPathA(path);
PathRemoveExtensionA(path);
sprintf_s(temp, 256, " \"DESCRIPTION\": \"%s\",\n", path);
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"CATEGORIES\": [\n");
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"Parameter adjustment\"\n");
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " ],\n");
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"INPUTS\": [\n");
sourceFile.write(temp, strlen(temp));
// Write the control data here
// Example
// {
// "NAME": "Speed",
// "TYPE": "float",
// "MIN": 0.0,
// "MAX": 4.0,
// "DEFAULT": 0.5
// },
for(unsigned int i = 0; i < filecontrols.size(); i++) {
sprintf_s(temp, 256, " {\n");
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"NAME\": \"%s\",\n", filecontrols.at(i).name.c_str());
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"TYPE\": \"%s\",\n", filecontrols.at(i).desc.c_str());
sourceFile.write(temp, strlen(temp));
if(filecontrols.at(i).desc != "text") {
sprintf_s(temp, 256, " \"MIN\": %.2f,\n", filecontrols.at(i).min);
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"MAX\": %.2f,\n", filecontrols.at(i).max);
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, " \"DEFAULT\": %.2f\n", filecontrols.at(i).def);
sourceFile.write(temp, strlen(temp));
}
else {
sprintf_s(temp, 256, " \"TEXT\": \"%s\"\n", filecontrols.at(i).text.c_str());
sourceFile.write(temp, strlen(temp));
}
sprintf_s(temp, 256, " },\n");
sourceFile.write(temp, strlen(temp));
}
sprintf_s(temp, 256, " ],\n");
sourceFile.write(temp, strlen(temp));
sprintf_s(temp, 256, "}*/\n");
sourceFile.write(temp, strlen(temp));
sourceFile.close();
// printf("Control file created\n[%s]\n", filepath);
}
else {
sprintf_s(temp, 256, "Control file not created\n[%s]", path);
MessageBoxA(NULL, temp, "Info", MB_OK);
// MessageBoxA(NULL, "File not created", "Info", MB_OK);
}
return true;
}
//---------------------------------------------------------
// Write control map with updated values
bool SpoutControls::WriteControls(void *pBuffer, std::vector<control> controls)
{
//
// Write the control data to shared memory
// The writer knows the memory map size to open it (m_dwSize)
//
float fValue = 0;
char desc[256];
char *buffer = NULL; // the buffer to store in shared memory
char *buf = NULL; // pointer within the buffer
int i, j;
buffer = (char *)malloc(m_dwSize*sizeof(unsigned char));
if(!buffer) return false;
// Clear the buffer to zero so that there is a null for each data line
ZeroMemory(buffer, m_dwSize*sizeof(unsigned char));
buf = buffer; // pointer within the buffer
// The first 4 bytes of the first line is the memory map size so the reader knows how big it is
// printf("Writing the memory map size (%d)\n", m_dwSize);
sprintf_s(desc, 256, "%4d", m_dwSize);
for(i = 0 ; i< 4; i++)
*buf++ = desc[i];
// The next 4 bytes contains the number of controls
ZeroMemory(desc, 256);
sprintf_s(desc, 256, "%4d", (DWORD)controls.size());
for(i = 0 ; i< 4; i++)
*buf++ = desc[i];
// Move on 268 bytes to the start of the controls (each memory map line is 276 bytes)
buf += 268;
// Next the controls and their data
// Name (16 bytes) Type (4 bytes) Data (256 bytes) - total 276 bytes per control
for(i = 0; i < (int)controls.size(); i++) {
// Control name - 16 bytes
ZeroMemory(desc, 256);
if(controls.at(i).name.c_str()[0])
sprintf_s(desc, 256, "%s", controls.at(i).name.c_str());
for(j = 0 ; j<16; j++)
*buf++ = desc[j];
// Control type - 4 bytes
ZeroMemory(desc, 256);
sprintf_s(desc, 256, "%4d", (DWORD)controls.at(i).type);
for(j = 0 ; j<4; j++)
*buf++ = desc[j];
// Control data - 256 bytes
ZeroMemory(desc, 256);
if(controls.at(i).type == 100) { // Text data
if(controls.at(i).text[0]) {
sprintf_s(desc, 256, "%s", controls.at(i).text.c_str());
}
}
else {
fValue = controls.at(i).value;
sprintf_s(desc, 256, "%f", fValue); // float data
}
// copy it with 256 length
for(j = 0 ; j<256; j++)
*buf++ = desc[j];
} // end all controls
// Now transfer to shared memory which will be the same size
memcpy( (void *)pBuffer, (void *)buffer, m_dwSize );
free((void *)buffer);
return true;
}
//---------------------------------------------------------
// Read controls from the memory map
bool SpoutControls::ReadControls(void *pBuffer, std::vector<control> &controls)
{
char *buf = NULL;
char temp[256];
int i, j, nControls;
control control;
//
// Get the controls
//
buf = (char *)pBuffer; // moveable pointer
buf += 4; // The first 4 bytes of the first line is the memory map size, so skip that
// the next 4 bytes contains the number of controls
for(i = 0; i<4; i++)
temp[i] = *buf++;
temp[4] = 0;
nControls = atoi(temp);
// Move on 268 bytes to the control data (each line is 276 bytes)
buf += 268;
// Clear the controls vector
controls.clear();
// Fill it again (use previously found size)
for(i = 0; i<nControls; i++) {
control.name.clear();
control.text.clear();
control.value = 0;
control.type = 0;
// First 16 bytes are the control name
ZeroMemory(temp, 256);
for(j = 0; j<16; j++)
temp[j] = *buf++;
temp[16] = 0;
if(temp[0])
control.name = temp;
// Control type
ZeroMemory(temp, 256);
for(j = 0; j<4; j++)
temp[j] = *buf++;
temp[4] = 0;
control.type = atoi(temp);
// Next 256 bytes on the same line are allocated to the float or string data
ZeroMemory(temp, 256);
for(j = 0; j<256; j++)
temp[j] = *buf++;
if(control.type == 100) { // text data
if(temp[0]) {
control.text = temp;
}
}
else { // float data
control.value = (float)atof(temp);
}
controls.push_back(control);
} // Done all controls
return true;
}
//---------------------------------------------------------
// Sender creates the mailslot
bool SpoutControls::CreateMail(std::string SlotName, HANDLE &hSlot)
{
HANDLE hslot = NULL;
std::string slotstring;
// printf("SpoutControls::CreateMail\n");
// Already exists ?
if (hSlot != NULL) {
// printf("SpoutControls::CreateMail - hSlot exists\n");
return true;
}
/*
// LJ DEBUG - check with CreateFile
// An error occurs if a mailslot with the specified name already exists.
// If CreateFile is called to access a non-existent mailslot, the ERROR_FILE_NOT_FOUND error code will be set
// If the function succeeds, the return value is an open handle to
// the specified file, device, named pipe, or mail slot.
// If the function fails, the return value is INVALID_HANDLE_VALUE.
// To get extended error information, call
HANDLE hFile;
hFile = CreateFileA(slotstring.c_str(),
GENERIC_WRITE,
FILE_SHARE_READ,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL);
// DWORD dwError = GetLastError();
if (hFile != INVALID_HANDLE_VALUE) {
// The system found the file specified
printf("SpoutControls::CreateMail - CreateFileA already exists\n");
CloseHandle(hFile);
return true;
}
printf("SpoutControls::CreateMail - CreateFileA returned %x\n", hFile);
CloseHandle(hFile);
*/
slotstring = "\\\\.\\mailslot\\";
slotstring += SlotName;
hslot = CreateMailslotA(slotstring.c_str(),
0, // no maximum message size
0, // Time-out for operations - set to zero - was originally 2msec
(LPSECURITY_ATTRIBUTES) NULL); // default security
if (hslot == INVALID_HANDLE_VALUE) { // (-1)
// Want no delay here
// DWORD dwError = GetLastError();
// printf("CreateMailslot (%s) failed with %d\n", SlotName.c_str(), dwError);
// Now should not happen
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// printf("CreateMailslot (%s) already exists (%x)(%x)\n", SlotName.c_str(), (unsigned int)hSlot, (unsigned int)m_hSlot);
return true;
}
return false;
}
hSlot = hslot;
// printf("Created mailslot handle [%x]\n", hSlot);
return true;
}
//---------------------------------------------------------
// Controller writes to the mailslot
bool SpoutControls::WriteMail(std::string SlotName, std::string SlotMessage)
{
std::string slotstring;
HANDLE hFile;
BOOL fResult;
DWORD dwWritten;
slotstring = "\\\\.\\mailslot\\";
slotstring += SlotName;
hFile = CreateFileA(slotstring.c_str(),
GENERIC_WRITE,
FILE_SHARE_READ,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL);
if (hFile == INVALID_HANDLE_VALUE) {
// The system cannot find the file specified
// printf("CreateFile failed with %d.\n", GetLastError());
return false;
}
fResult = WriteFile(hFile,
SlotMessage.c_str(),
(DWORD) (strlen(SlotMessage.c_str())+1)*sizeof(TCHAR),
&dwWritten,
(LPOVERLAPPED)NULL);
if (!fResult) {
// printf("WriteFile failed with error (%d)\n", GetLastError());
CloseHandle(hFile);
return false;
}
CloseHandle(hFile);
return true;
}
//---------------------------------------------------------
// Sender checks the mailslot for messages
bool SpoutControls::CheckMail(std::string SlotName, HANDLE hSlot)
{
if(hSlot == NULL)
return false;
std::string slotmessage; // Not used but could return the message
return ReadMail(SlotName, hSlot, slotmessage);
}
//---------------------------------------------------------
// Sender reads the mailslot to determine whether
// a message is ready and clears pending messages
bool SpoutControls::ReadMail(std::string SlotName, HANDLE hSlot, std::string &SlotMessage)
{
DWORD cbMessage, cMessage, cbRead;
BOOL fResult;
LPTSTR lpszBuffer;
char achID[80];
DWORD cAllMessages;
HANDLE hEvent;
OVERLAPPED ov;
if(hSlot == NULL)
return false;
cbMessage = cMessage = cbRead = 0;
hEvent = CreateEvent(NULL, false, false, TEXT("SpoutControlsSlotEvent"));
if( NULL == hEvent ) {
return false;
}
ov.Offset = 0;
ov.OffsetHigh = 0;
ov.hEvent = hEvent;
fResult = GetMailslotInfo( hSlot, // mailslot handle
(LPDWORD) NULL, // no maximum message size
&cbMessage, // size of next message
&cMessage, // number of messages
(LPDWORD)NULL); // no read time-out. TODO : 1/2 frame timeout ?
if (!fResult) {
// printf("GetMailslotInfo failed with %d.\n", GetLastError());
CloseHandle(hEvent);
return false;
}
if (cbMessage == MAILSLOT_NO_MESSAGE) {
CloseHandle(hEvent);
return false;
}
cAllMessages = cMessage;
while (cMessage != 0) { // retrieve all messages
// Allocate memory for the message.
// TODO - clean up
lpszBuffer = (LPTSTR) GlobalAlloc(GPTR, lstrlen((LPTSTR)achID)*sizeof(TCHAR) + cbMessage);
if( NULL == lpszBuffer ) return false;
lpszBuffer[0] = '\0';
fResult = ReadFile( hSlot,
lpszBuffer,
cbMessage,
&cbRead,
&ov);
if (!fResult) {
// printf("ReadFile failed with %d.\n", GetLastError());
GlobalFree((HGLOBAL) lpszBuffer);
CloseHandle(hEvent);
return false;
}
fResult = GetMailslotInfo( hSlot, // mailslot handle
(LPDWORD) NULL, // no maximum message size
&cbMessage, // size of next message
&cMessage, // number of messages
(LPDWORD) NULL); // no read time-out
if (!fResult) {
// printf("GetMailslotInfo failed (%d)\n", GetLastError());
GlobalFree((HGLOBAL) lpszBuffer);
CloseHandle(hEvent);
return false;
}
// We only return the last message here but it could be extended to a vector of strings
SlotMessage = (LPSTR)lpszBuffer;
GlobalFree((HGLOBAL) lpszBuffer);
} // end all messages
CloseHandle(hEvent);
return true;
}
//---------------------------------------------------------
void SpoutControls::CloseMap()
{
if(m_pBuffer) UnmapViewOfFile(m_pBuffer);
if(m_hSharedMemory) CloseHandle(m_hSharedMemory);
if(m_hAccessMutex) CloseHandle(m_hAccessMutex);
m_pBuffer = NULL;
m_hSharedMemory = NULL;
m_hAccessMutex = NULL;
}
//---------------------------------------------------------
bool SpoutControls::Cleanup()
{
// Cleanup for this class
// Release the filecontrols vector created by a sender
if(filecontrols.size() > 0) {
filecontrols.clear();
}
// Release all objects
if(m_pBuffer) UnmapViewOfFile(m_pBuffer);
if(m_hSharedMemory) CloseHandle(m_hSharedMemory);
if(m_hAccessMutex) CloseHandle(m_hAccessMutex);
m_pBuffer = NULL;
m_hSharedMemory = NULL;
m_hAccessMutex = NULL;
if(m_hSlot) {
// printf("Closing mailslot handle\n");
// For a sender, clear the map name from the registry
RemovePathFromRegistry(HKEY_CURRENT_USER, "Software\\Leading Edge\\Spout", "ControlMap");
CloseHandle(m_hSlot);
m_hSlot = NULL;
}
// Close the controller if it has been opened
HWND hwnd = FindWindowA(NULL, (LPCSTR)"Spout Controller");
if(hwnd) {
// ShowWindow(hwnd, SW_SHOWNORMAL); // causes a freeze if the window is hidden
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_ASYNCWINDOWPOS | SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
SendMessageA(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
return true;
}
| 29.970774
| 134
| 0.647155
|
initialfx
|
4c5abf814ba2ac2274c92395df2b592cff646d16
| 3,170
|
cpp
|
C++
|
FileZillaFTP/source/AdminInterface.cpp
|
JyothsnaMididoddi26/xampp
|
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
|
[
"Apache-2.0"
] | 1
|
2017-01-31T08:49:16.000Z
|
2017-01-31T08:49:16.000Z
|
FileZillaFTP/source/AdminInterface.cpp
|
JyothsnaMididoddi26/xampp
|
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
|
[
"Apache-2.0"
] | 2
|
2020-07-17T00:13:41.000Z
|
2021-05-08T17:01:54.000Z
|
FileZillaFTP/source/AdminInterface.cpp
|
JyothsnaMididoddi26/xampp
|
8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b
|
[
"Apache-2.0"
] | null | null | null |
// FileZilla Server - a Windows ftp server
// Copyright (C) 2002-2004 - Tim Kosse <tim.kosse@gmx.de>
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// AdminInterface.cpp: Implementierung der Klasse CAdminInterface.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AdminInterface.h"
#include "AdminSocket.h"
#include "Server.h"
//////////////////////////////////////////////////////////////////////
// Konstruktion/Destruktion
//////////////////////////////////////////////////////////////////////
CAdminInterface::CAdminInterface(CServer *pServer)
{
ASSERT(pServer);
m_pServer = pServer;
}
CAdminInterface::~CAdminInterface()
{
for (std::list<CAdminSocket *>::iterator iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++)
delete *iter;
}
BOOL CAdminInterface::Add(CAdminSocket *pAdminSocket)
{
if (pAdminSocket->Init())
{
m_AdminSocketList.push_back(pAdminSocket);
return TRUE;
}
return FALSE;
}
BOOL CAdminInterface::SendCommand(int nType, int nID, const void *pData, int nDataLength)
{
ASSERT((!nDataLength && !pData) || (pData && nDataLength));
std::list<CAdminSocket *> deleteList;
std::list<CAdminSocket *>::iterator iter;
for (iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++)
if (!(*iter)->SendCommand(nType, nID, pData, nDataLength))
{
deleteList.push_back(*iter);
}
for (iter = deleteList.begin(); iter != deleteList.end(); iter++)
VERIFY(Remove(*iter));
return TRUE;
}
BOOL CAdminInterface::Remove(CAdminSocket *pAdminSocket)
{
for (std::list<CAdminSocket *>::iterator iter = m_AdminSocketList.begin(); iter != m_AdminSocketList.end(); iter++)
if (*iter == pAdminSocket)
{
delete *iter;
m_AdminSocketList.erase(iter);
return TRUE;
}
return FALSE;
}
BOOL CAdminInterface::ProcessCommand(CAdminSocket *pAdminSocket, int nID, void *pData, int nDataLength)
{
m_pServer->ProcessCommand(pAdminSocket, nID, reinterpret_cast<unsigned char *>(pData), nDataLength);
return TRUE;
}
void CAdminInterface::CheckForTimeout()
{
std::list<CAdminSocket *> deleteList;
std::list<CAdminSocket *>::iterator iter;
for (iter=m_AdminSocketList.begin(); iter!=m_AdminSocketList.end(); iter++)
if ((*iter)->CheckForTimeout())
deleteList.push_back(*iter);
for (iter=deleteList.begin(); iter!=deleteList.end(); iter++)
VERIFY(Remove(*iter));
}
| 31.7
| 117
| 0.655205
|
JyothsnaMididoddi26
|
4c5b7b47c52278a64e3e8ca486aef44db48f8b04
| 4,007
|
cc
|
C++
|
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
|
OscarGame/blade
|
6987708cb011813eb38e5c262c7a83888635f002
|
[
"MIT"
] | 146
|
2018-12-03T08:08:17.000Z
|
2022-03-21T06:04:06.000Z
|
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 1
|
2019-01-18T03:35:49.000Z
|
2019-01-18T03:36:08.000Z
|
Source/BladeDevice/source/window/android/AndroidWindowMessagePump.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 31
|
2018-12-03T10:32:43.000Z
|
2021-10-04T06:31:44.000Z
|
/********************************************************************
created: 2013/12/28
filename: AndroidWindowMessagePump.cc
author: Crazii
purpose:
*********************************************************************/
#include <BladePCH.h>
#if BLADE_PLATFORM == BLADE_PLATFORM_ANDROID
#include <unistd.h>
#include <window/android/AndroidWindowMessagePump.h>
namespace Blade
{
//////////////////////////////////////////////////////////////////////////
AndroidMessagePump::AndroidMessagePump()
{
}
//////////////////////////////////////////////////////////////////////////
AndroidMessagePump::~AndroidMessagePump()
{
}
/************************************************************************/
/* IWindowMessagePump interface */
/************************************************************************/
//////////////////////////////////////////////////////////////////////////
void AndroidMessagePump::processMessage()
{
std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::mem_fun(&IMessageListener::preProcessMessages) );
int ident;
int events;
struct android_poll_source* source;
while((ident=::ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0)
{
if(source != NULL)
{
android_app* app = source->app;
if( source->id == LOOPER_ID_MAIN )
{
//process main cmd
source->cmd = AndroidMessagePump::androidThreadMessage(app);
source->preprocess(app, source);
std::for_each(mMessageListeners.begin(),mMessageListeners.end(),
std::bind2nd( std::mem_fun(&IMessageListener::preProcessMessage), source) );
source->process(app, source);
std::for_each(mMessageListeners.begin(),mMessageListeners.end(),
std::bind2nd( std::mem_fun(&IMessageListener::postProcessMessage), source) );
source->postprocess(app, source);
}
else if( source->id == LOOPER_ID_INPUT )
{
//process input event
while(::AInputQueue_getEvent(app->inputQueue, &(source->event) ) >= 0)
{
LOGV("New input event: type=%d\n", AInputEvent_getType(source->event));
if( ::AInputQueue_preDispatchEvent(app->inputQueue, source->event) )
continue;
source->preprocess(app, source);
std::for_each(mMessageListeners.begin(),mMessageListeners.end(),
std::bind2nd( std::mem_fun(&IMessageListener::preProcessMessage), source) );
source->process(app, source);
std::for_each(mMessageListeners.begin(),mMessageListeners.end(),
std::bind2nd( std::mem_fun(&IMessageListener::postProcessMessage), source) );
source->postprocess(app, source);
::AInputQueue_finishEvent(app->inputQueue, source->event, 1);
}
}
}
}
std::for_each(mMessageListeners.begin(),mMessageListeners.end(), std::mem_fun(&IMessageListener::postProcessMessages) );
}
//////////////////////////////////////////////////////////////////////////
bool AndroidMessagePump::addMessageListener(IMessageListener* listener)
{
if( listener != NULL )
return mMessageListeners.insert(listener).second;
else
return false;
}
//////////////////////////////////////////////////////////////////////////
bool AndroidMessagePump::removeMessageListener(IMessageListener* listener)
{
if( listener != NULL )
return mMessageListeners.erase(listener) == 1;
else
return false;
}
/************************************************************************/
/* */
/************************************************************************/
//////////////////////////////////////////////////////////////////////////
int8_t AndroidMessagePump::androidThreadMessage(struct android_app* android_app)
{
int8_t cmd;
if ( ::read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd) )
return cmd;
else
LOGE("No data on command pipe!");
return -1;
}
}//namespace Blade
#endif//BLADE_PLATFORM
| 32.314516
| 122
| 0.516346
|
OscarGame
|
4c5f08ba5759a8c633e2c29c73f944038e1e4e86
| 13,012
|
cc
|
C++
|
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | 3
|
2018-10-04T19:32:36.000Z
|
2021-09-02T07:37:30.000Z
|
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | null | null | null |
Modules/Transformation/src/irtkPartialBSplineFreeFormTransformationSV.cc
|
kevin-keraudren/IRTK
|
ce329b7f58270b6c34665dcfe9a6e941649f3b94
|
[
"Apache-2.0"
] | 4
|
2016-03-17T02:55:00.000Z
|
2018-02-03T05:40:05.000Z
|
/* The Image Registration Toolkit (IRTK)
*
* Copyright 2008-2015 Imperial College London
*
* 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 <irtkTransformation.h>
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
irtkPartialBSplineFreeFormTransformationSV
::irtkPartialBSplineFreeFormTransformationSV(irtkBSplineFreeFormTransformationSV *t, double f)
:
_Transformation(t),
_Fraction (f)
{
}
// -----------------------------------------------------------------------------
irtkPartialBSplineFreeFormTransformationSV
::~irtkPartialBSplineFreeFormTransformationSV()
{
}
// =============================================================================
// Transformation parameters
// =============================================================================
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::CopyFrom(const irtkTransformation *t)
{
const irtkPartialBSplineFreeFormTransformationSV *part = NULL;
if ((part = dynamic_cast<const irtkPartialBSplineFreeFormTransformationSV *>(t))) {
return _Transformation->CopyFrom(part->Transformation());
} else {
return _Transformation->CopyFrom(t);
}
}
// -----------------------------------------------------------------------------
int irtkPartialBSplineFreeFormTransformationSV::NumberOfDOFs() const
{
return _Transformation->NumberOfDOFs();
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Put(int dof, double x)
{
_Transformation->Put(dof, x);
}
// -----------------------------------------------------------------------------
double irtkPartialBSplineFreeFormTransformationSV::Get(int dof) const
{
return _Transformation->Get(dof);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Put(const DOFValue *x)
{
_Transformation->Put(x);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Add(const DOFValue *dx)
{
_Transformation->Add(dx);
}
// -----------------------------------------------------------------------------
double irtkPartialBSplineFreeFormTransformationSV::Update(const DOFValue *dx)
{
return _Transformation->Update(dx);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Get(DOFValue *x) const
{
_Transformation->Get(x);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::PutStatus(int dof, DOFStatus s)
{
_Transformation->PutStatus(dof, s);
}
// -----------------------------------------------------------------------------
DOFStatus irtkPartialBSplineFreeFormTransformationSV::GetStatus(int dof) const
{
return _Transformation->GetStatus(dof);
}
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::HasSameDOFsAs(const irtkTransformation *t) const
{
return HaveSameDOFs(_Transformation, t);
}
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::IsIdentity() const
{
return (_Fraction == .0) || _Transformation->IsIdentity();
}
// =============================================================================
// Parameters (non-DoFs)
// =============================================================================
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::Set(const char *param, const char *value)
{
return _Transformation->Set(param, value);
}
// -----------------------------------------------------------------------------
irtkParameterList irtkPartialBSplineFreeFormTransformationSV::Parameter() const
{
return _Transformation->Parameter();
}
// =============================================================================
// Point transformation
// =============================================================================
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::RequiresCachingOfDisplacements() const
{
return _Transformation->RequiresCachingOfDisplacements();
}
// -----------------------------------------------------------------------------
inline double irtkPartialBSplineFreeFormTransformationSV::UpperIntegrationLimit(double t, double t0) const
{
return _Fraction * _Transformation->UpperIntegrationLimit(t, t0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::GlobalTransform(double &x, double &y, double &z, double t, double t0) const
{
_Transformation->GlobalTransform(x, y, z, t, t0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::LocalTransform(double &x, double &y, double &z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->LocalTransform(x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Transform(double &x, double &y, double &z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Transform(x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::GlobalInverse(double &x, double &y, double &z, double t, double t0) const
{
_Transformation->GlobalInverse(x, y, z, t, t0);
}
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::LocalInverse(double &x, double &y, double &z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->LocalInverse(x, y, z, T, .0);
return true;
}
// -----------------------------------------------------------------------------
bool irtkPartialBSplineFreeFormTransformationSV::Inverse(double &x, double &y, double &z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Inverse(x, y, z, T, .0);
return true;
}
// ---------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Displacement(irtkGenericImage<double> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Displacement(disp, T, .0, wc);
}
// ---------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Displacement(irtkGenericImage<float> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Displacement(disp, T, .0, wc);
}
// ---------------------------------------------------------------------------
int irtkPartialBSplineFreeFormTransformationSV::InverseDisplacement(irtkGenericImage<double> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->InverseDisplacement(disp, T, .0, wc);
return 0;
}
// ---------------------------------------------------------------------------
int irtkPartialBSplineFreeFormTransformationSV::InverseDisplacement(irtkGenericImage<float> &disp, double t, double t0, const irtkWorldCoordsImage *wc) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->InverseDisplacement(disp, T, .0, wc);
return 0;
}
// =============================================================================
// Derivatives
// =============================================================================
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::GlobalJacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const
{
_Transformation->GlobalJacobian(jac, x, y, z, t, t0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::LocalJacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->LocalJacobian(jac, x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Jacobian(irtkMatrix &jac, double x, double y, double z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Jacobian(jac, x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::GlobalHessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const
{
_Transformation->GlobalHessian(h, x, y, z, t, t0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::LocalHessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->LocalHessian(h, x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Hessian(irtkMatrix h[3], double x, double y, double z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->Hessian(h, x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::JacobianDOFs(double jac[3], int dof, double x, double y, double z, double t, double t0) const
{
const double T = UpperIntegrationLimit(t, t0);
if (T) _Transformation->JacobianDOFs(jac, dof, x, y, z, T, .0);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV
::ParametricGradient(const irtkGenericImage<double> *in, double *out,
const irtkWorldCoordsImage *i2w, const irtkWorldCoordsImage *wc,
double t0, double w) const
{
const double T = UpperIntegrationLimit(in->GetTOrigin(), t0);
if (T) _Transformation->ParametricGradient(in, out, i2w, wc, T, .0, w);
}
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV
::ParametricGradient(const irtkGenericImage<double> **in, int n, double *out,
const irtkWorldCoordsImage *i2w, const irtkWorldCoordsImage *wc,
const double *t0, double w) const
{
double t, T;
for (int i = 0; i < n; ++i) {
t = in[i]->GetTOrigin();
T = UpperIntegrationLimit(t, t0 ? t0[i] : t);
if (T) _Transformation->ParametricGradient(in[i], out, i2w, wc, T, .0, w);
}
}
// =============================================================================
// I/O
// =============================================================================
// -----------------------------------------------------------------------------
void irtkPartialBSplineFreeFormTransformationSV::Print(irtkIndent indent) const
{
cout << indent << "Partial B-spline SV FFD" << endl;
_Transformation->Print(indent+1);
cout << indent << "Fraction of transformation applied: " << _Fraction << endl;
}
// -----------------------------------------------------------------------------
irtkCifstream &irtkPartialBSplineFreeFormTransformationSV::Read(irtkCifstream &from)
{
return _Transformation->Read(from);
}
// -----------------------------------------------------------------------------
irtkCofstream &irtkPartialBSplineFreeFormTransformationSV::Write(irtkCofstream &to) const
{
return _Transformation->Write(to);
}
| 40.409938
| 158
| 0.511912
|
kevin-keraudren
|
4c64128d35359e3e2bc9ef4b29a43e59c171f064
| 92,562
|
hpp
|
C++
|
include/voxelio/3rd_party/lodepng.hpp
|
Eisenwave/voxel-io
|
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
|
[
"MIT"
] | 12
|
2020-06-25T13:40:22.000Z
|
2021-12-06T04:00:29.000Z
|
include/voxelio/3rd_party/lodepng.hpp
|
Eisenwave/voxel-io
|
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
|
[
"MIT"
] | 2
|
2021-02-04T16:19:40.000Z
|
2021-06-25T09:39:20.000Z
|
include/voxelio/3rd_party/lodepng.hpp
|
Eisenwave/voxel-io
|
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
|
[
"MIT"
] | null | null | null |
/*
LodePNG version 20200306
Copyright (c) 2005-2020 Lode Vandevenne
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.
*/
#ifndef VXIO_LODEPNG_HPP
#define VXIO_LODEPNG_HPP
#include <cstddef>
#include "lodepngfwd.hpp"
extern const char* LODEPNG_VERSION_STRING;
// VOXELIO MODIFICATIONS ===============================================================================================
#define LODEPNG_NO_COMPILE_DECODER
#define LODEPNG_NO_COMPILE_DISK
#define LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
// =====================================================================================================================
/*
The following #defines are used to create code sections. They can be disabled
to disable code sections, which can give faster compile time and smaller binary.
The "NO_COMPILE" defines are designed to be used to pass as defines to the
compiler command to disable them without modifying this header, e.g.
-DLODEPNG_NO_COMPILE_ZLIB for gcc.
In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to
allow implementing a custom lodepng_crc32.
*/
/*deflate & zlib. If disabled, you must specify alternative zlib functions in
the custom_zlib field of the compress and decompress settings*/
#ifndef LODEPNG_NO_COMPILE_ZLIB
#define LODEPNG_COMPILE_ZLIB
#endif
/*png encoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_PNG
#define LODEPNG_COMPILE_PNG
#endif
/*deflate&zlib decoder and png decoder*/
#ifndef LODEPNG_NO_COMPILE_DECODER
#define LODEPNG_COMPILE_DECODER
#endif
/*deflate&zlib encoder and png encoder*/
#ifndef LODEPNG_NO_COMPILE_ENCODER
#define LODEPNG_COMPILE_ENCODER
#endif
/*the optional built in harddisk file loading and saving functions*/
#ifndef LODEPNG_NO_COMPILE_DISK
#define LODEPNG_COMPILE_DISK
#endif
/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/
#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
#define LODEPNG_COMPILE_ANCILLARY_CHUNKS
#endif
/*ability to convert error numerical codes to English text string*/
#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT
#define LODEPNG_COMPILE_ERROR_TEXT
#endif
/*Compile the default allocators (C's free, malloc and realloc). If you disable this,
you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your
source files with custom allocators.*/
#ifndef LODEPNG_NO_COMPILE_ALLOCATORS
#define LODEPNG_COMPILE_ALLOCATORS
#endif
/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/
#ifdef __cplusplus
#ifndef LODEPNG_NO_COMPILE_CPP
#define LODEPNG_COMPILE_CPP
#endif
#endif
#ifdef LODEPNG_COMPILE_CPP
#include <vector>
#include <string>
#endif /*LODEPNG_COMPILE_CPP*/
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_DECODER
/*
Converts PNG data in memory to raw pixel data.
out: Output parameter. Pointer to buffer that will contain the raw pixel data.
After decoding, its size is w * h * (bytes per pixel) bytes larger than
initially. Bytes per pixel depends on colortype and bitdepth.
Must be freed after usage with free(*out).
Note: for 16-bit per channel colors, uses big endian format like PNG does.
w: Output parameter. Pointer to width of pixel data.
h: Output parameter. Pointer to height of pixel data.
in: Memory buffer with the PNG file.
insize: size of the in buffer.
colortype: the desired color type for the raw output image. See explanation on PNG color types.
bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize);
/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,
const unsigned char* in, size_t insize);
#ifdef LODEPNG_COMPILE_DISK
/*
Load PNG from disk, from file with given name.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename);
/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,
const char* filename);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
of the output PNG image cannot be chosen, they are automatically determined
by the colortype, bitdepth and content of the input pixel data.
Note: for 16-bit per channel colors, needs big endian format like PNG does.
out: Output parameter. Pointer to buffer that will contain the PNG image data.
Must be freed after usage with free(*out).
outsize: Output parameter. Pointer to the size in bytes of the out buffer.
image: The raw pixel data to encode. The size of this buffer should be
w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.
w: width of the raw pixel data in pixels.
h: height of the raw pixel data in pixels.
colortype: the color type of the raw input image. See explanation on PNG color types.
bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
Return value: LodePNG error code (0 means no error).
*/
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned lodepng_encode_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth);
/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
unsigned lodepng_encode32_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h);
/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
unsigned lodepng_encode24_file(const char* filename,
const unsigned char* image, unsigned w, unsigned h);
#endif /*LODEPNG_COMPILE_DISK*/
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_CPP
namespace lodepng {
#ifdef LODEPNG_COMPILE_DECODER
/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype
is the format to output the pixels to. Default is RGBA 8-bit per channel.*/
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const unsigned char* in, size_t insize,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::vector<unsigned char>& in,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts PNG file from disk to raw pixel data in memory.
Same as the other decode functions, but instead takes a filename as input.
*/
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::string& filename,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
is that of the raw input data. The output PNG color type will be auto chosen.*/
unsigned encode(voxelio::OutputStream& out,
const voxelio::u8* in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#ifdef LODEPNG_COMPILE_DISK
/*
Converts 32-bit RGBA raw pixel data into a PNG file on disk.
Same as the other encode functions, but instead takes a filename as output.
NOTE: This overwrites existing files without warning!
*/
unsigned encode(const std::string& filename,
const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
unsigned encode(const std::string& filename,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*Returns an English description of the numerical error code.*/
const char* lodepng_error_text(unsigned code);
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
#ifdef LODEPNG_COMPILE_DECODER
/*Settings for zlib decompression*/
typedef struct LodePNGDecompressSettings LodePNGDecompressSettings;
struct LodePNGDecompressSettings {
/* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */
unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/
/*use custom zlib decoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGDecompressSettings*);
/*use custom deflate decoder instead of built in one (default: null)
if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate)*/
unsigned (*custom_inflate)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGDecompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Settings for zlib compression. Tweaking these settings tweaks the balance
between speed and compression ratio.
*/
typedef struct LodePNGCompressSettings LodePNGCompressSettings;
struct LodePNGCompressSettings /*deflate = compress*/ {
/*LZ77 related settings*/
unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/
unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/
unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/
unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/
unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/
unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
/*use custom zlib encoder instead of built in one (default: null)*/
unsigned (*custom_zlib)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGCompressSettings*);
/*use custom deflate encoder instead of built in one (default: null)
if custom_zlib is used, custom_deflate is ignored since only the built in
zlib function will call custom_deflate*/
unsigned (*custom_deflate)(unsigned char**, size_t*,
const unsigned char*, size_t,
const LodePNGCompressSettings*);
const void* custom_context; /*optional custom settings for custom functions*/
};
extern const LodePNGCompressSettings lodepng_default_compress_settings;
void lodepng_compress_settings_init(LodePNGCompressSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_PNG
/*
Color mode of an image. Contains all information required to decode the pixel
bits to RGBA colors. This information is the same as used in the PNG file
format, and is used both for PNG and raw image data in LodePNG.
*/
typedef struct LodePNGColorMode {
/*header (IHDR)*/
LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/
/*
palette (PLTE and tRNS)
Dynamically allocated with the colors of the palette, including alpha.
This field may not be allocated directly, use lodepng_color_mode_init first,
then lodepng_palette_add per color to correctly initialize it (to ensure size
of exactly 1024 bytes).
The alpha channels must be set as well, set them to 255 for opaque images.
When decoding, by default you can ignore this palette, since LodePNG already
fills the palette colors in the pixels of the raw RGBA output.
The palette is only supported for color type 3.
*/
unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/
size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/
/*
transparent color key (tRNS)
This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
For grayscale PNGs, r, g and b will all 3 be set to the same.
When decoding, by default you can ignore this information, since LodePNG sets
pixels with this key to transparent already in the raw RGBA output.
The color key is only supported for color types 0 and 2.
*/
unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
unsigned key_r; /*red/grayscale component of color key*/
unsigned key_g; /*green component of color key*/
unsigned key_b; /*blue component of color key*/
} LodePNGColorMode;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_color_mode_init(LodePNGColorMode* info);
void lodepng_color_mode_cleanup(LodePNGColorMode* info);
/*return value is error code (0 means no error)*/
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);
/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */
LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth);
void lodepng_palette_clear(LodePNGColorMode* info);
/*add 1 color to the palette*/
unsigned lodepng_palette_add(LodePNGColorMode* info,
unsigned char r, unsigned char g, unsigned char b, unsigned char a);
/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
unsigned lodepng_get_bpp(const LodePNGColorMode* info);
/*get the amount of color channels used, based on colortype in the struct.
If a palette is used, it counts as 1 channel.*/
unsigned lodepng_get_channels(const LodePNGColorMode* info);
/*is it a grayscale type? (only colortype 0 or 4)*/
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);
/*has it got an alpha channel? (only colortype 2 or 6)*/
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info);
/*has it got a palette? (only colortype 3)*/
unsigned lodepng_is_palette_type(const LodePNGColorMode* info);
/*only returns true if there is a palette and there is a value in the palette with alpha < 255.
Loops through the palette to check this.*/
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);
/*
Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
Returns false if the image can only have opaque pixels.
In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
or if "key_defined" is true.
*/
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info);
/*Returns the byte size of a raw image buffer with given width, height and color mode*/
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*The information of a Time chunk in PNG.*/
typedef struct LodePNGTime {
unsigned year; /*2 bytes used (0-65535)*/
unsigned month; /*1-12*/
unsigned day; /*1-31*/
unsigned hour; /*0-23*/
unsigned minute; /*0-59*/
unsigned second; /*0-60 (to allow for leap seconds)*/
} LodePNGTime;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Information about the PNG image, except pixels, width and height.*/
typedef struct LodePNGInfo {
/*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
unsigned compression_method;/*compression method of the original file. Always 0.*/
unsigned filter_method; /*filter method of the original file*/
unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/
LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*
Suggested background color chunk (bKGD)
This uses the same color mode and bit depth as the PNG (except no alpha channel),
with values truncated to the bit depth in the unsigned integer.
For grayscale and palette PNGs, the value is stored in background_r. The values
in background_g and background_b are then unused.
So when decoding, you may get these in a different color mode than the one you requested
for the raw pixels.
When encoding with auto_convert, you must use the color model defined in info_png.color for
these values. The encoder normally ignores info_png.color when auto_convert is on, but will
use it to interpret these values (and convert copies of them to its chosen color model).
When encoding, avoid setting this to an expensive color, such as a non-gray value
when the image is gray, or the compression will be worse since it will be forced to
write the PNG with a more expensive color mode (when auto_convert is on).
The decoder does not use this background color to edit the color of pixels. This is a
completely optional metadata feature.
*/
unsigned background_defined; /*is a suggested background color given?*/
unsigned background_r; /*red/gray/palette component of suggested background color*/
unsigned background_g; /*green component of suggested background color*/
unsigned background_b; /*blue component of suggested background color*/
/*
non-international text chunks (tEXt and zTXt)
The char** arrays each contain num strings. The actual messages are in
text_strings, while text_keys are keywords that give a short description what
the actual text represents, e.g. Title, Author, Description, or anything else.
All the string fields below including keys, names and language tags are null terminated.
The PNG specification uses null characters for the keys, names and tags, and forbids null
characters to appear in the main text which is why we can use null termination everywhere here.
A keyword is minimum 1 character and maximum 79 characters long. It's
discouraged to use a single line length longer than 79 characters for texts.
Don't allocate these text buffers yourself. Use the init/cleanup functions
correctly and use lodepng_add_text and lodepng_clear_text.
*/
size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
char** text_strings; /*the actual text*/
/*
international text chunks (iTXt)
Similar to the non-international text chunks, but with additional strings
"langtags" and "transkeys".
*/
size_t itext_num; /*the amount of international texts in this PNG*/
char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
char** itext_strings; /*the actual international text - UTF-8 string*/
/*time chunk (tIME)*/
unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
LodePNGTime time;
/*phys chunk (pHYs)*/
unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/
unsigned phys_x; /*pixels per unit in x direction*/
unsigned phys_y; /*pixels per unit in y direction*/
unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
/*
Color profile related chunks: gAMA, cHRM, sRGB, iCPP
LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color
profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please
use these values with a color management library.
See the PNG, ICC and sRGB specifications for more information about the meaning of these values.
*/
/* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */
unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */
unsigned gama_gamma; /* Gamma exponent times 100000 */
/* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */
unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */
unsigned chrm_white_x; /* White Point x times 100000 */
unsigned chrm_white_y; /* White Point y times 100000 */
unsigned chrm_red_x; /* Red x times 100000 */
unsigned chrm_red_y; /* Red y times 100000 */
unsigned chrm_green_x; /* Green x times 100000 */
unsigned chrm_green_y; /* Green y times 100000 */
unsigned chrm_blue_x; /* Blue x times 100000 */
unsigned chrm_blue_y; /* Blue y times 100000 */
/*
sRGB chunk: optional. May not appear at the same time as iCCP.
If gAMA is also present gAMA must contain value 45455.
If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000.
*/
unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */
unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */
/*
iCCP chunk: optional. May not appear at the same time as sRGB.
LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a
separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color
management and conversions.
For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC
profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and
enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile.
For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray
PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure
the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is
enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder
error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel
data if the pixels could be encoded as grayscale but the ICC profile is RGB.
To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so
make sure you compute it carefully to avoid the above problems.
*/
unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */
char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */
/*
The ICC profile in iccp_profile_size bytes.
Don't allocate this buffer yourself. Use the init/cleanup functions
correctly and use lodepng_set_icc and lodepng_clear_icc.
*/
unsigned char* iccp_profile;
unsigned iccp_profile_size; /* The size of iccp_profile in bytes */
/* End of color profile related chunks */
/*
unknown chunks: chunks not known by LodePNG, passed on byte for byte.
There are 3 buffers, one for each position in the PNG where unknown chunks can appear.
Each buffer contains all unknown chunks for that position consecutively.
The 3 positions are:
0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.
For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag
above in here, since the encoder will blindly follow this and could then encode an invalid PNG file
(such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use
this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST),
or any non-standard PNG chunk.
Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
*/
unsigned char* unknown_chunks_data[3];
size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGInfo;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_info_init(LodePNGInfo* info);
void lodepng_info_cleanup(LodePNGInfo* info);
/*return value is error code (0 means no error)*/
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/
void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/
void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/
/*replaces if exists*/
unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size);
void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*
Converts raw buffer from one color type to another color type, based on
LodePNGColorMode structs to describe the input and output color type.
See the reference manual at the end of this header file to see which color conversions are supported.
return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
of the output color type (lodepng_get_bpp).
For < 8 bpp images, there should not be padding bits at the end of scanlines.
For 16-bit per channel colors, uses big endian format like PNG does.
Return value is LodePNG error code
*/
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
unsigned w, unsigned h);
#ifdef LODEPNG_COMPILE_DECODER
/*
Settings for the decoder. This contains settings for the PNG and the Zlib
decoder, but not the Info settings from the Info structs.
*/
typedef struct LodePNGDecoderSettings {
LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
/* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */
unsigned ignore_crc; /*ignore CRC checksums*/
unsigned ignore_critical; /*ignore unknown critical chunks*/
unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/
/* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable
errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some
strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters
in string keys, etc... */
unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/
/*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/
unsigned remember_unknown_chunks;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGDecoderSettings;
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
typedef enum LodePNGFilterStrategy {
/*every filter at zero*/
LFS_ZERO = 0,
/*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/
LFS_ONE = 1,
LFS_TWO = 2,
LFS_THREE = 3,
LFS_FOUR = 4,
/*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
LFS_MINSUM,
/*Use the filter type that gives smallest Shannon entropy for this scanline. Depending
on the image, this is better or worse than minsum.*/
LFS_ENTROPY,
/*
Brute-force-search PNG filters by compressing each filter for each scanline.
Experimental, very slow, and only rarely gives better compression than MINSUM.
*/
LFS_BRUTE_FORCE,
/*use predefined_filters buffer: you specify the filter type for each scanline*/
LFS_PREDEFINED
} LodePNGFilterStrategy;
/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...),
which helps decide which color model to use for encoding.
Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/
typedef struct LodePNGColorStats {
unsigned colored; /*not grayscale*/
unsigned key; /*image is not opaque and color key is possible instead of full alpha*/
unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/
unsigned short key_g;
unsigned short key_b;
unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/
unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/
unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/
unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/
size_t numpixels;
/*user settings for computing/using the stats*/
unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/
unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/
} LodePNGColorStats;
void lodepng_color_stats_init(LodePNGColorStats* stats);
/*Get a LodePNGColorStats of the image. The stats must already have been inited.
Returns error code (e.g. alloc fail) or 0 if ok.*/
unsigned lodepng_compute_color_stats(LodePNGColorStats* stats,
const unsigned char* image, unsigned w, unsigned h,
const LodePNGColorMode* mode_in);
/*Settings for the encoder.*/
typedef struct LodePNGEncoderSettings {
LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/
/*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than
8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to
completely follow the official PNG heuristic, filter_palette_zero must be true and
filter_strategy must be LFS_MINSUM*/
unsigned filter_palette_zero;
/*Which filter strategy to use when not using zeroes due to filter_palette_zero.
Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/
LodePNGFilterStrategy filter_strategy;
/*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with
the same length as the amount of scanlines in the image, and each value must <= 5. You
have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
const unsigned char* predefined_filters;
/*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
If colortype is 3, PLTE is _always_ created.*/
unsigned force_palette;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*add LodePNG identifier and version as a text chunk, for debugging*/
unsigned add_id;
/*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
unsigned text_compression;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} LodePNGEncoderSettings;
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
/*The settings, state and information for extended encoding and decoding.*/
typedef struct LodePNGState {
#ifdef LODEPNG_COMPILE_DECODER
LodePNGDecoderSettings decoder; /*the decoding settings*/
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
LodePNGEncoderSettings encoder; /*the encoding settings*/
#endif /*LODEPNG_COMPILE_ENCODER*/
LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
unsigned error;
} LodePNGState;
/*init, cleanup and copy functions to use with this struct*/
void lodepng_state_init(LodePNGState* state);
void lodepng_state_cleanup(LodePNGState* state);
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_DECODER
/*
Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
getting much more information about the PNG image and color mode.
*/
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize);
/*
Read the PNG header, but not the actual data. This returns only the information
that is in the IHDR chunk of the PNG, such as width, height and color type. The
information is placed in the info_png field of the LodePNGState.
*/
unsigned lodepng_inspect(unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize);
#endif /*LODEPNG_COMPILE_DECODER*/
/*
Reads one metadata chunk (other than IHDR) of the PNG file and outputs what it
read in the state. Returns error code on failure.
Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const
to find the desired chunk type, and if non null use lodepng_inspect_chunk (with
chunk_pointer - start_of_file as pos).
Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...).
Ignores unsupported, unknown, non-metadata or IHDR chunks (without error).
Requirements: &in[pos] must point to start of a chunk, must use regular
lodepng_inspect first since format of most other chunks depends on IHDR, and if
there is a PLTE chunk, that one must be inspected before tRNS or bKGD.
*/
unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
const unsigned char* in, size_t insize);
#ifdef LODEPNG_COMPILE_ENCODER
/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGState* state);
#endif /*LODEPNG_COMPILE_ENCODER*/
/*
The lodepng_chunk functions are normally not needed, except to traverse the
unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
It also allows traversing the chunks of an encoded PNG file yourself.
The chunk pointer always points to the beginning of the chunk itself, that is
the first byte of the 4 length bytes.
In the PNG file format, chunks have the following format:
-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)
-4 bytes chunk type (ASCII a-z,A-Z only, see below)
-length bytes of data (may be 0 bytes if length was 0)
-4 bytes of CRC, computed on chunk name + data
The first chunk starts at the 8th byte of the PNG file, the entire rest of the file
exists out of concatenated chunks with the above format.
PNG standard chunk ASCII naming conventions:
-First byte: uppercase = critical, lowercase = ancillary
-Second byte: uppercase = public, lowercase = private
-Third byte: must be uppercase
-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
*/
/*
Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
There must be at least 4 bytes to read from. If the result value is too large,
it may be corrupt data.
*/
unsigned lodepng_chunk_length(const unsigned char* chunk);
/*puts the 4-byte type in null terminated string*/
void lodepng_chunk_type(char type[5], const unsigned char* chunk);
/*check if the type is the given type*/
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);
/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk);
/*0: public, 1: private (see PNG standard)*/
unsigned char lodepng_chunk_private(const unsigned char* chunk);
/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);
/*get pointer to the data of the chunk, where the input points to the header of the chunk*/
unsigned char* lodepng_chunk_data(unsigned char* chunk);
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);
/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
unsigned lodepng_chunk_check_crc(const unsigned char* chunk);
/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
void lodepng_chunk_generate_crc(unsigned char* chunk);
/*
Iterate to next chunks, allows iterating through all chunks of the PNG file.
Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call,
or the 8th byte of a PNG file which always has the first chunk), or alternatively may
point to the first byte of the PNG file (which is not a chunk but the magic header, the
function will then skip over it and return the first real chunk).
Will output pointer to the start of the next chunk, or at or beyond end of the file if there
is no more chunk after this or possibly if the chunk is corrupt.
Start this process at the 8th byte of the PNG file.
In a non-corrupt PNG file, the last chunk should have name "IEND".
*/
unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end);
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end);
/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/
unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]);
const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]);
/*
Appends chunk to the data in out. The given chunk should already have its chunk header.
The out variable and outsize are updated to reflect the new reallocated buffer.
Returns error code (0 if it went ok)
*/
unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk);
/*
Appends new chunk to out. The chunk to append is given by giving its length, type
and data separately. The type is a 4-letter string.
The out variable and outsize are updated to reflect the new reallocated buffer.
Returne error code (0 if it went ok)
*/
unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,
const char* type, const unsigned char* data);
/*Calculate CRC32 of buffer*/
unsigned lodepng_crc32(const unsigned char* buf, size_t len);
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB
/*
This zlib part can be used independently to zlib compress and decompress a
buffer. It cannot be used to create gzip files however, and it only supports the
part of zlib that is required for PNG, it does not support dictionaries.
*/
#ifdef LODEPNG_COMPILE_DECODER
/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings);
/*
Decompresses Zlib data. Reallocates the out buffer and appends the data. The
data must be according to the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/*
Compresses data with Zlib. Reallocates the out buffer and appends the data.
Zlib adds a small header and trailer around the deflate data.
The data is output in the format of the zlib specification.
Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
buffer and *outsize its size in bytes. out must be freed by user after usage.
*/
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings);
/*
Find length-limited Huffman code for given frequencies. This function is in the
public interface only for tests, it's used internally by lodepng_deflate.
*/
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
size_t numcodes, unsigned maxbitlen);
/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings);
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into buffer. The function allocates the out buffer, and
after usage you should free it.
out: output parameter, contains pointer to loaded buffer.
outsize: output parameter, size of the allocated out buffer
filename: the path to the file to load
return value: error code (0 means ok)
*/
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);
/*
Save a file from buffer to disk. Warning, if it exists, this function overwrites
the file without warning!
buffer: the buffer to write
buffersize: size of the buffer to write
filename: the path to the file to save to
return value: error code (0 means ok)
*/
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);
#endif /*LODEPNG_COMPILE_DISK*/
#ifdef LODEPNG_COMPILE_CPP
/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
namespace lodepng {
#ifdef LODEPNG_COMPILE_PNG
class State : public LodePNGState {
public:
State();
State(const State& other);
~State();
State& operator=(const State& other);
};
#ifdef LODEPNG_COMPILE_DECODER
/* Same as other lodepng::decode, but using a State for more settings and information. */
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const unsigned char* in, size_t insize);
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const std::vector<unsigned char>& in);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_DISK
/*
Load a file from disk into an std::vector.
return value: error code (0 means ok)
*/
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);
/*
Save the binary data in an std::vector to a file on disk. The file is overwritten
without warning.
*/
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_PNG */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
/* Zlib-decompress an unsigned char buffer */
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
/* Zlib-decompress an std::vector */
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
/* Zlib-compress an unsigned char buffer */
unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
/* Zlib-compress an std::vector */
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
/*
TODO:
[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
[.] check compatibility with various compilers - done but needs to be redone for every newer version
[X] converting color to 16-bit per channel types
[X] support color profile chunk types (but never let them touch RGB values by default)
[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST)
[ ] make sure encoder generates no chunks with size > (2^31)-1
[ ] partial decoding (stream processing)
[X] let the "isFullyOpaque" function check color keys and transparent palettes too
[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58)
[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ...
[ ] error messages with line numbers (and version)
[ ] errors in state instead of as return code?
[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk
[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes
[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...
[ ] allow user to give data (void*) to custom allocator
[X] provide alternatives for C library functions not present on some platforms (memcpy, ...)
*/
#endif // VXIO_LODEPNG_HPP
/*
LodePNG Documentation
---------------------
0. table of contents
--------------------
1. about
1.1. supported features
1.2. features not supported
2. C and C++ version
3. security
4. decoding
5. encoding
6. color conversions
6.1. PNG color types
6.2. color conversions
6.3. padding bits
6.4. A note about 16-bits per channel and endianness
7. error values
8. chunks and PNG editing
9. compiler support
10. examples
10.1. decoder C++ example
10.2. decoder C example
11. state settings reference
12. changes
13. contact information
1. about
--------
PNG is a file format to store raster images losslessly with good compression,
supporting different color types and alpha channel.
LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
Specification (Second Edition) - W3C Recommendation 10 November 2003.
The specifications used are:
*) Portable Network Graphics (PNG) Specification (Second Edition):
http://www.w3.org/TR/2003/REC-PNG-20031110
*) RFC 1950 ZLIB Compressed Data Format version 3.3:
http://www.gzip.org/zlib/rfc-zlib.html
*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
http://www.gzip.org/zlib/rfc-deflate.html
The most recent version of LodePNG can currently be found at
http://lodev.org/lodepng/
LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
extra functionality.
LodePNG exists out of two files:
-lodepng.h: the header file for both C and C++
-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage
If you want to start using LodePNG right away without reading this doc, get the
examples from the LodePNG website to see how to use it in code, or check the
smaller examples in chapter 13 here.
LodePNG is simple but only supports the basic requirements. To achieve
simplicity, the following design choices were made: There are no dependencies
on any external library. There are functions to decode and encode a PNG with
a single function call, and extended versions of these functions taking a
LodePNGState struct allowing to specify or get more information. By default
the colors of the raw image are always RGB or RGBA, no matter what color type
the PNG file uses. To read and write files, there are simple functions to
convert the files to/from buffers in memory.
This all makes LodePNG suitable for loading textures in games, demos and small
programs, ... It's less suitable for full fledged image editors, loading PNGs
over network (it requires all the image data to be available before decoding can
begin), life-critical systems, ...
1.1. supported features
-----------------------
The following features are supported by the decoder:
*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,
or the same color type as the PNG
*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image
*) Adam7 interlace and deinterlace for any color type
*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk
*) support for alpha channels, including RGBA color model, translucent palettes and color keying
*) zlib decompression (inflate)
*) zlib compression (deflate)
*) CRC32 and ADLER32 checksums
*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only,
plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system.
*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.
*) the following chunks are supported by both encoder and decoder:
IHDR: header information
PLTE: color palette
IDAT: pixel data
IEND: the final chunk
tRNS: transparency for palettized images
tEXt: textual information
zTXt: compressed textual information
iTXt: international textual information
bKGD: suggested background color
pHYs: physical dimensions
tIME: modification time
cHRM: RGB chromaticities
gAMA: RGB gamma correction
iCCP: ICC color profile
sRGB: rendering intent
1.2. features not supported
---------------------------
The following features are _not_ supported:
*) some features needed to make a conformant PNG-Editor might be still missing.
*) partial loading/stream processing. All data must be available and is processed in one call.
*) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG:
sBIT
hIST
sPLT
2. C and C++ version
--------------------
The C version uses buffers allocated with alloc that you need to free()
yourself. You need to use init and cleanup functions for each struct whenever
using a struct from the C version to avoid exploits and memory leaks.
The C++ version has extra functions with std::vectors in the interface and the
lodepng::State class which is a LodePNGState with constructor and destructor.
These files work without modification for both C and C++ compilers because all
the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers
ignore it, and the C code is made to compile both with strict ISO C90 and C++.
To use the C++ version, you need to rename the source file to lodepng.cpp
(instead of lodepng.c), and compile it with a C++ compiler.
To use the C version, you need to rename the source file to lodepng.c (instead
of lodepng.cpp), and compile it with a C compiler.
3. Security
-----------
Even if carefully designed, it's always possible that LodePNG contains possible
exploits. If you discover one, please let me know, and it will be fixed.
When using LodePNG, care has to be taken with the C version of LodePNG, as well
as the C-style structs when working with C++. The following conventions are used
for all C-style structs:
-if a struct has a corresponding init function, always call the init function when making a new one
-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks
-if a struct has a corresponding copy function, use the copy function instead of "=".
The destination must also be inited already.
4. Decoding
-----------
Decoding converts a PNG compressed image to a raw pixel buffer.
Most documentation on using the decoder is at its declarations in the header
above. For C, simple decoding can be done with functions such as
lodepng_decode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_decode. For C++, all decoding can be done with the
various lodepng::decode functions, and lodepng::State can be used for advanced
features.
When using the LodePNGState, it uses the following fields for decoding:
*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here
*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get
*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use
LodePNGInfo info_png
--------------------
After decoding, this contains extra information of the PNG image, except the actual
pixels, width and height because these are already gotten directly from the decoder
functions.
It contains for example the original color type of the PNG image, text comments,
suggested background color, etc... More details about the LodePNGInfo struct are
at its declaration documentation.
LodePNGColorMode info_raw
-------------------------
When decoding, here you can specify which color type you want
the resulting raw image to be. If this is different from the colortype of the
PNG, then the decoder will automatically convert the result. This conversion
always works, except if you want it to convert a color PNG to grayscale or to
a palette with missing colors.
By default, 32-bit color is used for the result.
LodePNGDecoderSettings decoder
------------------------------
The settings can be used to ignore the errors created by invalid CRC and Adler32
chunks, and to disable the decoding of tEXt chunks.
There's also a setting color_convert, true by default. If false, no conversion
is done, the resulting data will be as it was in the PNG (after decompression)
and you'll have to puzzle the colors of the pixels together yourself using the
color type information in the LodePNGInfo.
5. Encoding
-----------
Encoding converts a raw pixel buffer to a PNG compressed image.
Most documentation on using the encoder is at its declarations in the header
above. For C, simple encoding can be done with functions such as
lodepng_encode32, and more advanced decoding can be done with the struct
LodePNGState and lodepng_encode. For C++, all encoding can be done with the
various lodepng::encode functions, and lodepng::State can be used for advanced
features.
Like the decoder, the encoder can also give errors. However it gives less errors
since the encoder input is trusted, the decoder input (a PNG image that could
be forged by anyone) is not trusted.
When using the LodePNGState, it uses the following fields for encoding:
*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.
*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has
*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use
LodePNGInfo info_png
--------------------
When encoding, you use this the opposite way as when decoding: for encoding,
you fill in the values you want the PNG to have before encoding. By default it's
not needed to specify a color type for the PNG since it's automatically chosen,
but it's possible to choose it yourself given the right settings.
The encoder will not always exactly match the LodePNGInfo struct you give,
it tries as close as possible. Some things are ignored by the encoder. The
encoder uses, for example, the following settings from it when applicable:
colortype and bitdepth, text chunks, time chunk, the color key, the palette, the
background color, the interlace method, unknown chunks, ...
When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.
If the palette contains any colors for which the alpha channel is not 255 (so
there are translucent colors in the palette), it'll add a tRNS chunk.
LodePNGColorMode info_raw
-------------------------
You specify the color type of the raw image that you give to the input here,
including a possible transparent color key and palette you happen to be using in
your raw image data.
By default, 32-bit color is assumed, meaning your input has to be in RGBA
format with 4 bytes (unsigned chars) per pixel.
LodePNGEncoderSettings encoder
------------------------------
The following settings are supported (some are in sub-structs):
*) auto_convert: when this option is enabled, the encoder will
automatically choose the smallest possible color mode (including color key) that
can encode the colors of all pixels without information loss.
*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,
2 = dynamic huffman tree (best compression). Should be 2 for proper
compression.
*) use_lz77: whether or not to use LZ77 for compressed block types. Should be
true for proper compression.
*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value
2048 by default, but can be set to 32768 for better, but slow, compression.
*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE
chunk if force_palette is true. This can used as suggested palette to convert
to by viewers that don't support more than 256 colors (if those still exist)
*) add_id: add text chunk "Encoder: LodePNG <version>" to the image.
*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.
zTXt chunks use zlib compression on the text. This gives a smaller result on
large texts but a larger result on small texts (such as a single program name).
It's all tEXt or all zTXt though, there's no separate setting per text yet.
6. color conversions
--------------------
An important thing to note about LodePNG, is that the color type of the PNG, and
the color type of the raw image, are completely independent. By default, when
you decode a PNG, you get the result as a raw image in the color type you want,
no matter whether the PNG was encoded with a palette, grayscale or RGBA color.
And if you encode an image, by default LodePNG will automatically choose the PNG
color type that gives good compression based on the values of colors and amount
of colors in the image. It can be configured to let you control it instead as
well, though.
To be able to do this, LodePNG does conversions from one color mode to another.
It can convert from almost any color type to any other color type, except the
following conversions: RGB to grayscale is not supported, and converting to a
palette when the palette doesn't have a required color is not supported. This is
not supported on purpose: this is information loss which requires a color
reduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray
is easy, but there are multiple ways if you want to give some channels more
weight).
By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB
color, no matter what color type the PNG has. And by default when encoding,
LodePNG automatically picks the best color model for the output PNG, and expects
the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control
the color format of the images yourself, you can skip this chapter.
6.1. PNG color types
--------------------
A PNG image can have many color types, ranging from 1-bit color to 64-bit color,
as well as palettized color modes. After the zlib decompression and unfiltering
in the PNG image is done, the raw pixel data will have that color type and thus
a certain amount of bits per pixel. If you want the output raw image after
decoding to have another color type, a conversion is done by LodePNG.
The PNG specification gives the following color types:
0: grayscale, bit depths 1, 2, 4, 8, 16
2: RGB, bit depths 8 and 16
3: palette, bit depths 1, 2, 4 and 8
4: grayscale with alpha, bit depths 8 and 16
6: RGBA, bit depths 8 and 16
Bit depth is the amount of bits per pixel per color channel. So the total amount
of bits per pixel is: amount of channels * bitdepth.
6.2. color conversions
----------------------
As explained in the sections about the encoder and decoder, you can specify
color types and bit depths in info_png and info_raw to change the default
behaviour.
If, when decoding, you want the raw image to be something else than the default,
you need to set the color type and bit depth you want in the LodePNGColorMode,
or the parameters colortype and bitdepth of the simple decoding function.
If, when encoding, you use another color type than the default in the raw input
image, you need to specify its color type and bit depth in the LodePNGColorMode
of the raw image, or use the parameters colortype and bitdepth of the simple
encoding function.
If, when encoding, you don't want LodePNG to choose the output PNG color type
but control it yourself, you need to set auto_convert in the encoder settings
to false, and specify the color type you want in the LodePNGInfo of the
encoder (including palette: it can generate a palette if auto_convert is true,
otherwise not).
If the input and output color type differ (whether user chosen or auto chosen),
LodePNG will do a color conversion, which follows the rules below, and may
sometimes result in an error.
To avoid some confusion:
-the decoder converts from PNG to raw image
-the encoder converts from raw image to PNG
-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image
-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG
-when encoding, the color type in LodePNGInfo is ignored if auto_convert
is enabled, it is automatically generated instead
-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original
PNG image, but it can be ignored since the raw image has the color type you requested instead
-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion
between the color types is done if the color types are supported. If it is not
supported, an error is returned. If the types are the same, no conversion is done.
-even though some conversions aren't supported, LodePNG supports loading PNGs from any
colortype and saving PNGs to any colortype, sometimes it just requires preparing
the raw image correctly before encoding.
-both encoder and decoder use the same color converter.
The function lodepng_convert does the color conversion. It is available in the
interface but normally isn't needed since the encoder and decoder already call
it.
Non supported color conversions:
-color to grayscale when non-gray pixels are present: no error is thrown, but
the result will look ugly because only the red channel is taken (it assumes all
three channels are the same in this case so ignores green and blue). The reason
no error is given is to allow converting from three-channel grayscale images to
one-channel even if there are numerical imprecisions.
-anything to palette when the palette does not have an exact match for a from-color
in it: in this case an error is thrown
Supported color conversions:
-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA
-any gray or gray+alpha, to gray or gray+alpha
-anything to a palette, as long as the palette has the requested colors in it
-removing alpha channel
-higher to smaller bitdepth, and vice versa
If you want no color conversion to be done (e.g. for speed or control):
-In the encoder, you can make it save a PNG with any color type by giving the
raw color mode and LodePNGInfo the same color mode, and setting auto_convert to
false.
-In the decoder, you can make it store the pixel data in the same color type
as the PNG has, by setting the color_convert setting to false. Settings in
info_raw are then ignored.
6.3. padding bits
-----------------
In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines
have a bit amount that isn't a multiple of 8, then padding bits are used so that each
scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.
The raw input image you give to the encoder, and the raw output image you get from the decoder
will NOT have these padding bits, e.g. in the case of a 1-bit image with a width
of 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte,
not the first bit of a new byte.
6.4. A note about 16-bits per channel and endianness
----------------------------------------------------
LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like
for any other color format. The 16-bit values are stored in big endian (most
significant byte first) in these arrays. This is the opposite order of the
little endian used by x86 CPU's.
LodePNG always uses big endian because the PNG file format does so internally.
Conversions to other formats than PNG uses internally are not supported by
LodePNG on purpose, there are myriads of formats, including endianness of 16-bit
colors, the order in which you store R, G, B and A, and so on. Supporting and
converting to/from all that is outside the scope of LodePNG.
This may mean that, depending on your use case, you may want to convert the big
endian output of LodePNG to little endian with a for loop. This is certainly not
always needed, many applications and libraries support big endian 16-bit colors
anyway, but it means you cannot simply cast the unsigned char* buffer to an
unsigned short* buffer on x86 CPUs.
7. error values
---------------
All functions in LodePNG that return an error code, return 0 if everything went
OK, or a non-zero code if there was an error.
The meaning of the LodePNG error values can be retrieved with the function
lodepng_error_text: given the numerical error code, it returns a description
of the error in English as a string.
Check the implementation of lodepng_error_text to see the meaning of each code.
8. chunks and PNG editing
-------------------------
If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG
editor that should follow the rules about handling of unknown chunks, or if your
program is able to read other types of chunks than the ones handled by LodePNG,
then that's possible with the chunk functions of LodePNG.
A PNG chunk has the following layout:
4 bytes length
4 bytes type name
length bytes data
4 bytes CRC
8.1. iterating through chunks
-----------------------------
If you have a buffer containing the PNG image data, then the first chunk (the
IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the
signature of the PNG and are not part of a chunk. But if you start at byte 8
then you have a chunk, and can check the following things of it.
NOTE: none of these functions check for memory buffer boundaries. To avoid
exploits, always make sure the buffer contains all the data of the chunks.
When using lodepng_chunk_next, make sure the returned value is within the
allocated memory.
unsigned lodepng_chunk_length(const unsigned char* chunk):
Get the length of the chunk's data. The total chunk length is this length + 12.
void lodepng_chunk_type(char type[5], const unsigned char* chunk):
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):
Get the type of the chunk or compare if it's a certain type
unsigned char lodepng_chunk_critical(const unsigned char* chunk):
unsigned char lodepng_chunk_private(const unsigned char* chunk):
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):
Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).
Check if the chunk is private (public chunks are part of the standard, private ones not).
Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical
chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your
program doesn't handle that type of unknown chunk.
unsigned char* lodepng_chunk_data(unsigned char* chunk):
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):
Get a pointer to the start of the data of the chunk.
unsigned lodepng_chunk_check_crc(const unsigned char* chunk):
void lodepng_chunk_generate_crc(unsigned char* chunk):
Check if the crc is correct or generate a correct one.
unsigned char* lodepng_chunk_next(unsigned char* chunk):
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):
Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these
functions do no boundary checking of the allocated data whatsoever, so make sure there is enough
data available in the buffer to be able to go to the next chunk.
unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk):
unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,
const char* type, const unsigned char* data):
These functions are used to create new chunks that are appended to the data in *out that has
length *outsize. The append function appends an existing chunk to the new data. The create
function creates a new chunk with the given parameters and appends it. Type is the 4-letter
name of the chunk.
8.2. chunks in info_png
-----------------------
The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3
buffers (each with size) to contain 3 types of unknown chunks:
the ones that come before the PLTE chunk, the ones that come between the PLTE
and the IDAT chunks, and the ones that come after the IDAT chunks.
It's necessary to make the distinction between these 3 cases because the PNG
standard forces to keep the ordering of unknown chunks compared to the critical
chunks, but does not force any other ordering rules.
info_png.unknown_chunks_data[0] is the chunks before PLTE
info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT
info_png.unknown_chunks_data[2] is the chunks after IDAT
The chunks in these 3 buffers can be iterated through and read by using the same
way described in the previous subchapter.
When using the decoder to decode a PNG, you can make it store all unknown chunks
if you set the option settings.remember_unknown_chunks to 1. By default, this
option is off (0).
The encoder will always encode unknown chunks that are stored in the info_png.
If you need it to add a particular chunk that isn't known by LodePNG, you can
use lodepng_chunk_append or lodepng_chunk_create to the chunk data in
info_png.unknown_chunks_data[x].
Chunks that are known by LodePNG should not be added in that way. E.g. to make
LodePNG add a bKGD chunk, set background_defined to true and add the correct
parameters there instead.
9. compiler support
-------------------
No libraries other than the current standard C library are needed to compile
LodePNG. For the C++ version, only the standard C++ library is needed on top.
Add the files lodepng.c(pp) and lodepng.h to your project, include
lodepng.h where needed, and your program can read/write PNG files.
It is compatible with C90 and up, and C++03 and up.
If performance is important, use optimization when compiling! For both the
encoder and decoder, this makes a large difference.
Make sure that LodePNG is compiled with the same compiler of the same version
and with the same settings as the rest of the program, or the interfaces with
std::vectors and std::strings in C++ can be incompatible.
CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.
*) gcc and g++
LodePNG is developed in gcc so this compiler is natively supported. It gives no
warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++
version 4.7.1 on Linux, 32-bit and 64-bit.
*) Clang
Fully supported and warning-free.
*) Mingw
The Mingw compiler (a port of gcc for Windows) should be fully supported by
LodePNG.
*) Visual Studio and Visual C++ Express Edition
LodePNG should be warning-free with warning level W4. Two warnings were disabled
with pragmas though: warning 4244 about implicit conversions, and warning 4996
where it wants to use a non-standard function fopen_s instead of the standard C
fopen.
Visual Studio may want "stdafx.h" files to be included in each source file and
give an error "unexpected end of file while looking for precompiled header".
This is not standard C++ and will not be added to the stock LodePNG. You can
disable it for lodepng.cpp only by right clicking it, Properties, C/C++,
Precompiled Headers, and set it to Not Using Precompiled Headers there.
NOTE: Modern versions of VS should be fully supported, but old versions, e.g.
VS6, are not guaranteed to work.
*) Compilers on Macintosh
LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for
C and C++.
*) Other Compilers
If you encounter problems on any compilers, feel free to let me know and I may
try to fix it if the compiler is modern and standards compliant.
10. examples
------------
This decoder example shows the most basic usage of LodePNG. More complex
examples can be found on the LodePNG website.
10.1. decoder C++ example
-------------------------
#include "lodepng.h"
#include <iostream>
int main(int argc, char *argv[]) {
const char* filename = argc > 1 ? argv[1] : "test.png";
//load and decode
std::vector<unsigned char> image;
unsigned width, height;
unsigned error = lodepng::decode(image, width, height, filename);
//if there's an error, display it
if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
//the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
}
10.2. decoder C example
-----------------------
#include "lodepng.h"
int main(int argc, char *argv[]) {
unsigned error;
unsigned char* image;
size_t width, height;
const char* filename = argc > 1 ? argv[1] : "test.png";
error = lodepng_decode32_file(&image, &width, &height, filename);
if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error));
/ * use image here * /
free(image);
return 0;
}
11. state settings reference
----------------------------
A quick reference of some settings to set on the LodePNGState
For decoding:
state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums
state.decoder.zlibsettings.custom_...: use custom inflate function
state.decoder.ignore_crc: ignore CRC checksums
state.decoder.ignore_critical: ignore unknown critical chunks
state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors
state.decoder.color_convert: convert internal PNG color to chosen one
state.decoder.read_text_chunks: whether to read in text metadata chunks
state.decoder.remember_unknown_chunks: whether to read in unknown chunks
state.info_raw.colortype: desired color type for decoded image
state.info_raw.bitdepth: desired bit depth for decoded image
state.info_raw....: more color settings, see struct LodePNGColorMode
state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo
For encoding:
state.encoder.zlibsettings.btype: disable compression by setting it to 0
state.encoder.zlibsettings.use_lz77: use LZ77 in compression
state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize
state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match
state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching
state.encoder.zlibsettings.lazymatching: try one more LZ77 matching
state.encoder.zlibsettings.custom_...: use custom deflate function
state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png
state.encoder.filter_palette_zero: PNG filter strategy for palette
state.encoder.filter_strategy: PNG filter strategy to encode with
state.encoder.force_palette: add palette even if not encoding to one
state.encoder.add_id: add LodePNG identifier and version as a text chunk
state.encoder.text_compression: use compressed text chunks for metadata
state.info_raw.colortype: color type of raw input image you provide
state.info_raw.bitdepth: bit depth of raw input image you provide
state.info_raw: more color settings, see struct LodePNGColorMode
state.info_png.color.colortype: desired color type if auto_convert is false
state.info_png.color.bitdepth: desired bit depth if auto_convert is false
state.info_png.color....: more color settings, see struct LodePNGColorMode
state.info_png....: more PNG related settings, see struct LodePNGInfo
12. changes
-----------
The version number of LodePNG is the date of the change given in the format
yyyymmdd.
Some changes aren't backwards compatible. Those are indicated with a (!)
symbol.
Not all changes are listed here, the commit history in github lists more:
https://github.com/lvandeve/lodepng
*) 06 mar 2020: simplified some of the dynamic memory allocations.
*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct
overflow checks.
*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables.
*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette
if gray ICC profile) and non-ICC LodePNGColorProfile renamed to
LodePNGColorStats.
*) 30 dec 2018: code style changes only: removed newlines before opening braces.
*) 10 sep 2018: added way to inspect metadata chunks without full decoding.
*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use
palette index in case of palette.
*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This
change is backwards compatible unless you relied on unknown_chunks for those.
*) 11 jun 2018: less restrictive check for pixel size integer overflow
*) 14 jan 2018: allow optionally ignoring a few more recoverable errors
*) 17 sep 2017: fix memory leak for some encoder input error cases
*) 27 nov 2016: grey+alpha auto color model detection bugfix
*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort).
*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within
the limits of pure C90).
*) 08 dec 2015: Made load_file function return error if file can't be opened.
*) 24 okt 2015: Bugfix with decoding to palette output.
*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.
*) 24 aug 2014: Moved to github
*) 23 aug 2014: Reduced needless memory usage of decoder.
*) 28 jun 2014: Removed fix_png setting, always support palette OOB for
simplicity. Made ColorProfile public.
*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.
*) 22 dec 2013: Power of two windowsize required for optimization.
*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.
*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).
*) 11 mar 2013: (!) Bugfix with custom free. Changed from "my" to "lodepng_"
prefix for the custom allocators and made it possible with a new #define to
use custom ones in your project without needing to change lodepng's code.
*) 28 jan 2013: Bugfix with color key.
*) 27 okt 2012: Tweaks in text chunk keyword length error handling.
*) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode.
(no palette). Better deflate tree encoding. New compression tweak settings.
Faster color conversions while decoding. Some internal cleanups.
*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.
*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions
and made it work with function pointers instead.
*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc
and free functions and toggle #defines from compiler flags. Small fixes.
*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible.
*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed
redundant C++ codec classes. Reduced amount of structs. Everything changed,
but it is cleaner now imho and functionality remains the same. Also fixed
several bugs and shrunk the implementation code. Made new samples.
*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best
PNG color model and bit depth, based on the amount and type of colors of the
raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.
*) 9 okt 2011: simpler hash chain implementation for the encoder.
*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.
*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.
A bug with the PNG filtertype heuristic was fixed, so that it chooses much
better ones (it's quite significant). A setting to do an experimental, slow,
brute force search for PNG filter types is added.
*) 17 aug 2011: (!) changed some C zlib related function names.
*) 16 aug 2011: made the code less wide (max 120 characters per line).
*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.
*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.
*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman
to optimize long sequences of zeros.
*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and
LodePNG_InfoColor_canHaveAlpha functions for convenience.
*) 7 nov 2010: added LodePNG_error_text function to get error code description.
*) 30 okt 2010: made decoding slightly faster
*) 26 okt 2010: (!) changed some C function and struct names (more consistent).
Reorganized the documentation and the declaration order in the header.
*) 08 aug 2010: only changed some comments and external samples.
*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.
*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.
*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could
read by ignoring the problem but windows apps couldn't.
*) 06 jun 2008: added more error checks for out of memory cases.
*) 26 apr 2008: added a few more checks here and there to ensure more safety.
*) 06 mar 2008: crash with encoding of strings fixed
*) 02 feb 2008: support for international text chunks added (iTXt)
*) 23 jan 2008: small cleanups, and #defines to divide code in sections
*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.
*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.
*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added
Also various fixes, such as in the deflate and the padding bits code.
*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved
filtering code of encoder.
*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A
C++ wrapper around this provides an interface almost identical to before.
Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code
are together in these files but it works both for C and C++ compilers.
*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks
*) 30 aug 2007: bug fixed which makes this Borland C++ compatible
*) 09 aug 2007: some VS2005 warnings removed again
*) 21 jul 2007: deflate code placed in new namespace separate from zlib code
*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images
*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing
invalid std::vector element [0] fixed, and level 3 and 4 warnings removed
*) 02 jun 2007: made the encoder add a tag with version by default
*) 27 may 2007: zlib and png code separated (but still in the same file),
simple encoder/decoder functions added for more simple usage cases
*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),
moved some examples from here to lodepng_examples.cpp
*) 12 may 2007: palette decoding bug fixed
*) 24 apr 2007: changed the license from BSD to the zlib license
*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.
*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding
palettized PNG images. Plus little interface change with palette and texts.
*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.
Fixed a bug where the end code of a block had length 0 in the Huffman tree.
*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented
and supported by the encoder, resulting in smaller PNGs at the output.
*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.
*) 24 jan 2007: gave encoder an error interface. Added color conversion from any
greyscale type to 8-bit greyscale with or without alpha.
*) 21 jan 2007: (!) Totally changed the interface. It allows more color types
to convert to and is more uniform. See the manual for how it works now.
*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:
encode/decode custom tEXt chunks, separate classes for zlib & deflate, and
at last made the decoder give errors for incorrect Adler32 or Crc.
*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.
*) 29 dec 2006: Added support for encoding images without alpha channel, and
cleaned out code as well as making certain parts faster.
*) 28 dec 2006: Added "Settings" to the encoder.
*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.
Removed some code duplication in the decoder. Fixed little bug in an example.
*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.
Fixed a bug of the decoder with 16-bit per color.
*) 15 okt 2006: Changed documentation structure
*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the
given image buffer, however for now it's not compressed.
*) 08 sep 2006: (!) Changed to interface with a Decoder class
*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different
way. Renamed decodePNG to decodePNGGeneric.
*) 29 jul 2006: (!) Changed the interface: image info is now returned as a
struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.
*) 28 jul 2006: Cleaned the code and added new error checks.
Corrected terminology "deflate" into "inflate".
*) 23 jun 2006: Added SDL example in the documentation in the header, this
example allows easy debugging by displaying the PNG and its transparency.
*) 22 jun 2006: (!) Changed way to obtain error value. Added
loadFile function for convenience. Made decodePNG32 faster.
*) 21 jun 2006: (!) Changed type of info vector to unsigned.
Changed position of palette in info vector. Fixed an important bug that
happened on PNGs with an uncompressed block.
*) 16 jun 2006: Internally changed unsigned into unsigned where
needed, and performed some optimizations.
*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them
in LodePNG namespace. Changed the order of the parameters. Rewrote the
documentation in the header. Renamed files to lodepng.cpp and lodepng.h
*) 22 apr 2006: Optimized and improved some code
*) 07 sep 2005: (!) Changed to std::vector interface
*) 12 aug 2005: Initial release (C++, decoder only)
13. contact information
-----------------------
Feel free to contact me with suggestions, problems, comments, ... concerning
LodePNG. If you encounter a PNG image that doesn't work properly with this
decoder, feel free to send it and I'll use it to find and fix the problem.
My email address is (puzzle the account and domain together with an @ symbol):
Domain: gmail dot com.
Account: lode dot vandevenne.
Copyright (c) 2005-2020 Lode Vandevenne
*/
| 48.084156
| 136
| 0.75276
|
Eisenwave
|
4c64e7e41edd0448714ab80a001590deabd9bfc8
| 21,132
|
cpp
|
C++
|
sundog_engine/various/palmos/palm_functions.cpp
|
Sound-Linux-More/sunvox
|
7376fbe9f9bca92be1e17aefaac2e68b558d8357
|
[
"BSD-3-Clause"
] | 100
|
2016-01-15T02:43:07.000Z
|
2022-03-16T14:02:38.000Z
|
sundog_engine/various/palmos/palm_functions.cpp
|
Sound-Linux-More/sunvox
|
7376fbe9f9bca92be1e17aefaac2e68b558d8357
|
[
"BSD-3-Clause"
] | 2
|
2018-01-10T18:21:37.000Z
|
2021-12-05T01:48:08.000Z
|
sundog_engine/various/palmos/palm_functions.cpp
|
Sound-Linux-More/sunvox
|
7376fbe9f9bca92be1e17aefaac2e68b558d8357
|
[
"BSD-3-Clause"
] | 17
|
2016-05-16T19:48:19.000Z
|
2022-03-23T10:59:42.000Z
|
#include <PalmOS.h>
#include "VFSMgr.h"
#include "PceNativeCall.h"
#include "palm_functions.h"
// local definition of the emulation state structure
void *g_form_handler;
long *g_new_screen_size;
EmulStateType *emulStatePtr;
Call68KFuncType *call68KFuncPtr;
unsigned char args_stack[ 4 * 32 ];
unsigned char args_ptr = 0;
// =================
// PalmOS functions:
// =================
Char *StrCat( Char *dst, const Char *src )
{
CALL P4(dst) P4(src) return (Char*)TRAPP(sysTrapStrCat)
}
UInt16 StrLen( const Char *src )
{
CALL P4(src) return (UInt16)TRAP(sysTrapStrLen)
}
Int16 StrCompare( const Char *s1, const Char *s2 )
{
CALL P4(s1) P4(s2) return (UInt16)TRAP(sysTrapStrCompare)
}
Err MemSemaphoreReserve( Boolean writeAccess )
{
CALL P1(writeAccess) return (Err)TRAP(sysTrapMemSemaphoreReserve)
}
Err MemSemaphoreRelease( Boolean writeAccess )
{
CALL P1(writeAccess) return (Err)TRAP(sysTrapMemSemaphoreRelease)
}
UInt16 MemHeapID( UInt16 cardNo, UInt16 heapIndex )
{
CALL P2(cardNo) P2(heapIndex) return (UInt16)TRAP(sysTrapMemHeapID)
}
Err MemMove( void *dstP, const void *sP, Int32 numBytes )
{
CALL P4(dstP) P4(sP) P4(numBytes) return (Err)TRAP(sysTrapMemMove)
}
Err MemSet( void *dstP, Int32 numBytes, UInt8 value )
{
CALL P4(dstP) P4(numBytes) P1(value) return (Err)TRAP(sysTrapMemSet)
}
Int16 MemCmp ( const void* s1, const void* s2, Int32 numBytes )
{
CALL P4(s1) P4(s2) P4(numBytes) return (Int16)TRAP(sysTrapMemCmp)
}
Err MemChunkFree( MemPtr chunkDataP )
{
CALL P4(chunkDataP) return (Err)TRAP(sysTrapMemChunkFree)
}
MemPtr MemChunkNew( UInt16 heapID, UInt32 size, UInt16 attr )
{
CALL P2(heapID) P4(size) P2(attr) return (MemPtr)TRAPP(sysTrapMemChunkNew)
}
MemHandle MemHandleNew( UInt32 size )
{
CALL P4(size) return (MemHandle)TRAPP(sysTrapMemHandleNew)
}
Err MemHandleFree( MemHandle h )
{
CALL P4(h) return (Err)TRAP(sysTrapMemHandleFree)
}
UInt16 MemHandleLockCount( MemHandle h )
{
CALL P4(h) return (UInt16)TRAP(sysTrapMemHandleLockCount)
}
MemPtr MemHandleLock( MemHandle h )
{
CALL P4(h) return (MemPtr)TRAPP(sysTrapMemHandleLock)
}
Err MemHandleUnlock( MemHandle h )
{
CALL P4(h) return (Err)TRAP(sysTrapMemHandleUnlock)
}
UInt32 MemHandleSize( MemHandle h )
{
CALL P4(h) return (UInt32)TRAP(sysTrapMemHandleSize)
}
MemPtr MemPtrNew( UInt32 size )
{
CALL P4(size) return (MemPtr)TRAPP(sysTrapMemPtrNew)
}
UInt16 MemPtrHeapID( MemPtr p )
{
CALL P4(p) return (UInt16)TRAP(sysTrapMemPtrHeapID)
}
// =================
// VFS :
// =================
Err VFSVolumeEnumerate( UInt16 *volRefNumP, UInt32 *volIteratorP )
{
*volIteratorP = BSwap32( *volIteratorP ); // <->
CALL P4(volRefNumP) P4(volIteratorP)
emulStatePtr->regData[2] = vfsTrapVolumeEnumerate;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( volIteratorP ) *volIteratorP = BSwap32( *volIteratorP ); // <->
if( volRefNumP ) *volRefNumP = BSwap16( *volRefNumP ); // <-
return retval;
}
Err VFSFileOpen( UInt16 volRefNum, const Char *pathNameP,UInt16 openMode, FileRef *fileRefP )
{
CALL P2(volRefNum) P4(pathNameP) P2(openMode) P4(fileRefP)
emulStatePtr->regData[2] = vfsTrapFileOpen;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( fileRefP ) *fileRefP = (FileRef)BSwap32( *fileRefP ); // <-
return retval;
}
Err VFSFileClose( FileRef fileRef )
{
CALL P4(fileRef)
emulStatePtr->regData[2] = vfsTrapFileClose;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileCreate( UInt16 volRefNum, const Char *pathNameP )
{
CALL P2(volRefNum) P4(pathNameP)
emulStatePtr->regData[2] = vfsTrapFileCreate;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileReadData( FileRef fileRef, UInt32 numBytes, void *bufBaseP, UInt32 offset, UInt32 *numBytesReadP )
{
CALL P4(fileRef) P4(numBytes) P4(bufBaseP) P4(offset) P4(numBytesReadP)
emulStatePtr->regData[2] = vfsTrapFileReadData;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( numBytesReadP ) *numBytesReadP = BSwap32( *numBytesReadP ); // <-
return retval;
}
Err VFSFileRead( FileRef fileRef, UInt32 numBytes, void *bufP, UInt32 *numBytesReadP )
{
CALL P4(fileRef) P4(numBytes) P4(bufP) P4(numBytesReadP)
emulStatePtr->regData[2] = vfsTrapFileRead;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( numBytesReadP ) *numBytesReadP = BSwap32( *numBytesReadP ); // <-
return retval;
}
Err VFSFileWrite( FileRef fileRef, UInt32 numBytes, const void *dataP, UInt32 *numBytesWrittenP )
{
CALL P4(fileRef) P4(numBytes) P4(dataP) P4(numBytesWrittenP)
emulStatePtr->regData[2] = vfsTrapFileWrite;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( numBytesWrittenP ) *numBytesWrittenP = BSwap32( *numBytesWrittenP ); // <-
return retval;
}
Err VFSFileDelete( UInt16 volRefNum, const Char *pathNameP )
{
CALL P2(volRefNum) P4(pathNameP)
emulStatePtr->regData[2] = vfsTrapFileDelete;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileRename( UInt16 volRefNum, const Char *pathNameP, const Char *newNameP )
{
CALL P2(volRefNum) P4(pathNameP) P4(newNameP)
emulStatePtr->regData[2] = vfsTrapFileRename;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileSeek( FileRef fileRef, FileOrigin origin, Int32 offset )
{
CALL P4(fileRef) P2(origin) P4(offset)
emulStatePtr->regData[2] = vfsTrapFileSeek;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileEOF( FileRef fileRef )
{
CALL P4(fileRef)
emulStatePtr->regData[2] = vfsTrapFileEOF;
return (Err)TRAP(0xA348 & (0x00000FFF))
}
Err VFSFileTell( FileRef fileRef, UInt32 *filePosP )
{
CALL P4(fileRef) P4(filePosP)
emulStatePtr->regData[2] = vfsTrapFileTell;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( filePosP ) *filePosP = BSwap32( *filePosP ); // <-
return retval;
}
Err VFSFileSize( FileRef fileRef, UInt32 *fileSizeP )
{
CALL P4(fileRef) P4(fileSizeP)
emulStatePtr->regData[2] = vfsTrapFileSize;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
if( fileSizeP ) *fileSizeP = BSwap32( *fileSizeP ); // <-
return retval;
}
Err VFSDirEntryEnumerate( FileRef dirRef, UInt32 *dirEntryIteratorP, FileInfoType *infoP )
{
*dirEntryIteratorP = BSwap32( *dirEntryIteratorP ); // <->
infoP->attributes = BSwap32( infoP->attributes ); // <->
infoP->nameP = (Char*)BSwap32( infoP->nameP ); // <->
infoP->nameBufLen = BSwap16( infoP->nameBufLen ); // <->
CALL P4(dirRef) P4(dirEntryIteratorP) P4(infoP)
emulStatePtr->regData[2] = vfsTrapDirEntryEnumerate;
Err retval = (Err)TRAP(0xA348 & (0x00000FFF))
*dirEntryIteratorP = BSwap32( *dirEntryIteratorP ); // <->
infoP->attributes = BSwap32( infoP->attributes ); // <->
infoP->nameP = (Char*)BSwap32( infoP->nameP ); // <->
infoP->nameBufLen = BSwap16( infoP->nameBufLen ); // <->
return retval;
}
// =================
// DATABASES :
// =================
Err DmDatabaseInfo(
UInt16 cardNo, LocalID dbID, Char *nameP,
UInt16 *attributesP, UInt16 *versionP, UInt32 *crDateP,
UInt32 * modDateP, UInt32 *bckUpDateP,
UInt32 * modNumP, LocalID *appInfoIDP,
LocalID *sortInfoIDP, UInt32 *typeP,
UInt32 *creatorP )
{
CALL P2(cardNo) P4(dbID) P4(nameP) P4(attributesP) P4(versionP)
P4(crDateP) P4(modDateP) P4(bckUpDateP) P4(modNumP) P4(appInfoIDP)
P4(sortInfoIDP) P4(typeP) P4(creatorP)
Err retval = (Err)TRAP(sysTrapDmDatabaseInfo)
if( attributesP ) *attributesP = BSwap16( *attributesP );
if( versionP ) *versionP = BSwap16( *versionP );
if( crDateP ) *crDateP = BSwap32( *crDateP );
if( modNumP ) *modNumP = BSwap32( *modNumP );
if( appInfoIDP ) *appInfoIDP = (LocalID)BSwap32( *appInfoIDP );
if( sortInfoIDP ) *sortInfoIDP = (LocalID)BSwap32( *sortInfoIDP );
if( typeP ) *typeP = BSwap32( *typeP );
if( creatorP ) *creatorP = BSwap32( *creatorP );
return retval;
}
MemHandle DmGetResource( DmResType type, DmResID resID )
{
CALL P4(type) P2(resID)
return (MemHandle)TRAPP(sysTrapDmGetResource)
}
Err DmRecordInfo(
DmOpenRef dbP, UInt16 index,
UInt16 *attrP, UInt32 *uniqueIDP, LocalID *chunkIDP )
{
CALL P4(dbP) P2(index) P4(attrP) P4(uniqueIDP) P4(chunkIDP)
Err retval = (Err)TRAP(sysTrapDmRecordInfo)
if( attrP ) *attrP = BSwap16( *attrP ); // <-
if( uniqueIDP ) *uniqueIDP = BSwap32( *uniqueIDP ); // <-
if( chunkIDP ) *chunkIDP = (LocalID)BSwap32( *chunkIDP ); // <-
return retval;
}
DmOpenRef DmOpenDatabase( UInt16 cardNo, LocalID dbID, UInt16 mode )
{
CALL P2(cardNo) P4(dbID) P2(mode)
return (DmOpenRef)TRAPP(sysTrapDmOpenDatabase)
}
Err DmCreateDatabase( UInt16 cardNo, const Char *nameP, UInt32 creator, UInt32 type, Boolean resDB )
{
CALL P2(cardNo) P4(nameP) P4(creator) P4(type) P1(resDB)
return (Err)TRAP(sysTrapDmCreateDatabase)
}
Err DmDeleteDatabase( UInt16 cardNo, LocalID dbID )
{
CALL P2(cardNo) P4(dbID)
return (Err)TRAP(sysTrapDmDeleteDatabase)
}
LocalID DmFindDatabase( UInt16 cardNo, const Char *nameP )
{
CALL P2(cardNo) P4(nameP)
return (LocalID)TRAP(sysTrapDmFindDatabase)
}
Err DmGetNextDatabaseByTypeCreator(
Boolean newSearch, DmSearchStatePtr stateInfoP,
UInt32 type, UInt32 creator, Boolean onlyLatestVers,
UInt16 *cardNoP, LocalID *dbIDP )
{
CALL P1(newSearch) P4(stateInfoP) P4(type) P4(creator) P1(onlyLatestVers)
P4(cardNoP) P4(dbIDP)
Err retval = (Err)TRAP(sysTrapDmGetNextDatabaseByTypeCreator)
if( cardNoP ) *cardNoP = BSwap16( *cardNoP ); // <-
if( dbIDP ) *dbIDP = (LocalID)BSwap32( *dbIDP ); // <-
return retval;
}
Err DmCloseDatabase( DmOpenRef dbP )
{
CALL P4(dbP)
return (Err)TRAP(sysTrapDmCloseDatabase)
}
UInt16 DmNumRecords( DmOpenRef dbP )
{
CALL P4(dbP)
return (UInt16)TRAP(sysTrapDmNumRecords)
}
MemHandle DmNewRecord( DmOpenRef dbP, UInt16 *atP, UInt32 size )
{
*atP = BSwap16( *atP ); // <->
CALL P4(dbP) P4(atP) P4(size)
MemHandle retval = (MemHandle)TRAPP(sysTrapDmNewRecord)
*atP = BSwap16( *atP ); // <->
return retval;
}
MemHandle DmGetRecord( DmOpenRef dbP, UInt16 index )
{
CALL P4(dbP) P2(index)
return (MemHandle)TRAPP(sysTrapDmGetRecord)
}
MemHandle DmResizeRecord( DmOpenRef dbP, UInt16 index, UInt32 newSize )
{
CALL P4(dbP) P2(index) P4(newSize)
return (MemHandle)TRAPP(sysTrapDmResizeRecord)
}
Err DmReleaseRecord( DmOpenRef dbP, UInt16 index, Boolean dirty )
{
CALL P4(dbP) P2(index) P1(dirty)
return (Err)TRAP(sysTrapDmReleaseRecord)
}
Err DmWrite( void *recordP, UInt32 offset, const void *srcP, UInt32 bytes )
{
CALL P4(recordP) P4(offset) P4(srcP) P4(bytes)
return (Err)TRAP(sysTrapDmWrite)
}
Err DmWriteCheck( void *recordP, UInt32 offset, UInt32 bytes )
{
CALL P4(recordP) P4(offset) P4(bytes)
return (Err)TRAP(sysTrapDmWriteCheck)
}
// =================
// SOUND :
// =================
Err SndStreamCreate(
SndStreamRef *channel,
SndStreamMode mode,
UInt32 samplerate,
SndSampleType type,
SndStreamWidth width,
SndStreamBufferCallback func,
void *userdata,
UInt32 buffsize,
Boolean armNative )
{
CALL P4(channel) P1(mode) P4(samplerate) P2(type) P1(width) P4(func) P4(userdata) P4(buffsize) P1(armNative)
Err retval = (Err)TRAP(sysTrapSndStreamCreate)
*channel = (SndStreamRef)BSwap32( *channel ); // <-
return retval;
}
Err SndStreamDelete( SndStreamRef channel )
{
CALL P4(channel)
return (Err)TRAP(sysTrapSndStreamDelete)
}
Err SndStreamStart( SndStreamRef channel )
{
CALL P4(channel)
return (Err)TRAP(sysTrapSndStreamStart)
}
Err SndStreamPause( SndStreamRef channel, Boolean pause )
{
CALL P4(channel) P1(pause)
return (Err)TRAP(sysTrapSndStreamPause)
}
Err SndStreamStop( SndStreamRef channel )
{
CALL P4(channel)
return (Err)TRAP(sysTrapSndStreamStop)
}
Err SndStreamSetVolume( SndStreamRef channel, Int32 volume )
{
CALL P4(channel) P4(volume)
return (Err)TRAP(sysTrapSndStreamSetVolume)
}
// WINDOWS :
void WinDrawChars( const Char *chars, Int16 len, Coord x, Coord y )
{
CALL P4(chars) P2(len) P2(x) P2(y)
TRAP(sysTrapWinDrawChars)
}
WinHandle WinGetDisplayWindow( void )
{
CALL
return (WinHandle)TRAPP(sysTrapWinGetDisplayWindow)
}
BitmapType *WinGetBitmap( WinHandle winHandle )
{
CALL P4(winHandle)
return (BitmapType*)TRAPP(sysTrapWinGetBitmap);
}
void WinGetBounds( WinHandle winH, RectangleType *rP )
{
CALL P4(winH) P4(rP)
TRAP(sysTrapWinGetBounds)
rP->topLeft.x = BSwap16( rP->topLeft.x ); // <-
rP->topLeft.y = BSwap16( rP->topLeft.y ); // <-
rP->extent.x = BSwap16( rP->extent.x ); // <-
rP->extent.y = BSwap16( rP->extent.y ); // <-
}
void WinSetBounds( WinHandle winHandle, const RectangleType *rP )
{
RectangleType *r = (RectangleType*)rP;
r->topLeft.x = BSwap16( r->topLeft.x ); // ->
r->topLeft.y = BSwap16( r->topLeft.y ); // ->
r->extent.x = BSwap16( r->extent.x ); // ->
r->extent.y = BSwap16( r->extent.y ); // ->
CALL P4(winHandle) P4(rP)
TRAP(sysTrapWinSetBounds)
}
void WinSetClip( const RectangleType *rP )
{
RectangleType *r = (RectangleType*)rP;
r->topLeft.x = BSwap16( r->topLeft.x ); // ->
r->topLeft.y = BSwap16( r->topLeft.y ); // ->
r->extent.x = BSwap16( r->extent.x ); // ->
r->extent.y = BSwap16( r->extent.y ); // ->
CALL P4(rP)
TRAP(sysTrapWinSetClip)
}
void WinDrawRectangle( const RectangleType *rP, UInt16 cornerDiam )
{
RectangleType *r = (RectangleType*)rP;
r->topLeft.x = BSwap16( r->topLeft.x ); // ->
r->topLeft.y = BSwap16( r->topLeft.y ); // ->
r->extent.x = BSwap16( r->extent.x ); // ->
r->extent.y = BSwap16( r->extent.y ); // ->
CALL P4(rP) P2(cornerDiam)
TRAP(sysTrapWinDrawRectangle)
}
void WinDrawLine( Coord x1, Coord y1, Coord x2, Coord y2 )
{
CALL P2(x1) P2(y1) P2(x2) P2(y2)
TRAP(sysTrapWinDrawLine)
}
void WinDrawPixel( Coord x, Coord y )
{
CALL P2(x) P2(y)
TRAP(sysTrapWinDrawPixel)
}
Err WinGetPixelRGB( Coord x, Coord y, RGBColorType *rgbP )
{
CALL P2(x) P2(y) P4(rgbP)
TRAP(sysTrapWinGetPixelRGB)
}
void WinSetForeColorRGB( const RGBColorType *newRgbP, RGBColorType *prevRgbP )
{
CALL P4(newRgbP) P4(prevRgbP)
TRAP(sysTrapWinSetForeColorRGB)
}
UInt16 WinSetCoordinateSystem( UInt16 coordSys )
{
CALL P2(coordSys)
emulStatePtr->regData[2] = HDSelectorWinSetCoordinateSystem;
#ifdef sysTrapSysHighDensitySelector
return (UInt16)TRAP(sysTrapSysHighDensitySelector & (0x00000FFF))
#else
return (UInt16)TRAP(sysTrapHighDensityDispatch & (0x00000FFF))
#endif
}
#define WinSetWindowBounds(winH, rP) (WinSetBounds((winH), (rP)))
Err WinScreenGetAttribute( WinScreenAttrType selector, UInt32* attrP )
{
CALL P1(selector) P4(attrP)
emulStatePtr->regData[2] = HDSelectorWinScreenGetAttribute;
Err retval;
#ifdef sysTrapSysHighDensitySelector
retval = (Err)TRAP(sysTrapSysHighDensitySelector & (0x00000FFF))
#else
retval = (Err)TRAP(sysTrapHighDensityDispatch & (0x00000FFF))
#endif
*attrP = BSwap32( *attrP ); // <-
return retval;
}
Err WinScreenMode(
WinScreenModeOperation operation,
UInt32 *widthP,
UInt32 *heightP,
UInt32 *depthP,
Boolean *enableColorP )
{
*widthP = BSwap32( *widthP ); // <->
*heightP = BSwap32( *heightP ); // <->
*depthP = BSwap32( *depthP ); // <->
CALL P1(operation) P4(widthP) P4(heightP) P4(depthP) P4(enableColorP)
Err retval = (Err)TRAP(sysTrapWinScreenMode)
*widthP = BSwap32( *widthP ); // <->
*heightP = BSwap32( *heightP ); // <->
*depthP = BSwap32( *depthP ); // <->
return retval;
}
UInt8 *WinScreenLock( WinLockInitType initMode )
{
CALL P1(initMode)
return (UInt8*)TRAPP(sysTrapWinScreenLock);
}
void WinScreenUnlock( void )
{
CALL
TRAP(sysTrapWinScreenUnlock);
}
Err WinPalette( UInt8 operation, Int16 startIndex, UInt16 paletteEntries, RGBColorType *tableP )
{
CALL P1(operation) P2(startIndex) P2(paletteEntries) P4(tableP)
return (Err)TRAP(sysTrapWinPalette)
}
void WinDrawBitmap( BitmapPtr bitmapP, Coord x, Coord y )
{
CALL P4(bitmapP) P2(x) P2(y)
TRAP(sysTrapWinDrawBitmap)
}
// =================
// FORMS :
// =================
WinHandle FrmGetWindowHandle( const FormType *formP )
{
CALL P4(formP)
return (WinHandle)TRAPP(sysTrapFrmGetWindowHandle)
}
FormType *FrmGetActiveForm( void )
{
CALL
return (FormType*)TRAPP(sysTrapFrmGetActiveForm)
}
void FrmDrawForm( FormType *formP )
{
CALL P4(formP)
TRAP(sysTrapFrmDrawForm)
}
void FrmEraseForm( FormType *formP )
{
CALL P4(formP)
TRAP(sysTrapFrmEraseForm)
}
void FrmDeleteForm( FormType *formP )
{
CALL P4(formP)
TRAP(sysTrapFrmDeleteForm)
}
FormType *FrmInitForm( UInt16 rscID )
{
CALL P2(rscID)
return (FormType*)TRAPP(sysTrapFrmInitForm)
}
void FrmSetActiveForm( FormType *formP )
{
CALL P4(formP)
TRAP(sysTrapFrmSetActiveForm)
}
void FrmSetEventHandler( FormType *formP, FormEventHandlerType *handler )
{
CALL P4(formP) P4(handler)
TRAP(sysTrapFrmSetEventHandler)
}
void FrmGotoForm( UInt16 formId )
{
CALL P2(formId)
TRAP(sysTrapFrmGotoForm)
}
void FrmGetFormBounds( const FormType *formP, RectangleType *rP )
{
CALL P4(formP) P4(rP)
TRAP(sysTrapFrmGetFormBounds)
rP->topLeft.x = BSwap16( rP->topLeft.x ); // ->
rP->topLeft.y = BSwap16( rP->topLeft.y ); // ->
rP->extent.x = BSwap16( rP->extent.x ); // ->
rP->extent.y = BSwap16( rP->extent.y ); // ->
}
void FrmCloseAllForms( void )
{
CALL
TRAP(sysTrapFrmCloseAllForms)
}
// Events are in m68 format! You need convert it for using on the ARM
Boolean FrmDispatchEvent( EventType *eventP )
{
CALL P4(eventP)
return (Boolean)TRAP(sysTrapFrmDispatchEvent)
}
FormType *FrmGetFormPtr( UInt16 formId )
{
CALL P2(formId)
return (FormType*)TRAPP(sysTrapFrmGetFormPtr)
}
// =================
// FEATURES :
// =================
Err FtrGet( UInt32 creator, UInt16 featureNum, UInt32 *valueP )
{
CALL P4(creator) P2(featureNum) P4(valueP)
Err retval = (Err)TRAP(sysTrapFtrGet)
*valueP = BSwap32( *valueP ); // <-
return retval;
}
// =================
// EVENTS :
// =================
void EvtGetEvent( EventType *event, Int32 timeout )
{
CALL P4(event) P4(timeout)
TRAP(sysTrapEvtGetEvent)
}
Boolean MenuHandleEvent( MenuBarType *menuP, EventType *event, UInt16 *error )
{
CALL P4(menuP) P4(event) P4(error)
Boolean retval = (Boolean)TRAP(sysTrapMenuHandleEvent)
*error = BSwap16( *error ); // <-
return retval;
}
Boolean SysHandleEvent( EventPtr eventP )
{
CALL P4(eventP)
return (Boolean)TRAP(sysTrapSysHandleEvent)
}
// =================
// BITMAPS :
// =================
BitmapType* BmpCreate( Coord width, Coord height, UInt8 depth, ColorTableType * colortableP, UInt16 * error )
{
CALL P2(width) P2(height) P1(depth) P4(colortableP) P4(error)
BitmapType* retval = (BitmapType*)TRAPP(sysTrapBmpCreate)
*error = BSwap16( *error ); // <-
return retval;
}
void* BmpGetBits( BitmapType * bitmapP )
{
CALL P4(bitmapP)
return (void*)TRAPP(sysTrapBmpGetBits)
}
BitmapTypeV3* BmpCreateBitmapV3( const BitmapType* bitmapP, UInt16 density, const void* bitsP, const ColorTableType* colorTableP )
{
CALL P4(bitmapP) P2(density) P4(bitsP) P4(colorTableP)
emulStatePtr->regData[2] = HDSelectorBmpCreateBitmapV3;
#ifdef sysTrapSysHighDensitySelector
return (BitmapTypeV3*)TRAPP(sysTrapSysHighDensitySelector)
#else
return (BitmapTypeV3*)TRAPP(sysTrapHighDensityDispatch)
#endif
}
Err BmpDelete( BitmapType * bitmapP )
{
CALL P4(bitmapP)
return (Err)TRAP(sysTrapBmpDelete)
}
// =================
// TIME :
// =================
void TimSecondsToDateTime( UInt32 seconds, DateTimeType *dateTimeP )
{
CALL P4(seconds) P4(dateTimeP)
TRAP(sysTrapTimSecondsToDateTime)
if( dateTimeP )
{
dateTimeP->second = BSwap16( dateTimeP->second ); // <-
dateTimeP->minute = BSwap16( dateTimeP->minute ); // <-
dateTimeP->hour = BSwap16( dateTimeP->hour ); // <-
dateTimeP->day = BSwap16( dateTimeP->day ); // <-
dateTimeP->month = BSwap16( dateTimeP->month ); // <-
dateTimeP->year = BSwap16( dateTimeP->year ); // <-
dateTimeP->weekDay = BSwap16( dateTimeP->weekDay );// <-
}
}
UInt16 SysTicksPerSecond( void )
{
CALL
return (UInt16)TRAP(sysTrapSysTicksPerSecond)
}
UInt32 TimGetTicks( void )
{
CALL
return (UInt32)TRAP(sysTrapTimGetTicks)
}
UInt32 TimGetSeconds( void )
{
CALL
return (UInt32)TRAP(sysTrapTimGetSeconds)
}
// =================
// SYSTEM :
// =================
unsigned long KeyCurrentState( void )
{
CALL
return (unsigned long)TRAP(sysTrapKeyCurrentState)
}
UInt16 SysSetAutoOffTime( UInt16 seconds )
{
CALL P2(seconds)
return (UInt16)TRAP(sysTrapSysSetAutoOffTime)
}
Int16 SysRandom( Int32 newSeed )
{
CALL P4(newSeed)
return (UInt16)TRAP(sysTrapSysRandom)
}
| 26.349127
| 130
| 0.675989
|
Sound-Linux-More
|
4c66f3691c04f078b9c0457c9bb158bfd22867d2
| 27,034
|
cpp
|
C++
|
MWCNNLayerImpl.cpp
|
henryjimenez/DL-matlab
|
de77f6d5387a4feb43dd175100006138bbea755f
|
[
"BSD-2-Clause"
] | null | null | null |
MWCNNLayerImpl.cpp
|
henryjimenez/DL-matlab
|
de77f6d5387a4feb43dd175100006138bbea755f
|
[
"BSD-2-Clause"
] | null | null | null |
MWCNNLayerImpl.cpp
|
henryjimenez/DL-matlab
|
de77f6d5387a4feb43dd175100006138bbea755f
|
[
"BSD-2-Clause"
] | null | null | null |
#include "MWCNNLayerImpl.hpp"
#include "MWTargetNetworkImpl.hpp"
#include "cnn_api.hpp"
#include <cassert>
#include <cstring>
#include <stdio.h>
#if MW_LAYERS_TAP
extern void mw_interm_tap(arm_compute::Tensor& armTensor, int size, int
count); extern int tap_count;
#endif
MWCNNLayerImpl::MWCNNLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl*
ntwk_impl) : cnEykmOGhLuyKuadExWe(layer) , fylVqSnTjNbHDtlPhzaj(ntwk_impl) { } void
MWCNNLayerImpl::allocateOutputData(int i) { MWTensor* opTensor =
getLayer()->getOutputTensor(i); if (opTensor->getopBufIndex() < 0) {
getarmTensor(i)->allocator()->allocate(); } else {
#if defined(USE_18_11_LIBRARY) || defined(USE_19_02_LIBRARY)
getarmTensor(i)->allocator()->import_memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()],fylVqSnTjNbHDtlPhzaj->maxBufSize
*sizeof(float));
#elif defined(USE_19_05_LIBRARY)
getarmTensor(i)->allocator()->import_memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()]);
#else
getarmTensor(i)->allocator()->import_memory(arm_compute::Memory(fylVqSnTjNbHDtlPhzaj->memBuffer[opTensor->getopBufIndex()]));
#endif
} opTensor->setData((float*)getarmTensor(i)->buffer()); } void
MWCNNLayerImpl::deallocateOutputData(int i) { if
(cnEykmOGhLuyKuadExWe->getOutputTensor()->getopBufIndex() < 0) {
getarmTensor(i)->allocator()->free(); } } std::string
MWCNNLayerImpl::getLinuxPath(const char* fileName) { std::string
fileS(fileName); std::string key ("\\"); std::size_t found = 0; while(found !=
std::string::npos){ found = fileS.rfind(key); if (found!=std::string::npos)
fileS.replace (found,key.length(),"/"); } return fileS; } arm_compute::Tensor*
MWCNNLayerImpl::getprevLayerarmTensor(MWTensor* ipTensor) { int index =
ipTensor->getSourcePortIndex(); if (ipTensor->getOwner()->getImpl() == NULL) {
return
ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->getarmTensor(index);
} else { if (ipTensor->getOwner()->getImpl()->getarmTensor() == nullptr) {
return
ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->getarmTensor(
index); } else { return ipTensor->getOwner()->getImpl()->getarmTensor(index); }
} } std::shared_ptr<arm_compute::Tensor>
MWCNNLayerImpl::getARMTensorsharedPtr(MWTensor* ipTensor) { int index =
ipTensor->getSourcePortIndex(); if (ipTensor->getOwner()->getImpl() == NULL) {
return
ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->armTensor[index];
} else { if (ipTensor->getOwner()->getImpl()->getarmTensor() == nullptr) {
return
ipTensor->getOwner()->getInputTensor()->getOwner()->getImpl()->armTensor[index];
} else { return ipTensor->getOwner()->getImpl()->armTensor[index]; } } }
arm_compute::Tensor* MWCNNLayerImpl::getarmTensor(int index) { if
(armTensor.size() >= 1) { return armTensor[index].get(); } else { return
nullptr; } } void
MWCNNLayerImpl::setarmTensor(std::shared_ptr<arm_compute::Tensor> tensor, int
index) { armTensor[index] = tensor; }
MWInputLayerImpl::MWInputLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl*
ntwk_impl, int TfsmDFpPPOscKZifVzSQ, int wJyXsrUCMgxdIKVIJSyx, int QhTesEEIHwhNmHSeYbRR, int
zRhMJbzYfMHEzDwdpDGW, const char* avg_file_name) : MWCNNLayerImpl(layer,
ntwk_impl) , bYBVtTnVUuGDUlaTmmHp(zRhMJbzYfMHEzDwdpDGW) {
setarmTensor(std::make_shared<arm_compute::Tensor>()); if( bYBVtTnVUuGDUlaTmmHp
) { loadAvg(avg_file_name, TfsmDFpPPOscKZifVzSQ * wJyXsrUCMgxdIKVIJSyx, QhTesEEIHwhNmHSeYbRR); } }
MWInputLayerImpl::~MWInputLayerImpl() { } void
MWInputLayerImpl::propagateSize(){ MWInputLayer* inpLayer =
static_cast<MWInputLayer*>(getLayer()); MWTensor* ipTensor =
inpLayer->getInputTensor(0); getarmTensor()->allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long
unsigned int)ipTensor->getChannels(), (long unsigned
int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32)); } void
MWInputLayerImpl::loadAvg(const char* THfVbcZJtANcLKxEriuV, int channelSize, int
numChannels) { std::string fileString = getLinuxPath(THfVbcZJtANcLKxEriuV);
FILE* TbrNrGxaFFHrzKUcfHNZ = MWCNNLayer::openBinaryFile(fileString.c_str()); if
(TbrNrGxaFFHrzKUcfHNZ == NULL) {
std::cerr<<"Unable to open Input Average file"<<std::endl; } int gNROjwaqhxDPvBWUCUcQ
= channelSize * numChannels; JLDBTuxkNCsKfaFIEVHB = new std::vector<float>;
JLDBTuxkNCsKfaFIEVHB->reserve(gNROjwaqhxDPvBWUCUcQ); if(bYBVtTnVUuGDUlaTmmHp==1){
call_fread(JLDBTuxkNCsKfaFIEVHB->data(), sizeof(float), gNROjwaqhxDPvBWUCUcQ, TbrNrGxaFFHrzKUcfHNZ,
THfVbcZJtANcLKxEriuV); } else{ int channelOffset=0; std::vector<float>
ONvcEjLBnVNUdjMKOAwF(numChannels); call_fread(ONvcEjLBnVNUdjMKOAwF.data(),
sizeof(float), numChannels, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV); for(int
i=0;i<numChannels;i++){ std::fill_n(JLDBTuxkNCsKfaFIEVHB->begin()+channelOffset,
channelSize, ONvcEjLBnVNUdjMKOAwF[i]); channelOffset = channelOffset+channelSize;
} } fclose(TbrNrGxaFFHrzKUcfHNZ); return; } void
MWInputLayerImpl::allocateOutputData(int i) {
MWCNNLayerImpl::allocateOutputData(i); MWTensor* ipTensor =
getLayer()->getInputTensor(0); MWTensor* opTensor =
getLayer()->getOutputTensor(0); m_inputImage =
(float*)malloc(ipTensor->getBatchSize() * ipTensor->getChannels() *
ipTensor->getHeight() * ipTensor->getWidth() * sizeof(float)); if
((getarmTensor(i)->info()->total_size() / 4) == (opTensor->getBatchSize() *
opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) {
opTensor->setData((float*)getarmTensor(i)->buffer()); } else {
opTensor->setData(m_inputImage); } opTensor->setData(getData<float>()); } void
MWInputLayerImpl::predict() { float* inp = m_inputImage; int i, btch;
MWInputLayer* inpLayer = static_cast<MWInputLayer*>(getLayer()); MWTensor*
opTensor = inpLayer->getOutputTensor(0); float* out = m_inputImage; if
((getarmTensor()->info()->total_size() / 4) == (opTensor->getBatchSize() *
opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) { inp
= (float*)getarmTensor()->buffer(); out = (float*)getarmTensor()->buffer(); }
else { inp = m_inputImage; out = m_inputImage; } if (bYBVtTnVUuGDUlaTmmHp) {
for (btch = 0; btch < opTensor->getBatchSize(); btch++) {
#pragma omp parallel for
for (i = 0; i < opTensor->getChannels() * opTensor->getHeight() *
opTensor->getWidth(); i++) { out[i] = inp[i] - (*JLDBTuxkNCsKfaFIEVHB)[i]; } inp +=
opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth(); out +=
opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth(); } } if
((getarmTensor()->info()->total_size() / 4) != (opTensor->getBatchSize() *
opTensor->getChannels() * opTensor->getHeight() * opTensor->getWidth())) {
MWACLUtils::fillBufferToTensor(m_inputImage, *getarmTensor()); }
#if MW_INPUT_TAP
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } void MWInputLayerImpl::cleanup() { if (bYBVtTnVUuGDUlaTmmHp) { if
(JLDBTuxkNCsKfaFIEVHB) { delete JLDBTuxkNCsKfaFIEVHB; } } return; } void
MWInputLayerImpl::deallocate() { free(m_inputImage); m_inputImage = NULL;
return; } MWReLULayerImpl::MWReLULayerImpl(MWCNNLayer* layer,
MWTargetNetworkImpl* ntwk_impl, int inPlace) : MWCNNLayerImpl(layer, ntwk_impl)
, MW_Mangled_inPlace(inPlace) { if(MW_Mangled_inPlace){ MWTensor* ipTensor =
getLayer()->getInputTensor(); setarmTensor(getARMTensorsharedPtr(ipTensor));
}else{ setarmTensor(std::make_shared<arm_compute::Tensor>()); } }
MWReLULayerImpl::~MWReLULayerImpl() { } void MWReLULayerImpl::propagateSize() {
MWReLULayer* reluLayer = static_cast<MWReLULayer*>(getLayer()); MWTensor*
ipTensor = reluLayer->getInputTensor(); MWTensor* opTensor =
reluLayer->getOutputTensor(); m_actLayer =
std::unique_ptr<arm_compute::NEActivationLayer>(new
arm_compute::NEActivationLayer); arm_compute::Tensor* prevLayerarmTensor =
getprevLayerarmTensor(ipTensor); if(!MW_Mangled_inPlace){ bool
doesPrevLayerHas2DArmTensor = prevLayerarmTensor->info()->num_dimensions() <= 2
&& ipTensor->getHeight() == 1 && ipTensor->getWidth()==1; if
(doesPrevLayerHas2DArmTensor) {
getarmTensor()->allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)opTensor->getChannels(), (long
unsigned int)(opTensor->getSequenceLength()*opTensor->getBatchSize())), 1,
arm_compute::DataType::F32)); } else { getarmTensor()->allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long
unsigned int)opTensor->getChannels(), (long unsigned
int)(opTensor->getSequenceLength()*opTensor->getBatchSize())), 1,
arm_compute::DataType::F32)); } } m_actLayer->configure(prevLayerarmTensor,
getarmTensor(),
arm_compute::ActivationLayerInfo(arm_compute::ActivationLayerInfo::ActivationFunction::RELU));
return; } void MWReLULayerImpl::allocateOutputData(int i){ assert(i==0);
MWTensor* opTensor = getLayer()->getOutputTensor(i); if(MW_Mangled_inPlace){
MWTensor* ipTensor = getLayer()->getInputTensor();
opTensor->setData((float*)getprevLayerarmTensor(ipTensor)->buffer()); }else{
getarmTensor(i)->allocator()->allocate();
opTensor->setData((float*)getarmTensor(i)->buffer()); } } void
MWReLULayerImpl::deallocateOutputData(int i){ if(!MW_Mangled_inPlace)
getarmTensor(i)->allocator()->free(); } void MWReLULayerImpl::predict() {
MWReLULayer* reluLayer = static_cast<MWReLULayer*>(getLayer()); MWTensor*
opTensor = reluLayer->getOutputTensor(); m_actLayer->run();
#if MW_RELU_TAP
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } MWNormLayerImpl::MWNormLayerImpl(MWCNNLayer* layer,
MWTargetNetworkImpl* ntwk_impl, unsigned JABfZsGuaCAmcRcqOYEO, double
AuqaQHxmPQSyYRemQvyX, double BHuHNDGoRwGRouCxeMbw, double CDJtexcMbXMWAmnNZsNf) :
MWCNNLayerImpl(layer, ntwk_impl) , AuqaQHxmPQSyYRemQvyX(AuqaQHxmPQSyYRemQvyX) ,
BHuHNDGoRwGRouCxeMbw(BHuHNDGoRwGRouCxeMbw) , CDJtexcMbXMWAmnNZsNf(CDJtexcMbXMWAmnNZsNf) ,
JABfZsGuaCAmcRcqOYEO(JABfZsGuaCAmcRcqOYEO) {
setarmTensor(std::make_shared<arm_compute::Tensor>()); }
MWNormLayerImpl::~MWNormLayerImpl() { } void MWNormLayerImpl::propagateSize() {
MWNormLayer* normLayer = static_cast<MWNormLayer*>(getLayer()); MWTensor*
ipTensor = normLayer->getInputTensor(); m_normLayer =
std::unique_ptr<arm_compute::NENormalizationLayer>(new
arm_compute::NENormalizationLayer); arm_compute::Tensor* prevLayerarmTensor =
getprevLayerarmTensor(ipTensor); m_isIpArmTensorReshaped =
prevLayerarmTensor->info()->num_dimensions() <= 2 && ipTensor->getHeight() == 1
&& ipTensor->getWidth()==1; if(m_isIpArmTensorReshaped){ m_layerInputArmTensor
= std::make_shared<arm_compute::Tensor>();
m_layerInputArmTensor->allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long
unsigned int)ipTensor->getChannels(), (long unsigned
int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32)); m_reshapeKernel
= std::unique_ptr<arm_compute::NEReshapeLayer>(new
arm_compute::NEReshapeLayer); m_reshapeKernel->configure(prevLayerarmTensor,
m_layerInputArmTensor.get()); } else{ m_layerInputArmTensor =
getARMTensorsharedPtr(ipTensor); } getarmTensor()->allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(), (long
unsigned int)ipTensor->getChannels(), (long unsigned
int)ipTensor->getBatchSize()), 1, arm_compute::DataType::F32));
m_normLayer->configure(m_layerInputArmTensor.get(), getarmTensor(),
arm_compute::NormalizationLayerInfo(arm_compute::NormType::CROSS_MAP,
JABfZsGuaCAmcRcqOYEO, AuqaQHxmPQSyYRemQvyX, BHuHNDGoRwGRouCxeMbw,
CDJtexcMbXMWAmnNZsNf)); return; } void MWNormLayerImpl::allocate(){
if(m_isIpArmTensorReshaped){ m_layerInputArmTensor->allocator()->allocate(); }
return; } void MWNormLayerImpl::predict() { MWNormLayer* normLayer =
static_cast<MWNormLayer*>(getLayer()); MWTensor* opTensor =
normLayer->getOutputTensor(); if(m_isIpArmTensorReshaped){
m_reshapeKernel->run(); } m_normLayer->run();
#if MW_NORM_TAP
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } MWMaxPoolingLayerImpl::MWMaxPoolingLayerImpl(MWCNNLayer* layer,
MWTargetNetworkImpl* ntwk_impl, int GZGFVDrXwFLJleoTDywO, int GbdgxISzcqHOpzQEBrvP,
int IIiwAtyrOtLzLWAUlTey, int IpFhwalnAlrMvcuyQpQD, int FeVcBgtQmTLtmnNcJGMY, int
FLuSVNoPhAFKtLUchSvv, int GFggoMvRWucDMqzlWzCl, int GLovsOhUpzOJhKgXUAJY,
bool JsZenQeBPMhwsyEhVHiD, int hKyfKjPACkOBDvLdESxH) : MWCNNLayerImpl(layer,
ntwk_impl) , GZGFVDrXwFLJleoTDywO(GZGFVDrXwFLJleoTDywO) ,
GbdgxISzcqHOpzQEBrvP(GbdgxISzcqHOpzQEBrvP) ,
FeVcBgtQmTLtmnNcJGMY(FeVcBgtQmTLtmnNcJGMY) ,
FLuSVNoPhAFKtLUchSvv(FLuSVNoPhAFKtLUchSvv) ,
GFggoMvRWucDMqzlWzCl(GFggoMvRWucDMqzlWzCl) ,
GLovsOhUpzOJhKgXUAJY(GLovsOhUpzOJhKgXUAJY) ,
IIiwAtyrOtLzLWAUlTey(IIiwAtyrOtLzLWAUlTey) ,
IpFhwalnAlrMvcuyQpQD(IpFhwalnAlrMvcuyQpQD){ assert(hKyfKjPACkOBDvLdESxH == 1);
assert(!JsZenQeBPMhwsyEhVHiD);
setarmTensor(std::make_shared<arm_compute::Tensor>()); }
MWMaxPoolingLayerImpl::~MWMaxPoolingLayerImpl() { } float*
MWMaxPoolingLayerImpl::getIndexData() { assert(false); } void
MWMaxPoolingLayerImpl::propagateSize() { MWMaxPoolingLayer* maxPoolLayer =
static_cast<MWMaxPoolingLayer*>(getLayer()); MWTensor* ipTensor =
maxPoolLayer->getInputTensor(); MWTensor* opTensor =
maxPoolLayer->getOutputTensor(); m_maxPoolLayer =
std::unique_ptr<arm_compute::NEPoolingLayer>(new arm_compute::NEPoolingLayer);
arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor); if
((GZGFVDrXwFLJleoTDywO == -1) && (GbdgxISzcqHOpzQEBrvP == -1)) { GZGFVDrXwFLJleoTDywO =
ipTensor->getHeight(); GbdgxISzcqHOpzQEBrvP = ipTensor->getWidth(); }
getarmTensor()->allocator()->init(arm_compute::TensorInfo(arm_compute::TensorShape((long
unsigned int)opTensor->getWidth(), (long unsigned int)opTensor->getHeight(),
(long unsigned int)opTensor->getChannels(), (long unsigned
int)opTensor->getBatchSize()), 1, arm_compute::DataType::F32));
m_maxPoolLayer->configure( prevLayerarmTensor, getarmTensor(),
arm_compute::PoolingLayerInfo( arm_compute::PoolingType::MAX, GZGFVDrXwFLJleoTDywO,
arm_compute::PadStrideInfo(IpFhwalnAlrMvcuyQpQD, IIiwAtyrOtLzLWAUlTey,
GFggoMvRWucDMqzlWzCl, GLovsOhUpzOJhKgXUAJY, FeVcBgtQmTLtmnNcJGMY,
FLuSVNoPhAFKtLUchSvv, arm_compute::DimensionRoundingType::FLOOR))); return; }
void MWMaxPoolingLayerImpl::predict() { MWMaxPoolingLayer* maxPoolLayer =
static_cast<MWMaxPoolingLayer*>(getLayer()); MWTensor* opTensor =
maxPoolLayer->getOutputTensor(); m_maxPoolLayer->run();
#if MW_POOL_TAP
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } MWFCLayerImpl::MWFCLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl*
ntwk_impl, int m_NumInputFeatures, int m_NumOutputFeatures, const char*
m_weights_file, const char* m_bias_file) : MWCNNLayerImpl(layer, ntwk_impl) {
MWTensor* opTensor = getLayer()->getOutputTensor();
setarmTensor(std::make_shared<arm_compute::Tensor>()); int gNROjwaqhxDPvBWUCUcQ =
m_NumInputFeatures * m_NumOutputFeatures; wJyXsrUCMgxdIKVIJSyx =
CREATE_BUFFER(gNROjwaqhxDPvBWUCUcQ); OiVqrkNdXioJhALWMMvm =
CREATE_BUFFER(m_NumOutputFeatures); m_fcLayerWgtTensor.allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)(m_NumInputFeatures), (long unsigned int)(m_NumOutputFeatures)), 1,
arm_compute::DataType::F32)); m_fcLayerBiasTensor.allocator()->init(
arm_compute::TensorInfo(arm_compute::TensorShape((long unsigned
int)(m_NumOutputFeatures)), 1, arm_compute::DataType::F32));
loadWeights(m_weights_file, gNROjwaqhxDPvBWUCUcQ); loadBias(m_bias_file,
m_NumOutputFeatures); } MWFCLayerImpl::~MWFCLayerImpl() { } void
MWFCLayerImpl::propagateSize(){ MWFCLayer* fcLayer =
static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor =
fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor();
m_fcLayer = std::unique_ptr<arm_compute::NEFullyConnectedLayer>(new
arm_compute::NEFullyConnectedLayer); arm_compute::Tensor* prevLayerarmTensor =
getprevLayerarmTensor(ipTensor);
getarmTensor()->allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)(opTensor->getWidth()*
opTensor->getHeight()*opTensor->getChannels()), (long unsigned
int)(opTensor->getBatchSize()* opTensor->getSequenceLength())), 1,
arm_compute::DataType::F32)); m_fcLayer->configure(prevLayerarmTensor,
&m_fcLayerWgtTensor, &m_fcLayerBiasTensor, getarmTensor()); prepareWeights();
return; } void MWFCLayerImpl::allocate(){ MWFCLayer* fcLayer =
static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor =
fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor(); int
CufLFODQDXTAPyRqYodN = ipTensor->getChannels(); int
DRzwhbNPpftRRIXXfHzd = opTensor->getChannels();
MWACLUtils::allocateAndFillTensor(m_fcLayerWgtTensor, wJyXsrUCMgxdIKVIJSyx,
CufLFODQDXTAPyRqYodN * DRzwhbNPpftRRIXXfHzd, isWgtsPadded);
MWACLUtils::allocateAndFillTensor(m_fcLayerBiasTensor, OiVqrkNdXioJhALWMMvm,
DRzwhbNPpftRRIXXfHzd, isBiasPadded); return; } void
MWFCLayerImpl::loadWeights(const char* THfVbcZJtANcLKxEriuV, int gNROjwaqhxDPvBWUCUcQ)
{ float* wMySyzzledUmSLTWhuYH = GET_BUFFER(wJyXsrUCMgxdIKVIJSyx); std::string fileString =
getLinuxPath(THfVbcZJtANcLKxEriuV); FILE* TbrNrGxaFFHrzKUcfHNZ =
MWCNNLayer::openBinaryFile(fileString.c_str()); call_fread(wMySyzzledUmSLTWhuYH,
sizeof(float), gNROjwaqhxDPvBWUCUcQ, TbrNrGxaFFHrzKUcfHNZ, THfVbcZJtANcLKxEriuV);
fclose(TbrNrGxaFFHrzKUcfHNZ); } void MWFCLayerImpl::prepareWeights(){ float*
wvufwFZlsnpjbxmTBVYE = GET_BUFFER(wJyXsrUCMgxdIKVIJSyx); MWFCLayer* fcLayer =
static_cast<MWFCLayer*>(getLayer()); MWTensor* ipTensor =
fcLayer->getInputTensor(); MWTensor* opTensor = fcLayer->getOutputTensor(); int
CufLFODQDXTAPyRqYodN = ipTensor->getChannels() * ipTensor->getWidth() *
ipTensor->getHeight(); int DRzwhbNPpftRRIXXfHzd =
opTensor->getChannels(); int gNROjwaqhxDPvBWUCUcQ = CufLFODQDXTAPyRqYodN *
DRzwhbNPpftRRIXXfHzd; if (ipTensor->getHeight() != 1 &&
ipTensor->getWidth() != 1) { float* wMySyzzledUmSLTWhuYH =
(float*)malloc(sizeof(float) * ipTensor->getHeight() * ipTensor->getWidth());
for (int k = 0; k < gNROjwaqhxDPvBWUCUcQ / ipTensor->getHeight() /
ipTensor->getWidth(); k++) { for (int i = 0; i < ipTensor->getHeight() *
ipTensor->getWidth(); i++) wMySyzzledUmSLTWhuYH[i] = wvufwFZlsnpjbxmTBVYE[k *
ipTensor->getHeight() * ipTensor->getWidth() + i]; for (int j = 0; j <
ipTensor->getHeight(); j++) for (int i = 0; i < ipTensor->getWidth(); i++)
wvufwFZlsnpjbxmTBVYE[k * ipTensor->getHeight() * ipTensor->getWidth() + j *
ipTensor->getWidth() + i] = wMySyzzledUmSLTWhuYH[j + i * ipTensor->getHeight()]; }
free(wMySyzzledUmSLTWhuYH); } return; } void MWFCLayerImpl::loadBias(const char*
THfVbcZJtANcLKxEriuV, int DRzwhbNPpftRRIXXfHzd) { float* OzygUJRIZYnGLzSjgahB =
GET_BUFFER(OiVqrkNdXioJhALWMMvm); std::string fileString =
getLinuxPath(THfVbcZJtANcLKxEriuV); FILE* TbrNrGxaFFHrzKUcfHNZ =
MWCNNLayer::openBinaryFile(fileString.c_str()); call_fread(OzygUJRIZYnGLzSjgahB,
sizeof(float), DRzwhbNPpftRRIXXfHzd, TbrNrGxaFFHrzKUcfHNZ,
THfVbcZJtANcLKxEriuV); fclose(TbrNrGxaFFHrzKUcfHNZ); return; } void
MWFCLayerImpl::predict() { m_fcLayer->run();
#if MW_FC_TAP
MWFCLayer* fcLayer = static_cast<MWFCLayer*>(getLayer()); MWTensor* opTensor =
fcLayer->getOutputTensor(); mw_interm_tap(*getarmTensor(),
opTensor->getNumElements(), tap_count++);
#endif
return; } void MWFCLayerImpl::deallocate() { if (isWgtsPadded){
m_fcLayerWgtTensor.allocator()->free(); isWgtsPadded = false; } if
(isBiasPadded){ m_fcLayerBiasTensor.allocator()->free(); isWgtsPadded = false;
} return; } void MWFCLayerImpl::cleanup() { FREE_BUFFER_MEMORY(wJyXsrUCMgxdIKVIJSyx);
FREE_BUFFER_MEMORY(OiVqrkNdXioJhALWMMvm); return; }
MWSoftmaxLayerImpl::MWSoftmaxLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl*
ntwk_impl) : MWCNNLayerImpl(layer, ntwk_impl) , m_doesChannelwiseSoftmax(false)
{ setarmTensor(std::make_shared<arm_compute::Tensor>()); }
MWSoftmaxLayerImpl::~MWSoftmaxLayerImpl() { } void
MWSoftmaxLayerImpl::propagateSize() { MWSoftmaxLayer* sfmxLayer =
static_cast<MWSoftmaxLayer*>(getLayer()); MWTensor* ipTensor =
sfmxLayer->getInputTensor(); MWTensor* opTensor = sfmxLayer->getOutputTensor();
m_softmaxLayer = std::unique_ptr<arm_compute::NESoftmaxLayer>(new
arm_compute::NESoftmaxLayer); arm_compute::Tensor* prevLayerarmTensor =
getprevLayerarmTensor(ipTensor); bool doesPrevLayerHas2DArmTensor =
prevLayerarmTensor->info()->num_dimensions() <= 2 && ipTensor->getHeight() == 1
&& ipTensor->getWidth()==1; if (doesPrevLayerHas2DArmTensor) {
getarmTensor()->allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)opTensor->getChannels(), (long
unsigned int)(opTensor->getBatchSize()*opTensor->getSequenceLength())), 1,
arm_compute::DataType::F32)); } else { m_doesChannelwiseSoftmax = true;
getarmTensor()->allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)opTensor->getWidth(), (long
unsigned int)opTensor->getHeight(), (long unsigned int)opTensor->getChannels(),
(long unsigned int)(opTensor->getBatchSize()*opTensor->getSequenceLength())),
1, arm_compute::DataType::F32)); } if (!m_doesChannelwiseSoftmax) {
m_softmaxLayer->configure(prevLayerarmTensor, getarmTensor()); } else {
permuteToNHWC = std::unique_ptr<arm_compute::NEPermute>(new
arm_compute::NEPermute); permuteToNCHW =
std::unique_ptr<arm_compute::NEPermute>(new arm_compute::NEPermute);
arm_compute::PermutationVector nhwcPermuteDims(2, 0, 1), nchwPermuteDims(1, 2,
0); inputNHWCArmTensor.allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)ipTensor->getChannels(), (long
unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(),
1), 1, arm_compute::DataType::F32));
permuteToNHWC->configure(prevLayerarmTensor, &inputNHWCArmTensor,
nhwcPermuteDims);
tmpSfmaxNHWCArmTensor.allocator()->init(arm_compute::TensorInfo(
arm_compute::TensorShape((long unsigned int)ipTensor->getChannels(), (long
unsigned int)ipTensor->getWidth(), (long unsigned int)ipTensor->getHeight(),
1), 1, arm_compute::DataType::F32));
m_softmaxLayer->configure(&inputNHWCArmTensor, &tmpSfmaxNHWCArmTensor);
permuteToNCHW->configure(&tmpSfmaxNHWCArmTensor, getarmTensor(),
nchwPermuteDims); } return; } void MWSoftmaxLayerImpl::allocate() { if
(m_doesChannelwiseSoftmax) { inputNHWCArmTensor.allocator()->allocate();
tmpSfmaxNHWCArmTensor.allocator()->allocate(); } return; } void
MWSoftmaxLayerImpl::predict() { MWSoftmaxLayer* sfmxLayer =
static_cast<MWSoftmaxLayer*>(getLayer()); MWTensor* opTensor =
sfmxLayer->getOutputTensor(); if (!m_doesChannelwiseSoftmax) {
m_softmaxLayer->run(); } else { permuteToNHWC->run(); m_softmaxLayer->run();
permuteToNCHW->run(); }
#if MW_SFMX_TAP
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } void MWSoftmaxLayerImpl::deallocate() { if
(m_doesChannelwiseSoftmax) { inputNHWCArmTensor.allocator()->free();
tmpSfmaxNHWCArmTensor.allocator()->free(); } return; }
MWAvgPoolingLayerImpl::MWAvgPoolingLayerImpl(MWCNNLayer* layer,
MWTargetNetworkImpl* ntwk_impl, int GZGFVDrXwFLJleoTDywO, int GbdgxISzcqHOpzQEBrvP,
int IIiwAtyrOtLzLWAUlTey, int IpFhwalnAlrMvcuyQpQD, int FwLnexHgxHRquTKmNpoa, int
EvebzoroiuKkIxwjkGnD, int FpguQZSermqZCMRiUfML, int FshVHIJMRAhtQirYPlZd) :
MWCNNLayerImpl(layer, ntwk_impl) , GZGFVDrXwFLJleoTDywO(GZGFVDrXwFLJleoTDywO) ,
GbdgxISzcqHOpzQEBrvP(GbdgxISzcqHOpzQEBrvP) , IIiwAtyrOtLzLWAUlTey(IIiwAtyrOtLzLWAUlTey) ,
IpFhwalnAlrMvcuyQpQD(IpFhwalnAlrMvcuyQpQD) ,
FeVcBgtQmTLtmnNcJGMY(FwLnexHgxHRquTKmNpoa) ,
FLuSVNoPhAFKtLUchSvv(EvebzoroiuKkIxwjkGnD) ,
GFggoMvRWucDMqzlWzCl(FpguQZSermqZCMRiUfML) ,
GLovsOhUpzOJhKgXUAJY(FshVHIJMRAhtQirYPlZd) {
setarmTensor(std::make_shared<arm_compute::Tensor>()); }
MWAvgPoolingLayerImpl::~MWAvgPoolingLayerImpl() { } void
MWAvgPoolingLayerImpl::propagateSize() { MWAvgPoolingLayer* avgpoolLayer =
static_cast<MWAvgPoolingLayer*>(getLayer()); MWTensor* opTensor =
avgpoolLayer->getOutputTensor(); MWTensor* ipTensor =
avgpoolLayer->getInputTensor(); m_avgPoolLayer =
std::unique_ptr<arm_compute::NEPoolingLayer>(new arm_compute::NEPoolingLayer);
if ((GZGFVDrXwFLJleoTDywO == -1) && (GbdgxISzcqHOpzQEBrvP == -1)) { GZGFVDrXwFLJleoTDywO =
ipTensor->getHeight(); GbdgxISzcqHOpzQEBrvP = ipTensor->getWidth(); }
arm_compute::Tensor* prevLayerarmTensor = getprevLayerarmTensor(ipTensor);
getarmTensor()->allocator()->init(arm_compute::TensorInfo(arm_compute::TensorShape((long
unsigned int)opTensor->getWidth(), (long unsigned int)opTensor->getHeight(),
(long unsigned int)opTensor->getChannels(), (long unsigned
int)opTensor->getBatchSize()), 1, arm_compute::DataType::F32));
m_avgPoolLayer->configure( prevLayerarmTensor, getarmTensor(),
arm_compute::PoolingLayerInfo( arm_compute::PoolingType::AVG, GZGFVDrXwFLJleoTDywO,
arm_compute::PadStrideInfo(IpFhwalnAlrMvcuyQpQD, IIiwAtyrOtLzLWAUlTey,
GFggoMvRWucDMqzlWzCl, GLovsOhUpzOJhKgXUAJY, FeVcBgtQmTLtmnNcJGMY,
FLuSVNoPhAFKtLUchSvv, arm_compute::DimensionRoundingType::FLOOR))); return ; }
void MWAvgPoolingLayerImpl::predict() { m_avgPoolLayer->run();
#if MW_AVG_POOL_TAP
MWAvgPoolingLayer* avgpoolLayer = static_cast<MWAvgPoolingLayer*>(getLayer());
MWTensor* opTensor = avgpoolLayer->getOutputTensor();
mw_interm_tap(*getarmTensor(), opTensor->getNumElements(), tap_count++);
#endif
return; } MWOutputLayerImpl::MWOutputLayerImpl(MWCNNLayer* layer,
MWTargetNetworkImpl* ntwk_impl) : MWCNNLayerImpl(layer, ntwk_impl) { }
MWOutputLayerImpl::~MWOutputLayerImpl() { } void
MWOutputLayerImpl::propagateSize() { MWOutputLayer* opLayer =
static_cast<MWOutputLayer*>(getLayer()); MWTensor* ipTensor =
opLayer->getInputTensor(0); MWTensor* opTensor = opLayer->getOutputTensor(0);
m_outputArmTensor = getprevLayerarmTensor(ipTensor); } void
MWOutputLayerImpl::allocateOutputData(int i) { assert(i == 0); MWOutputLayer*
opLayer = static_cast<MWOutputLayer*>(getLayer()); MWTensor* opTensor =
opLayer->getOutputTensor(0); m_outputData =
(float*)malloc(opTensor->getNumElements() * sizeof(float));
opTensor->setData(m_outputData); if ((m_outputArmTensor->info()->total_size() /
4) == opTensor->getNumElements()) {
opTensor->setData((float*)m_outputArmTensor->buffer()); }
opTensor->setData(getData<float>()); } void MWOutputLayerImpl::predict() {
MWOutputLayer* opLayer = static_cast<MWOutputLayer*>(getLayer()); MWTensor*
opTensor = opLayer->getOutputTensor(0); if
((m_outputArmTensor->info()->total_size() / 4) != opTensor->getNumElements()) {
MWACLUtils::fillTensorToBuffer(opTensor->getData<float>(), *m_outputArmTensor);
} return; } void MWOutputLayerImpl::deallocateOutputData(int i) {
if(m_outputData){ free(m_outputData); m_outputData = NULL; } return; }
| 64.520286
| 136
| 0.774506
|
henryjimenez
|
4c6b8ca41338111eb30b19cf2f22b586572688df
| 592
|
hpp
|
C++
|
src/state.hpp
|
ebassi/node-clutter
|
760b8f5704a216dcd633658051c0778151b21391
|
[
"MIT"
] | 1
|
2017-08-31T00:58:33.000Z
|
2017-08-31T00:58:33.000Z
|
src/state.hpp
|
ebassi/node-clutter
|
760b8f5704a216dcd633658051c0778151b21391
|
[
"MIT"
] | null | null | null |
src/state.hpp
|
ebassi/node-clutter
|
760b8f5704a216dcd633658051c0778151b21391
|
[
"MIT"
] | null | null | null |
#ifndef NODE_CLUTTER_STATE_H_
#define NODE_CLUTTER_STATE_H_
#include <clutter/clutter.h>
#include <v8.h>
#include <node.h>
namespace clutter {
class State : public node::ObjectWrap {
public:
static void Initialize(v8::Handle<v8::Object> target);
static void PrototypeMethodsInit(v8::Handle<v8::FunctionTemplate> constructor_template);
ClutterState *_state;
protected:
State();
static v8::Handle<v8::Value> New(const v8::Arguments& args);
static v8::Handle<v8::Value> Set(const v8::Arguments& args);
static v8::Handle<v8::Value> SetState(const v8::Arguments& args);
};
}
#endif
| 21.142857
| 89
| 0.746622
|
ebassi
|
4c6baa5c68411296b4cc7a6cc74c1d9d6e6a8dd5
| 163
|
hpp
|
C++
|
kernel/keyboard.hpp
|
mox692/mos
|
211b36dade615cfd43d3bb077703b82b638eec10
|
[
"Apache-2.0"
] | null | null | null |
kernel/keyboard.hpp
|
mox692/mos
|
211b36dade615cfd43d3bb077703b82b638eec10
|
[
"Apache-2.0"
] | null | null | null |
kernel/keyboard.hpp
|
mox692/mos
|
211b36dade615cfd43d3bb077703b82b638eec10
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file keyboard.hpp
*
* キーボード制御プログラム.
*/
#pragma once
#include <deque>
#include "message.hpp"
void InitializeKeyboard(std::deque<Message>& msg_queue);
| 12.538462
| 56
| 0.687117
|
mox692
|
4c6e81dbf53824b66fe0a3f5b00c2e88a212be88
| 688
|
cpp
|
C++
|
ejercicios clase/ejercicioGasolina(random).cpp
|
Trx21-5672/IMEC-8A-5672
|
ff4f0f4bcd61425a9eccba7be1fb646849360d45
|
[
"MIT"
] | null | null | null |
ejercicios clase/ejercicioGasolina(random).cpp
|
Trx21-5672/IMEC-8A-5672
|
ff4f0f4bcd61425a9eccba7be1fb646849360d45
|
[
"MIT"
] | 1
|
2020-04-05T03:13:08.000Z
|
2020-04-05T03:13:08.000Z
|
ejercicios clase/ejercicioGasolina(random).cpp
|
Trx21-5672/IMEC-8A-5672
|
ff4f0f4bcd61425a9eccba7be1fb646849360d45
|
[
"MIT"
] | null | null | null |
#include <iostream>
//random seed
#include <cstdlib>
#include <ctime>
using namespace std;
const int x1=12;
const int x2=10;
const int precio=19;
int costo_final=0;
int m = 0;
int main(){
srand(time(NULL));
int lim_inf = 50;
int lim_sup = 150;
for (int i=0;i<2000;i++)
{
int velocidad = lim_inf + rand()%(lim_sup + 1 - lim_inf);
m++;
if (velocidad>100)
costo_final=costo_final+(x1*precio);
else
costo_final=costo_final+(x2*precio);
cout<<"el costo del combustible en el minuto "<<m<<" es "<<costo_final<<endl;
}
cout<<"el costo final del combustible es "<<costo_final<<endl;
return 0;
}
| 22.933333
| 85
| 0.597384
|
Trx21-5672
|
dbc8a8d1ebce122a4794f37b992e534ddb1cd498
| 4,370
|
hh
|
C++
|
servicesim_competition/src/Checkpoint.hh
|
raymondchaneee/servicesim
|
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
|
[
"Apache-2.0"
] | 6
|
2020-05-03T01:27:45.000Z
|
2021-12-14T06:36:48.000Z
|
servicesim_competition/src/Checkpoint.hh
|
raymondchaneee/servicesim
|
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
|
[
"Apache-2.0"
] | 1
|
2021-04-19T14:24:26.000Z
|
2021-04-19T14:24:26.000Z
|
servicesim_competition/src/Checkpoint.hh
|
raymondchaneee/servicesim
|
9e1c827aa0022d3f3c188be7d2ccf1ed20391d09
|
[
"Apache-2.0"
] | 6
|
2020-06-15T14:34:18.000Z
|
2021-09-28T19:50:17.000Z
|
/*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* 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 SERVICESIM_CHECKPOINT_HH_
#define SERVICESIM_CHECKPOINT_HH_
#include <sdf/sdf.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/msgs/boolean.pb.h>
#include <ignition/transport/Node.hh>
#include <gazebo/common/Time.hh>
namespace servicesim
{
class Checkpoint
{
/// \brief Constructor
/// \param[in] _sdf SDF element with configuration for this checkpoint.
public: Checkpoint(const sdf::ElementPtr &_sdf);
/// \brief Default destructor
public: virtual ~Checkpoint() = default;
/// \brief Check whether checkpoint has been completed.
/// Any publishers or subscribers should be created the first time this is
/// called, and cleaned up once it returns true.
/// \return True if completed.
public: virtual bool Check() = 0;
/// \brief Check whether to pause this checkpoint and return to the
/// previous one.
/// \return True if it should pause.
public: bool Paused() const;
/// \brief Check whether the checkpoint has started at least once
/// \return True if it has started.
public: bool Started() const;
/// \brief Call this the first time the checkpoint is checked.
public: void Start();
/// \brief Get the current score for this checkpoint.
/// \return Score
public: virtual double Score() const;
/// \brief Get the checkpoint's name
/// \return Checkpoint's name
public: std::string Name() const;
/// \brief Pause the checkpoint, ending the current interval. Only works if
/// canPause is true.
protected: void Pause();
/// \brief Set if this checkpoint is done. It also registers the time when
/// it was done.
/// \param[in] _done True if done
protected: void SetDone(const bool _done);
/// \brief Get whether this checkpoint is done
/// \return True if done.
protected: bool Done() const;
/// \brief The total penalty for this checkpoint
protected: double penalty{0.0};
/// \brief The weight for this checkpoint's time when scoring.
protected: double weightTime{0.0};
/// \brief The checkpoint's name
protected: std::string name;
/// \brief True if it's possible to restart the checkpoint.
protected: bool canPause{false};
/// \brief Vector of sim time intervals when the checkpoint was
/// running. The first time is the beginning of the interval, the
/// second is the end
private: std::vector<std::pair<gazebo::common::Time,
gazebo::common::Time>> intervals;
/// \brief True when checkpoint is complete.
private: bool done{false};
/// \brief True when checkpoint is paused.
private: bool paused{false};
};
/// \brief A checkpoint tied to a gazebo::ContainPlugin.
class ContainCheckpoint : public Checkpoint
{
/// \brief Constructor
/// \param[in] _sdf SDF element for this checkpoint.
public: ContainCheckpoint(const sdf::ElementPtr &_sdf);
/// \brief Check whether the contain checkpoint has been completed.
/// \return True if completed.
protected: bool Check() override;
/// \brief Callback when messages are received from the ContainPlugin.
/// \param[in] _msg True if contains.
private: void OnContain(const ignition::msgs::Boolean &_msg);
/// \brief Callabck for enable service
/// \param[in] _rep Response
/// \param[in] _result Result
private: void EnableCallback(const ignition::msgs::Boolean &_rep,
const bool _result);
/// \brief Ignition transport node for communication.
protected: ignition::transport::Node ignNode;
/// \brief Namespace for transport
protected: std::string ns;
/// \brief True if enabled
private: bool enabled{false};
};
}
#endif
| 32.61194
| 79
| 0.680092
|
raymondchaneee
|
dbca7033d2e551b6d754c8f530d7918631ff8de9
| 160
|
cpp
|
C++
|
chapter12/ex12_16.cpp
|
chaomi1998/CppPrimer_5th
|
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
|
[
"MIT"
] | null | null | null |
chapter12/ex12_16.cpp
|
chaomi1998/CppPrimer_5th
|
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
|
[
"MIT"
] | null | null | null |
chapter12/ex12_16.cpp
|
chaomi1998/CppPrimer_5th
|
9ecad51c21e5f57f2d682d9941812e1d51cc8a43
|
[
"MIT"
] | null | null | null |
#include <memory>
using std::unique_ptr;
int main()
{
unique_ptr<int> p1(new int(42));
unique_ptr<int> p2(p1);
unique_ptr<int> p3;
p3 = p1;
}
| 13.333333
| 36
| 0.60625
|
chaomi1998
|
dbd17702a329c4b83b51779eb2f79b9026e168d6
| 888
|
cpp
|
C++
|
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
|
vkashkumar/Competitive-Programming
|
c457e745208c0ca3e45b1ffce254a21504533f51
|
[
"MIT"
] | 2
|
2019-01-30T12:45:18.000Z
|
2021-05-06T19:02:51.000Z
|
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
|
vkashkumar/Competitive-Programming
|
c457e745208c0ca3e45b1ffce254a21504533f51
|
[
"MIT"
] | null | null | null |
leetcode/188.best-time-to-buy-and-sell-stock-iv.cpp
|
vkashkumar/Competitive-Programming
|
c457e745208c0ca3e45b1ffce254a21504533f51
|
[
"MIT"
] | 3
|
2020-10-02T15:42:04.000Z
|
2022-03-27T15:14:16.000Z
|
/*
* @lc app=leetcode id=188 lang=cpp
*
* [188] Best Time to Buy and Sell Stock IV
*/
// @lc code=start
class Solution {
public:
int maxProfit(int K, vector<int>& prices) {
int n = prices.size();
if(K>=n/2) {
int ans = 0;
for(int i=1;i<n;i++) {
if(prices[i] > prices[i-1]) {
ans += prices[i]-prices[i-1];
}
}
return ans;
}
int dp[1001][1001] = {0};
for(int k=1;k<=K;k++) {
for(int i=1;i<n;i++) {
int ans = 0;
for(int j=0;j<i;j++) {
if(prices[i] > prices[j])
ans = max(ans,prices[i]-prices[j] + dp[k-1][j]);
}
dp[k][i] = max(ans, dp[k][i-1]);
}
}
return dp[K][n-1];
}
};
// @lc code=end
| 24
| 72
| 0.371622
|
vkashkumar
|
dbd4bac249440c2fb749f49563a123b468e79220
| 572
|
cpp
|
C++
|
tests/test.cpp
|
Darioshka/lab_03
|
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
|
[
"MIT"
] | null | null | null |
tests/test.cpp
|
Darioshka/lab_03
|
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
|
[
"MIT"
] | null | null | null |
tests/test.cpp
|
Darioshka/lab_03
|
24d79f98900451ccd336d9c9b930d6c4d3d7f0dd
|
[
"MIT"
] | null | null | null |
// Copyright 2018 Your Name <your_email>
#include <gtest/gtest.h>
#include "header.hpp"
TEST(Example, EmptyTest) {
int*a = new int;
a[0] = 42;
int*b = new int;
b[0] = 20;
SharedPtr<int> link1(a);
SharedPtr<int> link2(link1);
SharedPtr<int> link3(b);
EXPECT_EQ(static_cast<int>(link1.get()[0]), 42);
EXPECT_EQ(static_cast<int>(link2.get()[0]), 42);
link1.swap(link3);
EXPECT_EQ(static_cast<int>(link1.get()[0]), 20);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 24.869565
| 52
| 0.624126
|
Darioshka
|
dbd83e5512cfabf81133a23131ebb9a96e15fba9
| 2,922
|
cpp
|
C++
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 310
|
2019-11-25T04:14:11.000Z
|
2022-03-31T23:39:19.000Z
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 79
|
2019-11-17T07:51:02.000Z
|
2022-03-22T08:49:41.000Z
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/Zones/CPolyLine.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 24
|
2020-05-10T09:37:55.000Z
|
2022-03-05T13:19:31.000Z
|
/*
!@
MIT License
Copyright (c) 2020 Skylicht Technology CO., LTD
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.
This file is part of the "Skylicht Engine".
https://github.com/skylicht-lab/skylicht-engine
!#
*/
#include "pch.h"
#include "CPolyLine.h"
#include "ParticleSystem/Particles/CParticle.h"
#include "ParticleSystem/Particles/CGroup.h"
namespace Skylicht
{
namespace Particle
{
CPolyLine::CPolyLine(const core::array<core::vector3df>& point) :
CZone(PolyLine),
m_length(0.0f),
m_normal(0.0f, 1.0f, 0.0f)
{
setLine(point);
}
CPolyLine::~CPolyLine()
{
}
void CPolyLine::setLine(const core::array<core::vector3df>& point)
{
if (point.size() < 2)
return;
m_point = point;
m_segments.set_used(0);
m_ratios.set_used(0);
m_length = 0.0f;
for (u32 i = 0, n = (u32)point.size(); i < n - 1; i++)
{
float d = point[i].getDistanceFrom(point[i + 1]);
m_length = m_length + d;
m_segments.push_back(d);
}
float d = 0.0f;
for (u32 i = 0, n = (u32)m_segments.size(); i < n; i++)
{
d = d + m_segments[i];
m_ratios.push_back(d / m_length);
}
}
void CPolyLine::generatePosition(CParticle& particle, bool full, CGroup* group)
{
float ratio = random(0.0f, 1.0f);
int segmentId = 0;
float length = 0.0f;
float l = 0.0f;
for (u32 i = 0, n = (u32)m_segments.size(); i < n; i++)
{
segmentId = i;
if (ratio < m_ratios[i])
{
l = (m_ratios[i] - ratio) * m_length;
break;
}
}
const core::vector3df& p1 = m_point[segmentId];
const core::vector3df& p2 = m_point[segmentId + 1];
core::vector3df pos = group->getTransformPosition(p1);
core::vector3df direction = group->getTransformPosition(p2) - pos;
direction.normalize();
particle.Position = pos + direction * l;
}
core::vector3df CPolyLine::computeNormal(const core::vector3df& point, CGroup* group)
{
return m_normal;
}
}
}
| 27.055556
| 141
| 0.688227
|
tsukoyumi
|
dbdb9f2fd3ab2ec71471a114984e2591469ef965
| 11,510
|
hpp
|
C++
|
src/ganon-classify/include/ganon-classify/Config.hpp
|
benvenutti/ganon
|
0d6f1b73eacb7659a0d541567b9aa60287e05f82
|
[
"MIT",
"BSD-3-Clause"
] | 1
|
2021-04-11T22:09:18.000Z
|
2021-04-11T22:09:18.000Z
|
src/ganon-classify/include/ganon-classify/Config.hpp
|
benvenutti/ganon
|
0d6f1b73eacb7659a0d541567b9aa60287e05f82
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/ganon-classify/include/ganon-classify/Config.hpp
|
benvenutti/ganon
|
0d6f1b73eacb7659a0d541567b9aa60287e05f82
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cinttypes>
#include <iomanip>
#include <iostream>
#include <map>
#include <ostream>
#include <string>
#include <vector>
namespace GanonClassify
{
struct FilterConfig
{
std::string ibf_file;
std::string map_file;
std::string tax_file;
int16_t max_error;
float min_kmers;
};
struct HierarchyConfig
{
std::vector< FilterConfig > filters;
int16_t max_error_unique;
int16_t strata_filter;
std::string output_file_lca;
std::string output_file_rep;
std::string output_file_all;
};
struct Config
{
public:
std::vector< std::string > single_reads;
std::vector< std::string > paired_reads;
std::vector< std::string > ibf;
std::vector< std::string > map;
std::vector< std::string > tax;
std::vector< std::string > hierarchy_labels{ "1_default" };
std::vector< float > min_kmers{ 0.25 };
std::vector< int16_t > max_error;
std::vector< int16_t > max_error_unique{ -1 };
std::vector< int16_t > strata_filter{ 0 };
uint16_t offset = 2;
std::string output_prefix = "";
bool output_all = false;
bool output_unclassified = false;
bool output_single = false;
uint16_t threads = 3;
uint32_t n_batches = 1000;
uint32_t n_reads = 400;
bool verbose = false;
bool quiet = false;
uint16_t threads_classify;
std::map< std::string, HierarchyConfig > parsed_hierarchy;
bool validate()
{
if ( ibf.size() == 0 || map.size() == 0 || tax.size() == 0
|| ( paired_reads.size() == 0 && single_reads.size() == 0 ) )
{
std::cerr << "--ibf, --map, --tax, --[single|paired]-reads are mandatory" << std::endl;
return false;
}
else if ( paired_reads.size() % 2 != 0 )
{
std::cerr << "--paired-reads should be an even number of files (pairs)" << std::endl;
return false;
}
bool valid_val = true;
for ( uint16_t i = 0; i < min_kmers.size(); ++i )
{
if ( min_kmers[i] < 0 || min_kmers[i] > 1 )
{
valid_val = false;
break;
}
}
if ( !valid_val )
{
std::cerr << "--min-kmers value should be between 0 and 1" << std::endl;
return false;
}
valid_val = true;
for ( uint16_t i = 0; i < max_error.size(); ++i )
{
if ( max_error[i] < 0 )
{
valid_val = false;
break;
}
}
if ( !valid_val )
{
std::cerr << "--max-error value should be greater than 0" << std::endl;
return false;
}
// default is min_kmers, if min_error is provided, use it
if ( max_error.size() > 0 )
min_kmers[0] = -1; // reset min_kmers
else
max_error.push_back( -1 ); // reset max_error
if ( threads <= 3 )
{
threads_classify = 1;
}
else
{
threads_classify = threads - 2;
}
if ( n_batches < 1 )
n_batches = 1;
if ( n_reads < 1 )
n_reads = 1;
if ( output_prefix.empty() )
{
output_all = false;
output_unclassified = false;
}
if ( offset < 1 )
offset = 1;
#ifndef GANON_OFFSET
offset = 1;
#endif
return parse_hierarchy();
}
bool parse_hierarchy()
{
if ( ibf.size() != map.size() || ibf.size() != tax.size() )
{
std::cerr << "The number of --ibf, --map and --tax should match" << std::endl;
return false;
}
// One hierarchy value for multiple hierarchies
if ( hierarchy_labels.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
hierarchy_labels.push_back( hierarchy_labels[0] );
}
}
else if ( hierarchy_labels.size() != ibf.size() )
{
std::cerr << "--hierarchy does not match with the number of --ibf, --map and --tax" << std::endl;
return false;
}
// If only one max error was given, repeat it for every filter
if ( max_error.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
max_error.push_back( max_error[0] );
}
}
else if ( max_error.size() != ibf.size() )
{
std::cerr << "Please provide a single or one-per-filter --max-error value[s]" << std::endl;
return false;
}
// If only one max error was given, repeat it for every filter
if ( min_kmers.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
min_kmers.push_back( min_kmers[0] );
}
}
else if ( min_kmers.size() != ibf.size() )
{
std::cerr << "Please provide a single or one-per-filter --min-kmers value[s]" << std::endl;
return false;
}
std::vector< std::string > sorted_hierarchy = hierarchy_labels;
std::sort( sorted_hierarchy.begin(), sorted_hierarchy.end() );
// get unique hierarcy labels
uint16_t unique_hierarchy =
std::unique( sorted_hierarchy.begin(), sorted_hierarchy.end() ) - sorted_hierarchy.begin();
if ( max_error_unique.size() == 1 && unique_hierarchy > 1 )
{
for ( uint16_t b = 1; b < unique_hierarchy; ++b )
{
max_error_unique.push_back( max_error_unique[0] );
}
}
else if ( max_error_unique.size() != unique_hierarchy )
{
std::cerr << "Please provide a single or one-per-hierarchy --max-error-unique value[s]" << std::endl;
return false;
}
if ( strata_filter.size() == 1 && unique_hierarchy > 1 )
{
for ( uint16_t b = 1; b < unique_hierarchy; ++b )
{
strata_filter.push_back( strata_filter[0] );
}
}
else if ( strata_filter.size() != unique_hierarchy )
{
std::cerr << "Please provide a single or one-per-hierarchy --strata-filter value[s]" << std::endl;
return false;
}
uint16_t hierarchy_count = 0;
for ( uint16_t h = 0; h < hierarchy_labels.size(); ++h )
{
auto filter_cfg = FilterConfig{ ibf[h], map[h], tax[h], max_error[h], min_kmers[h] };
if ( parsed_hierarchy.find( hierarchy_labels[h] ) == parsed_hierarchy.end() )
{ // not found
std::vector< FilterConfig > fc;
fc.push_back( filter_cfg );
std::string output_file_lca;
std::string output_file_rep;
std::string output_file_all;
if ( !output_prefix.empty() && unique_hierarchy > 1 && !output_single )
{
output_file_lca = output_prefix + "." + hierarchy_labels[h] + ".lca";
output_file_all = output_prefix + "." + hierarchy_labels[h] + ".all";
output_file_rep = output_prefix + ".rep";
}
else if ( !output_prefix.empty() )
{
output_file_lca = output_prefix + ".lca";
output_file_all = output_prefix + ".all";
output_file_rep = output_prefix + ".rep";
}
parsed_hierarchy[hierarchy_labels[h]] = HierarchyConfig{ fc,
max_error_unique[hierarchy_count],
strata_filter[hierarchy_count],
output_file_lca,
output_file_rep,
output_file_all };
++hierarchy_count;
}
else
{ // found
parsed_hierarchy[hierarchy_labels[h]].filters.push_back( filter_cfg );
}
}
return true;
}
};
inline std::ostream& operator<<( std::ostream& stream, const Config& config )
{
constexpr auto newl{ "\n" };
constexpr auto separator{ "----------------------------------------------------------------------" };
stream << separator << newl;
stream << "Database hierarchy:" << newl;
for ( auto const& hierarchy_config : config.parsed_hierarchy )
{
if ( !hierarchy_config.first.empty() )
{
stream << hierarchy_config.first << ")" << newl;
stream << " --max-error-unique: " << hierarchy_config.second.max_error_unique << newl;
stream << " --strata-filter: " << hierarchy_config.second.strata_filter << newl;
}
for ( auto const& filter_config : hierarchy_config.second.filters )
{
if ( filter_config.min_kmers > -1 )
stream << " --min-kmers: " << filter_config.min_kmers << newl;
if ( filter_config.max_error > -1 )
stream << " --max-error: " << filter_config.max_error << newl;
stream << " --ibf: " << filter_config.ibf_file << newl;
stream << " --map: " << filter_config.map_file << newl;
stream << " --tax: " << filter_config.tax_file << newl;
}
stream << " Output files:" << newl;
stream << " " << hierarchy_config.second.output_file_lca << newl;
stream << " " << hierarchy_config.second.output_file_rep << newl;
if ( config.output_all )
stream << " " << hierarchy_config.second.output_file_all << newl;
}
stream << newl;
stream << "Input files:" << newl;
stream << "--reads-single " << newl;
for ( const auto& s : config.single_reads )
stream << " " << s << newl;
stream << "--reads-paired " << newl;
for ( const auto& s : config.paired_reads )
stream << " " << s << newl;
stream << newl;
stream << "Parameters:" << newl;
stream << "--offset " << config.offset << newl;
stream << "--output-prefix " << config.output_prefix << newl;
stream << "--output-all " << config.output_all << newl;
stream << "--output-unclassified " << config.output_unclassified << newl;
stream << "--output-single " << config.output_single << newl;
stream << "--threads " << config.threads << newl;
stream << "--n-batches " << config.n_batches << newl;
stream << "--n-reads " << config.n_reads << newl;
stream << "--verbose " << config.verbose << newl;
stream << "--quiet " << config.quiet << newl;
stream << separator << newl;
return stream;
}
} // namespace GanonClassify
| 34.878788
| 113
| 0.482884
|
benvenutti
|
dbdd5abe0accf7f06ccea27f68a7c55dbbaa260a
| 51,996
|
cpp
|
C++
|
src/pafpython/PythonWrapper.cpp
|
fdyjfd/paf
|
fb6b275532483184b5e02f2d6850e503eb9bfad1
|
[
"MIT"
] | 1
|
2021-04-02T10:17:59.000Z
|
2021-04-02T10:17:59.000Z
|
src/pafpython/PythonWrapper.cpp
|
fdyjfd/paf
|
fb6b275532483184b5e02f2d6850e503eb9bfad1
|
[
"MIT"
] | null | null | null |
src/pafpython/PythonWrapper.cpp
|
fdyjfd/paf
|
fb6b275532483184b5e02f2d6850e503eb9bfad1
|
[
"MIT"
] | null | null | null |
#include <new.h>
#include "Python.h"
#include "../pafcore/Variant.h"
#include "../pafcore/InstanceMethod.h"
#include "../pafcore/NameSpace.h"
#include "../pafcore/NameSpace.mh"
#include "../pafcore/Metadata.mh"
#include "../pafcore/Type.mh"
#include "../pafcore/ClassType.h"
#include "../pafcore/EnumType.h"
#include "../pafcore/EnumType.mh"
#include "../pafcore/InstanceField.h"
#include "../pafcore/StaticField.h"
#include "../pafcore/InstanceProperty.h"
#include "../pafcore/InstanceArrayProperty.h"
#include "../pafcore/StaticProperty.h"
#include "../pafcore/StaticArrayProperty.h"
#include "../pafcore/InstanceMethod.h"
#include "../pafcore/StaticMethod.h"
#include "../pafcore/Enumerator.h"
#include "../pafcore/PrimitiveType.h"
#include "Utility.h"
#include "PythonWrapper.h"
#include "PythonSubclassInvoker.h"
BEGIN_PAFPYTHON
const size_t max_param_count = 20;
struct VariantWrapper
{
PyObject_HEAD
char m_var[sizeof(pafcore::Variant)];
};
static PyTypeObject s_VariantWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.Object",
sizeof(VariantWrapper),
};
struct InstanceArrayPropertyWrapper
{
PyObject_HEAD
pafcore::InstanceArrayProperty* m_property;
VariantWrapper* m_self;
};
static PyTypeObject s_InstanceArrayPropertyWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.InstanceArrayProperty",
sizeof(InstanceArrayPropertyWrapper),
};
struct StaticArrayPropertyWrapper
{
PyObject_HEAD
pafcore::StaticArrayProperty* m_property;
};
static PyTypeObject s_StaticArrayPropertyWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.StaticArrayProperty",
sizeof(StaticArrayPropertyWrapper),
};
struct InstanceMethodWrapper
{
PyObject_HEAD
pafcore::InstanceMethod* m_method;
VariantWrapper* m_self;
};
static PyTypeObject s_InstanceMethodWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.InstanceMethod",
sizeof(InstanceMethodWrapper),
};
struct FunctionInvokerWrapper
{
PyObject_HEAD
pafcore::FunctionInvoker m_invoker;
};
static PyTypeObject s_FunctionInvokerWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.FunctionInvoker",
sizeof(FunctionInvokerWrapper),
};
struct ProxyCreatorWrapper
{
PyObject_HEAD
pafcore::ClassType* m_classType;
};
static PyTypeObject s_ProxyCreatorWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.ProxyCreator",
sizeof(ProxyCreatorWrapper),
};
struct TypeCasterWrapper
{
PyObject_HEAD
pafcore::Type* m_type;
};
static PyTypeObject s_TypeCasterWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.TypeCaster",
sizeof(TypeCasterWrapper),
};
PyObject* VariantWrapper_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
VariantWrapper* self;
self = (VariantWrapper*)type->tp_alloc(type, 0);
if (self != NULL)
{
void* var = self->m_var;
pafcore::Variant* variant = new(var)pafcore::Variant;
}
return (PyObject*)self;
}
void VariantWrapper_dealloc(VariantWrapper* self)
{
pafcore::Variant* variant = (pafcore::Variant*)self->m_var;
variant->~Variant();
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* FunctionInvokerWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
FunctionInvokerWrapper* self;
self = (FunctionInvokerWrapper*)type->tp_alloc(type, 0);
self->m_invoker = 0;
return (PyObject*)self;
}
void InstanceArrayPropertyWrapper_dealloc(InstanceArrayPropertyWrapper* self)
{
Py_XDECREF(self->m_self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* InstanceArrayPropertyWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
InstanceArrayPropertyWrapper* self;
self = (InstanceArrayPropertyWrapper*)type->tp_alloc(type, 0);
self->m_property = 0;
self->m_self = 0;
return (PyObject*)self;
}
PyObject* StaticArrayPropertyWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
StaticArrayPropertyWrapper* self;
self = (StaticArrayPropertyWrapper*)type->tp_alloc(type, 0);
self->m_property = 0;
return (PyObject*)self;
}
void InstanceMethodWrapper_dealloc(InstanceMethodWrapper* self)
{
Py_XDECREF(self->m_self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* InstanceMethodWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
InstanceMethodWrapper* self;
self = (InstanceMethodWrapper*)type->tp_alloc(type, 0);
self->m_method = 0;
self->m_self = 0;
return (PyObject*)self;
}
PyObject* ProxyCreatorWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
ProxyCreatorWrapper* self;
self = (ProxyCreatorWrapper*)type->tp_alloc(type, 0);
self->m_classType = 0;
return (PyObject*)self;
}
PyObject* TypeCasterWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
TypeCasterWrapper* self;
self = (TypeCasterWrapper*)type->tp_alloc(type, 0);
self->m_type = 0;
return (PyObject*)self;
}
PyObject* VariantToPython(pafcore::Variant* variant)
{
PyObject* object = VariantWrapper_new(&s_VariantWrapper_Type, 0, 0);
pafcore::Variant* var = (pafcore::Variant*)((VariantWrapper*)object)->m_var;
var->move(*variant);
return object;
}
pafcore::Variant* PythonToVariant(pafcore::Variant* value, PyObject* pyObject)
{
pafcore::Variant* res = value;
PyObject* type = PyObject_Type(pyObject);
if(PyObject_TypeCheck(pyObject, &s_VariantWrapper_Type))
{
res = (pafcore::Variant*)((VariantWrapper*)pyObject)->m_var;
}
else if(PyBool_Check(pyObject))
{
bool b = (pyObject != Py_False);
value->assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &b);
}
else if(PyLong_Check(pyObject))
{
PY_LONG_LONG i = PyLong_AsLongLong(pyObject);
value->assignPrimitive(RuntimeTypeOf<PY_LONG_LONG>::RuntimeType::GetSingleton(), &i);
}
else if(PyFloat_Check(pyObject))
{
double d = PyFloat_AsDouble(pyObject);
value->assignPrimitive(RuntimeTypeOf<double>::RuntimeType::GetSingleton(), &d);
}
else if(PyUnicode_Check(pyObject))
{
Py_ssize_t size;
char* s = PyUnicode_AsUTF8AndSize(pyObject, &size);
value->assignPrimitivePtr(RuntimeTypeOf<char>::RuntimeType::GetSingleton(), (void*)s, true, ::pafcore::Variant::by_ptr);
}
return res;
}
pafcore::ErrorCode GetStaticField(PyObject*& pyObject, pafcore::StaticField* field)
{
pafcore::Variant value;
if(field->isArray())
{
value.assignArray(field->m_type, (void*)field->m_address, field->m_arraySize, field->m_constant, ::pafcore::Variant::by_array);
}
else
{
value.assignPtr(field->m_type, (void*)field->m_address, field->m_constant, ::pafcore::Variant::by_ref);
}
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode SetStaticField(pafcore::StaticField* field, PyObject* pyAttr)
{
if(field->isArray())
{
return pafcore::e_field_is_an_array;
}
if(field->isConstant())
{
return pafcore::e_field_is_constant;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(field->m_type, (void*)field->m_address))
{
return pafcore::e_invalid_field_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode GetInstanceField(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceField* field)
{
size_t baseOffset;
if(!static_cast<pafcore::ClassType*>(that->m_type)->getClassOffset(baseOffset, field->m_objectType))
{
return pafcore::e_invalid_type;
}
size_t fieldAddress = (size_t)that->m_pointer + baseOffset + field->m_offset;
pafcore::Variant value;
if(field->isArray())
{
value.assignArray(field->m_type, (void*)fieldAddress, field->m_arraySize, field->m_constant, ::pafcore::Variant::by_array);
}
else
{
value.assignPtr(field->m_type, (void*)fieldAddress, field->m_constant, ::pafcore::Variant::by_ref);
}
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode SetInstanceField(pafcore::Variant* that, pafcore::InstanceField* field, PyObject* pyAttr)
{
if(field->isArray())
{
return pafcore::e_field_is_an_array;
}
if(field->isConstant())
{
return pafcore::e_field_is_constant;
}
size_t baseOffset;
if(!static_cast<pafcore::ClassType*>(that->m_type)->getClassOffset(baseOffset, field->m_objectType))
{
return pafcore::e_invalid_object_type;
}
size_t fieldAddress = (size_t)that->m_pointer + baseOffset + field->m_offset;
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(field->m_type, (void*)fieldAddress))
{
return pafcore::e_invalid_field_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode GetStaticProperty(PyObject*& pyObject, pafcore::StaticProperty* property)
{
if(0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(&value);
if(pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetStaticArrayPropertySize(PyObject*& pyObject, pafcore::StaticArrayProperty* property)
{
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_sizer)(&value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetStaticArrayProperty(PyObject*& pyObject, pafcore::StaticArrayProperty* property, size_t index)
{
if (0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(index, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode SetStaticProperty(pafcore::StaticProperty* property, PyObject* pyAttr)
{
if(0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(attr);
return errorCode;
}
pafcore::ErrorCode SetStaticArrayPropertySize(pafcore::StaticArrayProperty* property, PyObject* pyAttr)
{
if (0 == property->m_resizer)
{
return pafcore::e_array_property_is_not_dynamic;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_resizer)(attr);
return errorCode;
}
pafcore::ErrorCode SetStaticArrayProperty(pafcore::StaticArrayProperty* property, size_t index, PyObject* pyAttr)
{
if (0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(index, attr);
return errorCode;
}
pafcore::ErrorCode MakeStaticArrayProperty(PyObject*& pyObject, pafcore::StaticArrayProperty* property)
{
PyObject* object = StaticArrayPropertyWrapper_new(&s_StaticArrayPropertyWrapper_Type, 0, 0);
((StaticArrayPropertyWrapper*)object)->m_property = property;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode GetInstanceProperty(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceProperty* property)
{
if(0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(that, &value);
if(pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetInstanceArrayPropertySize(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceArrayProperty* property)
{
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_sizer)(that, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetInstanceArrayProperty(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceArrayProperty* property, size_t index)
{
if (0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(that, index, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode SetInstanceProperty(pafcore::Variant* that, pafcore::InstanceProperty* property, PyObject* pyAttr)
{
if(0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(that, attr);
return errorCode;
}
pafcore::ErrorCode SetInstanceArrayPropertySize(pafcore::Variant* that, pafcore::InstanceArrayProperty* property, PyObject* pyAttr)
{
if (0 == property->m_resizer)
{
return pafcore::e_array_property_is_not_dynamic;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_resizer)(that, attr);
return errorCode;
}
pafcore::ErrorCode SetInstanceArrayProperty(pafcore::Variant* that, pafcore::InstanceArrayProperty* property, size_t index, PyObject* pyAttr)
{
if (0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(that, index, attr);
return errorCode;
}
pafcore::ErrorCode MakeInstanceArrayProperty(PyObject*& pyObject, VariantWrapper* self, pafcore::InstanceArrayProperty* property)
{
PyObject* object = InstanceArrayPropertyWrapper_new(&s_InstanceArrayPropertyWrapper_Type, 0, 0);
((InstanceArrayPropertyWrapper*)object)->m_property = property;
((InstanceArrayPropertyWrapper*)object)->m_self = self;
Py_INCREF(self);
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode SetArraySize(pafcore::Variant* that, PyObject* pyAttr)
{
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if (!attr->castToPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &that->m_arraySize))
{
return pafcore::e_invalid_property_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode MakeFunctionInvoker(PyObject*& pyObject, pafcore::FunctionInvoker invoker)
{
PyObject* object = FunctionInvokerWrapper_new(&s_FunctionInvokerWrapper_Type, 0, 0);
((FunctionInvokerWrapper*)object)->m_invoker = invoker;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode MakeInstanceMethod(PyObject*& pyObject, VariantWrapper* self, pafcore::InstanceMethod* method)
{
PyObject* object = InstanceMethodWrapper_new(&s_InstanceMethodWrapper_Type, 0, 0);
((InstanceMethodWrapper*)object)->m_method = method;
((InstanceMethodWrapper*)object)->m_self = self;
Py_INCREF(self);
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode GetNestedType(PyObject*& pyObject, pafcore::Type* nestedType)
{
pafcore::Variant value;
value.assignReferencePtr(RuntimeTypeOf<pafcore::Type>::RuntimeType::GetSingleton(), nestedType, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode GetPrimitiveOrEnum(PyObject*& pyObject, pafcore::Variant* variant)
{
if(variant->m_type->isPrimitive())
{
if(variant->byValue() || variant->byRef())
{
pafcore::PrimitiveType* primitiveType = static_cast<pafcore::PrimitiveType*>(variant->m_type);
switch(primitiveType->m_typeCategory)
{
case pafcore::float_type:
case pafcore::double_type:
case pafcore::long_double_type:
{
double value;
primitiveType->castTo(&value, RuntimeTypeOf<double>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyFloat_FromDouble(value);
}
break;
case pafcore::bool_type:
{
bool value;
primitiveType->castTo(&value, RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = value ? Py_True : Py_False;
}
break;
case pafcore::unsigned_long_long_type:
{
unsigned PY_LONG_LONG value;
primitiveType->castTo(&value, RuntimeTypeOf<unsigned PY_LONG_LONG>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromUnsignedLongLong(value);
}
break;
case pafcore::long_long_type:
{
PY_LONG_LONG value;
primitiveType->castTo(&value, RuntimeTypeOf<PY_LONG_LONG>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromLongLong(value);
}
break;
case pafcore::unsigned_char_type:
case pafcore::unsigned_short_type:
case pafcore::unsigned_int_type:
case pafcore::unsigned_long_type:
{
unsigned long value;
primitiveType->castTo(&value, RuntimeTypeOf<unsigned long>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromUnsignedLong(value);
}
break;
default:
{
long value;
primitiveType->castTo(&value, RuntimeTypeOf<long>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromLong(value);
}
}
return pafcore::s_ok;
}
else
{
pafcore::PrimitiveType* primitiveType = static_cast<pafcore::PrimitiveType*>(variant->m_type);
if(pafcore::char_type == primitiveType->m_typeCategory)
{
pyObject = PyUnicode_FromString((const char*)variant->m_pointer);
return pafcore::s_ok;
}
else if(pafcore::wchar_type == primitiveType->m_typeCategory)
{
pyObject = PyUnicode_FromWideChar((const wchar_t*)variant->m_pointer, -1);
return pafcore::s_ok;
}
}
}
else if(variant->m_type->isEnum())
{
if(variant->byValue() || variant->byRef())
{
long value;
variant->castToPrimitive(RuntimeTypeOf<long>::RuntimeType::GetSingleton(), &value);
pyObject = PyLong_FromLong(value);
return pafcore::s_ok;
}
}
return pafcore::e_invalid_type;
}
pafcore::ErrorCode SetPrimitiveOrEnum(pafcore::Variant* variant, PyObject* pyAttr)
{
if (variant->isConstant())
{
return pafcore::e_field_is_constant;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if (!attr->castToPrimitive(variant->m_type, variant->m_pointer))
{
return pafcore::e_invalid_property_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode MakeProxyCreator(PyObject*& pyObject, pafcore::ClassType* classType)
{
PyObject* object = ProxyCreatorWrapper_new(&s_ProxyCreatorWrapper_Type, 0, 0);
((ProxyCreatorWrapper*)object)->m_classType = classType;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode MakeTypeCaster(PyObject*& pyObject, pafcore::Type* type)
{
PyObject* object = TypeCasterWrapper_new(&s_TypeCasterWrapper_Type, 0, 0);
((TypeCasterWrapper*)object)->m_type = type;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode Variant_GetAttr(PyObject*& pyObject, VariantWrapper* self, const char *name)
{
pafcore::Variant* variant = (pafcore::Variant*)self->m_var;
if(variant->isNull())
{
if (strcmp(name, "_isNullPtr_") == 0)//_isNullPtr_
{
bool isNullPtr = (0 == variant->m_pointer);
pafcore::Variant var;
var.assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &isNullPtr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
return pafcore::e_void_variant;
}
switch(variant->m_type->m_category)
{
case pafcore::name_space:
{
pafcore::NameSpace* ns = (pafcore::NameSpace*)variant->m_pointer;
pafcore::Metadata* member = ns->findMember(name);
if(0 != member)
{
pafcore::Variant value;
value.assignReferencePtr(RuntimeTypeOf<pafcore::Metadata>::RuntimeType::GetSingleton(), member, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
}
break;
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)variant->m_pointer;
pafcore::Metadata* member = type->findClassMember(name, true);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_field:
return GetStaticField(pyObject, static_cast<pafcore::StaticField*>(member));
case pafcore::static_property:
return GetStaticProperty(pyObject, static_cast<pafcore::StaticProperty*>(member));
case pafcore::static_array_property:
return MakeStaticArrayProperty(pyObject, static_cast<pafcore::StaticArrayProperty*>(member));
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
case pafcore::enum_type:
case pafcore::class_type:
return GetNestedType(pyObject, static_cast<pafcore::Type*>(member));
}
}
}
break;
case pafcore::primitive_type:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)variant->m_pointer;
pafcore::Metadata* member = type->findTypeMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
default:
assert(false);
}
}
}
break;
case pafcore::enum_type:
{
pafcore::EnumType* et = (pafcore::EnumType*)variant->m_pointer;
pafcore::Enumerator* enumerator = et->findEnumerator(name);
if(0 != enumerator)
{
pafcore::Variant value;
value.assignEnum(enumerator->m_type, &enumerator->m_value);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
}
break;
}
pafcore::Metadata* member;
member = variant->m_type->findMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::instance_field:
return GetInstanceField(pyObject, variant, static_cast<pafcore::InstanceField*>(member));
case pafcore::static_field:
return GetStaticField(pyObject, static_cast<pafcore::StaticField*>(member));
case pafcore::instance_property:
return GetInstanceProperty(pyObject, variant, static_cast<pafcore::InstanceProperty*>(member));
case pafcore::static_property:
return GetStaticProperty(pyObject, static_cast<pafcore::StaticProperty*>(member));
case pafcore::instance_array_property:
return MakeInstanceArrayProperty(pyObject, self, static_cast<pafcore::InstanceArrayProperty*>(member));
case pafcore::static_array_property:
return MakeStaticArrayProperty(pyObject, static_cast<pafcore::StaticArrayProperty*>(member));
case pafcore::instance_method:
return MakeInstanceMethod(pyObject, self, static_cast<pafcore::InstanceMethod*>(member));
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
case pafcore::enum_type:
case pafcore::class_type:
return GetNestedType(pyObject, static_cast<pafcore::Type*>(member));
default:
assert(false);
}
}
else if (name[0] == '_')
{
switch (name[1])
{
case '\0'://_
if (variant->m_type->isPrimitive() || variant->m_type->isEnum())
{
return GetPrimitiveOrEnum(pyObject, variant);
}
break;
case 'C':
if (strcmp(&name[2], "astPtr_") == 0)//_CastPtr_
{
if (pafcore::void_type == variant->m_type->m_category ||
pafcore::primitive_type == variant->m_type->m_category ||
pafcore::enum_type == variant->m_type->m_category ||
pafcore::class_type == variant->m_type->m_category)
{
pafcore::Type* type = (pafcore::Type*)variant->m_pointer;
return MakeTypeCaster(pyObject, type);
}
else
{
return pafcore::e_is_not_type;
}
}
break;
case 'D':
if (strcmp(&name[2], "erive_") == 0)//_Derive_
{
if (pafcore::class_type == variant->m_type->m_category)
{
pafcore::ClassType* classType = (pafcore::ClassType*)variant->m_pointer;
return MakeProxyCreator(pyObject, classType);
}
else
{
return pafcore::e_is_not_class;
}
}
break;
case 'a':
if (strcmp(&name[2], "ddress_") == 0)//_address_
{
pafcore::Variant address;
address.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_pointer);
pyObject = VariantToPython(&address);
return pafcore::s_ok;
}
break;
case 'c':
if (strcmp(&name[2], "ount_") == 0)//_count_
{
pafcore::Variant count;
count.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_arraySize);
pyObject = VariantToPython(&count);
return pafcore::s_ok;
}
break;
case 'i':
if (strcmp(&name[2], "sNullPtr_") == 0)//_isNullPtr_
{
bool isNullPtr = (0 == variant->m_pointer);
pafcore::Variant var;
var.assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &isNullPtr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
break;
case 'n':
if (strcmp(&name[2], "ullPtr_") == 0)//_nullPtr_
{
if (pafcore::void_type == variant->m_type->m_category ||
pafcore::primitive_type == variant->m_type->m_category ||
pafcore::enum_type == variant->m_type->m_category ||
pafcore::class_type == variant->m_type->m_category)
{
pafcore::Type* type = (pafcore::Type*)variant->m_pointer;
pafcore::Variant var;
var.assignPtr(type, 0, false, pafcore::Variant::by_ptr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
else
{
return pafcore::e_is_not_type;
}
}
break;
case 's':
if (strcmp(&name[2], "ize_") == 0)//_size_
{
pafcore::Variant size;
size.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_type->m_size);
pyObject = VariantToPython(&size);
return pafcore::s_ok;
}
break;
case 't':
if (strcmp(&name[2], "ype_") == 0)//_type_
{
pafcore::Variant typeVar;
typeVar.assignReferencePtr(RuntimeTypeOf<pafcore::Type>::RuntimeType::GetSingleton(), variant->m_type, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&typeVar);
return pafcore::s_ok;
}
break;
}
}
return pafcore::e_member_not_found;
}
pafcore::ErrorCode Variant_SetAttr(pafcore::Variant* variant, char* name, PyObject* pyAttr)
{
switch(variant->m_type->m_category)
{
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)variant->m_pointer;
pafcore::Metadata* member = type->findClassMember(name, true);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_field:
return SetStaticField(static_cast<pafcore::StaticField*>(member), pyAttr);
case pafcore::static_property:
return SetStaticProperty(static_cast<pafcore::StaticProperty*>(member), pyAttr);
}
}
}
break;
}
pafcore::Metadata* member;
member = variant->m_type->findMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::instance_field:
return SetInstanceField(variant, static_cast<pafcore::InstanceField*>(member), pyAttr);
case pafcore::static_field:
return SetStaticField(static_cast<pafcore::StaticField*>(member), pyAttr);
case pafcore::instance_property:
return SetInstanceProperty(variant, static_cast<pafcore::InstanceProperty*>(member), pyAttr);
case pafcore::static_property:
return SetStaticProperty(static_cast<pafcore::StaticProperty*>(member), pyAttr);
}
}
else if (name[0] == '_')
{
switch (name[1])
{
case '\0':
if ((variant->m_type->isPrimitive() || variant->m_type->isEnum()) &&
(variant->byValue() || variant->byRef()))//_
{
return SetPrimitiveOrEnum(variant, pyAttr);
}
break;
case 'c':
if (strcmp(&name[2], "ount_") == 0)//_count_
{
return SetArraySize(variant, pyAttr);
}
break;
}
}
return pafcore::e_member_not_found;
}
pafcore::ErrorCode Variant_Subscript(PyObject*& pyObject, VariantWrapper* wrapper, size_t index)
{
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
pafcore::Variant item;
if(!variant->subscript(item, index))
{
return pafcore::e_index_out_of_range;
}
pyObject = VariantToPython(&item);
return pafcore::s_ok;
}
pafcore::ErrorCode Variant_AssignSubscript(VariantWrapper* wrapper, size_t index, PyObject* pyAttr)
{
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
pafcore::Variant item;
if(!variant->subscript(item, index))
{
return pafcore::e_index_out_of_range;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(item.m_type, item.m_pointer))
{
return pafcore::e_invalid_type;
}
return pafcore::s_ok;
}
PyObject* VariantWrapper_getattr(VariantWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode = Variant_GetAttr(res, wrapper, name);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int VariantWrapper_setattr(VariantWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::Variant* self = (pafcore::Variant*)wrapper->m_var;
pafcore::ErrorCode errorCode = Variant_SetAttr(self, name, pyAttr);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* VariantWrapper_call(VariantWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::FunctionInvoker invoker = 0;
pafcore::Variant* self = (pafcore::Variant*)wrapper->m_var;
switch(self->m_type->m_category)
{
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)self->m_pointer;
pafcore::Metadata* member = type->findClassMember("New", false);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
if(pafcore::static_method == memberType->m_category)
{
invoker = static_cast<pafcore::StaticMethod*>(member)->m_invoker;
}
}
}
break;
case pafcore::primitive_type:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)self->m_pointer;
assert(strcmp(type->m_staticMethods[0].m_name, "New") == 0);
invoker = type->m_staticMethods[0].m_invoker;
}
break;
case pafcore::static_method:
{
pafcore::StaticMethod* method = (pafcore::StaticMethod*)self->m_pointer;
invoker = method->m_invoker;
}
break;
case pafcore::instance_method:
{
pafcore::InstanceMethod* method = (pafcore::InstanceMethod*)self->m_pointer;
invoker = method->m_invoker;
}
break;
}
if(0 != invoker)
{
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count];
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*invoker)(&result, args, numArgs);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_is_not_type));
}
return 0;
}
Py_ssize_t VariantWrapper_length(VariantWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
Py_ssize_t len;
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
if (pafcore::void_object == variant->m_type->m_category && variant->byValue())
{
errorCode = pafcore::e_void_variant;
}
else
{
errorCode = pafcore::s_ok;
len = variant->m_arraySize;
}
if (pafcore::s_ok == errorCode)
{
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
bool VariantWrapper_ParseSubscript(size_t& num, PyObject* pyObject)
{
PyObject* type = PyObject_Type(pyObject);
if(PyObject_TypeCheck(pyObject, &s_VariantWrapper_Type))
{
pafcore::Variant* variant = (pafcore::Variant*)((VariantWrapper*)pyObject)->m_var;
if(variant->byValue() || variant->byRef())
{
if(variant->castToPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &num))
{
return true;
}
}
}
if(PyLong_Check(pyObject))
{
num = PyLong_AsSize_t(pyObject);
return true;
}
return false;
}
PyObject* VariantWrapper_subscript(VariantWrapper* wrapper, PyObject* subscript)
{
size_t index;
if(!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = Variant_Subscript(res, wrapper, index);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int VariantWrapper_assign_subscript(VariantWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if(!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = Variant_AssignSubscript(wrapper, index, value);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* InstanceArrayPropertyWrapper_getattr(InstanceArrayPropertyWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = GetInstanceArrayPropertySize(res, (pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int InstanceArrayPropertyWrapper_setattr(InstanceArrayPropertyWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = SetInstanceArrayPropertySize((pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, pyAttr);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
Py_ssize_t InstanceArrayPropertyWrapper_length(InstanceArrayPropertyWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
pafcore::Variant value;
errorCode = (*wrapper->m_property->m_sizer)((pafcore::Variant*)wrapper->m_self->m_var, &value);
if (pafcore::s_ok == errorCode)
{
Py_ssize_t len;
value.castToPrimitive(RuntimeTypeOf<Py_ssize_t>::RuntimeType::GetSingleton(), &len);
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
PyObject* InstanceArrayPropertyWrapper_subscript(InstanceArrayPropertyWrapper* wrapper, PyObject* subscript)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = GetInstanceArrayProperty(res, (pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, index);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int InstanceArrayPropertyWrapper_assign_subscript(InstanceArrayPropertyWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = SetInstanceArrayProperty((pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, index, value);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* StaticArrayPropertyWrapper_getattr(StaticArrayPropertyWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = GetStaticArrayPropertySize(res, wrapper->m_property);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int StaticArrayPropertyWrapper_setattr(StaticArrayPropertyWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = SetStaticArrayPropertySize(wrapper->m_property, pyAttr);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
Py_ssize_t StaticArrayPropertyWrapper_length(StaticArrayPropertyWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
pafcore::Variant value;
errorCode = (*wrapper->m_property->m_sizer)(&value);
if (pafcore::s_ok == errorCode)
{
Py_ssize_t len;
value.castToPrimitive(RuntimeTypeOf<Py_ssize_t>::RuntimeType::GetSingleton(), &len);
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
PyObject* StaticArrayPropertyWrapper_subscript(StaticArrayPropertyWrapper* wrapper, PyObject* subscript)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = GetStaticArrayProperty(res, wrapper->m_property, index);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int StaticArrayPropertyWrapper_assign_subscript(StaticArrayPropertyWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = SetStaticArrayProperty(wrapper->m_property, index, value);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* InstanceMethodWrapper_call(InstanceMethodWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::InstanceMethod* method = wrapper->m_method;
VariantWrapper* self = wrapper->m_self;
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count + 1];
args[0] = (pafcore::Variant*)self->m_var;
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i+1] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, numArgs + 1);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
PyObject* FunctionInvokerWrapper_call(FunctionInvokerWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::FunctionInvoker invoker = wrapper->m_invoker;
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count];
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*invoker)(&result, args, numArgs);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
PyObject* ProxyCreatorWrapper_call(ProxyCreatorWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::ClassType* classType = wrapper->m_classType;
Py_ssize_t numArgs = PyTuple_Size(parameters);
PyObject* pyArg = PyTuple_GetItem(parameters, 0);
if(pyArg)
{
PythonSubclassInvoker* subclassInvoker = paf_new PythonSubclassInvoker(pyArg);
void* implementor = classType->createSubclassProxy(subclassInvoker);
pafcore::Variant impVar;
if(classType->isValue())
{
impVar.assignValuePtr(classType, implementor, false, ::pafcore::Variant::by_new_ptr);
}
else
{
impVar.assignReferencePtr(classType, implementor, false, ::pafcore::Variant::by_new_ptr);
}
return VariantToPython(&impVar);
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_arg_type_1));
return 0;
}
PyObject* TypeCasterWrapper_call(TypeCasterWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::Type* type = wrapper->m_type;
Py_ssize_t numArgs = PyTuple_Size(parameters);
PyObject* pyArg = PyTuple_GetItem(parameters, 0);
if (pyArg)
{
pafcore::Variant value;
pafcore::Variant* arg = PythonToVariant(&value, pyArg);
pafcore::Variant dstPtr;
arg->reinterpretCastToPtr(dstPtr, type);
return VariantToPython(&dstPtr);
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_arg_type_1));
return 0;
}
PyObject* VariantWrapper_unaryOperator(PyObject* pyObject, const char* op)
{
pafcore::Variant arguments[1];
pafcore::Variant* args[1];
args[0] = PythonToVariant(&arguments[0], pyObject);
pafcore::InstanceMethod* method;
switch (args[0]->m_type->m_category)
{
case pafcore::primitive_object:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)args[0]->m_type;
method = type->findInstanceMethod(op);
}
break;
case pafcore::value_object:
case pafcore::reference_object:
{
pafcore::ClassType* type = (pafcore::ClassType*)args[0]->m_type;
method = type->findInstanceMethod(op, true);
}
break;
default:
method = 0;
};
if (0 != method)
{
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, 1);
if (pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_member_not_found));
}
return 0;
}
PyObject* VariantWrapper_binaryOperator(PyObject* pyObject1, PyObject* pyObject2, const char* op)
{
pafcore::Variant arguments[2];
pafcore::Variant* args[2];
args[0] = PythonToVariant(&arguments[0], pyObject1);
args[1] = PythonToVariant(&arguments[1], pyObject2);
pafcore::InstanceMethod* method;
switch (args[0]->m_type->m_category)
{
case pafcore::primitive_object:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)args[0]->m_type;
method = type->findInstanceMethod(op);
}
break;
case pafcore::value_object:
case pafcore::reference_object:
{
pafcore::ClassType* type = (pafcore::ClassType*)args[0]->m_type;
method = type->findInstanceMethod(op, true);
}
break;
default:
method = 0;
};
if (0 != method)
{
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, 2);
if (pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_member_not_found));
}
return 0;
}
//PyObject* VariantWrapper_compoundAssignmentOperator(PyObject* pyObject1, PyObject* pyObject2, pafcore::FunctionInvoker invoker)
//{
// pafcore::Variant arguments[2];
// pafcore::Variant* args[2];
// args[0] = PythonToVariant(&arguments[0], pyObject1);
// args[1] = PythonToVariant(&arguments[1], pyObject2);
// pafcore::Variant result;
// pafcore::ErrorCode errorCode = (*invoker)(&result, args, 2);
// if(pafcore::s_ok == errorCode)
// {
// Py_INCREF(pyObject1);
// return pyObject1;
// }
// PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
// return 0;
//}
PyObject* VariantWrapper_add(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_add");
}
PyObject* VariantWrapper_subtract(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_subtract");
}
PyObject* VariantWrapper_multiply(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_multiply");
}
PyObject* VariantWrapper_mod(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_mod");
}
PyObject* VariantWrapper_negative(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_negate");
}
PyObject* VariantWrapper_positive(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_plus");
}
PyObject* VariantWrapper_invert(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_bitwiseNot");
}
PyObject* VariantWrapper_lshift(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_leftShift");
}
PyObject* VariantWrapper_rshift(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_rightShift");
}
PyObject* VariantWrapper_and(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseAnd");
}
PyObject* VariantWrapper_xor(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseXor");
}
PyObject* VariantWrapper_or(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseOr");
}
//
//PyObject* VariantWrapper_inplace_add(PyObject* pyObject1, PyObject* pyObject2)
//{
// return VariantWrapper_compoundAssignmentOperator(pyObject1, pyObject2, pafcore::PrimitiveType::Primitive_op_addAssign);
//}
static PyNumberMethods s_VariantWrapper_Operators =
{
VariantWrapper_add,//binaryfunc nb_add;
VariantWrapper_subtract,//binaryfunc nb_subtract;
VariantWrapper_multiply,//binaryfunc nb_multiply;
VariantWrapper_mod,//binaryfunc nb_remainder;
0,//binaryfunc nb_divmod;
0,//ternaryfunc nb_power;
VariantWrapper_negative,//unaryfunc nb_negative;
VariantWrapper_positive,//unaryfunc nb_positive;
0,//unaryfunc nb_absolute;
0,//inquiry nb_bool;
VariantWrapper_invert,//unaryfunc nb_invert;
VariantWrapper_lshift,//binaryfunc nb_lshift;
VariantWrapper_rshift,//binaryfunc nb_rshift;
VariantWrapper_and,//binaryfunc nb_and;
VariantWrapper_xor,//binaryfunc nb_xor;
VariantWrapper_or,//binaryfunc nb_or;
0,//unaryfunc nb_int;
0,//void *nb_reserved; /* the slot formerly known as nb_long */
0,//unaryfunc nb_float;
0,//binaryfunc nb_inplace_add;
0,//binaryfunc nb_inplace_subtract;
0,//binaryfunc nb_inplace_multiply;
0,//binaryfunc nb_inplace_remainder;
0,//ternaryfunc nb_inplace_power;
0,//binaryfunc nb_inplace_lshift;
0,//binaryfunc nb_inplace_rshift;
0,//binaryfunc nb_inplace_and;
0,//binaryfunc nb_inplace_xor;
0,//binaryfunc nb_inplace_or;
0,//binaryfunc nb_floor_divide;
0,//binaryfunc nb_true_divide;
0,//binaryfunc nb_inplace_floor_divide;
0,//binaryfunc nb_inplace_true_divide;
0,//unaryfunc nb_index;
0,//binaryfunc nb_matrix_multiply;
0,//binaryfunc nb_inplace_matrix_multiply;
};
PyObject* VariantWrapper_richcmp(PyObject* pyObject1, PyObject* pyObject2, int op)
{
switch(op)
{
case Py_LT:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_less");
case Py_LE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_lessEqual");
case Py_EQ:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_equal");
case Py_NE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_notEqual");
case Py_GT:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_greater");
case Py_GE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_greaterEqual");
}
return 0;
}
static PyMappingMethods s_VariantWrapper_Array_Methods =
{
(lenfunc)VariantWrapper_length,
(binaryfunc)VariantWrapper_subscript,
(objobjargproc)VariantWrapper_assign_subscript
};
static PyMappingMethods s_InstanceArrayPropertyWrapper_Array_Methods =
{
(lenfunc)InstanceArrayPropertyWrapper_length,
(binaryfunc)InstanceArrayPropertyWrapper_subscript,
(objobjargproc)InstanceArrayPropertyWrapper_assign_subscript
};
static PyMappingMethods s_StaticArrayPropertyWrapper_Array_Methods =
{
(lenfunc)StaticArrayPropertyWrapper_length,
(binaryfunc)StaticArrayPropertyWrapper_subscript,
(objobjargproc)StaticArrayPropertyWrapper_assign_subscript
};
static PyModuleDef s_PafPythonModule =
{
PyModuleDef_HEAD_INIT,
"PafPython",
0,
-1,
};
PyMODINIT_FUNC PyInit_PafPython_()
{
PyObject* module;
s_VariantWrapper_Type.tp_dealloc = (destructor)VariantWrapper_dealloc;
s_VariantWrapper_Type.tp_getattr = (getattrfunc)VariantWrapper_getattr;
s_VariantWrapper_Type.tp_setattr = (setattrfunc)VariantWrapper_setattr;
s_VariantWrapper_Type.tp_call = (ternaryfunc)VariantWrapper_call;
s_VariantWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_VariantWrapper_Type.tp_new = VariantWrapper_new;
s_VariantWrapper_Type.tp_as_number = &s_VariantWrapper_Operators;
s_VariantWrapper_Type.tp_as_mapping = &s_VariantWrapper_Array_Methods;
s_VariantWrapper_Type.tp_richcompare = &VariantWrapper_richcmp;
if (PyType_Ready(&s_VariantWrapper_Type) < 0)
{
return NULL;
}
s_InstanceArrayPropertyWrapper_Type.tp_dealloc = (destructor)InstanceArrayPropertyWrapper_dealloc;
s_InstanceArrayPropertyWrapper_Type.tp_getattr = (getattrfunc)InstanceArrayPropertyWrapper_getattr;
s_InstanceArrayPropertyWrapper_Type.tp_setattr = (setattrfunc)InstanceArrayPropertyWrapper_setattr;
s_InstanceArrayPropertyWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_InstanceArrayPropertyWrapper_Type.tp_new = InstanceArrayPropertyWrapper_new;
s_InstanceArrayPropertyWrapper_Type.tp_as_mapping = &s_InstanceArrayPropertyWrapper_Array_Methods;
if (PyType_Ready(&s_InstanceArrayPropertyWrapper_Type) < 0)
{
return NULL;
}
s_StaticArrayPropertyWrapper_Type.tp_getattr = (getattrfunc)StaticArrayPropertyWrapper_getattr;
s_StaticArrayPropertyWrapper_Type.tp_setattr = (setattrfunc)StaticArrayPropertyWrapper_setattr;
s_StaticArrayPropertyWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_StaticArrayPropertyWrapper_Type.tp_new = StaticArrayPropertyWrapper_new;
s_StaticArrayPropertyWrapper_Type.tp_as_mapping = &s_StaticArrayPropertyWrapper_Array_Methods;
if (PyType_Ready(&s_StaticArrayPropertyWrapper_Type) < 0)
{
return NULL;
}
s_InstanceMethodWrapper_Type.tp_dealloc = (destructor)InstanceMethodWrapper_dealloc;
s_InstanceMethodWrapper_Type.tp_call = (ternaryfunc)InstanceMethodWrapper_call;
s_InstanceMethodWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_InstanceMethodWrapper_Type.tp_new = InstanceMethodWrapper_new;
if (PyType_Ready(&s_InstanceMethodWrapper_Type) < 0)
{
return NULL;
}
s_FunctionInvokerWrapper_Type.tp_call = (ternaryfunc)FunctionInvokerWrapper_call;
s_FunctionInvokerWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_FunctionInvokerWrapper_Type.tp_new = FunctionInvokerWrapper_new;
if (PyType_Ready(&s_FunctionInvokerWrapper_Type) < 0)
{
return NULL;
}
s_ProxyCreatorWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_ProxyCreatorWrapper_Type.tp_new = ProxyCreatorWrapper_new;
s_ProxyCreatorWrapper_Type.tp_call = (ternaryfunc)ProxyCreatorWrapper_call;
if (PyType_Ready(&s_ProxyCreatorWrapper_Type) < 0)
{
return NULL;
}
s_TypeCasterWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_TypeCasterWrapper_Type.tp_new = TypeCasterWrapper_new;
s_TypeCasterWrapper_Type.tp_call = (ternaryfunc)TypeCasterWrapper_call;
if (PyType_Ready(&s_TypeCasterWrapper_Type) < 0)
{
return NULL;
}
module = PyModule_Create(&s_PafPythonModule);
if (module == NULL)
{
return NULL;
}
Py_INCREF(&s_VariantWrapper_Type);
PyObject* root = VariantWrapper_new(&s_VariantWrapper_Type, 0, 0);
pafcore::Variant* var = (pafcore::Variant*)((VariantWrapper*)root)->m_var;
var->assignReferencePtr(RuntimeTypeOf<pafcore::NameSpace>::RuntimeType::GetSingleton(), pafcore::NameSpace::GetGlobalNameSpace(), false, ::pafcore::Variant::by_ptr);
PyModule_AddObject(module, "paf", root);
return module;
}
END_PAFPYTHON
PyMODINIT_FUNC PyInit_PafPython()
{
return pafpython::PyInit_PafPython_();
}
| 29.244094
| 166
| 0.748846
|
fdyjfd
|
dbdec26c028ff42e9f5f193c9eea7efe879435dd
| 4,500
|
cpp
|
C++
|
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2019-08-31T08:06:48.000Z
|
2019-08-31T08:06:48.000Z
|
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | null | null | null |
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2020-01-07T10:46:23.000Z
|
2020-01-07T10:46:23.000Z
|
double AODVsndcode(int seg, void* data) {
AODVsnd_Data* d = (AODVsnd_Data*) data;
int myID = d->nodeID;
MailboxMsg *mailboxmsg;
GenericNwkMsg *nwkmsg;
DataMsg *datamsg;
RREQMsg *rreqmsg;
int dest;
double now, etime;
RouteEntry *dest_entry;
DataNode *dn;
switch (seg) {
case 1:
ttFetch("AODVSndBox");
return 0.0001;
case 2:
mailboxmsg = (MailboxMsg*) ttRetrieve("AODVSndBox");
now = ttCurrentTime();
switch (mailboxmsg->type) {
case APPL_DATA:
// Data message from application
datamsg = (DataMsg*) mailboxmsg->datamsg;
delete mailboxmsg;
mexPrintf("Time: %f Application in Node# %d wants to send to Node# %d Data: %f\n", now, myID, datamsg->dest, datamsg->data);
dest_entry = &(d->routing_table[datamsg->dest-1]);
// Is the entry valid?
if (!dest_entry->valid) {
// Not found in routing table
mexPrintf("No (valid) route exists\n");
// Increment broadcast ID and sequence number
d->RREQID++;
d->seqNbrs[myID-1]++;
// Create RREQ
rreqmsg = new RREQMsg;
rreqmsg->hopCnt = 0;
rreqmsg->RREQID = d->RREQID;
rreqmsg->dest = datamsg->dest;
rreqmsg->destSeqNbr = d->seqNbrs[datamsg->dest-1];
rreqmsg->src = myID;
rreqmsg->srcSeqNbr = d->seqNbrs[myID-1];
d->sendTo = 0; // broadcast
d->msg = new GenericNwkMsg;
d->msg->type = RREQ;
d->msg->intermed = myID;
d->msg->msg = rreqmsg;
d->size = 24*8; // 24 bytes
// buffer data until route has been established
// mexPrintf("Buffering message %d\n", d->buffer[datamsg->dest-1]->length()+1);
// d->buffer[datamsg->dest-1]->appendNode(new DataNode(datamsg, ""));
// exectime
etime = 0.0001;;
} else {
// Route to destination exists in table
mexPrintf("Route exists in table ");
mexPrintf("nextHop: %d #Hops: %d\n", dest_entry->nextHop, dest_entry->hops);
// Send data to first node on route to destination
d->sendTo = dest_entry->nextHop;
d->msg = new GenericNwkMsg;
d->msg->type = DATA;
d->msg->intermed = myID;
d->msg->msg = datamsg;
d->size = datamsg->size;
// Update expiry time
d->routing_table[datamsg->dest-1].exptime = now + ACTIVE_ROUTE_TIMEOUT;
updateExpiryTimer(d->routing_table, d->dataTimer, myID);
etime = 0.0001;;
}
return etime;
case ROUTE_EST:
// Message from AODVRcv that a route has been established
dest = mailboxmsg->dest;
delete mailboxmsg;
mexPrintf("Time: %f A new route has been established between Node#%d and Node#%d\n", now, myID, dest);
dest_entry = &(d->routing_table[dest-1]);
// mexPrintf("nextHop: %d #Hops: %d\n", dest_entry->nextHop, dest_entry->hops);
// mexPrintf("%d data messages in buffer\n", d->buffer[dest-1]->length());
d->bufferDest = dest;
d->doEmptyBuffer = 0; // Buffer should be emptied
// Update expiry timer
d->routing_table[dest-1].exptime = now + ACTIVE_ROUTE_TIMEOUT;
updateExpiryTimer(d->routing_table, d->dataTimer, myID);
return 0.0001;;
}
case 3:
// Send buffered data messages?
if (d->doEmptyBuffer) {
dn = (DataNode*) d->buffer[d->bufferDest-1]->getFirst();
if (dn != NULL) {
// Retrieve next message in buffer
datamsg = (DataMsg*) dn->data;
// mexPrintf("Buffer Size: %d Sending buffered message towards Node#%d\n", d->buffer[d->bufferDest-1]->length(), d->bufferDest);
dn->remove();
delete dn;
// Retrieve route entry
dest_entry = &(d->routing_table[datamsg->dest-1]);
nwkmsg = new GenericNwkMsg;
nwkmsg->type = DATA;
nwkmsg->intermed = myID;
nwkmsg->msg = datamsg;
ttSendMsg(1, dest_entry->nextHop, nwkmsg, datamsg->size);
ttSleep(0.001);
return 0.0001;
} else {
// Finished sending data messages
// mexPrintf("Buffer emptied\n");
d->doEmptyBuffer = 0;
ttSetNextSegment(1); // Loop back
return 0.0001;
}
} else {
ttSendMsg(1, d->sendTo, d->msg, d->size);
ttSetNextSegment(1); // Loop back
return 0.0001;
}
case 4:
ttSetNextSegment(3);
return 0.0001;
}
return FINISHED; // to supress compilation warnings
}
| 14.469453
| 136
| 0.582222
|
raulest50
|
dbdf58de09ffeed6854c5f822b4fa4d7caa9d730
| 1,563
|
cpp
|
C++
|
sdk/object/entity.cpp
|
playday3008/herby
|
3ab4594588c4776182f18edf89d461adef583614
|
[
"MIT"
] | null | null | null |
sdk/object/entity.cpp
|
playday3008/herby
|
3ab4594588c4776182f18edf89d461adef583614
|
[
"MIT"
] | null | null | null |
sdk/object/entity.cpp
|
playday3008/herby
|
3ab4594588c4776182f18edf89d461adef583614
|
[
"MIT"
] | null | null | null |
#include "entity.hpp"
#include "csgo/engine.hpp"
C_BaseEntity* C_BaseEntity::GetBaseEntity(int index)
{
auto client_entity = csgo::m_client_entity_list->GetClientEntity(index);
return (client_entity ? client_entity->GetBaseEntity() : nullptr);
}
int C_BaseEntity::GetMoveType()
{
auto& netvar = csgo::engine::NetPropSystem::Instance();
return netvar.GetDataMap(this->GetPredDescMap(), "m_MoveType");
}
C_AnimationLayer& C_BaseAnimatingOverlay::GetAnimOverlay(int i)
{
static auto field = csgo::engine::NetPropSystem::Instance().GetDataMap(this->GetPredDescMap(), "m_AnimOverlay");
return (*reinterpret_cast<C_AnimationLayer**>(reinterpret_cast<int>(this) + 0x2980))[i];
}
Activity C_BaseAnimatingOverlay::GetSequenceActivity(int sequence)
{
model_t* mdl = this->GetModel();
if (mdl)
{
studiohdr_t* hdr = csgo::m_model_info->GetStudioModel(mdl);
if (hdr)
{
static int offset = memory::scan<int>(L"client.dll","55 8B EC 53 8B 5D 08 56 8B F1 83");
static auto get_sequence_activity = reinterpret_cast<int(__fastcall*)(void*, studiohdr_t*, int)>(offset);
return static_cast<Activity>(get_sequence_activity(this, hdr, sequence));
}
}
return Activity::ACT_RESET;
}
C_CSPlayer* C_CSPlayer::GetCSPlayer(int index)
{
auto base_entity = C_BaseEntity::GetBaseEntity(index);
return ToCSPlayer(base_entity);
}
C_CSPlayer* C_CSPlayer::GetLocalPlayer()
{
auto index = csgo::m_engine_client->GetLocalPlayer();
return GetCSPlayer(index);
}
C_World* C_World::GetWorld()
{
return reinterpret_cast<C_World*>(C_BaseEntity::GetBaseEntity(0));
}
| 28.944444
| 113
| 0.751759
|
playday3008
|
dbdf5e502674a08010f428b1000f028875412737
| 14,606
|
cpp
|
C++
|
InitFile/Tests/ifTestSupport.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
InitFile/Tests/ifTestSupport.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
InitFile/Tests/ifTestSupport.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
//--------------------------------------------------------------------------------------------------
//
// File: Tests/ifTestSupport.cpp
//
// Project: IF
//
// Contains: The function and class definitions for InitFile test programs.
//
// Written by: Norman Jaffe
//
// Copyright: (c) 2020 by OpenDragon.
//
// All rights reserved. Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and / or
// other materials provided with the distribution.
// * Neither the name of the copyright holders nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// Created: 2020-09-25
//
//--------------------------------------------------------------------------------------------------
#include "ifTestSupport.h"
//#include <odlEnable.h>
#include <odlInclude.h>
#include <ifBase.h>
#include <csignal>
#include <sstream>
#if MAC_OR_LINUX_
# include <unistd.h>
#else // ! MAC_OR_LINUX_
# include <Windows.h>
#endif // ! MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#endif // defined(__APPLE__)
/*! @file
@brief The function and class definitions for %InitFile test programs. */
# if defined(__APPLE__)
# pragma clang diagnostic pop
# endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Namespace references
#endif // defined(__APPLE__)
using namespace InitFile;
#if defined(__APPLE__)
# pragma mark Private structures, constants and variables
#endif // defined(__APPLE__)
/*! @brief The signal to use for internally-detected timeouts. */
#if MAC_OR_LINUX_
# define STANDARD_SIGNAL_TO_USE_ SIGUSR2
#else // ! MAC_OR_LINUX_
# define STANDARD_SIGNAL_TO_USE_ 42
#endif // ! MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma mark Global constants and variables
#endif // defined(__APPLE__)
std::string InitFile::kDQ{"\""};
#if defined(__APPLE__)
# pragma mark Local functions
#endif // defined(__APPLE__)
#if MAC_OR_LINUX_
/*! @brief The signal handler to catch requests to stop the service.
@param[in] signal The signal being handled. */
[[noreturn]]
static void
localCatcher
(int NOT_USED_(signal))
{
ODL_ENTER(); //####
//ODL_I1("signal = ", signal); //####
#if 0
if (lLogger)
{
std::string message{"Exiting due to signal "};
message += std::to_string(signal);
message += " = ";
message += NameOfSignal(signal);
lLogger->error(message.c_str());
}
#endif//0
ODL_EXIT_EXIT(1); //####
exit(1);
} // localCatcher
#endif // MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma mark Class methods
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Constructors and Destructors
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Actions and Accessors
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Global functions
#endif // defined(__APPLE__)
bool
InitFile::CanReadFromStandardInput
(void)
{
ODL_ENTER(); //####
#if MAC_OR_LINUX_
pid_t fg = tcgetpgrp(STDIN_FILENO);
#else // ! MAC_OR_LINUX_
HWND wind = GetConsoleWindow();
#endif // ! MAC_OR_LINUX_
bool result = false;
#if MAC_OR_LINUX_
if (-1 == fg)
{
// Piped
result = true;
}
else if (getpgrp() == fg)
{
// Foreground
result = true;
}
else
{
// Background
result = false;
}
#else // ! MAC_OR_LINUX_
result = (nullptr != wind);
#endif // ! MAC_OR_LINUX_
ODL_EXIT_B(result); //####
return result;
} // InitFile::CanReadFromStandardInput
std::string
InitFile::ConvertDoubleToString
(const double value)
{
ODL_ENTER(); //####
ODL_D1("value = ", value); //####
// Note that boost::lexical_cast<std::string>(double) generates strings with trailing digits.
// That is, 1E-22 winds up as 9.9999999999999E-21, which is platform-sensitive.
std::ostringstream holder;
holder << std::defaultfloat << value;
std::string result{holder.str()};
ODL_EXIT_s(result); //####
return result;
} // InitFile::ConvertDoubleToString
bool
InitFile::ConvertToDouble
(const char * startPtr,
double & result)
{
ODL_ENTER(); //####
ODL_S1("startPtr = ", startPtr); //####
ODL_P1("result = ", &result); //####
bool okSoFar;
char * endPtr;
double value = strtod(startPtr, &endPtr);
if ((startPtr != endPtr) && (! *endPtr))
{
result = value;
ODL_D1("result <- ", result); //####
okSoFar = true;
}
else
{
okSoFar = false;
}
ODL_EXIT_B(okSoFar); //####
return okSoFar;
} // InitFile::ConvertToDouble
bool
InitFile::ConvertToInt64
(const char * startPtr,
int64_t & result)
{
ODL_ENTER(); //####
ODL_S1("startPtr = ", startPtr); //####
ODL_P1("result = ", &result); //####
bool okSoFar;
char * endPtr;
int64_t value = strtoll(startPtr, &endPtr, 10);
if ((startPtr != endPtr) && (! *endPtr))
{
result = value;
ODL_I1("result <- ", result); //####
okSoFar = true;
}
else
{
okSoFar = false;
}
ODL_EXIT_B(okSoFar); //####
return okSoFar;
} // InitFile::ConvertToInt64
void
InitFile::Initialize
(const std::string & NOT_USED_(progName))
{
ODL_ENTER(); //####
//ODL_S1s("progName = ", progName); //####
try
{
#if defined(__APPLE__)
sranddev();
#else // ! defined(__APPLE__)
srand(static_cast<unsigned int>(time(nullptr)));
#endif // ! defined(__APPLE__)
//Value::initialize();
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_EXIT(); //####
} // InitFile::Initialize
const char *
InitFile::NameOfSignal
(const int theSignal)
{
const char * result;
#if MAC_OR_LINUX_
switch (theSignal)
{
case SIGHUP :
result = "SIGHUP[hangup]";
break;
case SIGINT :
result = "SIGINT[interrupt]";
break;
case SIGQUIT :
result = "SIGQUIT[quit]";
break;
case SIGILL :
result = "SIGILL[illegal instruction]";
break;
case SIGTRAP :
result = "SIGTRAP[trace trap]";
break;
case SIGABRT :
result = "SIGABRT[abort()]";
break;
# if (defined(_POSIX_C_SOURCE) && (! defined(_DARWIN_C_SOURCE)))
case SIGPOLL :
result = "SIGPOLL[pollable evebt]";
break;
# else // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGEMT :
result = "SIGEMT[EMT instruction]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGFPE :
result = "SIGFPE[floating point exception]";
break;
case SIGKILL :
result = "SIGKILL[kill]";
break;
case SIGBUS :
result = "SIGBUS[bus error]";
break;
case SIGSEGV :
result = "SIGSEGV[segmentation violation]";
break;
case SIGSYS :
result = "SIGSYS[bad argument to system call]";
break;
case SIGPIPE :
result = "SIGPIPE[write on a pipe with no one to read it]";
break;
case SIGALRM :
result = "SIGALRM[alarm clock]";
break;
case SIGTERM :
result = "SIGTERM[software termination signal from kill]";
break;
case SIGURG :
result = "SIGURG[urgent condition on IO channel]";
break;
case SIGSTOP :
result = "SIGSTOP[sendable stop signal not from tty]";
break;
case SIGTSTP :
result = "SIGTSTP[stop signal from tty]";
break;
case SIGCONT :
result = "SIGCONT[continue a stopped process]";
break;
case SIGCHLD :
result = "SIGCHLD[to parent on child stop or exit]";
break;
case SIGTTIN :
result = "SIGTTIN[to readers pgrp upon background tty read]";
break;
case SIGTTOU :
result = "SIGTTOU[like TTIN for output if (tp->t_local <OSTOP)]";
break;
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGIO :
result = "SIGIO[input/output possible signal]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGXCPU :
result = "SIGXCPU[exceeded CPU time limit]";
break;
case SIGXFSZ :
result = "SIGXFSZ[exceeded file size limit]";
break;
case SIGVTALRM :
result = "SIGVTALRM[virtual time alarm]";
break;
case SIGPROF :
result = "SIGPROF[profiling time alarm]";
break;
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGWINCH :
result = "SIGWINCH[window size changes]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGINFO :
result = "SIGINFO[information request]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGUSR1 :
result = "SIGUSR1[user defined signal 1]";
break;
case SIGUSR2 :
result = "SIGUSR2[user defined signal 2]";
break;
default :
result = "unknown";
break;
}
#else // ! MAC_OR_LINUX_
switch (theSignal)
{
case SIGINT :
result = "SIGINT[interrupt]";
break;
case SIGABRT :
result = "SIGABRT[abort()]";
break;
default :
result = "unknown";
break;
}
#endif // ! MAC_OR_LINUX_
return result;
} // InitFile::NameOfSignal
double
InitFile::RandomDouble
(const double minValue,
const double maxValue)
{
double zeroOne = (static_cast<double>(rand()) / RAND_MAX);
return (zeroOne * (maxValue - minValue)) + minValue;
} // InitFile::RandomDouble
void
InitFile::SetSignalHandlers
(InitFile::SignalHandler theHandler)
{
#if MAC_OR_LINUX_
sigset_t blocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
act.sa_handler = theHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
# if (defined(SIGABRT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGABRT, &act, nullptr);
# endif // defined(SIGABRT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGHUP) && (SIGHUP != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGHUP, &act, nullptr);
# endif // defined(SIGHUP) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGINT) && (SIGINT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGINT, &act, nullptr);
# endif // defined(SIGINT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGQUIT) && (SIGQUIT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGQUIT, &act, nullptr);
# endif // defined(SIGQUIT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGUSR1) && (SIGUSR1 != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGUSR1, &act, nullptr);
# endif // defined(SIGUSR1) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGUSR2) && (SIGUSR2 != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGUSR2, &act, nullptr);
# endif // defined(SIGUSR2) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
sigemptyset(&blocking);
sigaddset(&blocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_BLOCK, &blocking, nullptr);
#else // ! MAC_OR_LINUX
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::SetSignalHandlers
void
InitFile::SetUpCatcher
(void)
{
#if MAC_OR_LINUX_
sigset_t unblocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
sigemptyset(&unblocking);
sigaddset(&unblocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_UNBLOCK, &unblocking, nullptr);
act.sa_handler = localCatcher;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(STANDARD_SIGNAL_TO_USE_, &act, nullptr);
#else // ! MAC_OR_LINUX_
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::SetUpCatcher
void
InitFile::ShutDownCatcher
(void)
{
#if MAC_OR_LINUX_
sigset_t blocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
sigemptyset(&blocking);
sigaddset(&blocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_BLOCK, &blocking, nullptr);
act.sa_handler = SIG_DFL;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(STANDARD_SIGNAL_TO_USE_, &act, nullptr);
#else // ! MAC_OR_LINUX_
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::ShutDownCatcher
| 27.768061
| 100
| 0.598863
|
opendragon
|
dbe01a7a918e25d8af6f4f4186ca3f27826f9e95
| 1,617
|
cc
|
C++
|
net/socket.cc
|
xingdl2007/polly
|
c23906d7f58d2eb263cb102b0343dccd5a245881
|
[
"BSD-3-Clause"
] | 2
|
2018-04-12T21:13:18.000Z
|
2018-06-10T14:18:04.000Z
|
net/socket.cc
|
xingdl2007/polly
|
c23906d7f58d2eb263cb102b0343dccd5a245881
|
[
"BSD-3-Clause"
] | null | null | null |
net/socket.cc
|
xingdl2007/polly
|
c23906d7f58d2eb263cb102b0343dccd5a245881
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2018 The Polly Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdlib.h>
#include <sys/socket.h>
#include "socket.h"
#include "log/logger.h"
namespace polly {
void Socket::Bind(InetAddress const &addr_) {
auto addr = addr_.SockAddress();
int ret = ::bind(sockfd_, reinterpret_cast<sockaddr *> (&addr), sizeof addr);
if (ret == -1) {
LOG_FATAL << "Socket::Bind() failed, port: " << addr_.Port();
::abort();
}
}
void Socket::ShutdownWrite() {
if (::shutdown(sockfd_, SHUT_WR) < 0) {
LOG_ERROR << "Socket::ShutdownWrite()";
}
}
// only support IPv4 + TCP for simplicity
int NewNonBlockingSocket() {
int sockfd = ::socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (sockfd == -1) {
LOG_FATAL << "NewNonBlockingSocket() failed";
::abort();
}
return sockfd;
}
struct sockaddr_in getLocalAddr(int sockfd) {
struct sockaddr_in localaddr;
bzero(&localaddr, sizeof localaddr);
socklen_t addrlen = sizeof localaddr;
if (::getsockname(sockfd, reinterpret_cast<sockaddr *>(&localaddr), &addrlen) < 0) {
LOG_ERROR << "sockets::getLocalAddr";
}
return localaddr;
}
struct sockaddr_in getPeerAddr(int sockfd) {
struct sockaddr_in peeraddr;
bzero(&peeraddr, sizeof peeraddr);
socklen_t addrlen = sizeof peeraddr;
if (::getpeername(sockfd, reinterpret_cast<sockaddr *>(&peeraddr), &addrlen) < 0) {
LOG_ERROR << "sockets::getPeerAddr";
}
return peeraddr;
}
} // namespace polly
| 27.87931
| 86
| 0.687075
|
xingdl2007
|
dbe839aaaa905f258032ddd7d5ff5568245b3081
| 1,465
|
hpp
|
C++
|
include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 34
|
2020-08-14T14:32:51.000Z
|
2022-02-16T23:20:02.000Z
|
include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 19
|
2020-08-20T20:04:39.000Z
|
2022-02-28T14:34:37.000Z
|
include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 7
|
2020-08-14T14:18:17.000Z
|
2022-02-01T10:59:24.000Z
|
// Copyright (c) 2020, QuantStack and XVega Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#ifndef XVEGA_ENCODING_HREF_HPP
#define XVEGA_ENCODING_HREF_HPP
#include <xproperty/xobserved.hpp>
#include <xtl/xoptional.hpp>
#include <xtl/xjson.hpp>
#include <nlohmann/json.hpp>
#include "../../../../utils/custom_datatypes.hpp"
#include "../../encoding-channel-options/aggregate.hpp"
#include "../../encoding-channel-options/bin.hpp"
#include "../../encoding-channel-options/field.hpp"
#include "../../encoding-channel-options/timeunit.hpp"
namespace nl = nlohmann;
namespace xv
{
struct Href : public xp::xobserved<Href>
{
XPROPERTY(xtl::xoptional<agg_type>, Href, aggregate);
XPROPERTY(xtl::xoptional<bin_type>, Href, bin);
// XPROPERTY(xtl::xoptional<condition_type>, Href, condition);
XPROPERTY(xtl::xoptional<field_type>, Href, field);
XPROPERTY(xtl::xoptional<string_object_type>, Href, format);
XPROPERTY(xtl::xoptional<std::string>, Href, formatType);
XPROPERTY(xtl::xoptional<std::string>, Href, labelExpr);
XPROPERTY(xtl::xoptional<time_unit_type>, Href, timeUnit);
XPROPERTY(xtl::xoptional<string_vec_none_type>, Href, title);
XPROPERTY(xtl::xoptional<std::string>, Href, type);
};
XVEGA_API void to_json(nl::json& j, const Href& data);
}
#endif
| 32.555556
| 75
| 0.698976
|
domoritz
|
dbf6e33ac75bfa73b68fa656dddc3b1e5f035c7a
| 808
|
hpp
|
C++
|
Siv3D/include/Siv3D/EmojiDictionary.hpp
|
ai2playgame/OpenSiv3D
|
e8814b4bb2baf23fcfc300325f700b842cce79b1
|
[
"MIT"
] | null | null | null |
Siv3D/include/Siv3D/EmojiDictionary.hpp
|
ai2playgame/OpenSiv3D
|
e8814b4bb2baf23fcfc300325f700b842cce79b1
|
[
"MIT"
] | null | null | null |
Siv3D/include/Siv3D/EmojiDictionary.hpp
|
ai2playgame/OpenSiv3D
|
e8814b4bb2baf23fcfc300325f700b842cce79b1
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <memory>
# include "Fwd.hpp"
# include "String.hpp"
# include "Array.hpp"
namespace s3d
{
class EmojiDictionary
{
private:
class EmojiDictionaryDetail;
std::shared_ptr<EmojiDictionaryDetail> pImpl;
public:
EmojiDictionary();
EmojiDictionary(const FilePath& path);
~EmojiDictionary();
bool load(const FilePath& path);
[[nodiscard]] size_t check(String::const_iterator it, const String::const_iterator& itEnd);
void clear();
const Array<Array<uint32>>& getList() const;
};
}
| 17.955556
| 93
| 0.612624
|
ai2playgame
|
dbf8b652b081c6876c2586a5371fc019198306ec
| 962
|
cpp
|
C++
|
CodeForces/964B/13538902_AC_15ms_3304kB.cpp
|
BakaErii/ACM_Collection
|
d368b15c7f1c84472424d5e61e5ebc667f589025
|
[
"WTFPL"
] | null | null | null |
CodeForces/964B/13538902_AC_15ms_3304kB.cpp
|
BakaErii/ACM_Collection
|
d368b15c7f1c84472424d5e61e5ebc667f589025
|
[
"WTFPL"
] | null | null | null |
CodeForces/964B/13538902_AC_15ms_3304kB.cpp
|
BakaErii/ACM_Collection
|
d368b15c7f1c84472424d5e61e5ebc667f589025
|
[
"WTFPL"
] | null | null | null |
/**
* @author Moe_Sakiya sakiya@tun.moe
* @date 2018-04-17 22:33:09
*
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int n, A, B, C, T;
int arr[1001];
int value[1001];
bool isRead[1001];
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
int i, j;
unsigned long long int ans = 0;
scanf("%d %d %d %d %d", &n, &A, &B, &C, &T);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
value[i] = A;
}
for(i = 1; i < T; i++) {
for(j = 0; j < n; j++) {
if(isRead[j] != true && arr[j] <= i) {
if(value[j] + C - B > value[j]) {
value[j] -= B;
ans += C;
} else {
ans += value[j];
isRead[j] = true;
}
}
}
}
for(j = 0; j < n; j++)
if(isRead[j] == false)
ans += value[j];
printf("%llu\n", ans);
return 0;
}
| 17.178571
| 45
| 0.529106
|
BakaErii
|
dbf90495427ac7591c1027b14ba3c08bdde28591
| 1,513
|
cpp
|
C++
|
ch04/e4-08.cpp
|
nanonashy/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 3
|
2021-12-17T17:25:18.000Z
|
2022-03-02T15:52:23.000Z
|
ch04/e4-08.cpp
|
nashinium/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 1
|
2020-04-22T07:16:34.000Z
|
2020-04-22T10:04:04.000Z
|
ch04/e4-08.cpp
|
nashinium/PPPUCpp2ndJP
|
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
|
[
"MIT"
] | 1
|
2020-04-22T08:13:51.000Z
|
2020-04-22T08:13:51.000Z
|
// 問題文:
// 「チェス」を考案したものに褒美を与えようと考えた皇帝が、望みは何かと尋ねたという昔話があ
// る。そのものは、チェス盤の1つ目の升目に1グレインのコメ、2つ目の升目に2グレインの米、
// 3つ目の升目には4グレインの米といったように、64の升目ごとに2倍のの量の米を所望した。謙
// 虚な申し出のように思えたが、帝国にはそれだけの米がなかった。少なくとも1,000グレイン、
// 少なくとも100万グレイン、そして少なくとも10億グレインの米を褒美として与えるのに必要
// な升目の数を計算するプログラムを作成する。当然ながら、ループが必要である。また、現在の
// 升目を追跡するための int 型の変数、現在の升目のグレイン量を追跡するための
// int 型の変数、 それまでのすべての升目のグレイン量を追跡するための int
// 型の変数がおそらく必要になるだろ
// ろう。ループを繰り返すたびにすべての変数の値を書き出し、現在の状況がわかるようにすると
// よいだろう。
//
// コメント:
// 1000グレインは10升目まで、100万グレインは20升目まで、10億グレインは30升目までとなった。
#include "../include/std_lib_facilities.h"
int main() {
bool exit = false;
std::string input;
int total_grain{0};
int add_grain{1};
int times{0};
int request_grain{0};
cout << "グレイン数を入力してください...(quitで終了します)\n"
<< "times\t\tadded grain\t\ttotal grain\n>> ";
while (!exit) {
if (std::cin >> request_grain) {
total_grain = 0;
add_grain = 1;
times = 0;
while (total_grain < request_grain) {
++times;
total_grain += add_grain;
add_grain *= 2;
std::cout << times << "\t\t" << add_grain / 2 << "\t\t"
<< total_grain << '\n';
}
} else {
std::cin.clear();
std::cin >> input;
if (input == "quit")
exit = true;
}
std::cout << ">> ";
}
return 0;
}
| 29.096154
| 72
| 0.551223
|
nanonashy
|
dbf9e591593ea426d4d2006806c04acacfe7ecd2
| 2,337
|
cpp
|
C++
|
Ray/Mono/RScript.cpp
|
CAt0mIcS/Ray
|
898ebbfe1207513045718a4fb1df339621568de4
|
[
"MIT"
] | null | null | null |
Ray/Mono/RScript.cpp
|
CAt0mIcS/Ray
|
898ebbfe1207513045718a4fb1df339621568de4
|
[
"MIT"
] | null | null | null |
Ray/Mono/RScript.cpp
|
CAt0mIcS/Ray
|
898ebbfe1207513045718a4fb1df339621568de4
|
[
"MIT"
] | null | null | null |
#include "RScript.h"
#include <mono/jit/jit.h>
#include <mono/metadata/object.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-config.h>
namespace At0::Ray::Mono
{
bool Script::s_MonoInitialized = false;
Script::Script(std::string_view compiledFilePath)
{
MonoInit();
m_Domain = mono_jit_init(compiledFilePath.data());
if (!m_Domain)
ThrowRuntime("[Mono::Script] Failed to initialize mono jit for assembly \"{0}\"",
compiledFilePath);
// Open a assembly in the domain
m_Assembly = mono_domain_assembly_open(m_Domain, compiledFilePath.data());
if (!m_Assembly)
ThrowRuntime("[Mono::Script] Failed to open assembly \"{0}\"", compiledFilePath);
// Get a image from the assembly
m_Image = mono_assembly_get_image(m_Assembly);
if (!m_Image)
ThrowRuntime(
"[Mono::Script] Failed to get image from the assembly \"{0}\"", compiledFilePath);
}
Script Script::FromFile(std::string_view filepath)
{
MonoInit();
if (!Compile(filepath))
ThrowRuntime("[Mono::Script] Failed to compile script file \"{0}\"", filepath);
return Script{ std::filesystem::path(filepath).replace_extension("dll").string() };
}
Script Script::FromCompiled(std::string_view filepath)
{
MonoInit();
return Script{ filepath };
}
StaticFunction Script::GetStaticFunction(std::string_view functionDescriptor) const
{
return StaticFunction{ functionDescriptor, m_Image };
}
Object Script::GetObject(std::string_view className) const
{
return Object{ className, m_Domain, m_Image };
}
bool Script::Compile(std::string_view filepath)
{
RAY_MEXPECTS(!String::Contains(filepath, " "),
"[Mono::Script] Filepath to script not allowed to contain spaces");
#ifdef _WIN32
std::string command =
String::Serialize("\"C:/Program Files/Mono/bin/mcs\" {0} -target:library", filepath);
#else
std::string command = String::Serialize("mcs {0} -target:library", filepath);
#endif
// Compile the script
return system(command.c_str()) == 0;
}
void Script::MonoInit()
{
if (!s_MonoInitialized)
{
#ifdef _WIN32
mono_set_dirs("C:\\Program Files\\Mono\\lib", "C:\\Program Files\\Mono\\etc");
mono_config_parse(NULL);
#endif
s_MonoInitialized = true;
}
}
} // namespace At0::Ray::Mono
| 26.556818
| 88
| 0.708601
|
CAt0mIcS
|
dbfa42d8d9f64bb063ac1f7144888d06207464df
| 730
|
cpp
|
C++
|
codeforces/1433/B.cpp
|
Mohammad-Elsharkawy/CompetitiveProgramming
|
8d052465ff08cb36e66b7e6c6813090ac410bf1d
|
[
"MIT"
] | null | null | null |
codeforces/1433/B.cpp
|
Mohammad-Elsharkawy/CompetitiveProgramming
|
8d052465ff08cb36e66b7e6c6813090ac410bf1d
|
[
"MIT"
] | null | null | null |
codeforces/1433/B.cpp
|
Mohammad-Elsharkawy/CompetitiveProgramming
|
8d052465ff08cb36e66b7e6c6813090ac410bf1d
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200005;
int arr[55];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--){
int n;
cin>>n;
int st=0,en=0;
for(int i=0;i<n;i++){cin>>arr[i];}
for (int i=0;i<n;i++) {
if (arr[i] == 1) {
st = i;
break;
}
}
for (int i=n-1;i>=0;i--){
if(arr[i]==1){
en=i;
break;
}}
int ans=0;
for(int i=st;i<=en;i++)
{
if(arr[i]==0) ans++;
}
cout<<ans<<endl;
}
return 0;
}
| 16.590909
| 39
| 0.367123
|
Mohammad-Elsharkawy
|
dbfe04cf1c58c348023fb999e085cafe93b144da
| 1,805
|
cpp
|
C++
|
handout/Game/Source/SceneIntro.cpp
|
MHF13/VideoPlayer
|
861790d7482bb32c36f8be77e4a57482cd3d207c
|
[
"MIT"
] | null | null | null |
handout/Game/Source/SceneIntro.cpp
|
MHF13/VideoPlayer
|
861790d7482bb32c36f8be77e4a57482cd3d207c
|
[
"MIT"
] | null | null | null |
handout/Game/Source/SceneIntro.cpp
|
MHF13/VideoPlayer
|
861790d7482bb32c36f8be77e4a57482cd3d207c
|
[
"MIT"
] | null | null | null |
#include "App.h"
#include "Input.h"
#include "Textures.h"
#include "Audio.h"
#include "Render.h"
#include "Fonts.h"
#include "SceneIntro.h"
#include "SceneManager.h"
#include <SDL_mixer\include\SDL_mixer.h>
#include "Defs.h"
#include "Log.h"
SceneIntro::SceneIntro()
{
active = true;
name.Create("sceneIntro");
}
SceneIntro::~SceneIntro()
{
}
bool SceneIntro::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
bool SceneIntro::Start()
{
fullScreen = false;
app->SetLastScene((Module*)this);
transition = false;
app->render->camera.x = app->render->camera.y = 0;
posX = 100, posY = 100;
padding = 50;
return true;
}
bool SceneIntro::PreUpdate()
{
return true;
}
bool SceneIntro::Update(float dt)
{
bool ret = true;
if (app->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN) {
TransitionToScene(SceneType::LEVEL1);
}
if (app->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN) {
fullScreen = !fullScreen;
app->fullScreen = fullScreen;
app->win->FullScreen(app->fullScreen);
app->render->FullScreen();
}
if (app->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN) {
return false;
}
return ret;
}
bool SceneIntro::PostUpdate()
{
bool ret = true;
for (int i = 0; i < 3; i++) {
switch (i)
{
case 0:
sprintf_s(Text, 20, "Play Video: 1");
break;
case 1:
sprintf_s(Text, 20, "Full Screen: 2");
break;
case 2:
sprintf_s(Text, 20, "Exit: 3");
break;
default:
break;
}
app->fonts->BlitText(posX, posY + (padding * i), 0, Text, { 255, 255, 255 });
}
return ret;
}
bool SceneIntro::CleanUp()
{
if (!active)
return true;
LOG("Freeing scene");
active = false;
return true;
}
bool SceneIntro::LoadState(pugi::xml_node& data)
{
return true;
}
bool SceneIntro::SaveState(pugi::xml_node& data) const
{
return true;
}
| 13.884615
| 79
| 0.645429
|
MHF13
|
e000e988ce3722403b6fc67add980d8361d4bb25
| 1,393
|
hpp
|
C++
|
engine/include/ph/util/GltfWriter.hpp
|
PetorSFZ/PhantasyEngine
|
befe8e9499b7fd93d8765721b6841337a57b0dd6
|
[
"Zlib"
] | null | null | null |
engine/include/ph/util/GltfWriter.hpp
|
PetorSFZ/PhantasyEngine
|
befe8e9499b7fd93d8765721b6841337a57b0dd6
|
[
"Zlib"
] | null | null | null |
engine/include/ph/util/GltfWriter.hpp
|
PetorSFZ/PhantasyEngine
|
befe8e9499b7fd93d8765721b6841337a57b0dd6
|
[
"Zlib"
] | null | null | null |
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// 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.
#pragma once
namespace ph {
/*
The glTF writer is temporarily broken as the way resources are handled by Phantasy Engine has
changed. It should not be too much trouble to fix, but it was not high priority as these changes
were made.
// Writes all the assets corresponding to the meshes specified to glTF.
bool writeAssetsToGltf(
const char* writePath,
const LevelAssets& assets,
const DynArray<uint32_t>& meshIndices) noexcept;
*/
} // namespace ph
| 36.657895
| 96
| 0.758794
|
PetorSFZ
|
e0088941fbfffd55079b88cf6b541ff017203d01
| 3,635
|
cc
|
C++
|
src/network/client_handler.cc
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 17
|
2016-11-27T13:13:40.000Z
|
2021-09-07T06:42:25.000Z
|
src/network/client_handler.cc
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 22
|
2017-01-18T06:10:18.000Z
|
2019-05-15T03:49:19.000Z
|
src/network/client_handler.cc
|
zzunny97/Graduate-Velox
|
d820e7c8cee52f22d7cd9027623bd82ca59733ca
|
[
"Apache-2.0"
] | 5
|
2017-07-24T15:19:32.000Z
|
2022-02-19T09:11:01.000Z
|
#include "client_handler.hh"
#include "../messages/factory.hh"
#include "../common/context_singleton.hh"
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/spawn.hpp>
#include <exception>
#include <boost/scoped_ptr.hpp>
using namespace eclipse::network;
using namespace std;
using boost::scoped_ptr;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;
// Constructor {{{
ClientHandler::ClientHandler (uint32_t p):
nodes(context.settings.get<vec_str> ("network.nodes")),
port(p),
id(context.id)
{
}
void ClientHandler::attach(NetObserver* n) {
local_router = n;
}
// }}}
// connect {{{
void ClientHandler::connect(uint32_t i, shared_ptr<Server> server) {
spawn(context.io, [this, index = i, server_copy=server, node=nodes[i]]
(boost::asio::yield_context yield) {
try {
shared_ptr<Server> s = server_copy;
boost::system::error_code ec;
tcp::resolver resolver (context.io);
tcp::resolver::query query (node, to_string(port));
auto it = resolver.async_resolve(query, yield[ec]);
if (ec)
BOOST_THROW_EXCEPTION(std::runtime_error("Resolving"));
tcp::endpoint ep (*it);
s->get_socket().async_connect(ep, yield[ec]);
while (ec == boost::asio::error::timed_out) {
s->get_socket().close();
WARN("Re-connecting to %s:%u", node.c_str(), port);
s->get_socket().async_connect(ep, yield[ec]);
}
if (ec)
BOOST_THROW_EXCEPTION(std::runtime_error("Connecting"));
tcp::no_delay option(true);
s->get_socket().set_option(option);
rw_lock.lock();
current_servers.insert({index, s});
rw_lock.unlock();
s->do_write_buffer();
} catch (exception& e) {
ERROR("Connect coroutine exception %s", e.what());
throw;
} catch (boost::exception& e) {
ERROR("Connect corourine exception %s", diagnostic_information(e).c_str());
throw;
}
});
}
// }}}
// try_reuse_client {{{
bool ClientHandler::try_reuse_client(uint32_t i, shared_ptr<std::string> str) {
// If connection is still on.
rw_lock.lock_shared();
auto it = current_servers.find(i);
rw_lock.unlock_shared();
if (it != current_servers.end()) {
shared_ptr<Server> ptr = current_servers[i].lock();
if (ptr) {
DEBUG("REUSING SOCKET");
ptr->do_write(str);
return true;
} else {
rw_lock.lock();
current_servers.erase(i);
rw_lock.unlock();
}
}
return false;
}
// }}}
// send {{{
bool ClientHandler::send(uint32_t i, messages::Message* m) {
if (i >= nodes.size()) return false;
shared_ptr<std::string> message_serialized (save_message(m));
if (!try_reuse_client(i, message_serialized)) {
auto server = make_shared<Server>(local_router);
server->commit(message_serialized);
connect(i, server);
}
return true;
}
// }}}
// send str{{{
bool ClientHandler::send(uint32_t i, shared_ptr<string> str) {
if (i >= nodes.size()) return false;
if (!try_reuse_client(i, str)) {
auto server = make_shared<Server>(local_router);
server->commit(str);
connect(i, server);
}
return true;
}
// }}}
// send_and_replicate {{{
bool ClientHandler::send_and_replicate(std::vector<int> node_indices, messages::Message* m) {
shared_ptr<std::string> message_serialized (save_message(m));
for (auto i : node_indices) {
send(i, message_serialized);
}
return true;
}
// }}}
| 26.727941
| 93
| 0.625585
|
zzunny97
|
e008b58e2dff76f4f02393c22eeb36519dc3929e
| 1,952
|
cpp
|
C++
|
opencl/source/kernel/image_transformer.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 1
|
2019-03-01T13:54:45.000Z
|
2019-03-01T13:54:45.000Z
|
opencl/source/kernel/image_transformer.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 5
|
2019-03-26T17:26:07.000Z
|
2021-03-30T12:17:10.000Z
|
opencl/source/kernel/image_transformer.cpp
|
lukaszgotszaldintel/compute-runtime
|
9b12dc43904806db07616ffb8b1c4495aa7d610f
|
[
"MIT"
] | 4
|
2018-05-09T10:04:27.000Z
|
2018-07-12T13:33:31.000Z
|
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/kernel/image_transformer.h"
#include "shared/source/helpers/ptr_math.h"
#include "opencl/source/mem_obj/image.h"
#include "opencl/source/program/kernel_info.h"
namespace NEO {
void ImageTransformer::registerImage3d(uint32_t argIndex) {
if (std::find(argIndexes.begin(), argIndexes.end(), argIndex) == argIndexes.end()) {
argIndexes.push_back(argIndex);
}
}
void ImageTransformer::transformImagesTo2dArray(const KernelInfo &kernelInfo, const std::vector<Kernel::SimpleKernelArgInfo> &kernelArguments, void *ssh) {
for (auto const &argIndex : argIndexes) {
const auto &arg = kernelInfo.kernelDescriptor.payloadMappings.explicitArgs[argIndex];
if (arg.getExtendedTypeInfo().isTransformable) {
auto clMemObj = static_cast<cl_mem>(kernelArguments.at(argIndex).object);
auto image = castToObjectOrAbort<Image>(clMemObj);
auto surfaceState = ptrOffset(ssh, arg.as<ArgDescImage>().bindful);
image->transformImage3dTo2dArray(surfaceState);
}
}
transformed = true;
}
void ImageTransformer::transformImagesTo3d(const KernelInfo &kernelInfo, const std::vector<Kernel::SimpleKernelArgInfo> &kernelArguments, void *ssh) {
for (auto const &argIndex : argIndexes) {
const auto &arg = kernelInfo.kernelDescriptor.payloadMappings.explicitArgs[argIndex];
auto clMemObj = static_cast<cl_mem>(kernelArguments.at(argIndex).object);
auto image = castToObjectOrAbort<Image>(clMemObj);
auto surfaceState = ptrOffset(ssh, arg.as<ArgDescImage>().bindful);
image->transformImage2dArrayTo3d(surfaceState);
}
transformed = false;
}
bool ImageTransformer::didTransform() const {
return transformed;
}
bool ImageTransformer::hasRegisteredImages3d() const {
return !argIndexes.empty();
}
} // namespace NEO
| 39.04
| 155
| 0.721311
|
lukaszgotszaldintel
|
e009d19d55138021b147a48ad8b257c77d85b3b4
| 602
|
hpp
|
C++
|
smart_tales_ii/game/ui/scorebubble.hpp
|
TijmenUU/smarttalesii
|
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
|
[
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null |
smart_tales_ii/game/ui/scorebubble.hpp
|
TijmenUU/smarttalesii
|
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
|
[
"CC-BY-3.0",
"CC-BY-4.0"
] | 11
|
2018-02-08T14:50:16.000Z
|
2022-01-21T19:54:24.000Z
|
smart_tales_ii/game/ui/scorebubble.hpp
|
TijmenUU/smarttalesii
|
c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba
|
[
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null |
/*
scorebubble.hpp
This class is nothing more than a number floating upwards.
It has a lifetime and velocity defined in its cpp file.
*/
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
class ScoreBubble : public sf::Drawable
{
private:
sf::Text text;
float timeAlive = 0.f; // in seconds
protected:
void draw(sf::RenderTarget & target, sf::RenderStates states) const override;
public:
bool ShouldRemove() const;
// Return value indicates it is to be removed
bool Update(const sf::Time & elapsed);
ScoreBubble(const sf::Vector2f spawnPosition, const unsigned int score);
};
| 20.758621
| 78
| 0.739203
|
TijmenUU
|
e00aa79854d72fc0c9d2e918db9f38ff06131034
| 1,209
|
cpp
|
C++
|
recordMagData.cpp
|
chuanstudyup/MPU9250
|
aa41c58e8100b56bdcb1261d9617552378417257
|
[
"Apache-2.0"
] | 5
|
2021-09-15T09:10:08.000Z
|
2022-02-09T11:44:14.000Z
|
recordMagData.cpp
|
chuanstudyup/MPU9250
|
aa41c58e8100b56bdcb1261d9617552378417257
|
[
"Apache-2.0"
] | null | null | null |
recordMagData.cpp
|
chuanstudyup/MPU9250
|
aa41c58e8100b56bdcb1261d9617552378417257
|
[
"Apache-2.0"
] | 4
|
2021-09-15T09:10:44.000Z
|
2022-02-09T11:44:17.000Z
|
#include "MPU9250.h"
#include <fstream>
using namespace std;
int main()
{
MPU9250 mpu;
bcm2835_init();
mpu.verbose(true);
if(!mpu.setup(0x68))
{
while(1){
printf("MPU connection failed.\n");
delay(5000);
}
}else
printf("MPU setup successfully!\n");
mpu.initRecordCalData(); //记录用来校准的原始数据时,先把校准参数都设置为0或1
delay(5000);
mpu.calibrateAccelGyro(); //粗校准:静置,自动校准acc和gyro的偏移量,然后写入到器件中
mpu.print_calibration();
printf("MagBias: %f, %f, %f\n",mpu.getMagBiasX(),mpu.getMagBiasY(),mpu.getMagBiasZ());
printf("MagScale: %f, %f, %f\n",mpu.getMagScaleX(),mpu.getMagScaleY(),mpu.getMagScaleZ());
delay(3000);
//以下开始记录精校准用的原始数据,
ofstream magFile;
magFile.open("magData.csv",ios::app|ios::out);
float startTime = millis()/1000.f;
while(1)
{
if(mpu.update()){
float now = millis()/1000.f-startTime;
float magx = mpu.getMagX();
float magy = mpu.getMagY();
float magz = mpu.getMagZ();
printf("time=%f, magx=%f, magy=%f, magz=%f\n",
now,magx,magy,magz);
magFile <<now<<","<<magx<<","<<magy<<","<<magz<<endl;
delay(8);
}else{
printf("mpu.update failed\n");
}
}
magFile.close();
return 0;
}
// g++ -o recordMagData recordMagData.cpp ArduTime.cpp -l bcm2835
| 24.673469
| 91
| 0.652605
|
chuanstudyup
|
e00c96ad564ea7fc974d666898080db71d109d7b
| 2,890
|
hpp
|
C++
|
include/TE/DrawManager.hpp
|
bitDaft/grid-game-system
|
e11e45b6ed3ce12e04ebf76c93c3d8cc5335679e
|
[
"MIT"
] | 1
|
2020-06-24T16:16:49.000Z
|
2020-06-24T16:16:49.000Z
|
include/DrawManager.hpp
|
bitDaft/Project-TE
|
f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3
|
[
"MIT"
] | null | null | null |
include/DrawManager.hpp
|
bitDaft/Project-TE
|
f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3
|
[
"MIT"
] | null | null | null |
/*
* File: DrawManager.hpp
* Project: Project-TE
* Created Date: Sunday December 1st 2019
* Author: bitDaft
* -----
* Last Modified: Saturday December 28th 2019 11:24:55 pm
* Modified By: bitDaft at <ajaxhis@tutanota.com>
* -----
* Copyright (c) 2019 bitDaft
*/
#ifndef DRAWMANAGER_HPP
#define DRAWMANAGER_HPP
#include <vector>
#include <SFML/System/Time.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include "IDrawable.hpp"
/**
* This class manages the drawing queue and drawing of all the objects added to the queue
* ^ Manual initialization of this class is not needed as only one object of this class is needed
* ^ That object is created and managed by the Game class
* ^ Any functionality that needs to be given to drawables can be opened through the IDrawable interface
* TODO allow changing of queues of objects
*/
class DrawManager
{
public:
// constructor destructor
DrawManager();
virtual ~DrawManager();
/**
* Initializes the object to start the drawing pipeline
* @return void
*/
void initialize();
/**
* This runs through all the object queues and draws them to the RenderTexture
* @param dt the remaining delta time needed to calculate an interpolated state
* @param renderTexture a renderable texture to which the objects should be drawn to
* @return void
*/
void draw(const sf::Time &dt, sf::RenderTexture &renderTexture);
/**
* Prevents an object queue from drawing its objects
* @param queuePos the position of the queue which should not be drawn
* @return void
*/
void stopQueue(int queuePos);
/**
* Allows an object queue from drawing its objects
* @param queuePos the position of the queue which should be allowed to be drawn
* @return void
*/
void resumeQueue(int queuePos);
/**
* Pushes a pointer of an IDrawable object into an object queue
* @param queuePos the queue into which the IDrawable pointer is to be pushed into
* @param drawable the IDrawable that is be added to the drawing queue
* @return void
*/
int pushToQueue(int queuePos, IDrawable *drawable);
/**
* Removes a pointer of an IDrawable object from an object queue
* @param queuePos the queue from which the IDrawable pointer is to be removed
* @param objectPos the position of the object in the given queue
* @return void
*/
void removeFromQueue(int queuePos, int objectPos);
private:
/**
* Adds a new object queue
* @param count number of new queues to be added
* @return void
*/
void addQueue(int count);
/**
* Cleans up all deleted and removed objects from the drawing queue to free up space
* @param i the queue to cleanup
* @return void
*/
void cleanupQueue(int pos);
private:
std::vector<bool> drawCheck;
int queueCount;
bool setupDone;
std::vector<std::vector<IDrawable *>> drawList;
};
#endif
| 28.058252
| 104
| 0.703806
|
bitDaft
|
e015da95851bf7c2cfc045b0baefd8d0ecb543a9
| 2,251
|
cpp
|
C++
|
source/basic/ref_ptr.cpp
|
JianboYan/cppthings-learning
|
71c15213474786795fb09800efd3cf19ee562681
|
[
"MIT"
] | null | null | null |
source/basic/ref_ptr.cpp
|
JianboYan/cppthings-learning
|
71c15213474786795fb09800efd3cf19ee562681
|
[
"MIT"
] | null | null | null |
source/basic/ref_ptr.cpp
|
JianboYan/cppthings-learning
|
71c15213474786795fb09800efd3cf19ee562681
|
[
"MIT"
] | null | null | null |
//
// ref_ptr.cpp
// CppThings
//
// Created by Ryan on 2020/10/2.
//
#include <iostream>
#include <vector>
namespace RefPtr{
using namespace std;
// 1. 指针与引用的区别
// 1.1. 定义初始化
// int &ri; // error: Declaration of reference variable 'ri' requires an initializer
int i;
int &ri = i; // 定义必须初始化
int *pi; // 定义可以不初始化
// 1.2. 指针可以为空,引用不可以
void test_p(int* p)
{
if(p != nullptr) //对p所指对象赋值时需先判断p是否为空指针
*p = 3;
return;
}
void test_r(int& r)
{
r = 3; //由于引用不能为空,所以此处无需判断r的有效性就可以对r直接赋值
return;
}
int MAIN(){
// 1.3. 引用不能更换目标
int num = 1, count = 2;
int &rn = num;
rn = count; // 并不是重新修改引用到count,只是修改num的值为count的值
CTLLOG_1(rn); // rn is 2
CTLLOG_1(num); // num is 2
rn = 3;
CTLLOG_1(count); // count is 2
CTLLOG_1(num); // num is 3
return 0;
}
// 2. 引用定义
int MAIN(){
// 2.1 左值引用: 常规引用,一般表示对象的身份
// 2.2 右值引用:就是必须绑定到右值(一个临时对象、将要销毁的对象)的引用,一般表示对象的值
// 2.2.1 右值引用可实现转移语义(Move Sementics)和精确传递(Perfect Forwarding)
// 2.2.2 右值引用可以消除两个对象交互时不必要的对象拷贝,节省运算存储资源,提高效率
// 2.2.3 右值引用能够更简洁明确地定义泛型函数
int num = 2;
// int &i = 1; // error: Non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
int &i = num;
// int && ii = i; // error: Rvalue reference to type 'int' cannot bind to lvalue of type 'int'
int &&ii = 2;
ii = 3;
CTLLOG_1(ii);// ii is 3。❓:说好的引用不能转换目标呢?
// 2.3. 引用折叠
// 2.3.1 X& &、X& &&、X&& & 可折叠成 X&
// 2.3.2 X&& && 可折叠成 X&&
// int& &ri = i; // error: 'ri' declared as a reference to a reference
// TODO: 增加示例
return 0;
}
// 2.4. 引用参数
void test(const vector<int> &data)
{
}
int MAIN()
{
vector<int> data{1,2,3,4,5,6,7,8};
test(data);
// 2.5. 引用型返回值
vector<int> v(10);
v[5] = 10; //[]操作符返回引用,然后vector对应元素才能被修改
//如果[]操作符不返回引用而是指针的话,赋值语句则需要这样写
// *v[5] = 10; //这种书写方式,完全不符合我们对[]调用的认知,容易产生误解 error: Indirection requires pointer operand ('std::__1::__vector_base<int, std::__1::allocator<int> >::value_type' (aka 'int') invalid)
return 0;
}
// 3. 指针与引用的性能差距
// 结论:使用引用和指针生成的汇编代码完全一样,所以其实引用就是指针的一种简便使用,这点从debug状态下,引用的值为指向对象的地址就可以看出来
// 多说一句,空指针的发明是一个价值10亿美元的糟糕设计,引用算是对指针里会出现空指针的一种设计完善。
}
| 20.651376
| 187
| 0.59307
|
JianboYan
|
e0179465b9cb5aa3cf0b479421f9f0457b5cc1ac
| 14,008
|
cpp
|
C++
|
Source/FAP.cpp
|
biug/XBot
|
20f51094ee18aeaa58d769a894c68b4f05f900d4
|
[
"MIT"
] | 1
|
2017-09-21T19:08:42.000Z
|
2017-09-21T19:08:42.000Z
|
Source/FAP.cpp
|
biug/XBot
|
20f51094ee18aeaa58d769a894c68b4f05f900d4
|
[
"MIT"
] | null | null | null |
Source/FAP.cpp
|
biug/XBot
|
20f51094ee18aeaa58d769a894c68b4f05f900d4
|
[
"MIT"
] | null | null | null |
#include "FAP.h"
#include "BWAPI.h"
XBot::FastAPproximation fap;
namespace XBot {
FastAPproximation::FastAPproximation() {
}
void FastAPproximation::addUnitPlayer1(FAPUnit fu) {
player1.push_back(fu);
}
void FastAPproximation::addIfCombatUnitPlayer1(FAPUnit fu) {
if (fu.groundDamage || fu.airDamage || fu.unitType == BWAPI::UnitTypes::Terran_Medic)
addUnitPlayer1(fu);
}
void FastAPproximation::addUnitPlayer2(FAPUnit fu) {
player2.push_back(fu);
}
void FastAPproximation::addIfCombatUnitPlayer2(FAPUnit fu) {
if (fu.groundDamage || fu.airDamage || fu.unitType == BWAPI::UnitTypes::Terran_Medic)
addUnitPlayer2(fu);
}
void FastAPproximation::simulate(int nFrames) {
while (nFrames--) {
if (!player1.size() || !player2.size())
break;
didSomething = false;
isimulate();
if (!didSomething)
break;
}
}
std::pair <int, int> FastAPproximation::playerScores() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth)
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth)
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair <int, int> FastAPproximation::playerScoresUnits() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth && !u.unitType.isBuilding())
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth && !u.unitType.isBuilding())
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair <int, int> FastAPproximation::playerScoresBuildings() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth && u.unitType.isBuilding())
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth && u.unitType.isBuilding())
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair<std::vector<FastAPproximation::FAPUnit>*, std::vector<FastAPproximation::FAPUnit>*> FastAPproximation::getState() {
return { &player1, &player2 };
}
void FastAPproximation::clearState() {
player1.clear(), player2.clear();
}
void FastAPproximation::dealDamage(const FastAPproximation::FAPUnit &fu, int damage, BWAPI::DamageType damageType) const {
if (fu.shields >= damage - fu.shieldArmor) {
fu.shields -= damage - fu.shieldArmor;
return;
}
else if(fu.shields) {
damage -= (fu.shields + fu.shieldArmor);
fu.shields = 0;
}
if (!damage)
return;
if (damageType == BWAPI::DamageTypes::Concussive) {
if(fu.unitSize == BWAPI::UnitSizeTypes::Large)
damage = damage / 2;
else if(fu.unitSize == BWAPI::UnitSizeTypes::Medium)
damage = (damage * 3) / 4;
}
else if (damageType == BWAPI::DamageTypes::Explosive) {
if (fu.unitSize == BWAPI::UnitSizeTypes::Small)
damage = damage / 2;
else if (fu.unitSize == BWAPI::UnitSizeTypes::Medium)
damage = (damage * 3) / 4;
}
#ifdef _DEBUG
//damage = MAX(1, damage - fu.armor);
fu.damageTaken += damage;
fu.health -= damage;
#else
fu.health -= std::max(1, damage - fu.armor);
#endif
}
int inline FastAPproximation::distButNotReally(const FastAPproximation::FAPUnit &u1, const FastAPproximation::FAPUnit &u2) const {
return (u1.x - u2.x)*(u1.x - u2.x) + (u1.y - u2.y)*(u1.y - u2.y);
}
bool FastAPproximation::isSuicideUnit(BWAPI::UnitType ut) {
return (ut == BWAPI::UnitTypes::Zerg_Scourge || ut == BWAPI::UnitTypes::Terran_Vulture_Spider_Mine || ut == BWAPI::UnitTypes::Zerg_Infested_Terran);
}
void FastAPproximation::unitsim(const FastAPproximation::FAPUnit &fu, std::vector <FastAPproximation::FAPUnit> &enemyUnits) {
if (fu.attackCooldownRemaining) {
didSomething = true;
return;
}
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++ enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && sqrt(closestDist) <= fu.speed && !(fu.x == closestEnemy->x && fu.y == closestEnemy->y)) {
fu.x = closestEnemy->x;
fu.y = closestEnemy->y;
closestDist = 0;
didSomething = true;
}
if (closestEnemy != enemyUnits.end() && closestDist <= (closestEnemy->flying ? fu.groundMaxRange : fu.airMinRange)) {
if (closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType), fu.attackCooldownRemaining = fu.airCooldown;
else {
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType);
fu.attackCooldownRemaining = fu.groundCooldown;
if (fu.elevation != -1 && closestEnemy->elevation != -1)
if (closestEnemy->elevation > fu.elevation)
fu.attackCooldownRemaining += fu.groundCooldown;
}
if (closestEnemy->health < 1) {
auto temp = *closestEnemy;
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
unitDeath(temp, enemyUnits);
}
didSomething = true;
return;
}
else if(closestEnemy != enemyUnits.end() && sqrt(closestDist) > fu.speed) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
fu.x += (int)(dx*(fu.speed / sqrt(dx*dx + dy*dy)));
fu.y += (int)(dy*(fu.speed / sqrt(dx*dx + dy*dy)));
didSomething = true;
return;
}
}
void FastAPproximation::medicsim(const FAPUnit & fu, std::vector<FAPUnit> &friendlyUnits) {
auto closestHealable = friendlyUnits.end();
int closestDist;
for (auto it = friendlyUnits.begin(); it != friendlyUnits.end(); ++it) {
if (it->isOrganic && it->health < it->maxHealth && !it->didHealThisFrame) {
int d = distButNotReally(fu, *it);
if (closestHealable == friendlyUnits.end() || d < closestDist) {
closestHealable = it;
closestDist = d;
}
}
}
if (closestHealable != friendlyUnits.end()) {
fu.x = closestHealable->x;
fu.y = closestHealable->y;
closestHealable->health += (closestHealable->healTimer += 400) / 256;
closestHealable->healTimer %= 256;
if (closestHealable->health > closestHealable->maxHealth)
closestHealable->health = closestHealable->maxHealth;
closestHealable->didHealThisFrame = false;
}
}
bool FastAPproximation::suicideSim(const FAPUnit & fu, std::vector<FAPUnit>& enemyUnits) {
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && sqrt(closestDist) <= fu.speed) {
if(closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType);
else
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType);
if (closestEnemy->health < 1) {
auto temp = *closestEnemy;
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
unitDeath(temp, enemyUnits);
}
didSomething = true;
return true;
}
else if (closestEnemy != enemyUnits.end() && sqrt(closestDist) > fu.speed) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
fu.x += (int)(dx*(fu.speed / sqrt(dx*dx + dy*dy)));
fu.y += (int)(dy*(fu.speed / sqrt(dx*dx + dy*dy)));
didSomething = true;
}
return false;
}
void FastAPproximation::isimulate() {
for (auto fu = player1.begin(); fu != player1.end();) {
if (isSuicideUnit(fu->unitType)) {
bool result = suicideSim(*fu, player2);
if (result)
fu = player1.erase(fu);
else
++fu;
}
else {
if (fu->unitType == BWAPI::UnitTypes::Terran_Medic)
medicsim(*fu, player1);
else
unitsim(*fu, player2);
++fu;
}
}
for (auto fu = player2.begin(); fu != player2.end();) {
if (isSuicideUnit(fu->unitType)) {
bool result = suicideSim(*fu, player1);
if (result)
fu = player2.erase(fu);
else
++fu;
}
else {
if (fu->unitType == BWAPI::UnitTypes::Terran_Medic)
medicsim(*fu, player2);
else
unitsim(*fu, player1);
++fu;
}
}
for (auto &fu : player1) {
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
if (fu.didHealThisFrame)
fu.didHealThisFrame = false;
}
for (auto &fu : player2) {
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
if (fu.didHealThisFrame)
fu.didHealThisFrame = false;
}
}
void FastAPproximation::unitDeath(const FAPUnit &fu, std::vector<FAPUnit> &itsFriendlies) {
if (fu.unitType == BWAPI::UnitTypes::Terran_Bunker) {
convertToUnitType(fu, BWAPI::UnitTypes::Terran_Marine);
for(unsigned i = 0; i < 4; ++ i)
itsFriendlies.push_back(fu);
}
}
void FastAPproximation::convertToUnitType(const FAPUnit &fu, BWAPI::UnitType ut)
{
XBot::UnitInfo ui;
ui.lastPosition = BWAPI::Position(fu.x, fu.y);
ui.player = fu.player;
ui.type = ut;
FAPUnit funew(ui);
funew.attackCooldownRemaining = fu.attackCooldownRemaining;
funew.elevation = fu.elevation;
fu.operator=(funew);
}
FastAPproximation::FAPUnit::FAPUnit(BWAPI::Unit u): FAPUnit(UnitInfo(u)) {
}
FastAPproximation::FAPUnit::FAPUnit(UnitInfo ui) :
x(ui.lastPosition.x),
y(ui.lastPosition.y),
speed(ui.player->topSpeed(ui.type)),
health(ui.lastHealth),
maxHealth(ui.type.maxHitPoints()),
shields(ui.lastShields),
shieldArmor(ui.player->getUpgradeLevel(BWAPI::UpgradeTypes::Protoss_Plasma_Shields)),
maxShields(ui.type.maxShields()),
armor(ui.player->armor(ui.type)),
flying(ui.type.isFlyer()),
groundDamage(ui.player->damage(ui.type.groundWeapon())),
groundCooldown(ui.type.groundWeapon().damageFactor() && ui.type.maxGroundHits() ? ui.player->weaponDamageCooldown(ui.type) / (ui.type.groundWeapon().damageFactor() * ui.type.maxGroundHits()) : 0),
groundMaxRange(ui.player->weaponMaxRange(ui.type.groundWeapon())),
groundMinRange(ui.type.groundWeapon().minRange()),
groundDamageType(ui.type.groundWeapon().damageType()),
airDamage(ui.player->damage(ui.type.airWeapon())),
airCooldown(ui.type.airWeapon().damageFactor() && ui.type.maxAirHits() ? ui.type.airWeapon().damageCooldown() / (ui.type.airWeapon().damageFactor() * ui.type.maxAirHits()) : 0),
airMaxRange(ui.player->weaponMaxRange(ui.type.airWeapon())),
airMinRange(ui.type.airWeapon().minRange()),
airDamageType(ui.type.airWeapon().damageType()),
unitType(ui.type),
isOrganic(ui.type.isOrganic()),
score(ui.type.destroyScore()),
player(ui.player)
{
static int nextId = 0;
id = nextId++;
if (ui.type == BWAPI::UnitTypes::Protoss_Carrier) {
groundDamage = ui.player->damage(BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon());
groundDamageType = BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon().damageType();
groundCooldown = 5;
groundMaxRange = 32 * 8;
airDamage = groundDamage;
airDamageType = groundDamageType;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
}
else if (ui.type == BWAPI::UnitTypes::Terran_Bunker) {
groundDamage = ui.player->damage(BWAPI::WeaponTypes::Gauss_Rifle);
groundCooldown = BWAPI::UnitTypes::Terran_Marine.groundWeapon().damageCooldown() / 4;
groundMaxRange = ui.player->weaponMaxRange(BWAPI::UnitTypes::Terran_Marine.groundWeapon()) + 32;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
}
else if (ui.type == BWAPI::UnitTypes::Protoss_Reaver) {
groundDamage = ui.player->damage(BWAPI::WeaponTypes::Scarab);
}
if (ui.unit && ui.unit->isStimmed()) {
groundCooldown /= 2;
airCooldown /= 2;
}
if (ui.unit && ui.unit->isVisible() && !ui.unit->isFlying()) {
elevation = BWAPI::Broodwar->getGroundHeight(ui.unit->getTilePosition());
}
groundMaxRange *= groundMaxRange;
groundMinRange *= groundMinRange;
airMaxRange *= airMaxRange;
airMinRange *= airMinRange;
groundDamage *= 2;
airDamage *= 2;
shieldArmor *= 2;
armor *= 2;
health *= 2;
maxHealth *= 2;
shields *= 2;
maxShields *= 2;
}
const FastAPproximation::FAPUnit &FastAPproximation::FAPUnit::operator=(const FAPUnit & other) const {
x = other.x, y = other.y;
health = other.health, maxHealth = other.maxHealth;
shields = other.shields, maxShields = other.maxShields;
speed = other.speed, armor = other.armor, flying = other.flying, unitSize = other.unitSize;
groundDamage = other.groundDamage, groundCooldown = other.groundCooldown, groundMaxRange = other.groundMaxRange, groundMinRange = other.groundMinRange, groundDamageType = other.groundDamageType;
airDamage = other.airDamage, airCooldown = other.airCooldown, airMaxRange = other.airMaxRange, airMinRange = other.airMinRange, airDamageType = other.airDamageType;
score = other.score;
attackCooldownRemaining = other.attackCooldownRemaining;
unitType = other.unitType; isOrganic = other.isOrganic;
healTimer = other.healTimer; didHealThisFrame = other.didHealThisFrame;
elevation = other.elevation;
player = other.player;
return *this;
}
bool FastAPproximation::FAPUnit::operator<(const FAPUnit & other) const {
return id < other.id;
}
}
| 29.366876
| 198
| 0.666119
|
biug
|
e01a758c3acfc94a99a93f10bbd5db16f70d2f6e
| 522
|
cpp
|
C++
|
Homework/3.35.cpp
|
TuringGu/C-code
|
76085120a930a900e7d686065261032288858fb6
|
[
"MIT"
] | null | null | null |
Homework/3.35.cpp
|
TuringGu/C-code
|
76085120a930a900e7d686065261032288858fb6
|
[
"MIT"
] | null | null | null |
Homework/3.35.cpp
|
TuringGu/C-code
|
76085120a930a900e7d686065261032288858fb6
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE=100;
class Stock{
public:
Stock()
{
strcpy_s(stockcode, " ");
}
Stock(char na[MAXSIZE], int q = 1000, double p = 8.98)
{
strcpy_s(stockcode, na);
quan = q;
price = p;
}
void print()
{
cout << stockcode<<" " << quan <<" "<< price << endl;
}
private:
char stockcode[MAXSIZE];
int quan;
double price;
};
int main()
{
Stock A("600001",3000,5.67);
Stock B("600001");
A.print();
B.print();
char x;
cin >> x;
return 0;
}
| 13.736842
| 57
| 0.599617
|
TuringGu
|
e01e77202b5a9ef61ef96c1246e34c6f9ed6f18f
| 16,962
|
hpp
|
C++
|
flat_map.hpp
|
pingwindyktator/cpp_sandbox
|
815a80f826aa0ea718389ebda0f8e6513a051de1
|
[
"WTFPL"
] | 1
|
2018-02-15T21:06:17.000Z
|
2018-02-15T21:06:17.000Z
|
flat_map.hpp
|
pingwindyktator/cpp_sandbox
|
815a80f826aa0ea718389ebda0f8e6513a051de1
|
[
"WTFPL"
] | null | null | null |
flat_map.hpp
|
pingwindyktator/cpp_sandbox
|
815a80f826aa0ea718389ebda0f8e6513a051de1
|
[
"WTFPL"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace sandbox {
template<class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T>>>
class flat_map
{
public:
using key_type = Key;
using mapped_type = T;
// using value_type = std::pair<const Key, T>;
using value_type = std::pair<Key, T>;
using storage_type = std::vector<value_type, Allocator>;
using size_type = typename storage_type::size_type;
using difference_type = typename storage_type::difference_type;
using key_compare = Compare;
using allocator_type = Allocator;
using reference = typename storage_type::reference;
using const_reference = typename storage_type::const_reference;
using pointer = typename storage_type::pointer;
using const_pointer = typename storage_type::const_pointer;
using iterator = typename storage_type::iterator;
using const_iterator = typename storage_type::const_iterator;
using reverse_iterator = typename storage_type::reverse_iterator;
using const_reverse_iterator = typename storage_type::const_reverse_iterator;
public:
class value_compare
{
friend class flat_map;
protected:
explicit value_compare(Compare c) : comp(c)
{}
public:
bool operator()(const value_type &lhs, const value_type &rhs) const
{
return comp(lhs.first, rhs.first);
}
public:
// for convinience
bool operator()(const key_type &lhs, const value_type &rhs) const
{
return comp(lhs, rhs.first);
}
bool operator()(const value_type &lhs, const key_type &rhs) const
{
return comp(lhs.first, rhs);
}
bool operator()(const key_type &lhs, const key_type &rhs) const
{
return comp(lhs, rhs);
}
protected:
Compare comp;
};
public:
flat_map() : flat_map(Compare())
{
}
explicit flat_map(const Compare &comp, const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
}
template<class In>
flat_map(In first, In last, const Compare &comp = Compare(), const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
insert(first, last);
}
template<class In>
flat_map(In first, In last, const Allocator &alloc) : storage_(alloc)
{
insert(first, last);
}
flat_map(const flat_map &other) : comp_(other.comp_), storage_(other.storage_)
{
}
flat_map(const flat_map &other, const Allocator &alloc) : comp_(other.comp_), storage_(other.storage_, alloc)
{
}
flat_map(const flat_map &&other) noexcept : comp_(std::move(other.comp_)), storage_(std::move(other.storage_))
{
}
flat_map(const flat_map &&other, const Allocator &alloc) : comp_(std::move(other.comp_)), storage_(std::move(other.storage_), alloc)
{
}
flat_map(std::initializer_list<value_type> init, const Compare &comp = Compare(), const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
insert(init);
}
flat_map(std::initializer_list<value_type> init, const Allocator &alloc) : comp_(Compare()), storage_(alloc)
{
insert(init);
}
~flat_map() = default;
flat_map &operator=(const flat_map &other)
{
flat_map(other).swap(*this);
return *this;
}
flat_map &operator=(flat_map &&other) noexcept
{
flat_map(std::move(other)).swap(*this);
return *this;
}
flat_map &operator=(std::initializer_list<value_type> ilist)
{
flat_map(ilist).swap(*this);
return *this;
}
allocator_type get_allocator() const
{
return storage_.get_allocator();
}
T &at(const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
throw std::out_of_range("out_of_range");
}
}
const T &at(const Key &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
throw std::out_of_range("out_of_range");
}
}
T &operator[](const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
// create it
auto n = storage_.emplace(it, key, T());
return n->second;
}
}
T &operator[](Key &&key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
// create it
auto n = storage_.emplace(it, std::forward<Key>(key), T());
return n->second;
}
}
iterator begin()
{
return storage_.begin();
}
const_iterator begin() const
{
return storage_.begin();
}
const_iterator cbegin() const
{
return storage_.cbegin();
}
iterator end()
{
return storage_.end();
}
const_iterator end() const
{
return storage_.end();
}
const_iterator cend() const
{
return storage_.cend();
}
reverse_iterator rbegin()
{
return storage_.rbegin();
}
const_reverse_iterator rbegin() const
{
return storage_.rbegin();
}
const_reverse_iterator crbegin() const
{
return storage_.crbegin();
}
reverse_iterator rend()
{
return storage_.rend();
}
const_reverse_iterator rend() const
{
return storage_.rend();
}
const_reverse_iterator crend() const
{
return storage_.crend();
}
bool empty() const
{
return storage_.empty();
}
size_type size() const
{
return storage_.size();
}
size_type max_size() const
{
return storage_.max_size();
}
void clear()
{
storage_.clear();
}
std::pair<iterator, bool> insert(const value_type &value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, value);
return std::make_pair(n, true);
}
}
template<class P>
std::pair<iterator, bool> insert(P &&value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, std::forward<P>(value));
return std::make_pair(n, true);
}
}
std::pair<iterator, bool> insert(value_type &&value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, std::move_if_noexcept(value));
return std::make_pair(n, true);
}
}
std::pair<iterator, bool> insert(const_iterator hint, const value_type &value)
{
(void) hint;
return insert(value);
}
template<class P>
std::pair<iterator, bool> insert(const_iterator hint, P &&value)
{
(void) hint;
return insert(std::forward<P>(value));
}
std::pair<iterator, bool> insert(const_iterator hint, value_type &&value)
{
(void) hint;
return insert(std::move_if_noexcept(value));
}
template<class In>
void insert(In first, In last)
{
while (first != last)
{
insert(*first++);
}
}
void insert(std::initializer_list<value_type> ilist)
{
for (auto &&value : ilist)
{
insert(std::move_if_noexcept(value));
}
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const key_type &key, M &&obj)
{
auto it = insert(key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(key_type &&key, M &&obj)
{
auto it = insert(std::move_if_noexcept(key));
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const_iterator hint, const key_type &key, M &&obj)
{
auto it = insert(hint, key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const_iterator hint, key_type &&key, M &&obj)
{
auto it = insert(hint, key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
// TODO: try_emplace
template<class... Args>
std::pair<iterator, bool> emplace(Args &&... args)
{
using std::begin;
using std::end;
value_type temp(std::forward<Args>(args)...);
auto it = std::lower_bound(begin(storage_), end(storage_), temp, comp_);
if (it != end(storage_) && !comp_(temp, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.emplace(it, std::move_if_noexcept(temp));
return std::make_pair(n, true);
}
}
template<class... Args>
std::pair<iterator, bool> emplace_hint(const_iterator hint, Args &&... args)
{
(void) hint;
using std::begin;
using std::end;
value_type temp(std::forward<Args>(args)...);
auto it = std::lower_bound(begin(storage_), end(storage_), temp, comp_);
if (it != end(storage_) && !comp_(temp, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.emplace(it, std::move_if_noexcept(temp));
return std::make_pair(n, true);
}
}
iterator erase(const_iterator pos)
{
return storage_.erase(pos);
}
iterator erase(iterator pos)
{
return storage_.erase(pos);
}
iterator erase(const_iterator first, const_iterator last)
{
return storage_.erase(first, last);
}
size_type erase(const key_type &key)
{
size_type c = 0;
auto r = equal_range(key);
auto first = r.first;
auto second = r.second;
while (first != second)
{
erase(first++);
++c;
}
return c;
}
void swap(flat_map &other)
{
using std::swap;
swap(comp_, other.comp_);
swap(storage_, other.storage_);
}
size_type count(const Key &key) const
{
size_type c = 0;
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
while (it != end(storage_) && !comp_(key, *it))
{
++c;
}
return c;
}
template<class K>
size_type count(const K &key) const
{
size_type c = 0;
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
while (it != end(storage_) && !comp_(key, *it))
{
++c;
}
return c;
}
iterator find(const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
const_iterator find(const Key &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
template<class K>
iterator find(const K &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
template<class K>
const_iterator find(const K &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
std::pair<iterator, iterator> equal_range(const Key &key)
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
std::pair<const_iterator, const_iterator> equal_range(const Key &key) const
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
template<class K>
std::pair<iterator, iterator> equal_range(const K &key)
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
template<class K>
std::pair<const_iterator, const_iterator> equal_range(const K &key) const
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
iterator lower_bound(const Key &key)
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
const_iterator lower_bound(const Key &key) const
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
iterator lower_bound(const K &key)
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
const_iterator lower_bound(const K &key) const
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
iterator upper_bound(const Key &key)
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
const_iterator upper_bound(const Key &key) const
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
iterator upper_bound(const K &key)
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
const_iterator upper_bound(const K &key) const
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
key_compare key_comp() const
{
return comp_.comp;
}
value_compare value_comp() const
{
return comp_;
}
private:
value_compare comp_{};
storage_type storage_;
};
}
| 24.547033
| 154
| 0.545219
|
pingwindyktator
|
e020dbb997287980cb17e804366dd87eb2338188
| 108
|
cpp
|
C++
|
ro-string-db/string_pool/run_local_tests.cpp
|
vladcc/ro-string-db
|
6f27a71e583f1816277c4027b51fe45c29e017fd
|
[
"MIT"
] | 1
|
2020-09-20T22:12:53.000Z
|
2020-09-20T22:12:53.000Z
|
ro-string-db/string_pool/run_local_tests.cpp
|
vladcc/ro-string-db
|
6f27a71e583f1816277c4027b51fe45c29e017fd
|
[
"MIT"
] | null | null | null |
ro-string-db/string_pool/run_local_tests.cpp
|
vladcc/ro-string-db
|
6f27a71e583f1816277c4027b51fe45c29e017fd
|
[
"MIT"
] | null | null | null |
#include "test_string_pool.hpp"
int main()
{
run_test_string_pool();
return test_string_pool_failed();
}
| 13.5
| 34
| 0.759259
|
vladcc
|
e0249a262cd61106e21005cfabe5f19fb889e8a7
| 1,456
|
cpp
|
C++
|
3DLfC4D shaders/source/DL_Principled_Object.cpp
|
FilipMalmberg/3Delight-for-Cinema-4D
|
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
|
[
"MIT"
] | null | null | null |
3DLfC4D shaders/source/DL_Principled_Object.cpp
|
FilipMalmberg/3Delight-for-Cinema-4D
|
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
|
[
"MIT"
] | null | null | null |
3DLfC4D shaders/source/DL_Principled_Object.cpp
|
FilipMalmberg/3Delight-for-Cinema-4D
|
3394f8cd9e1121b8c35aa4e2b2443450ef82cbff
|
[
"MIT"
] | null | null | null |
#include "c4d.h"
#include "IDs.h"
/*
We want our shaders to be directly on the create menu of materials
instead of being on create->shader->YourShaderDir->yourShader
to do so we use C4DPL_BUILDMENU to dynamically enhance the menu
In C4D you can only call objects or commands to C4DPL_BUILDMENU.
But cinema4d register an object or command using RegisterObjectPlugin()
and RegisterCommnadPlugin() and we have used RegisterMaterialPlugin()
to register our Dl_principled shader so we can not call it on C4DPL_BUILDMENU
because it does not have a command created for it/
Thus we create this Command plugin and we use it on C4DPL_BUILDMENU to add it
to the create menu of materials. And each time this class is called we create a new
Dl_Principled material. Meanwhile we have hidden Dl_Principled material from
create->shader->3Delight->Dl_Principled because we are calling it directly
using this class and in an easier way from UI part.
*/
class DL_Principled_command : public CommandData
{
public:
virtual Bool Execute(BaseDocument* doc);
};
Bool DL_Principled_command::Execute(BaseDocument* doc)
{
Material* material = (Material*)BaseMaterial::Alloc(DL_PRINCIPLED);
if (!material)
return false;
doc->InsertMaterial(material);
return true;
}
Bool Register_DlPrincipled_Object(void)
{
return RegisterCommandPlugin(DL_PRINCIPLED_COMMAND, "3Delight Principled"_s, PLUGINFLAG_HIDE, 0, String(),NewObjClear(DL_Principled_command));
}
| 33.860465
| 143
| 0.791896
|
FilipMalmberg
|
e024cf04b6e9269577717c77c6dc6388843a8cc2
| 1,904
|
hpp
|
C++
|
library/include/darcel/data_types/callable_data_type.hpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | null | null | null |
library/include/darcel/data_types/callable_data_type.hpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | null | null | null |
library/include/darcel/data_types/callable_data_type.hpp
|
spiretrading/darcel
|
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
|
[
"MIT"
] | 1
|
2020-04-17T13:25:25.000Z
|
2020-04-17T13:25:25.000Z
|
#ifndef DARCEL_CALLABLE_DATA_TYPE_HPP
#define DARCEL_CALLABLE_DATA_TYPE_HPP
#include "darcel/data_types/data_type.hpp"
#include "darcel/data_types/data_type_visitor.hpp"
#include "darcel/data_types/data_types.hpp"
#include "darcel/semantics/function.hpp"
namespace darcel {
//! A data type used to represent all of a function declaration's overloads.
class CallableDataType final : public DataType {
public:
//! Constructs a callable data type.
/*!
\param f The function this data type represents.
*/
CallableDataType(std::shared_ptr<Function> f);
//! Returns the function represented.
const std::shared_ptr<Function> get_function() const;
const Location& get_location() const override;
const std::string& get_name() const override;
void apply(DataTypeVisitor& visitor) const override;
protected:
bool is_equal(const DataType& rhs) const override;
private:
std::string m_name;
std::shared_ptr<Function> m_function;
};
inline CallableDataType::CallableDataType(std::shared_ptr<Function> f)
: m_name("@" + f->get_name()),
m_function(std::move(f)) {}
inline const std::shared_ptr<Function>
CallableDataType::get_function() const {
return m_function;
}
inline const Location& CallableDataType::get_location() const {
return m_function->get_location();
}
inline const std::string& CallableDataType::get_name() const {
return m_name;
}
inline void CallableDataType::apply(DataTypeVisitor& visitor) const {
visitor.visit(*this);
}
inline bool CallableDataType::is_equal(const DataType& rhs) const {
auto& other = static_cast<const CallableDataType&>(rhs);
return m_function == other.get_function();
}
inline void DataTypeVisitor::visit(const CallableDataType& node) {
visit(static_cast<const DataType&>(node));
}
}
#endif
| 27.594203
| 78
| 0.707458
|
spiretrading
|
e02b48f54b5e5ee32c43890c1ec0aa11543fe7a8
| 7,990
|
cpp
|
C++
|
os/internal/threads.cpp
|
JehTeh/jel
|
2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b
|
[
"MIT"
] | 14
|
2018-10-09T00:08:26.000Z
|
2021-09-24T19:49:42.000Z
|
os/internal/threads.cpp
|
JehTeh/jel
|
2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b
|
[
"MIT"
] | null | null | null |
os/internal/threads.cpp
|
JehTeh/jel
|
2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b
|
[
"MIT"
] | null | null | null |
/** @file os/internal/threads.cpp
* @brief Implementation of the threading wrappers for jel.
*
* @detail
* The Thread wrappers used by the jel perform two functions: Abstracting the C API of the RTOS
* and providing some additional setup and teardown capability, such as exception capture. This
* is done by wrapping the user supplied function and void* arg pointer in a custom dispatcher
* function that accepts a pointer to the Thread object itself, where the user supplied function
* and arg pointers are stored. The call to this function is then wrapped by the dispatcher with
* all needed functionality, including global try/catch guards and any instrumentation that is
* enabled.
*
* @author Jonathan Thomson
*/
/**
* MIT License
*
* Copyright 2018, Jonathan Thomson
*
* 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.
*/
/** C/C++ Standard Library Headers */
#include <cassert>
/** jel Library Headers */
#include "os/api_threads.hpp"
#include "os/api_exceptions.hpp"
#include "os/api_system.hpp"
#include "os/internal/indef.hpp"
namespace jel
{
GenericThread_Base::GenericThread_Base()
{
/** Nothing is done here. All initialization is performed in the startThread() function to ensure
* the Thread* object has completed construction. */
}
void GenericThread_Base::startThread(Thread* threadObject)
{
Thread::ThreadInfo* inf = threadObject->inf_.get();
inf->handle_ = nullptr;
if(inf->cbMem_ && inf->stackMem_)
{
assert(false); //Static thread construction is currently TODO - not simple with freeRTOS, self
//deleting tasks run into issues with memory ownership when idle task attempts to delete them.
}
else
{
//Create with minimum priority. This allows us to insert thread into the ireg_ before it
//executes.
if(xTaskCreate(reinterpret_cast<void(*)(void*)>(&dispatcher),
inf->name_, inf->maxStack_bytes_ / 4 + (inf->maxStack_bytes_ % 4), inf,
static_cast<uint32_t>(Thread::Priority::minimum),
&inf->handle_) != pdPASS)
{
throw Exception{ExceptionCode::threadConstructionFailed,
"Failed to allocate the required memory when constructing a new Thread."};
}
#ifdef ENABLE_THREAD_STATISTICS
Thread::ireg_->push_back(inf);
#endif
vTaskPrioritySet(inf->handle_, static_cast<uint32_t>(inf->priority_));
}
}
void GenericThread_Base::dispatcher(void* threadInf)
{
Thread::ThreadInfo* inf = reinterpret_cast<Thread::ThreadInfo*>(threadInf);
inf->handle_ = xTaskGetCurrentTaskHandle();
#ifdef ENABLE_THREAD_STATISTICS
inf->totalRuntime_ = Duration::zero();
inf->lastEntry_ = SteadyClock::now();
#endif
try
{
inf->userFunc_(inf->userArgPtr_);
}
catch(const std::exception e)
{
switch(inf->ehPolicy_)
{
case Thread::ExceptionHandlerPolicy::haltThread:
{
while(true)
{
ThisThread::sleepfor(Duration::seconds(1));
}
}
break;
case Thread::ExceptionHandlerPolicy::terminate:
std::terminate();
}
}
catch(...)
{
switch(inf->ehPolicy_)
{
case Thread::ExceptionHandlerPolicy::haltThread:
{
while(true)
{
ThisThread::sleepfor(Duration::seconds(1));
}
}
break;
case Thread::ExceptionHandlerPolicy::terminate:
std::terminate();
}
}
if(inf->isDetached_)
{
#ifdef ENABLE_THREAD_STATISTICS
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == inf->handle_)
{
Thread::ireg_->erase(it);
}
}
#endif
delete inf;
}
}
#ifdef ENABLE_THREAD_STATISTICS
std::unique_ptr<Thread::InfoRegistry> Thread::ireg_;
#endif
Thread::Thread(FunctionSignature userFunction, void* args, const char* name,
const size_t stackSize_bytes, const Priority priority, const ExceptionHandlerPolicy ehPolicy)
{
//Allocate and configure inf_ structure. This needs to be seperate from the thread object so that
//if the thread is detached the inf_ still exists.
inf_ = std::make_unique<ThreadInfo>();
inf_->userFunc_ = userFunction; inf_->userArgPtr_ = args; inf_->name_ = name;
inf_->maxStack_bytes_ = stackSize_bytes; inf_->priority_ = priority; inf_->ehPolicy_ = ehPolicy;
inf_->isDetached_ = false; inf_->isDeleted_ = false;
inf_->cbMem_ = nullptr; inf_->stackMem_ = nullptr;
#ifdef ENABLE_THREAD_STATISTICS
inf_->totalRuntime_ = Duration::zero();
inf_->lastEntry_ = Timestamp::min();
if(Thread::ireg_ == nullptr)
{
Thread::ireg_ = std::make_unique<Thread::InfoRegistry>();
}
#endif
startThread(this);
}
Thread::~Thread() noexcept
{
if(inf_ != nullptr)
{
#ifdef ENABLE_THREAD_STATISTICS
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == inf_->handle_)
{
Thread::ireg_->erase(it);
}
}
#endif
if(inf_->handle_ != nullptr)
{
vTaskDelete(inf_->handle_);
}
inf_.reset();
}
}
#ifdef ENABLE_THREAD_STATISTICS
void Thread::schedulerEntry(Handle handle)
{
for(ThreadInfo* it : *ireg_)
{
if(it->handle_ == handle)
{
it->lastEntry_ = SteadyClock::now();
break;
}
}
}
void Thread::schedulerExit(Handle handle)
{
for(ThreadInfo* it : *ireg_)
{
if(it->handle_ == handle)
{
it->totalRuntime_ += SteadyClock::now() - it->lastEntry_;
break;
}
}
}
void Thread::schedulerThreadCreation(Handle)
{
}
void Thread::schedulerAddIdleTask(Handle h, ThreadInfo* inf)
{
(void)h; //Handle no longer used after refactoring from std::map to vector.
if(ireg_ == nullptr)
{
ireg_ = std::make_unique<InfoRegistry>();
}
ireg_->push_back(inf);
}
#endif
const char* Thread::lookupName(const Handle& handle)
{
return pcTaskGetName(handle);
}
void Thread::detach()
{
inf_->isDetached_ = true;
inf_.release();
}
void ThisThread::sleepfor(const Duration& time) noexcept
{
vTaskDelay(toTicks(time));
}
void ThisThread::yield() noexcept
{
taskYIELD();
}
void ThisThread::deleteSelf(bool performCompleteErasure) noexcept
{
if(performCompleteErasure)
{
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == xTaskGetCurrentTaskHandle())
{
delete(*it);
Thread::ireg_->erase(it);
break;
}
}
}
else
{
for(auto&& it : *Thread::ireg_)
{
if(it->handle_ == xTaskGetCurrentTaskHandle())
{
it->isDeleted_ = true;
it->minStackBeforeDeletion_bytes_ = uxTaskGetStackHighWaterMark(nullptr) * 4;
break;
}
}
}
vTaskDelete(nullptr);
}
const char* ThisThread::name()
{
if(System::inIsr())
{
return "ISR";
}
if(System::cpuExceptionActive())
{
return "EXCPT";
}
return pcTaskGetName(nullptr);
}
void* ThisThread::handle()
{
return xTaskGetCurrentTaskHandle();
}
}
/** namespace jel */
| 26.993243
| 100
| 0.673967
|
JehTeh
|
e02b80492b11d593f0c813c15a06408f4db5b6ec
| 3,948
|
cpp
|
C++
|
XYModem/examples/example_ymodem.cpp
|
Riuzakiii/XYModem
|
97d5dba9285aaefa2668865e4088a579cccc53a7
|
[
"MIT"
] | null | null | null |
XYModem/examples/example_ymodem.cpp
|
Riuzakiii/XYModem
|
97d5dba9285aaefa2668865e4088a579cccc53a7
|
[
"MIT"
] | null | null | null |
XYModem/examples/example_ymodem.cpp
|
Riuzakiii/XYModem
|
97d5dba9285aaefa2668865e4088a579cccc53a7
|
[
"MIT"
] | null | null | null |
/*
* Usage : ./ymodem.exe -f "filepath" -port COM1
* -h : get help
* -port : the serial port of your device. If you don't add a port after this, it will display the available ports
* -f "filepath1": send file (filepath should be absolute, don't
* know what happens if the path is relative) -hex : activate the hexadecimal
* output of the messages send to the device
*/
#include "XYModem.h"
#include "Devices/SerialHandler.h"
#include "CLIParser.h"
using namespace xymodem;
int main (int argc, [[maybe_unused]] char* argv[])
{
auto serialDevice = serial::Serial ();
CLIParser cliParser;
serialDevice.setBaudrate (115200);
const uint32_t interByteTimeout = 100000;
const uint32_t readTimeoutConstant = 20;
const uint32_t readTimeoutMultiplier = 0;
const uint32_t writeTimeoutConstant = 20;
const uint32_t writeTimeoutMultiplier = 0;
serialDevice.setTimeout (interByteTimeout,
readTimeoutConstant,
readTimeoutMultiplier,
writeTimeoutConstant,
writeTimeoutMultiplier);
auto serialHandler = std::make_shared<SerialHandler>(serialDevice);
auto logger = std::make_shared<Spdlogger>();
YModemSender<xymodem::payloadSize1K> ymodem (serialHandler, logger);
std::vector<std::shared_ptr<File>> files;
bool withHex = false;
std::string lastParam;
cliParser.setCommands({
{"-h", [&logger](std::string_view){
logger->info("This program allows you to send one or more files "
"using the YModem file transfer protocol.\n Options "
":\n -h : get help \n -f \"filepath1\" -port "
"\"serial port of the device\""
"\"filepath2\" ... : send one or more files \n");}},
{"-f", [&files, &logger](std::string_view value){
logger->info (value);
files.emplace_back (std::make_shared<DesktopFile>(value.data()));
}},
{"--hex", [&withHex](std::string_view){withHex = true;}},
{"-port", [&serialDevice, &logger](std::string_view val){
logger->info ("Available devices");
const auto availablePorts = serial::list_ports ();
const auto serialPort =
std::find_if (availablePorts.begin (),
availablePorts.end (),
[&val, &logger] (auto& device) {
logger->info (device.description);
logger->info (device.port);
logger->info (device.hardware_id);
return device.port == val;
});
if (serialPort != availablePorts.end ())
{
serialDevice.setPort (serialPort->port);
serialDevice.open ();
}
else
{
logger->error ("Unable to find the requested device");
}
}}
});
try
{
// parse command line arguments and launch related commands
cliParser.parse (argc, argv);
if (!files.empty ())
{
ymodem.transmit (
files, [] (float) {}, [] () { return false; }, withHex);
}
}
catch (serial::IOException& e)
{
logger->warn (e.what ());
assert (false);
}
catch (XYModemExceptions::Timeout const& e)
{
logger->warn (e.what ());
}
catch (XYModemExceptions::CouldNotOpenFile const& e)
{
logger->warn (e.what ());
}
catch (XYModemExceptions::TransmissionAborted const& e)
{
logger->warn (e.what ());
}
catch (std::exception const& e)
{
logger->warn (e.what ());
assert (false);
}
}
| 36.220183
| 114
| 0.531408
|
Riuzakiii
|
e02d2784f099894e23c86d2570450059dd5d44ee
| 3,978
|
cpp
|
C++
|
src/line.cpp
|
ansko/geom3d
|
a46d53d28c61491cdaeea38314da12ea00b2c3db
|
[
"Apache-2.0"
] | null | null | null |
src/line.cpp
|
ansko/geom3d
|
a46d53d28c61491cdaeea38314da12ea00b2c3db
|
[
"Apache-2.0"
] | null | null | null |
src/line.cpp
|
ansko/geom3d
|
a46d53d28c61491cdaeea38314da12ea00b2c3db
|
[
"Apache-2.0"
] | null | null | null |
#include "point.hpp"
#include "line.hpp"
#include "line_segment.hpp"
#include "plane.hpp"
#include "polygon.hpp"
namespace geom3d
{
Point
Line::pt1() const
{
return pt1_;
}
Point
Line::pt2() const
{
return pt2_;
}
double
Line::distance_to(const Point &pt) const
{
double x1 = pt1_.x(), x2 = pt2_.x(), x = pt.x(),
y1 = pt1_.y(), y2 = pt2_.y(), y = pt.y(),
z1 = pt1_.z(), z2 = pt2_.z(), z = pt.z(),
dx = x2 - x1, dy = y2 - y1, dz = z2 - z1, // vec(pt1_ -> pt2_)
len = sqrt(dx*dx + dy*dy + dz*dz),
dx1 = x - x1, dy1 = y - y1, dz1 = z - z1, // vec(pt1_ -> pt)
len1 = sqrt(dx1*dx1 + dy1*dy1 + dz1*dz1);
if (almost_equal(len1) || almost_equal(len))
{
return 0;
}
double cos_angle = (dx*dx1 + dy*dy1 + dz*dz1) / len / len1,
sin_angle = sqrt(1 - cos_angle*cos_angle),
distance = len * sin_angle;
return std::abs(distance);
}
double
Line::distance_to(const LineSegment &ls) const
{
double x1t = pt1_.x(), x2t = pt2_.x(), x1o = ls.pt1().x(), x2o = ls.pt2().x(),
y1t = pt1_.y(), y2t = pt2_.y(), y1o = ls.pt1().y(), y2o = ls.pt2().y(),
z1t = pt1_.z(), z2t = pt2_.z(), z1o = ls.pt1().z(), z2o = ls.pt2().z(),
dxt = x2t - x1t, dyt = y2t - y1t, dzt = z2t - z1t,
lent = sqrt(dxt*dxt + dyt*dyt + dzt*dzt),
dxo = x2o - x1o, dyo = y2o - y1o, dzo = z2o - z1o,
leno = sqrt(dxo*dxo + dyo*dyo + dzo*dzo),
cos_angle = (dxt*dxo + dyt*dyo + dzt*dzo) / lent / leno;
if (almost_equal(std::abs(cos_angle), 1))
{ // Parallel case
return distance_to(ls.pt1());
}
// surely not parallel
// ptt(xt, yt, zt) on *this, pto(xo, yo, zo) on other;
// dxt, -dxo = x1o-x1t
// dyt, -dyo = y1o - y1t
// minimum exists, det != 0
double det = dxo*dyt - dxt*dyo,
det_alpha = dxo*(y1o-y1t) - dyo*(x1o-x1t),
det_beta = dxt*(y1o-y1t) - dyt*(x1o-x1t),
alpha = det_alpha / det,
beta = det_beta / det;
if (beta < 0.)
{
beta = 0.;
}
if (beta > 1.)
{
beta = 1.;
}
double xt = x1t + alpha*dxt, yt = y1t + alpha*dyt, zt = z1t + alpha*dzt,
xo = x1o + beta*dxo, yo = y1o + beta*dyo, zo = z1o + beta*dzo,
dx = xo - xt, dy = yo - yt, dz = zo - zt;
return sqrt(dx*dx + dy*dy + dz*dz);
}
double
Line::distance_to(const Line &l) const
{
double x1t = pt1_.x(), x2t = pt2_.x(), x1o = l.pt1().x(), x2o = l.pt2().x(),
y1t = pt1_.y(), y2t = pt2_.y(), y1o = l.pt1().y(), y2o = l.pt2().y(),
z1t = pt1_.z(), z2t = pt2_.z(), z1o = l.pt1().z(), z2o = l.pt2().z(),
dxt = x2t - x1t, dyt = y2t - y1t, dzt = z2t - z1t,
lent = sqrt(dxt*dxt + dyt*dyt + dzt*dzt),
dxo = x2o - x1o, dyo = y2o - y1o, dzo = z2o - z1o,
leno = sqrt(dxo*dxo + dyo*dyo + dzo*dzo),
cos_angle = (dxt*dxo + dyt*dyo + dzt*dzo) / lent / leno;
if (almost_equal(std::abs(cos_angle), 1))
{ // Parallel case
return distance_to(l.pt1());
}
// surely not parallel
// ptt(xt, yt, zt) on *this, pto(xo, yo, zo) on other;
// dxt, -dxo = x1o-x1t
// dyt, -dyo = y1o - y1t
// minimum exists, det != 0
double det = dxo*dyt - dxt*dyo,
det_alpha = dxo*(y1o-y1t) - dyo*(x1o-x1t),
det_beta = dxt*(y1o-y1t) - dyt*(x1o-x1t),
alpha = det_alpha / det,
beta = det_beta / det,
xt = x1t + alpha*dxt, yt = y1t + alpha*dyt, zt = z1t + alpha*dzt,
xo = x1o + beta*dxo, yo = y1o + beta*dyo, zo = z1o + beta*dzo,
dx = xo - xt, dy = yo - yt, dz = zo - zt;
return sqrt(dx*dx + dy*dy + dz*dz);
}
double
Line::distance_to(const Plane &pl) const
{
return pl.distance_to(*this);
}
double
Line::distance_to(const Polygon &poly) const
{
return poly.distance_to(*this);
}
} // ns geom3d
| 29.25
| 82
| 0.498994
|
ansko
|
e02de197270a1e8b93e668161b4a4dae6dc79c54
| 3,040
|
cpp
|
C++
|
Projects/ShipGame/src/Main.cpp
|
SemperParatusGithub/SemperGL
|
b2866b43224cc1afa17c7ce0445507eb4733adc8
|
[
"MIT"
] | 7
|
2020-11-10T23:43:49.000Z
|
2021-04-25T20:13:40.000Z
|
Projects/ShipGame/src/Main.cpp
|
SemperParatusGithub/SemperGL
|
b2866b43224cc1afa17c7ce0445507eb4733adc8
|
[
"MIT"
] | null | null | null |
Projects/ShipGame/src/Main.cpp
|
SemperParatusGithub/SemperGL
|
b2866b43224cc1afa17c7ce0445507eb4733adc8
|
[
"MIT"
] | null | null | null |
#include "Level.h"
enum State
{
MainMenu = 0, Playing, Dead, Close
};
int main()
{
sgl::Core::Init();
sgl::Window window("Ship Game", 1280, 720);
window.SetIcon(sgl::WindowIcon("res/icons/Icon.png"));
window.SetVsync(1);
bool fullscreen = false;
window.SetEventCallback([&](sgl::Event &e)
{
if (e.isType<sgl::KeyPressedEvent>() && e.GetKeyCode() == sgl::Key::F11)
{
if (!fullscreen) {
fullscreen = true;
window.SetFullscreen();
window.SetViewport(0, 0, window.GetWidth(), window.GetHeight());
}
else {
window.SetSize(1280, 720);
window.SetPosition({ 200.0f, 200.0f });
window.SetViewport(0, 0, 1280, 720);
fullscreen = false;
}
}
});
ImGuiIO io = ImGui::GetIO();
ImFont *font = io.Fonts->AddFontFromFileTTF("res/fonts/OpenSans/OpenSans-Bold.ttf", 120.0f);
State GameState = MainMenu;
sgl::Clock clock;
// Player
Player player;
bool respawnt = false;
// Level
Level level;
level.Reset();
// Textures
sgl::Texture backgroundTex("res/textures/Background.jpg");
// Game Loop
while (window.IsOpen())
{
auto deltaTime = clock.Restart();
sgl::ImGuiUtil::BeginFrame();
window.OnUpdate();
if (GameState == MainMenu)
{
if (sgl::Input::IsKeyPressed(sgl::Key::Space) || sgl::Input::IsMouseButtonPressed(sgl::Mouse::Button0))
GameState = Playing;
if (respawnt)
{
sgl::Clock::Sleep(500);
respawnt = false;
}
window.Clear();
auto pos = ImGui::GetWindowPos();
pos.x += window.GetWidth() * 0.5f - 300.0f;
pos.y += window.GetHeight() * 0.6f;
std::string highScore = std::string("Highscore: ") + std::to_string(player.GetHighscore());
ImGui::GetForegroundDrawList()->AddText(font, 120.0f, pos, 0xffffffff, "Click to Play!");
ImGui::GetForegroundDrawList()->AddText(font, 48.0f, ImGui::GetWindowPos(), 0xffffffff, highScore.c_str());
sgl::Renderer2D::BeginScene(0, 0, 1280, 720);
sgl::Renderer2D::DrawQuad({ 640.0f, 360.0f, 0.0f }, { 1280.0f, 720.0f }, backgroundTex);
player.OnRender();
sgl::Renderer2D::EndScene();
}
else if (GameState == Playing)
{
// Update
player.OnUpdate(deltaTime);
level.OnUpdate(deltaTime, player.GetHorizontalVelocity());
if (level.CheckForCollision(player))
GameState = Dead;
window.Clear();
// Render Score
std::string score = std::string("Score: ") + std::to_string(player.GetScore());
ImGui::GetForegroundDrawList()->AddText(font, 48.0f, ImGui::GetWindowPos(), 0xffffffff, score.c_str());
sgl::Renderer2D::BeginScene(0, 0, 1280, 720);
sgl::Renderer2D::DrawQuad( { 640.0f, 360.0f, 0.0f }, { 1280.0f, 720.0f }, backgroundTex);
level.OnRender();
player.OnRender();
sgl::Renderer2D::EndScene();
}
else if (GameState == Dead)
{
if (player.GetScore() > player.GetHighscore())
player.SetHighscore(player.GetScore());
player = Player();
level = Level();
respawnt = true;
GameState = MainMenu;
}
else if (GameState == Close)
{
window.Close();
}
sgl::ImGuiUtil::EndFrame();
}
}
| 25.123967
| 110
| 0.642434
|
SemperParatusGithub
|
e0306a85bdbba3a75ea283908382efea5e64e581
| 2,684
|
cpp
|
C++
|
untests/sources/untests_core/debug.cpp
|
NechukhrinN/enduro2d
|
774f120395885a6f0f21418c4de024e7668ee436
|
[
"MIT"
] | 92
|
2018-08-07T14:45:33.000Z
|
2021-11-14T20:37:23.000Z
|
untests/sources/untests_core/debug.cpp
|
NechukhrinN/enduro2d
|
774f120395885a6f0f21418c4de024e7668ee436
|
[
"MIT"
] | 43
|
2018-09-30T20:48:03.000Z
|
2020-04-20T20:05:26.000Z
|
untests/sources/untests_core/debug.cpp
|
NechukhrinN/enduro2d
|
774f120395885a6f0f21418c4de024e7668ee436
|
[
"MIT"
] | 13
|
2018-08-08T13:45:28.000Z
|
2020-10-02T11:55:58.000Z
|
/*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include "_core.hpp"
using namespace e2d;
namespace
{
using namespace e2d;
class test_sink final : public debug::sink {
public:
str on_message_acc;
static str s_on_message_acc;
bool on_message(debug::level lvl, str_view text) noexcept final {
E2D_UNUSED(lvl);
on_message_acc.append(text.cbegin(), text.cend());
s_on_message_acc.append(text.cbegin(), text.cend());
return true;
}
};
str test_sink::s_on_message_acc;
}
TEST_CASE("debug"){
{
debug d;
test_sink& s = d.register_sink<test_sink>();
REQUIRE(test_sink::s_on_message_acc.empty());
d.trace("h");
d.warning("e");
REQUIRE(test_sink::s_on_message_acc == "he");
d.set_min_level(debug::level::error);
d.trace("el");
d.warning("lo");
REQUIRE(test_sink::s_on_message_acc == "he");
d.error("ll");
REQUIRE(test_sink::s_on_message_acc == "hell");
d.fatal("o");
REQUIRE(test_sink::s_on_message_acc == "hello");
d.unregister_sink(s);
d.fatal("!!!");
REQUIRE(test_sink::s_on_message_acc == "hello");
}
{
modules::initialize<debug>();
test_sink& s1 = the<debug>().register_sink_ex<test_sink>(debug::level::warning);
test_sink& s2 = the<debug>().register_sink_ex<test_sink>(debug::level::error);
REQUIRE(s1.on_message_acc.empty());
REQUIRE(s2.on_message_acc.empty());
the<debug>().trace("w");
REQUIRE(s1.on_message_acc.empty());
REQUIRE(s2.on_message_acc.empty());
the<debug>().warning("w");
REQUIRE(s1.on_message_acc == "w");
REQUIRE(s2.on_message_acc.empty());
the<debug>().error("q");
REQUIRE(s1.on_message_acc == "wq");
REQUIRE(s2.on_message_acc == "q");
the<debug>().fatal("e");
REQUIRE(s1.on_message_acc == "wqe");
REQUIRE(s2.on_message_acc == "qe");
the<debug>().set_min_level(debug::level::fatal);
the<debug>().error("r");
REQUIRE(s1.on_message_acc == "wqe");
REQUIRE(s2.on_message_acc == "qe");
the<debug>().fatal("r");
REQUIRE(s1.on_message_acc == "wqer");
REQUIRE(s2.on_message_acc == "qer");
modules::shutdown<debug>();
}
}
| 34.857143
| 88
| 0.552534
|
NechukhrinN
|
e03268d013bd44d5ed1d9bc787bf40e15fb1cb46
| 51,165
|
cpp
|
C++
|
src/GUI/scrollbar.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | 1
|
2018-04-01T16:47:52.000Z
|
2018-04-01T16:47:52.000Z
|
src/GUI/scrollbar.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | null | null | null |
src/GUI/scrollbar.cpp
|
HonzaMD/Krkal2
|
e53e9b096d89d1441ec472deb6d695c45bcae41f
|
[
"OLDAP-2.5"
] | null | null | null |
///////////////////////////////////////////////
//
// scrollbar.cpp
//
// Implementace pro scrollbar a jeho casti scrollbarButtons
//
// A: Jan Poduska
//
///////////////////////////////////////////////
#include "stdafx.h"
#include "scrollbar.h"
#include "widgets.h"
#include "dxbliter.h"
//////////////////////////////////////////////////////////////////////
// CGUIScrollBar
//////////////////////////////////////////////////////////////////////
CGUIScrollBar::CGUIScrollBar(enum EScrollBarTypes _scrollBarType, float _x, float _y, float length, float width, float _shift, bool _autohide, bool _slider_resize, CGUIWindow *wnd, char* styleName[3][2], CGUIRectHost* pictures[3], CGUIScrollBar* _dual)
: CGUIMultiWidget(_x,_y)
{
/*-------------------------------------------------------------------------
Velikost scrollbaru: - delka aspon 2x vetsi nez sirka
- slider je minimalne velky jako up, down buttony (sirka x sirka)
- sirka a vyska musi byt aspon takova, aby se tam vesly aspon up, down buttony
- pageUp, pageDown, Nothing buttony jsou pod ostatnima, aby neprekryvaly pri malych velikostech
(vel. mensi nez je mozna velikost buttonu)
- pokud se nevejde slider => pageUp, PageDown buttony se nezobrazuji,
misto mezi up a down je vyplneno nereagujici bitmapou (buttonem?)
-------------------------------------------------------------------------*/
RemoveFromTrash();
SetAvailableEvents(0,0);
float len, pos;
int i;
scrollBarType = _scrollBarType;
autohide = _autohide;
slider_resize=_slider_resize;
active=false;
corner = 0;
shift = _shift;
if(!wnd)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Parent window is not defined");
}
if(length<=2*width)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Height & width of scrollbar are badly defined, scrollbar cannot construct");
}
for(i=0;i<6;i++)
buttons[i] = 0;
dual = _dual;
if(dual && (dual->active || !dual->autohide))
{
long_version=false;
length -=width;
}else{
long_version=true;
}
try{
switch(scrollBarType)
{
case Vertical : sx = width;
sy = length;
SetAnchor(WIDGET_FIX,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
if(wnd->vp_sy >= wnd->bw_size_normal_y)
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0); // buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,len,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,pos,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width+pos+len,width,(length-2*width)-(pos+len),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = -width;
dy = 0;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(width-dx+ox,oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x,y+length-width,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x,y+length,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
case Horizontal : sx = length;
sy = width;
SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FIX,WIDGET_FIX);
if(wnd->vp_sx >= wnd->bw_size_normal_x)
{
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0);// buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,len,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,pos,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width+pos+len,0,(length-2*width)-(pos+len),width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = 0;
dy = -width;
wnd->ChangeViewPortBWSize(dx,dy);
if(dy>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x+length-width, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x+length, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
}
AddElem(buttons[5]); // nejspodneji je neaktivni stred
AddElem(buttons[1]); // pageup
AddElem(buttons[3]); // pageDown
AddElem(buttons[2]); // slider
AddElem(buttons[0]); // na vrcholu up
AddElem(buttons[4]); // a down
// kvuli moznym prekryvum pri prislis male velikosti tlacitka (mensi nez mozne minimum)
// MsgSetConsume(MsgMouseL|MsgMouseOver); // nesmim konzumovat musim preposilat az k buttonum
SetSize(sx,sy);
if(window)
window->SetWindowSize(sx, sy);
wnd->AddFrontElem(this);
wnd->AcceptEvent(GetID(),EUpdateScrollbars);
wnd->AcceptEvent(GetID(),EMouseWheel);
if(corner)
{
corner->MsgSetProduce(MsgNone);
corner->SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
wnd->AddFrontElem(corner);
}
if(dual)
{
dual->dual=this;
if((dual->active || !dual->autohide) && (active || !autohide)) // && dual->long_version
{
dual->RebuildScrollbar();
}else if(corner)
corner->SetVisible(0);
}
for(i=0;i<6;i++)
buttons[i]->RemoveFromTrash();
}catch(CExc)
{
for(i=0;i<6;i++)
SAFE_DELETE(buttons[i]);
if(corner)
wnd->RemoveFrontElem(corner);
SAFE_DELETE(corner);
throw;
}
}
CGUIScrollBar::CGUIScrollBar(enum EScrollBarTypes _scrollBarType, float _x, float _y, float length, float width, float _shift, bool _autohide, bool _slider_resize, CGUIWindow *wnd, char* styleName[4][2], CGUIRectHost* pictures[3], CGUIScrollBar* _dual, bool simple)
: CGUIMultiWidget(_x,_y)
{
/*-------------------------------------------------------------------------
Velikost scrollbaru: - delka aspon 2x vetsi nez sirka
- slider je minimalne velky jako up, down buttony (sirka x sirka)
- sirka a vyska musi byt aspon takova, aby se tam vesly aspon up, down buttony
- pageUp, pageDown, Nothing buttony jsou pod ostatnima, aby neprekryvaly pri malych velikostech
(vel. mensi nez je mozna velikost buttonu)
- pokud se nevejde slider => pageUp, PageDown buttony se nezobrazuji,
misto mezi up a down je vyplneno nereagujici bitmapou (buttonem?)
-------------------------------------------------------------------------*/
RemoveFromTrash();
SetAvailableEvents(0,0);
float len, pos;
int i;
scrollBarType = _scrollBarType;
autohide = _autohide;
slider_resize=_slider_resize;
active=false;
corner = 0;
shift = _shift;
if(!wnd)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Parent window is not defined");
}
if(length<=2*width)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Height & width of scrollbar are badly defined, scrollbar cannot construct");
}
for(i=0;i<6;i++)
buttons[i] = 0;
dual = _dual;
if(dual && (dual->active || !dual->autohide))
{
long_version=false;
length -=width;
}else{
long_version=true;
}
try{
switch(scrollBarType)
{
case Vertical : sx = width;
sy = length;
SetAnchor(WIDGET_FIX,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
if(wnd->vp_sy >= wnd->bw_size_normal_y)
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true,scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0); // buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,len,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,pos,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]),true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width+pos+len,width,(length-2*width)-(pos+len),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = -width;
dy = 0;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(width-dx+ox,oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x,y+length-width,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x,y+length,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
case Horizontal : sx = length;
sy = width;
SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FIX,WIDGET_FIX);
if(wnd->vp_sx >= wnd->bw_size_normal_x)
{
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false,scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0);// buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true,scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,len,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,pos,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width+pos+len,0,(length-2*width)-(pos+len),width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = 0;
dy = -width;
wnd->ChangeViewPortBWSize(dx,dy);
if(dy>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x+length-width, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x+length, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
}
AddElem(buttons[5]); // nejspodneji je neaktivni stred
AddElem(buttons[1]); // pageup
AddElem(buttons[3]); // pageDown
AddElem(buttons[2]); // slider
AddElem(buttons[0]); // na vrcholu up
AddElem(buttons[4]); // a down
// kvuli moznym prekryvum pri prislis male velikosti tlacitka (mensi nez mozne minimum)
// MsgSetConsume(MsgMouseL|MsgMouseOver); // nesmim konzumovat musim preposilat az k buttonum
SetSize(sx,sy);
if(window)
window->SetWindowSize(sx, sy);
wnd->AddFrontElem(this);
wnd->AcceptEvent(GetID(),EUpdateScrollbars);
wnd->AcceptEvent(GetID(),EMouseWheel);
if(corner)
{
corner->MsgSetProduce(MsgNone);
corner->SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
wnd->AddFrontElem(corner);
}
if(dual)
{
dual->dual=this;
if((dual->active || !dual->autohide) && (active || !autohide)) // && dual->long_version
{
dual->RebuildScrollbar();
}else if(corner)
corner->SetVisible(0);
}
for(i=0;i<6;i++)
buttons[i]->RemoveFromTrash();
}catch(CExc)
{
for(i=0;i<6;i++)
SAFE_DELETE(buttons[i]);
if(corner)
wnd->RemoveFrontElem(corner);
SAFE_DELETE(corner);
throw;
}
}
CGUIScrollBar::~CGUIScrollBar()
{
}
void CGUIScrollBar::RemoveFromEngine()
{
CGUIMultiWidget::RemoveFromEngine();
float dx, dy;
if(!parent || parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollBar::RemoveFromEngine> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) parent;
if(active || !autohide)
{
switch(scrollBarType)
{
case Vertical : dx = sx;
dy = 0;
break;
case Horizontal : dx = 0;
dy = sy;
break;
}
float ox, oy;
ox=dx;
oy=dy;
wnd->ChangeViewPortBWSize(dx,dy);
dx-=ox;dy-=oy;
if(dx<0||dy<0)
{
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox+dx,oy+dy);
}
}
if(corner)
{
wnd->DeleteFrontElem(corner);
corner=0;
}
if(dual)
{
dual->dual=0;
if((dual->active || !dual->autohide) && (active || !autohide))
dual->RebuildScrollbar();
dual = 0;
}
active=false;
autohide=false;
}
void CGUIScrollBar::Resize(float _sx, float _sy)
{
float dx, dy;
CheckResize(_sx,_sy);
GetSize(dx,dy);
dx=_sx-dx; // rozdily ve velikostech
dy=_sy-dy;
SetSize(_sx,_sy);
if(window)
window->SetWindowSize(sx, sy);
RebuildScrollbar();
}
void CGUIScrollBar::RebuildScrollbar()
{
// vola se pri zmene parametru okna nebo scrollbaru
// zmena: sx, sy, vp_x/vp_y, vp_sx/vp_sy, bw_normal_size_x/bw_normal_size_y
float width, length;
float len, pos;
//int i;
bool resize = false;
float dx, dy;
bool old_state=active; // stary stav "active" pred zmenou parametru scrollbaru (kvuli uprave velikosti viewportu => detekce zmeny)
if(!parent || parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollBar::RebuildScrollbar> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) parent;
switch(scrollBarType)
{
case Vertical : width = sx;
length = sy;
dx = sx;
dy = 0;
break;
case Horizontal : width = sy;
length = sx;
dx = 0;
dy = sy;
break;
}
if(dual && (dual->active || !dual->autohide ))
{
if(long_version)
{
long_version=false;
length -=width;
resize=true;
}
}else{
if(!long_version)
{
long_version=true;
length +=width;
resize=true;
}
}
if(resize)
{
switch(scrollBarType)
{
case Vertical : Resize(width, length); return; // resize vyvola rekurzivne tuto proceduru
case Horizontal : Resize(length, width); return;
}
}
switch(scrollBarType)
{
case Vertical : if((wnd->vp_sy >= wnd->bw_size_normal_y) ||
(active && dual && dual->active && wnd->vp_sy+dual->sy>= wnd->bw_size_normal_y && (wnd->vp_sx + sx >= wnd->bw_size_normal_x)))
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
// button[0] beze zmeny
buttons[4]->Move(0,length-width);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5]->Move(0,width);
buttons[5]->Resize(width, length - 2*width);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
//for(i=0;i<6;i++)
// buttons[i]->SetVisible(0);
}else{
//SetVisible(1);
// zobrazit jen kraje a neaktivni stred (5)
SetVisible(1);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
if(!active && autohide)
SetVisible(1);
active=true;
//SetVisibility(1);
// buttons[0] beze zmeny
buttons[4]->Move(0,length-width);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[5]->Move(0,width);
buttons[5]->Resize(width,length - 2*width);
buttons[5]->SetVisible(1);
}else{
buttons[2]->Move(0,width+pos);
buttons[2]->Resize(width,len);
buttons[1]->Move(0,width);
buttons[1]->Resize(width,pos);
buttons[3]->Move(0,width+pos+len);
buttons[3]->Resize(width,(length-2*width)-(pos+len));
buttons[1]->SetVisible(1);buttons[3]->SetVisible(1);buttons[2]->SetVisible(1);
buttons[5]->SetVisible(0);
}
}
break;
case Horizontal : if((wnd->vp_sx >= wnd->bw_size_normal_x) ||
(active && dual && dual->active && wnd->vp_sx+dual->sx>= wnd->bw_size_normal_x && (wnd->vp_sy + sy >= wnd->bw_size_normal_y)))
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
// button[0] beze zmeny
buttons[4]->Move(length-width,0);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5]->Move(width,0);
buttons[5]->Resize(length - 2*width,width);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
//for(i=0;i<6;i++)
// buttons[i]->SetVisible(0);
}else{
// zobrazit jen kraje a neaktivni stred (5)
//SetVisibility(1);
SetVisible(1);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
if(!active && autohide)
SetVisible(1);
active=true;
//SetVisibility(1);
// buttons[0] beze zmeny
buttons[4]->Move(length-width,0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[5]->Move(width,0);
buttons[5]->Resize(length - 2*width, width);
buttons[5]->SetVisible(1);
}else{
buttons[2]->Move(width+pos, 0);
buttons[2]->Resize(len, width);
buttons[1]->Move(width, 0);
buttons[1]->Resize(pos, width);
buttons[3]->Move(width+pos+len, 0);
buttons[3]->Resize((length-2*width)-(pos+len), width);
buttons[1]->SetVisible(1);buttons[3]->SetVisible(1);buttons[2]->SetVisible(1);
buttons[5]->SetVisible(0);
}
}
break;
}
// zmenseni/zvetseni viewportu o misto, ktere zabira/nezabira scrollbar
if(autohide && old_state!=active)
{
float ox, oy;
if(old_state && !active)
{
ox=dx;
oy=dy;
wnd->ChangeViewPortBWSize(dx,dy);
dx-=ox;dy-=oy;
if(dx<0||dy<0)
{
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox+dx,oy+dy);
}
}else if(!old_state && active)
{
dx = ox = - dx;
dy = oy = - dy;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>ox || dy>oy)
{
wnd->GetSize(ox,oy);
if(scrollBarType==Vertical && dx>-width)
wnd->ResizeFrontOnly(width-dx+ox,oy);
if(scrollBarType==Horizontal && dy>-width)
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
dual->RebuildScrollbar();
}
if(corner)
{
if(dual && (dual->active || !dual->autohide) && (active || !autohide))
corner->SetVisible(1);
else
corner->SetVisible(0);
}
/*
if(dual && (dual->active || !dual->autohide) && dual->long_version && (active || !autohide))
{
dual->RebuildScrollbar();
}
if(dual && (dual->active || !dual->autohide) && !dual->long_version && !active && autohide)
{
dual->RebuildScrollbar();
}
*/
}
void CGUIScrollBar::EventHandler(CGUIEvent *event)
{
if(!event)
return;
if(event->eventID == EUpdateScrollbars)
RebuildScrollbar();
if(event->eventID == EMouseWheel && active && parent && parent->GetType() >= PTWindow)
{
if(scrollBarType == Vertical)
{
((CGUIWindow*)parent)->SetWindowPositionVP(0,-event->pInt*STD_SCROLLBAR_MWHEEL_COEF*shift,false);
RebuildScrollbar();
mainGUI->SendCursorPos(); // !@#$ aktualizace kurzoru
mainGUI->GetEvent(0);
}else if(!dual || (dual && !dual->active))
{
((CGUIWindow*)parent)->SetWindowPositionVP(-event->pInt*STD_SCROLLBAR_MWHEEL_COEF*shift,0,false);
RebuildScrollbar();
mainGUI->SendCursorPos(); // !@#$ aktualizace kurzoru
mainGUI->GetEvent(0);
}
}
delete(event);
}
//////////////////////////////////////////////////////////////////////
// CGUIScrollbarButton
//////////////////////////////////////////////////////////////////////
CGUIScrollbarButton::CGUIScrollbarButton(CGUIScrollBar* _sb, float _x, float _y, float _sx, float _sy, CGUIStyle *_up, CGUIStyle *_down, CGUIStyle *_mark, enum EScrollBarTypes _scrollBarType, enum EScrollBarButtonTypes _scrollBarButtonType, CGUIStaticText *_label, CGUIRectHost *_picture)
: CGUIButton(_x,_y,_sx,_sy,_up,_down,_mark,_label, _picture)
{
//RemoveFromTrash();
scrollBarType = _scrollBarType;
scrollBarButtonType = _scrollBarButtonType;
sb = _sb;
px = py = 0;
mouse_down=false;
MsgAcceptConsume(MsgTimer);
keySensitive=false;
//AddToTrash();
}
CGUIScrollbarButton::CGUIScrollbarButton(CGUIScrollBar* _sb, float _x, float _y, float _sx, float _sy, CGUIStyle *_up, CGUIStyle *_down, CGUIStyle *_mark, bool resizable, enum EScrollBarTypes _scrollBarType, enum EScrollBarButtonTypes _scrollBarButtonType, CGUIStaticText *_label, CGUIRectHost *_picture)
: CGUIButton(_x,_y,_sx,_sy,_up,_down,_mark, resizable, _label, _picture)
{
//RemoveFromTrash();
scrollBarType = _scrollBarType;
scrollBarButtonType = _scrollBarButtonType;
sb = _sb;
px = py = 0;
mouse_down=false;
MsgAcceptConsume(MsgTimer);
keySensitive=false;
//AddToTrash();
}
CGUIScrollbarButton::~CGUIScrollbarButton()
{
timerGUI->DeleteAllRequests(this);
}
void CGUIScrollbarButton::OnClick()
{
// podle typu scrollovat
// nepouziva se OnClick, ale reaguje se uz na zpravy nizsi urovne - MouseLeft, MouseMove, ...
// viz. dale
}
int CGUIScrollbarButton::MouseLeft(float x, float y, UINT mouseState, UINT keyState)
{ // mouseState 1 == stisknuti cudlitka
CGUIButton::MouseLeft(x,y,mouseState, keyState);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseLeft> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
switch(scrollBarButtonType)
{
case S_Up : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_PageUp : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Slider : if(button_state==2)
{
mouse_down=true;
float bx,by;
GetPos(bx,by);
px=x-bx;
py=y-by;
}else{
mouse_down=false;
px=0;
py=0;
}
break;
case S_PageDown : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Down : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Nothing : break;
}
if(!mouseState)
wnd->FocusOldTOBackEl();
return 0;
}
int CGUIScrollbarButton::MouseOver(float x, float y, UINT over,UINT state)
{
int old_button_state = button_state;
CGUIButton::MouseOver(x,y,over,state);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseOver> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
float bx, by;
float width, length;
float dd;
GetPos(bx,by);
if(scrollBarButtonType == S_Slider && button_state==2)
{
switch(scrollBarType)
{
case Vertical : sb->GetSize(width, length);
if((length - 2*width - sy) && (wnd->bw_size_normal_y - wnd->vp_sy)) // kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((y-by-py) / (length - 2*width - sy) * (wnd->bw_size_normal_y - wnd->vp_sy));
else
dd=0;
wnd->SetWindowPositionVP(0,dd,false);
sb->RebuildScrollbar();
break;
case Horizontal : sb->GetSize(length, width);
if((length - 2*width - sx) && (wnd->bw_size_normal_x - wnd->vp_sx)) // kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((x-bx-px) / (length - 2*width - sx) * (wnd->bw_size_normal_x - wnd->vp_sx));
else
dd = 0;
wnd->SetWindowPositionVP(dd, 0,false);
sb->RebuildScrollbar();
break;
}
}else if(scrollBarButtonType != S_Slider && old_button_state!=button_state && button_state==2)
{ // zmenil se stav buttonu (najel jsem zpet nad tlacitko po predchozim zmacknuti a vyjeti) a tlacitko je zmacknute
switch(scrollBarButtonType)
{
case S_Up : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
break;
case S_PageUp : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
break;
case S_PageDown : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
break;
case S_Down : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
break;
case S_Nothing : break;
}
if(scrollBarButtonType!= S_Nothing)
{
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}
}else if((scrollBarButtonType == S_PageUp || scrollBarButtonType == S_PageDown)
&& button_state==2 && !timerGUI->ContainRequest(this))
// zarizuje cinnost za TimerImpulse
// v TimerImpulse nevime zda se kurzor stale naleza nad tlacitkem, to zjistime az
// poslanim zadosti o polohu kurzoru, pokud je odpoved kladna, dostaneme se sem a tady zaridime
// posunuti okna, ktere mel puvodne vykonat TimerImpulse
{
switch(scrollBarButtonType)
{
case S_PageUp : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
break;
case S_PageDown : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
break;
}
}
return 0;
}
int CGUIScrollbarButton::MouseLeftFocus(float x, float y, UINT mouseState, UINT keyState, typeID ID)
{
CGUIButton::MouseLeftFocus(x,y,mouseState, keyState,ID);
if(scrollBarButtonType == S_Slider)
{
mouse_down=false;
px=0;
py=0;
}
return 0;
}
int CGUIScrollbarButton::MouseOverFocus(float x, float y, UINT over,UINT state, typeID ID)
{
int old_button_state = button_state;
CGUIButton::MouseOverFocus(x,y,over,state,ID);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseOverFocus> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
if(mouse_down && !(state & MK_LBUTTON))
{
mouse_down=0;
px=py=0;
}
float bx, by;
float width, length;
float dd;
GetPos(bx,by);
if(scrollBarButtonType == S_Slider && mouse_down)
{
switch(scrollBarType)
{
case Vertical : sb->GetSize(width, length);
if((length - 2*width - sy) && (wnd->bw_size_normal_y - wnd->vp_sy))// kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((y-by-py) / (length - 2*width - sy) * (wnd->bw_size_normal_y - wnd->vp_sy));
else
dd = 0;
wnd->SetWindowPositionVP(0,dd,false);
sb->RebuildScrollbar();
break;
case Horizontal : sb->GetSize(length, width);
if((length - 2*width - sx) && (wnd->bw_size_normal_x - wnd->vp_sx))// kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((x-bx-px) / (length - 2*width - sx) * (wnd->bw_size_normal_x - wnd->vp_sx));
else
dd = 0;
wnd->SetWindowPositionVP(dd, 0,false);
sb->RebuildScrollbar();
break;
}
}else if(scrollBarButtonType != S_Slider && scrollBarButtonType != S_Nothing &&
old_button_state == 2 && button_state != old_button_state)
{
timerGUI->DeleteRequest(this);
}
return 0;
}
int CGUIScrollbarButton::TimerImpulse(typeID timerID, float time)
{
if(!sb || !sb->active || button_state!=2)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::TimerImpulse> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
switch(scrollBarButtonType)
{
case S_Up : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
break;
case S_PageUp : mainGUI->SendCursorPos();
return 0;
/*
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
*/
break;
case S_PageDown : mainGUI->SendCursorPos();
return 0;
/*
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
*/
break;
case S_Down : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
break;
}
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
return 0;
}
| 40.192459
| 305
| 0.619936
|
HonzaMD
|
e03d6aa003ca8bd54ec8993b909c9093fa671d35
| 717
|
cpp
|
C++
|
APIs_Drivers/DigitalIn_ex_1/main.cpp
|
adbridge/mbed-os-examples-docs_only
|
3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c
|
[
"Apache-2.0"
] | 4
|
2018-11-21T06:56:02.000Z
|
2021-12-02T13:51:18.000Z
|
APIs_Drivers/DigitalIn_ex_1/main.cpp
|
adbridge/mbed-os-examples-docs_only
|
3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c
|
[
"Apache-2.0"
] | 62
|
2018-10-12T16:19:19.000Z
|
2021-09-19T23:44:21.000Z
|
APIs_Drivers/DigitalIn_ex_1/main.cpp
|
adbridge/mbed-os-examples-docs_only
|
3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c
|
[
"Apache-2.0"
] | 27
|
2018-10-12T15:52:45.000Z
|
2021-08-13T05:42:33.000Z
|
/*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
DigitalIn mypin(SW2); // change this to the button on your board
DigitalOut myled(LED1);
int main()
{
// check mypin object is initialized and connected to a pin
if (mypin.is_connected()) {
printf("mypin is connected and initialized! \n\r");
}
// Optional: set mode as PullUp/PullDown/PullNone/OpenDrain
mypin.mode(PullNone);
// press the button and see the console / led change
while (1) {
printf("mypin has value : %d \n\r", mypin.read());
myled = mypin; // toggle led based on value of button
ThisThread::sleep_for(250);
}
}
| 25.607143
| 65
| 0.645746
|
adbridge
|
e0411a6404bca9d2b90aefb3ef94b78edb1ee377
| 8,848
|
cpp
|
C++
|
src/puzzles.cpp
|
LeifAndersen/remarkable_puzzles
|
2745eceeb5965406d3e9dd5fbf6b5057706a3f69
|
[
"MIT"
] | 8
|
2021-01-14T16:07:05.000Z
|
2021-12-07T11:35:31.000Z
|
src/puzzles.cpp
|
LeifAndersen/remarkable_puzzles
|
2745eceeb5965406d3e9dd5fbf6b5057706a3f69
|
[
"MIT"
] | 15
|
2021-01-14T21:00:03.000Z
|
2022-01-04T04:09:12.000Z
|
src/puzzles.cpp
|
LeifAndersen/remarkable_puzzles
|
2745eceeb5965406d3e9dd5fbf6b5057706a3f69
|
[
"MIT"
] | 2
|
2021-01-14T20:56:15.000Z
|
2021-03-04T19:59:13.000Z
|
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sys/time.h>
#include "puzzles.hpp"
#include "config.hpp"
// === Debug ===
#include "debug.hpp"
#ifdef NDEBUG
#undef DEBUG_FRONTEND
#undef DEBUG_DRAW
#undef DEBUG_TIMER
#endif
#ifdef DEBUG_FRONTEND
#define DEBUG_DRAW
#define DEBUG_TIMER
#endif
#ifdef DEBUG_DRAW
#define dbg_draw debugf
#define dbg_color(color) __dbg_color(handle, color)
int __dbg_color(void *handle, int color) {
float * rgb = static_cast<DrawingApi*>(handle)->get_color(color);
int r = rgb[0] * 255;
int g = rgb[1] * 255;
int b = rgb[2] * 255;
return (r << 16) | (g << 8) | b;
}
#else
#define dbg_draw(...)
#define dbg_color(...)
#endif
#ifdef DEBUG_TIMER
#define dbg_timer debugf
#else
#define dbg_timer(...)
#endif
// === Frontend definitions ===
void frontend::init_midend(DrawingApi * drawer, const game *ourgame)
{
if (me != NULL)
midend_free(me);
this->ourgame = ourgame;
config = Config::from_game(ourgame);
me = midend_new(this, ourgame, &cpp_drawing_api, drawer);
drawer->set_frontend(this);
drawer->update_colors();
}
bool frontend::load_from_file(const std::string & filename)
{
std::ifstream f(filename);
if (!f) {
std::cerr << "Error opening save file for reading: " << filename << std::endl;
return false;
}
auto write_fn = [](void * fs, void * buf, int len) {
std::ifstream * f = static_cast<std::ifstream *>(fs);
f->read(static_cast<char*>(buf), len);
return f->good();
};
const char * err = midend_deserialise(me, write_fn, &f);
if (err == NULL) {
return true;
} else {
std::cerr << "Error parsing save file: " << filename << std::endl;
std::cerr << err << std::endl;
return false;
}
}
bool frontend::save_to_file(const std::string & filename)
{
std::ofstream f(filename);
if (!f) {
std::cerr << "Error opening save file for writing: " << filename << std::endl;
return false;
}
auto write_fn = [](void * fs, const void * buf, int len) {
std::ofstream * f = static_cast<std::ofstream *>(fs);
if (f)
f->write(static_cast<const char*>(buf), len);
};
midend_serialise(me, write_fn, &f);
return f.good();
}
// === Midend API ===
extern "C" {
void fatal(const char *fmt, ...);
void get_random_seed(void **randseed, int *randseedsize);
void frontend_default_colour(frontend *fe, float *output);
void deactivate_timer(frontend *fe);
void activate_timer(frontend *fe);
}
#ifndef PUZZLES_FATAL_NODEF
void fatal(const char *fmt, ...)
{
/* Lifted from nestedvm.c */
va_list ap;
std::fprintf(stderr, "fatal error: ");
va_start(ap, fmt);
std::vfprintf(stderr, fmt, ap);
va_end(ap);
std::fprintf(stderr, "\n");
std::exit(1);
}
#endif
#ifndef PUZZLES_GET_RANDOM_SEED_NODEF
void get_random_seed(void **randseed, int *randseedsize)
{
/* Lifted from nestedvm.c */
struct timeval *tvp = snew(struct timeval);
gettimeofday(tvp, NULL);
*randseed = (void *)tvp;
*randseedsize = sizeof(struct timeval);
}
#endif
void frontend_default_colour(frontend *fe, float *output)
{
fe->frontend_default_colour(output);
}
void deactivate_timer(frontend *fe)
{
dbg_timer("deactivate_timer()\n");
fe->deactivate_timer();
}
void activate_timer(frontend *fe)
{
dbg_timer("activate_timer()\n");
fe->activate_timer();
}
// == Drawing API ==
void DrawingApi::update_colors()
{
// load colors from midend
if (colors != nullptr)
sfree(colors);
colors = midend_colours(fe->me, &ncolors);
// overwrite with colors from the config file
const std::vector<float> & cfg_colors = fe->config.colors;
if (!cfg_colors.empty()) {
for (int i = 0; i < std::min<int>(ncolors, cfg_colors.size()); i++) {
if (cfg_colors[i] < 0.0) continue;
colors[3*i+0] = cfg_colors[i];
colors[3*i+1] = cfg_colors[i];
colors[3*i+2] = cfg_colors[i];
}
}
}
void cpp_draw_text(void *handle, int x, int y, int fonttype,
int fontsize, int align, int colour,
const char *text)
{
dbg_draw("draw_text(%d, %d, %d, %d, %d, %x, \"%s\")\n",
x, y, fonttype, fontsize, align, dbg_color(colour), text);
static_cast<DrawingApi*>(handle)
->draw_text(x, y, fonttype, fontsize, align, colour, text);
}
void cpp_draw_rect(void *handle, int x, int y, int w, int h, int colour)
{
dbg_draw("draw_rect(%d, %d, %d, %d, %x)\n", x, y, w, h, dbg_color(colour));
static_cast<DrawingApi*>(handle)->draw_rect(x, y, w, h, colour);
}
void cpp_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
{
dbg_draw("draw_line(%d, %d, %d, %d, %x)\n", x1, y1, x2, y2, dbg_color(colour));
static_cast<DrawingApi*>(handle)->draw_line(x1, y1, x2, y2, colour);
}
void cpp_draw_polygon(void *handle, int *coords, int npoints,
int fillcolour, int outlinecolour)
{
#ifdef DEBUG_DRAW
dbg_draw("draw_polygon(");
dbg_draw("[");
for (int i = 0; i < 2*npoints; i+=2) {
dbg_draw("%d, %d", coords[i], coords[i+1]);
if (i < 2*(npoints-1))
dbg_draw(",");
}
dbg_draw("], ");
dbg_draw("%d, ");
if (fillcolour == -1)
dbg_draw("-1, ");
else
dbg_draw("%x, ", dbg_color(fillcolour));
dbg_draw("%x)\n", dbg_color(outlinecolour));
#endif
static_cast<DrawingApi*>(handle)
->draw_polygon(coords, npoints, fillcolour, outlinecolour);
}
void cpp_draw_circle(void *handle, int cx, int cy, int radius,
int fillcolour, int outlinecolour)
{
#ifdef DEBUG_DRAW
dbg_draw("draw_circle(%d, %d, %d, ", cx, cy, radius);
if (fillcolour == -1)
dbg_draw("-1, ");
else
dbg_draw("%x, ", dbg_color(fillcolour));
dbg_draw("%x)\n", dbg_color(outlinecolour));
#endif
static_cast<DrawingApi*>(handle)
->draw_circle(cx, cy, radius, fillcolour, outlinecolour);
}
void cpp_draw_thick_line(void *handle, float thickness,
float x1, float y1, float x2, float y2,
int colour)
{
dbg_draw("draw_thick_line(%f, %f, %f, %f, %f, %x)\n",
thickness, x1, x2, y1, y2, dbg_color(colour));
static_cast<DrawingApi*>(handle)
->draw_thick_line(thickness, x1, y1, x2, y2, colour);
}
void cpp_draw_update(void *handle, int x, int y, int w, int h)
{
dbg_draw("draw_update(%d, %d, %d, %d)\n", x, y, w, h);
static_cast<DrawingApi*>(handle)->draw_update(x, y, w, h);
}
void cpp_clip(void *handle, int x, int y, int w, int h)
{
dbg_draw("clip(%d, %d, %d, %d)\n", x, y, w, h);
static_cast<DrawingApi*>(handle)->clip(x, y, w, h);
}
void cpp_unclip(void *handle)
{
dbg_draw("unclip()\n");
static_cast<DrawingApi*>(handle)->unclip();
}
void cpp_start_draw(void *handle)
{
dbg_draw("start_draw()\n");
static_cast<DrawingApi*>(handle)->start_draw();
}
void cpp_end_draw(void *handle)
{
dbg_draw("end_draw()\n");
static_cast<DrawingApi*>(handle)->end_draw();
}
void cpp_status_bar(void *handle, const char *text)
{
dbg_draw("status_bar(\"%s\")\n", text);
static_cast<DrawingApi*>(handle)->status_bar(text);
}
blitter * cpp_blitter_new(void *handle, int w, int h)
{
dbg_draw("blitter_new(%d, %d) => ");
blitter * bl = static_cast<DrawingApi*>(handle)->blitter_new(w, h);
dbg_draw("%p\n", (void*)bl);
return bl;
}
void cpp_blitter_free(void *handle, blitter *bl)
{
dbg_draw("blitter_free(%p)\n", (void*)bl);
static_cast<DrawingApi*>(handle)->blitter_free(bl);
}
void cpp_blitter_save(void *handle, blitter *bl, int x, int y)
{
dbg_draw("blitter_save(%p, %d, %d)\n", (void*)bl, x, y);
static_cast<DrawingApi*>(handle)->blitter_save(bl, x, y);
}
void cpp_blitter_load(void *handle, blitter *bl, int x, int y)
{
dbg_draw("blitter_load(%p, %d, %d)\n", (void*)bl, x, y);
static_cast<DrawingApi*>(handle)->blitter_load(bl, x, y);
}
char * cpp_text_fallback(void *handle, const char *const *strings,
int nstrings)
{
return static_cast<DrawingApi*>(handle)->text_fallback(strings, nstrings);
}
struct drawing_api frontend::cpp_drawing_api = {
cpp_draw_text,
cpp_draw_rect,
cpp_draw_line,
cpp_draw_polygon,
cpp_draw_circle,
cpp_draw_update,
cpp_clip,
cpp_unclip,
cpp_start_draw,
cpp_end_draw,
cpp_status_bar,
cpp_blitter_new,
cpp_blitter_free,
cpp_blitter_save,
cpp_blitter_load,
NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
NULL, NULL, /* line_width, line_dotted */
cpp_text_fallback,
};
| 26.41194
| 86
| 0.615732
|
LeifAndersen
|
e043eb1f59f4577012d4abf7160302b79a6c3e6b
| 8,144
|
cpp
|
C++
|
NYPR/PlateLocate/NYPlateDetect.cpp
|
NathanYu1124/PLR_Vision
|
2eceda3462e656a257a6cabb18fef6bee448fb9b
|
[
"Apache-2.0"
] | 17
|
2018-06-20T17:48:47.000Z
|
2021-12-01T10:40:27.000Z
|
NYPR/PlateLocate/NYPlateDetect.cpp
|
rsingh2083/PLR_Vision
|
2eceda3462e656a257a6cabb18fef6bee448fb9b
|
[
"Apache-2.0"
] | null | null | null |
NYPR/PlateLocate/NYPlateDetect.cpp
|
rsingh2083/PLR_Vision
|
2eceda3462e656a257a6cabb18fef6bee448fb9b
|
[
"Apache-2.0"
] | 10
|
2019-03-02T07:15:34.000Z
|
2021-08-11T12:07:06.000Z
|
//
// NYPlateDetect.cpp
// NYPlateRecognition
//
// Created by NathanYu on 24/01/2018.
// Copyright © 2018 NathanYu. All rights reserved.
//
#include "NYPlateDetect.hpp"
// 检测图片中的车牌
vector<NYPlate> NYPlateDetect::detectPlates(Mat src)
{
vector<NYPlate> platesVec;
vector<NYPlate> sobel_plates;
vector<NYPlate> color_plates;
NYPlateLocate locater;
NYPlateJudge judge;
// 初始化svm模型地址
judge.SVM_MODEL_PATH = svmModelPath;
// 颜色定位
color_plates = locater.plateLocateWithColor(src);
color_plates = judge.judgePlates(color_plates);
platesVec.insert(platesVec.end(), color_plates.begin(), color_plates.end());
// cout << "color plates size : " << color_plates.size() << endl;
// sobel定位
sobel_plates = locater.plateLocateWithSobel(src);
sobel_plates = judge.judgePlates(sobel_plates);
reProcessPlates(src, sobel_plates);
// cout << "sobel plates size : " << sobel_plates.size() << endl;
platesVec.insert(platesVec.end(), sobel_plates.begin(),sobel_plates.end());
// 去除重复的车牌,去除sobel与color的交集
platesVec = deleteRepeatPlates(color_plates, sobel_plates);
// cout << "total plates size : " << platesVec.size() << endl;
// 设置车牌颜色
for (int i = 0; i < platesVec.size(); i++) {
}
return platesVec;
}
// 检测视频流中的车牌: 牺牲精度,提高处理速度
vector<NYPlate> NYPlateDetect::detectPlatesInVideo(Mat src)
{
vector<NYPlate> platesVec;
NYPlateLocate locater;
NYPlateJudge judge;
// 初始化svm模型地址
judge.SVM_MODEL_PATH = svmModelPath;
// 仅sobel定位
platesVec = locater.plateLocateWithSobel(src);
platesVec = judge.judgePlates(platesVec);
reProcessPlates(src, platesVec);
return platesVec;
}
// 去除重复的车牌 (根据车牌区域中心位置去除)
vector<NYPlate> NYPlateDetect::deleteRepeatPlates(vector<NYPlate> colorVec, vector<NYPlate> sobelVec)
{
vector<NYPlate> resultVec;
if ((colorVec.size() == 0) && (sobelVec.size() != 0)) {
return sobelVec;
} else if ((colorVec.size() != 0) && (sobelVec.size() == 0)){
return colorVec;
} else if ((colorVec.size() == 0) && (sobelVec.size() == 0)){
return resultVec;
} else {
vector<NYPlate>::iterator color_itr = colorVec.begin();
vector<NYPlate>::iterator sobel_itr = sobelVec.begin();
while (color_itr != colorVec.end()) {
NYPlate color_plate = NYPlate(*color_itr);
RotatedRect color_rect = color_plate.getPlatePos();
// 每次都重新指向头指针
sobel_itr = sobelVec.begin();
while (sobel_itr != sobelVec.end()) {
NYPlate sobel_plate = NYPlate(*sobel_itr);
RotatedRect sobel_rect = sobel_plate.getPlatePos();
float offset_x = sobel_rect.center.x - color_rect.center.x;
float offset_y = sobel_rect.center.y - sobel_rect.center.y;
if (abs(offset_x) < 20 && abs(offset_y) < 20) {
sobelVec.erase(sobel_itr);
} else{
sobel_itr++;
}
}
color_itr++;
}
resultVec.insert(resultVec.end(), colorVec.begin(),colorVec.end());
resultVec.insert(resultVec.end(), sobelVec.begin(),sobelVec.end());
return resultVec;
}
}
// 车牌区域精定位
void NYPlateDetect::reProcessPlates(Mat src, vector<NYPlate> &plates)
{
for (int i = 0; i < plates.size(); i++) {
RotatedRect roi_rect = plates[i].getPlatePos();
// 先扩大ROI区域,1,避免ROI区域只截取到部分车牌 2,为下面的膨胀操作提供足够的空间
// roi_rect.size.width += 20;
// roi_rect.size.height += 20;
// 纠正用RotatedRect截取ROI,宽/高<1 错误截取的问题
if (roi_rect.angle < (-70) && roi_rect.size.width < roi_rect.size.height) {
swap(roi_rect.size.width, roi_rect.size.height);
}
Mat roi_mat;
getRectSubPix(src, roi_rect.size, roi_rect.center, roi_mat);
// 转换到HSV空间
Color plateColor = plates[i].getPlateColor();
Mat roi_hsv;
if (plateColor == BLUE) { // 蓝牌
roi_hsv = locater.convertColorToGray(roi_mat, BLUE);
} else if (plateColor == YELLOW) { // 黄牌
roi_hsv = locater.convertColorToGray(roi_mat, YELLOW);
} else { // 未知暂定为蓝牌
roi_hsv = locater.convertColorToGray(roi_mat, BLUE);
}
// 去除噪声
GaussianBlur(roi_hsv, roi_hsv, Size(3, 3), 0,0, BORDER_DEFAULT);
Mat element = getStructuringElement(MORPH_RECT, Size(13,7));
dilate(roi_hsv, roi_hsv, element);
// Canny边缘检测
Canny(roi_hsv, roi_hsv, 50, 200, 3);
// hough变换找直线
vector<Vec4i> lines;
HoughLinesP(roi_hsv, lines, 1, CV_PI/180, 50,50,10);
cvtColor(roi_hsv, roi_hsv, COLOR_GRAY2BGR);
float changedAngle = 0;
int line_count = 0;
for (size_t i = 0; i < lines.size(); i++) {
Vec4i line = lines[i];
Point p1 = Point(line[0], line[1]);
Point p2 = Point(line[2], line[3]);
cv::line(roi_hsv, p1, p2, Scalar(0,255,0), 1, LINE_AA);
float angle = atan2(p1.y-p2.y, p1.x-p2.x) * 180 / CV_PI;
if (angle > 170 || angle < -170) {
if ((angle < 0 && changedAngle > 0) || (angle > 0 && changedAngle < 0)) {
angle = - angle;
}
changedAngle += angle;
line_count++;
}
}
// 直线的平均倾斜角度
changedAngle = changedAngle / line_count;
Mat roi_rotated;
float angle = 0;
if (changedAngle < 0) { // 调整到-180
angle = -(-180 - changedAngle);
} else if (changedAngle == 0) {
angle = 0;
}
else { // 调整到180
if (changedAngle > 170) {
angle = -(180 - changedAngle);
}
}
Point2f center(roi_rect.size.width / 2, roi_rect.size.height / 2); // 旋转中心
Mat matrix = getRotationMatrix2D(center, angle, 1); // 旋转矩阵
Mat src_rotated;
warpAffine(roi_mat, roi_rotated, matrix, Size(roi_rect.size.width, roi_rect.size.height), INTER_CUBIC); // 仿射变换旋转Mat
// 精定位,只截取车牌区域
Mat temp = roi_rotated.clone();
Mat region;
if (plateColor == BLUE) { // 蓝色车牌
region = locater.convertColorToGray(temp, BLUE);
} else if (plateColor == YELLOW) { // 黄色车牌
region = locater.convertColorToGray(temp, YELLOW);
} else { // 车牌颜色未知,暂按蓝色处理
region = locater.convertColorToGray(temp, BLUE);
}
Mat src_closed;
Mat ele = getStructuringElement(MORPH_RECT, Size(17, 3));
morphologyEx(region, src_closed, MORPH_CLOSE, ele);
vector<vector<Point>> contours;
findContours(src_closed, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
vector<RotatedRect> out_rects;
vector<vector<Point>>::iterator itr = contours.begin();
float maxArea = 0;
RotatedRect maxRect;
while (itr != contours.end()) {
RotatedRect mr = minAreaRect((Mat)*itr);
float area = mr.size.width * mr.size.height;
if (area > maxArea) {
maxArea = area;
maxRect = mr;
}
itr++;
}
// 纠正用RotatedRect截取ROI,宽/高<1 错误截取的问题
if (maxRect.angle < (-70) && maxRect.size.width < maxRect.size.height) {
swap(maxRect.size.width, maxRect .size.height);
}
Mat subRegion;
getRectSubPix(roi_rotated, maxRect.size, maxRect.center, subRegion);
if (maxArea > 0 && maxArea < 4800) {
resize(subRegion, subRegion, Size(136, 36));
// 保存旋转后的plate
plates[i].setPlateMat(subRegion);
}
// 保存旋转后的plate
plates[i].setPlateMat(subRegion);
}
}
// 初始化svm模型地址
void NYPlateDetect::setSVMModelPath(string svmPath)
{
svmModelPath = svmPath;
}
| 28.376307
| 125
| 0.564219
|
NathanYu1124
|
e04ceeb56788a5b8cda7f248428ac669cd955aeb
| 1,731
|
cpp
|
C++
|
Easy/valid-parentheses.cpp
|
utkarshavardhana/LeetCode-Problems
|
1b574945c59d8050a55a9d1c922dde65e6bb7c75
|
[
"MIT"
] | 1
|
2020-05-10T07:21:24.000Z
|
2020-05-10T07:21:24.000Z
|
Easy/valid-parentheses.cpp
|
utkarshavardhana/LeetCode-Problems
|
1b574945c59d8050a55a9d1c922dde65e6bb7c75
|
[
"MIT"
] | null | null | null |
Easy/valid-parentheses.cpp
|
utkarshavardhana/LeetCode-Problems
|
1b574945c59d8050a55a9d1c922dde65e6bb7c75
|
[
"MIT"
] | null | null | null |
// Problem: https://leetcode.com/problems/valid-parentheses/
//
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
//
// An input string is valid if:
//
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Note that an empty string is also considered valid.
//
// Example 1:
// Input: "()"
// Output: true
//
// Example 2:
// Input: "()[]{}"
// Output: true
//
// Example 3:
// Input: "(]"
// Output: false
//
// Example 4:
// Input: "([)]"
// Output: false
//
// Example 5:
// Input: "{[]}"
// Output: true
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char c : s) {
if(c == '(' or c == '{' or c == '[') {
st.push(c);
} else {
if(st.empty()) {
return false;
}
if(c == ')') {
if(st.top() == '(') {
st.pop();
} else {
return false;
}
} else if(c == '}') {
if(st.top() == '{') {
st.pop();
} else {
return false;
}
} else {
if(st.top() == '[') {
st.pop();
} else {
return false;
}
}
}
}
if(!st.empty()) {
return false;
}
return true;
}
};
| 25.086957
| 122
| 0.353553
|
utkarshavardhana
|
e04dfe2331a9c141b5ae3fec88e534d0f6549211
| 1,486
|
cpp
|
C++
|
Valtrook/Valtrook/RenderingEngine.cpp
|
animeenginedev/Valtrook
|
10cf7332643765534f8a4263cc4e422c4356487b
|
[
"MIT"
] | null | null | null |
Valtrook/Valtrook/RenderingEngine.cpp
|
animeenginedev/Valtrook
|
10cf7332643765534f8a4263cc4e422c4356487b
|
[
"MIT"
] | null | null | null |
Valtrook/Valtrook/RenderingEngine.cpp
|
animeenginedev/Valtrook
|
10cf7332643765534f8a4263cc4e422c4356487b
|
[
"MIT"
] | null | null | null |
#include "RenderingEngine.h"
#include <gl\glew.h>
#include <iostream>
#include <sstream>
namespace Val {
Window RenderingEngine::window;
RenderingEngine::RenderingEngine() {
}
RenderingEngine::~RenderingEngine() {
}
void RenderingEngine::InitWindow() {
window.create(0);
std::stringstream str = std::stringstream();
str << glGetString(GL_VERSION) << "\n";
std::cout << str.str();
}
void RenderingEngine::initialise() {
renderer.initialise();
GUIRenderer.initialise();
shaderObject = new GenericShaderObject();
}
void RenderingEngine::render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthFunc(GL_LEQUAL);
renderer.prepare();
GUIRenderer.prepare();
while (!renderer.isPrepared() && !GUIRenderer.isPrepared()) {
}
shaderObject->attach();
renderer.render();
shaderObject->setLineMode(true);
renderer.renderLines();
shaderObject->setLineMode(false);
if (GUIRenderer.VertexCount() > 0) {
glEnable(GL_DEPTH_TEST);
glClear(GL_DEPTH_BUFFER_BIT);
GUIRenderer.render();
shaderObject->setLineMode(true);
GUIRenderer.renderLines();
shaderObject->setLineMode(false);
}
window.swapBuffer();
renderer.clear();
GUIRenderer.clear();
}
VBOBatcher * RenderingEngine::getRenderer() {
return &renderer;
}
VBOBatcher * RenderingEngine::getGUIRenderer() {
return &GUIRenderer;
}
Window RenderingEngine::getWindow() {
return window;
}
}
| 20.081081
| 63
| 0.711306
|
animeenginedev
|
e05059cf8c65f90777bcff5cebe533bfa326746b
| 2,229
|
hpp
|
C++
|
src/SynthesizeSegment.hpp
|
haruneko/uzume_vocoder
|
63343118fd8d0dd8b7ebb92d98f023bfa6b9855e
|
[
"MIT"
] | 1
|
2020-04-28T06:29:25.000Z
|
2020-04-28T06:29:25.000Z
|
src/SynthesizeSegment.hpp
|
haruneko/uzume
|
63343118fd8d0dd8b7ebb92d98f023bfa6b9855e
|
[
"MIT"
] | null | null | null |
src/SynthesizeSegment.hpp
|
haruneko/uzume
|
63343118fd8d0dd8b7ebb92d98f023bfa6b9855e
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Hal@shurabaP. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
#ifndef __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
#define __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
#include "Spectrogram.hpp"
namespace uzume { namespace vocoder {
/**
* SegmentSignal is a value class for Segment synthesis output.
* This class is not responsible for memory allocation.
* Make sure neither SegmentSignal#indexMin nor SegmentSignal#indexMax is out of array range.
*/
class SegmentSignal final {
public:
SegmentSignal() = delete;
SegmentSignal(double *waveStartPoint, int indexMin, int indexMax, unsigned int samplingFrequency)
: waveStartPoint(waveStartPoint), indexMin(indexMin), indexMax(indexMax), samplingFrequency(samplingFrequency) {
}
double *waveStartPoint;
int indexMin;
int indexMax;
unsigned int samplingFrequency;
};
/**
* SegmentSignal is a value class for Segment synthesis input.
* This class is not responsible for memory allocation.
* SegmentParameters#startPhase and SegmentParameters#startFractionalTimeShift should be set
* when SynthesizeSegment begins synthesis from the middle of music sentence, otherwise they should be 0.0.
*/
class SegmentParameters final {
public:
SegmentParameters() = delete;
SegmentParameters(const Spectrogram *spectrogram, double startPhase, double startFractionalTimeShift)
: spectrogram(spectrogram), startPhase(startPhase), startFractionalTimeShift(startFractionalTimeShift) {
}
const Spectrogram *spectrogram;
double startPhase;
double startFractionalTimeShift;
};
/**
* SynthesizeSegment synthesize a single Segment.
*/
class SynthesizeSegment {
public:
SynthesizeSegment() = default;
SynthesizeSegment(const SynthesizeSegment&) = delete;
virtual ~SynthesizeSegment() = default;
/**
* SynthesizeSegment#() synthesize a single Segment into output from input.
* @return true if synthesis is successful.
* @return false otherwise.
*/
virtual bool operator()(SegmentSignal *output, SegmentParameters *input) = 0;
};
} }
#endif // __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
| 33.772727
| 124
| 0.75729
|
haruneko
|
e050f21091ba16d03fa8ce813149006f205678e6
| 3,217
|
cpp
|
C++
|
CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp
|
Cwc-Test/CpcdosOS2.1
|
d52c170be7f11cc50de38ef536d4355743d21706
|
[
"Apache-2.0"
] | 30
|
2016-09-06T06:58:43.000Z
|
2021-12-23T11:59:38.000Z
|
CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp
|
Cwc-Test/CpcdosOS2.1
|
d52c170be7f11cc50de38ef536d4355743d21706
|
[
"Apache-2.0"
] | 21
|
2016-08-11T09:43:43.000Z
|
2017-01-29T12:52:56.000Z
|
CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp
|
Cwc-Test/CpcdosOS2.1
|
d52c170be7f11cc50de38ef536d4355743d21706
|
[
"Apache-2.0"
] | 17
|
2016-10-24T06:08:16.000Z
|
2022-02-18T17:27:14.000Z
|
//===-- AMDGPUHSATargetObjectFile.cpp - AMDGPU Object Files ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AMDGPUTargetObjectFile.h"
#include "AMDGPU.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/Support/ELF.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Generic Object File
//===----------------------------------------------------------------------===//
MCSection *AMDGPUTargetObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
SectionKind Kind,
Mangler &Mang,
const TargetMachine &TM) const {
if (Kind.isReadOnly() && AMDGPU::isReadOnlySegment(GV))
return TextSection;
return TargetLoweringObjectFileELF::SelectSectionForGlobal(GV, Kind, Mang, TM);
}
//===----------------------------------------------------------------------===//
// HSA Object File
//===----------------------------------------------------------------------===//
void AMDGPUHSATargetObjectFile::Initialize(MCContext &Ctx,
const TargetMachine &TM){
TargetLoweringObjectFileELF::Initialize(Ctx, TM);
InitializeELF(TM.Options.UseInitArray);
TextSection = AMDGPU::getHSATextSection(Ctx);
DataGlobalAgentSection = AMDGPU::getHSADataGlobalAgentSection(Ctx);
DataGlobalProgramSection = AMDGPU::getHSADataGlobalProgramSection(Ctx);
RodataReadonlyAgentSection = AMDGPU::getHSARodataReadonlyAgentSection(Ctx);
}
bool AMDGPUHSATargetObjectFile::isAgentAllocationSection(
const char *SectionName) const {
return cast<MCSectionELF>(DataGlobalAgentSection)
->getSectionName()
.equals(SectionName);
}
bool AMDGPUHSATargetObjectFile::isAgentAllocation(const GlobalValue *GV) const {
// Read-only segments can only have agent allocation.
return AMDGPU::isReadOnlySegment(GV) ||
(AMDGPU::isGlobalSegment(GV) && GV->hasSection() &&
isAgentAllocationSection(GV->getSection()));
}
bool AMDGPUHSATargetObjectFile::isProgramAllocation(
const GlobalValue *GV) const {
// The default for global segments is program allocation.
return AMDGPU::isGlobalSegment(GV) && !isAgentAllocation(GV);
}
MCSection *AMDGPUHSATargetObjectFile::SelectSectionForGlobal(
const GlobalValue *GV, SectionKind Kind,
Mangler &Mang,
const TargetMachine &TM) const {
if (Kind.isText() && !GV->hasComdat())
return getTextSection();
if (AMDGPU::isGlobalSegment(GV)) {
if (isAgentAllocation(GV))
return DataGlobalAgentSection;
if (isProgramAllocation(GV))
return DataGlobalProgramSection;
}
return AMDGPUTargetObjectFile::SelectSectionForGlobal(GV, Kind, Mang, TM);
}
| 36.556818
| 81
| 0.578489
|
Cwc-Test
|
e051f2422e3ff0ebeea24593e27b4b2762c4b2aa
| 539
|
hpp
|
C++
|
src/player_human.hpp
|
a-n-t-h-o-n-y/cursed-chess
|
a932f48bac0431c927e7ec569e8d167e3b261754
|
[
"MIT"
] | null | null | null |
src/player_human.hpp
|
a-n-t-h-o-n-y/cursed-chess
|
a932f48bac0431c927e7ec569e8d167e3b261754
|
[
"MIT"
] | null | null | null |
src/player_human.hpp
|
a-n-t-h-o-n-y/cursed-chess
|
a932f48bac0431c927e7ec569e8d167e3b261754
|
[
"MIT"
] | null | null | null |
#ifndef CHESS_PLAYER_HUMAN_HPP
#define CHESS_PLAYER_HUMAN_HPP
#include <mutex>
#include "move.hpp"
#include "player.hpp"
#include "shared_user_input.hpp"
namespace chess {
class Chess_engine;
} // namespace chess
namespace chess::player {
inline auto human() -> Player
{
return {"Human", [](Chess_engine const&) {
auto lock = std::unique_lock{Shared_user_input::move.mtx};
return Shared_user_input::move.get(lock);
}};
}
} // namespace chess::player
#endif // CHESS_PLAYER_HUMAN_HPP
| 21.56
| 74
| 0.679035
|
a-n-t-h-o-n-y
|
e053d66898ad019e0101859f68cd0c73e58218db
| 1,284
|
hpp
|
C++
|
include/Game/Item.hpp
|
darwin-s/nanocraft
|
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
|
[
"Apache-2.0"
] | 2
|
2021-08-12T10:05:53.000Z
|
2021-08-13T16:25:49.000Z
|
include/Game/Item.hpp
|
darwin-s/nanocraft
|
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
|
[
"Apache-2.0"
] | null | null | null |
include/Game/Item.hpp
|
darwin-s/nanocraft
|
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 Sirbu Dan
//
// 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 NC_GAME_ITEM_HPP
#define NC_GAME_ITEM_HPP
#include <World/Tile.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <string>
namespace nc {
class Item {
public:
explicit Item(const std::string& name = "null");
Item(const std::string& texture, const std::string& name);
void setTexture(const std::string& texture);
sf::Sprite& getSprite();
const sf::Sprite& getSprite() const;
void setPlaceableTile(const std::string& name);
Tile* getPlaceableTile() const;
void setName(const std::string& name);
std::string getName() const;
private:
sf::Sprite m_sprite;
std::string m_name;
std::string m_placeableTile;
};
}
#endif // !NC_GAME_ITEM_HPP
| 29.181818
| 75
| 0.715732
|
darwin-s
|
e0546cb6216e6946ff2b3bec378ac70d890d1da8
| 465
|
cpp
|
C++
|
src/tools/tools__MB.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/tools/tools__MB.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
src/tools/tools__MB.cpp
|
violador/catalyst
|
40d5c1dd04269a0764a9804711354a474bc43c15
|
[
"Unlicense"
] | null | null | null |
//
//
//
/// @brief Returns the conversion factor from bytes to megabytes.
//
/// @return @f$ 0.000000954 @f$
//
inline const double MB()
{
return 0.000000954;
};
//
//
//
/// @param [in] data_size A numerical (only) argument in byte units.
//
/// @brief Converts the given @c data_size to megabyte units.
//
/// @return @f$ := \times 0.000000954 @f$
//
template<typename data_type>
inline double MB(const data_type &data_size)
{
return data_size*0.000000954;
};
| 17.884615
| 68
| 0.664516
|
violador
|
e054d96afb4867d6e5dee9a2d51042dce8b99679
| 5,457
|
hpp
|
C++
|
src/backend/cuda/kernel/resize.hpp
|
ckeitz/arrayfire
|
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
|
[
"BSD-3-Clause"
] | 4
|
2015-12-16T09:41:32.000Z
|
2018-10-29T10:38:53.000Z
|
src/backend/cuda/kernel/resize.hpp
|
ckeitz/arrayfire
|
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
|
[
"BSD-3-Clause"
] | 3
|
2015-11-15T18:43:47.000Z
|
2015-12-16T09:43:14.000Z
|
src/backend/cuda/kernel/resize.hpp
|
pavanky/arrayfire
|
f983a79c7d402450bd2a704bbc1015b89f0cd504
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <dispatch.hpp>
#include <Param.hpp>
#include <err_cuda.hpp>
#include <debug_cuda.hpp>
namespace cuda
{
namespace kernel
{
// Kernel Launch Config Values
static const unsigned TX = 16;
static const unsigned TY = 16;
///////////////////////////////////////////////////////////////////////////
// nearest-neighbor resampling
///////////////////////////////////////////////////////////////////////////
template<typename T>
__host__ __device__
void resize_n(Param<T> out, CParam<T> in,
const dim_type o_off, const dim_type i_off,
const dim_type blockIdx_x, const dim_type blockIdx_y,
const float xf, const float yf)
{
const dim_type ox = threadIdx.x + blockIdx_x * blockDim.x;
const dim_type oy = threadIdx.y + blockIdx_y * blockDim.y;
dim_type ix = round(ox * xf);
dim_type iy = round(oy * yf);
if (ox >= out.dims[0] || oy >= out.dims[1]) { return; }
if (ix >= in.dims[0]) { ix = in.dims[0] - 1; }
if (iy >= in.dims[1]) { iy = in.dims[1] - 1; }
out.ptr[o_off + ox + oy * out.strides[1]] = in.ptr[i_off + ix + iy * in.strides[1]];
}
///////////////////////////////////////////////////////////////////////////
// bilinear resampling
///////////////////////////////////////////////////////////////////////////
template<typename T>
__host__ __device__
void resize_b(Param<T> out, CParam<T> in,
const dim_type o_off, const dim_type i_off,
const dim_type blockIdx_x, const dim_type blockIdx_y,
const float xf_, const float yf_)
{
const dim_type ox = threadIdx.x + blockIdx_x * blockDim.x;
const dim_type oy = threadIdx.y + blockIdx_y * blockDim.y;
float xf = ox * xf_;
float yf = oy * yf_;
dim_type ix = floorf(xf);
dim_type iy = floorf(yf);
if (ox >= out.dims[0] || oy >= out.dims[1]) { return; }
if (ix >= in.dims[0]) { ix = in.dims[0] - 1; }
if (iy >= in.dims[1]) { iy = in.dims[1] - 1; }
float b = xf - ix;
float a = yf - iy;
const dim_type ix2 = ix + 1 < in.dims[0] ? ix + 1 : ix;
const dim_type iy2 = iy + 1 < in.dims[1] ? iy + 1 : iy;
const T *iptr = in.ptr + i_off;
const T p1 = iptr[ix + in.strides[1] * iy ];
const T p2 = iptr[ix + in.strides[1] * iy2];
const T p3 = iptr[ix2 + in.strides[1] * iy ] ;
const T p4 = iptr[ix2 + in.strides[1] * iy2];
T val = (1.0f-a) * (1.0f-b) * p1 +
(a) * (1.0f-b) * p2 +
(1.0f-a) * (b) * p3 +
(a) * (b) * p4;
out.ptr[o_off + ox + oy * out.strides[1]] = val;
}
///////////////////////////////////////////////////////////////////////////
// Resize Kernel
///////////////////////////////////////////////////////////////////////////
template<typename T, af_interp_type method>
__global__
void resize_kernel(Param<T> out, CParam<T> in,
const dim_type b0, const dim_type b1, const float xf, const float yf)
{
const dim_type bIdx = blockIdx.x / b0;
const dim_type bIdy = blockIdx.y / b1;
// channel adjustment
const dim_type i_off = bIdx * in.strides[2] + bIdy * in.strides[3];
const dim_type o_off = bIdx * out.strides[2] + bIdy * out.strides[3];
const dim_type blockIdx_x = blockIdx.x - bIdx * b0;
const dim_type blockIdx_y = blockIdx.y - bIdy * b1;
// core
if(method == AF_INTERP_NEAREST) {
resize_n(out, in, o_off, i_off, blockIdx_x, blockIdx_y, xf, yf);
} else if(method == AF_INTERP_BILINEAR) {
resize_b(out, in, o_off, i_off, blockIdx_x, blockIdx_y, xf, yf);
}
}
///////////////////////////////////////////////////////////////////////////
// Wrapper functions
///////////////////////////////////////////////////////////////////////////
template <typename T, af_interp_type method>
void resize(Param<T> out, CParam<T> in)
{
dim3 threads(TX, TY, 1);
dim3 blocks(divup(out.dims[0], threads.x), divup(out.dims[1], threads.y));
dim_type blocksPerMatX = blocks.x;
dim_type blocksPerMatY = blocks.y;
if (in.dims[2] > 1) { blocks.x *= in.dims[2]; }
if (in.dims[3] > 1) { blocks.y *= in.dims[3]; }
float xf = (float)in.dims[0] / (float)out.dims[0];
float yf = (float)in.dims[1] / (float)out.dims[1];
resize_kernel<T, method><<<blocks, threads>>>(out, in, blocksPerMatX, blocksPerMatY, xf, yf);
POST_LAUNCH_CHECK();
}
}
}
| 40.422222
| 105
| 0.439069
|
ckeitz
|
e0576645a761fdeaebb6655a7fbee24b356879da
| 25,721
|
cpp
|
C++
|
src/Socket.cpp
|
seppeon/NetChat
|
9b30513179f5d97a39ad9444dc94640976218b77
|
[
"MIT"
] | null | null | null |
src/Socket.cpp
|
seppeon/NetChat
|
9b30513179f5d97a39ad9444dc94640976218b77
|
[
"MIT"
] | null | null | null |
src/Socket.cpp
|
seppeon/NetChat
|
9b30513179f5d97a39ad9444dc94640976218b77
|
[
"MIT"
] | null | null | null |
#include "Socket.h"
#include "WinsockRaii.h"
#include "WindowsSocketRaii.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
namespace Net
{
std::string GetStatusDescription(BindStatus status) noexcept
{
switch(status)
{
case BindStatus::Success: return "Bind successful.";
case BindStatus::NotInitialised: return "A successful Startup call must occur before using this function.";
case BindStatus::NetworkDown: return "A network subsystem has failed.";
case BindStatus::Access: return "This error is returned if nn attempt to bind a datagram socket to the broadcast address failed because the setsockopt option SO_BROADCAST is not enabled.";
case BindStatus::AddressInUse: return "This error is returned if a process on the computer is already bound to the same fully qualified address and the socket has not been marked to allow address reuse with SO_REUSEADDR. For example, the IP ad";
case BindStatus::AddressNotAvaliable: return "This error is returned if the specified address pointed to by the name parameter is not a valid local IP address on this computer.";
case BindStatus::InvalidPointerArgument: return "This error is returned if the name parameter is NULL, the name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorr";
case BindStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case BindStatus::SocketAlreadyBound: return "This error is returned of the socket s is already bound to an address.";
case BindStatus::NoPortsAvaliable: return "An indication that there aren't enough ephemeral ports to allocate for the bind.";
case BindStatus::NotASocket: return "This error is returned if the descriptor in the s parameter is not a socket.";
}
return "";
}
std::string GetStatusDescription(ListenStatus status) noexcept
{
switch(status)
{
case ListenStatus::Success: return "Listen successful.";
case ListenStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ListenStatus::NetworkDown: return "The network subsystem has failed.";
case ListenStatus::AddressInUse: return "The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs during execution";
case ListenStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ListenStatus::UnboundSocket: return "The socket has not been bound with bind.";
case ListenStatus::AlreadyConnected: return "The socket is already connected.";
case ListenStatus::NoMoreDescriptors: return "No more socket descriptors are available.";
case ListenStatus::NoBufferSpace: return "No buffer space is available.";
case ListenStatus::NotASocket: return "This error is returned if the descriptor in the parameter is not a socket.";
case ListenStatus::NotSupported: return "The referenced socket is not of a type that supports the listen operation. ";
}
return "";
}
std::string GetStatusDescription(AcceptStatus status) noexcept
{
switch (status)
{
case AcceptStatus::Success: return "Accepted successfully.";
case AcceptStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case AcceptStatus::ConnectionReset: return "An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call.";
case AcceptStatus::Cancelled: return "A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.";
case AcceptStatus::ListenNotInvoked: return "The listen function was not invoked prior to accept.";
case AcceptStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case AcceptStatus::NoMoreDescriptors: return "The queue is nonempty upon entry to accept and there are no descriptors available.";
case AcceptStatus::NetworkDown: return "The network subsystem has failed.";
case AcceptStatus::NoBufferSpace: return "No buffer space is available.";
case AcceptStatus::NotASocket: return "The descriptor is not a socket.";
case AcceptStatus::NotSupported: return "The referenced socket is not a type that supports connection-oriented service.";
case AcceptStatus::WouldBlock: return "The socket is marked as nonblocking and no connections are present to be accepted.";
}
return "";
}
std::string GetStatusDescription(SendStatus status) noexcept
{
switch (status)
{
case SendStatus::Success: return "Sent successfully.";
case SendStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case SendStatus::NetworkDown: return "The network subsystem has failed.";
case SendStatus::BroadcastAddressNotEnabled: return "The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket option to enable use of the broadcast address.";
case SendStatus::Cancelled: return "A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.";
case SendStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case SendStatus::InvalidBufferParameter: return "The buf parameter is not completely contained in a valid part of the user address space.";
case SendStatus::NetworkReset: return "The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.";
case SendStatus::NoBufferSpace: return "No buffer space is available.";
case SendStatus::NotConnected: return "The socket is not connected.";
case SendStatus::NotASocket: return "The descriptor is not a socket.";
case SendStatus::NotSupported: return "MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.";
case SendStatus::Shutdown: return "The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.";
case SendStatus::WouldBlock: return "The socket is marked as nonblocking and the requested operation would block.";
case SendStatus::MessageTooLarge: return "The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.";
case SendStatus::HostUnreachable: return "The remote host cannot be reached from this host at this time.";
case SendStatus::UnboundSocket: return "The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.";
case SendStatus::ConnectionAborted: return "The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.";
case SendStatus::ConnectionReset: return "The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a \"Port Unreachable\" ICMP packet. The application should close the socket as it is no longer usable.";
case SendStatus::Timeout: return "The connection has been dropped, because of a network failure or because the system on the other end went down without notice. ";
}
return "";
}
std::string GetStatusDescription(ReceiveStatus status) noexcept
{
switch (status)
{
case ReceiveStatus::Success: return "Received successfully.";
case ReceiveStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ReceiveStatus::NetworkDown: return "The network subsystem has failed.";
case ReceiveStatus::InvalidBufferParameter: return "The buf parameter is not completely contained in a valid part of the user address space.";
case ReceiveStatus::NotConnected: return "The socket is not connected.";
case ReceiveStatus::Cancelled: return "The (blocking) call was canceled through WSACancelBlockingCall.";
case ReceiveStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ReceiveStatus::ConnectionReset: return "For a connection-oriented socket, this error indicates that the connection has been broken due to keep-alive activity that detected a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired.";
case ReceiveStatus::NotASocket: return "The descriptor is not a socket.";
case ReceiveStatus::NotSupported: return "MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only send operations.";
case ReceiveStatus::Shutdown: return "The socket has been shut down; it is not possible to receive on a socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH.";
case ReceiveStatus::WouldBlock: return "The socket is marked as nonblocking and the receive operation would block.";
case ReceiveStatus::MessageTooLarge: return "The message was too large to fit into the specified buffer and was truncated.";
case ReceiveStatus::UnboundSocket: return "The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative.";
case ReceiveStatus::ConnectionAborted: return "The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.";
case ReceiveStatus::Timeout: return "The connection has been dropped because of a network failure or because the peer system failed to respond.";
case ReceiveStatus::RemoteConnectionReset: return "The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket as it is no longer usable. On a UDP-datagram socket, this error would indicate that a previous send operation resulted in an ICMP \"Port Unreachable\" message.";
}
return "";
}
std::string GetStatusDescription(ConnectStatus status) noexcept
{
switch (status)
{
case ConnectStatus::Success: return "Connected successfully.";
case ConnectStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ConnectStatus::NetworkDown: return "The network subsystem has failed.";
case ConnectStatus::AddressInUse: return "The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs when executing bind, but could be delayed until the connect function if the bind was to a wildcard address (INADDR_ANY or in6addr_any) for the local IP address. A specific address needs to be implicitly bound by the connect function.";
case ConnectStatus::Cancelled: return "The blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.";
case ConnectStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ConnectStatus::ConnectInProgress: return "A nonblocking connect call is in progress on the specified socket.";
case ConnectStatus::InvalidAddress: return "The remote address is not a valid address (such as INADDR_ANY or in6addr_any) .";
case ConnectStatus::AddressFamilyNotSupported: return "Addresses in the specified family cannot be used with this socket.";
case ConnectStatus::ConnectionRefused: return "The attempt to connect was forcefully rejected.";
case ConnectStatus::InvalidSocketDetails: return "The sockaddr structure pointed to by the name contains incorrect address format for the associated address family or the namelen parameter is too small. This error is also returned if the sockaddr structure pointed to by the name parameter with a length specified in the namelen parameter is not in a valid part of the user address space.";
case ConnectStatus::ListeningSocket: return "The parameter s is a listening socket, it shouldn't be.";
case ConnectStatus::IsConnected: return "The socket is already connected (connection-oriented sockets only).";
case ConnectStatus::NetworkUnreachable: return "The network cannot be reached from this host at this time.";
case ConnectStatus::HostUnreachable: return "A socket operation was attempted to an unreachable host.";
case ConnectStatus::NoBufferSpace: return "No buffer space is available. The socket cannot be connected.";
case ConnectStatus::NotASocket: return "The descriptor specified in the s parameter is not a socket.";
case ConnectStatus::ConnectTimeout: return "An attempt to connect timed out without establishing a connection.";
case ConnectStatus::WouldBlock: return "The socket is marked as nonblocking and the connection cannot be completed immediately.";
case ConnectStatus::BroadcastNotEnabled: return "An attempt to connect a datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled. ";
}
return "";
}
static auto GetFamily(IpVersion version) noexcept
{
switch (version)
{
case IpVersion::Ipv4: return AF_INET;
case IpVersion::Ipv6: return AF_INET6;
default: return 0;
}
}
static sockaddr_in6 GetIpv6SocketStruct(Ip const & ip, uint16_t port) noexcept
{
auto ip_version = ip.GetVersion();
auto family = GetFamily(ip_version);
sockaddr_in6 output
{
.sin6_family{ static_cast<short>(family) },
.sin6_port{ htons(port) },
};
(void)inet_pton(family, ToString(ip).c_str(), (void *)&output.sin6_addr.s6_addr);
return output;
}
static sockaddr_in GetIpv4SocketStruct(Ip const & ip, uint16_t port) noexcept
{
auto ip_version = ip.GetVersion();
auto family = GetFamily(ip_version);
sockaddr_in output
{
.sin_family{ static_cast<short>(family) },
.sin_port{ htons(port) }
};
(void)inet_pton(family, ToString(ip).c_str(), (void *)&output.sin_addr);
return output;
}
static sockaddr_in6 GetIpv6AnySocketStruct(uint16_t port) noexcept
{
return
{
.sin6_family{ AF_INET6 },
.sin6_port{ htons(port) },
.sin6_addr{ in6addr_any }
};
}
static sockaddr_in GetIpv4AnySocketStruct(uint16_t port) noexcept
{
return
{
.sin_family{ AF_INET },
.sin_port{ htons(port) },
.sin_addr{ INADDR_ANY }
};
}
static BindStatus TranslateBindResult(int r) noexcept
{
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return BindStatus::NotInitialised;
case WSAENETDOWN: return BindStatus::NetworkDown;
case WSAEACCES: return BindStatus::Access;
case WSAEADDRINUSE: return BindStatus::AddressInUse;
case WSAEADDRNOTAVAIL: return BindStatus::AddressNotAvaliable;
case WSAEFAULT: return BindStatus::InvalidPointerArgument;
case WSAEINPROGRESS: return BindStatus::OperationInProgress;
case WSAEINVAL: return BindStatus::SocketAlreadyBound;
case WSAENOBUFS: return BindStatus::NoPortsAvaliable;
case WSAENOTSOCK: return BindStatus::NotASocket;
}
}
return BindStatus::Success;
}
static ConnectStatus TranslateConnectResult(int r) noexcept
{
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return ConnectStatus::NotInitialized;
case WSAENETDOWN: return ConnectStatus::NetworkDown;
case WSAEADDRINUSE: return ConnectStatus::AddressInUse;
case WSAEINTR: return ConnectStatus::Cancelled;
case WSAEINPROGRESS: return ConnectStatus::OperationInProgress;
case WSAEALREADY: return ConnectStatus::ConnectInProgress;
case WSAEADDRNOTAVAIL: return ConnectStatus::InvalidAddress;
case WSAEAFNOSUPPORT: return ConnectStatus::AddressFamilyNotSupported;
case WSAECONNREFUSED: return ConnectStatus::ConnectionRefused;
case WSAEFAULT: return ConnectStatus::InvalidSocketDetails;
case WSAEINVAL: return ConnectStatus::ListeningSocket;
case WSAEISCONN: return ConnectStatus::IsConnected;
case WSAENETUNREACH: return ConnectStatus::NetworkUnreachable;
case WSAEHOSTUNREACH: return ConnectStatus::HostUnreachable;
case WSAENOBUFS: return ConnectStatus::NoBufferSpace;
case WSAENOTSOCK: return ConnectStatus::NotASocket;
case WSAETIMEDOUT: return ConnectStatus::ConnectTimeout;
case WSAEWOULDBLOCK: return ConnectStatus::WouldBlock;
case WSAEACCES: return ConnectStatus::BroadcastNotEnabled;
default: return ConnectStatus::Unknown;
}
}
return ConnectStatus::Success;
}
struct WindowsSocket : BaseSocket
{
WinsockRaii winsock;
WindowsSocketRaii socket;
WindowsSocket(socket_handle handle) noexcept
: socket{ handle }
{}
WindowsSocket(int domain, int type, int protocol)
: socket{ domain, type, protocol }
{}
WindowsSocket(WindowsSocket&&) noexcept = default;
WindowsSocket& operator = (WindowsSocket&&) noexcept = default;
virtual ~WindowsSocket() override {}
BindStatus Bind(Ip const & ip, uint16_t port) const noexcept override
{
auto process = [&](auto sock_address) -> BindStatus
{
return TranslateBindResult(bind(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip.GetVersion())
{
case IpVersion::Ipv4: return process(GetIpv4SocketStruct(ip, port));
case IpVersion::Ipv6: return process(GetIpv6SocketStruct(ip, port));
default: return BindStatus::Unknown;
}
}
BindStatus Bind(IpVersion ip_version, uint16_t port) const noexcept override
{
auto process = [&](auto sock_address) -> BindStatus
{
return TranslateBindResult(bind(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip_version)
{
case IpVersion::Ipv4: return process(GetIpv4AnySocketStruct(port));
case IpVersion::Ipv6: return process(GetIpv6AnySocketStruct(port));
default: return BindStatus::Unknown;
}
}
ConnectStatus Connect(Ip const & ip, uint16_t port) const noexcept
{
auto process = [&](auto sock_address) -> ConnectStatus
{
return TranslateConnectResult(connect(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip.GetVersion())
{
case IpVersion::Ipv4: return process(GetIpv4SocketStruct(ip, port));
case IpVersion::Ipv6: return process(GetIpv6SocketStruct(ip, port));
default: return ConnectStatus::Unknown;
}
}
ListenStatus Listen(size_t backlog) const noexcept override
{
auto r = listen(socket.Get(), backlog);
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return ListenStatus::NotInitialized;
case WSAENETDOWN: return ListenStatus::NetworkDown;
case WSAEADDRINUSE: return ListenStatus::AddressInUse;
case WSAEINPROGRESS: return ListenStatus::OperationInProgress;
case WSAEINVAL: return ListenStatus::UnboundSocket;
case WSAEISCONN: return ListenStatus::AlreadyConnected;
case WSAEMFILE: return ListenStatus::NoMoreDescriptors;
case WSAENOBUFS: return ListenStatus::NoBufferSpace;
case WSAENOTSOCK: return ListenStatus::NotASocket;
case WSAEOPNOTSUPP: return ListenStatus::NotSupported;
default: return ListenStatus::Unknown;
}
}
return ListenStatus::Success;
}
AcceptResult Accept() const noexcept override
{
auto r = accept(socket.Get(), NULL, NULL);
if (r == INVALID_SOCKET)
{
switch(WSAGetLastError())
{
case WSANOTINITIALISED: return { AcceptStatus::NotInitialized };
case WSAECONNRESET: return { AcceptStatus::ConnectionReset };
case WSAEINTR: return { AcceptStatus::Cancelled };
case WSAEINVAL: return { AcceptStatus::ListenNotInvoked };
case WSAEINPROGRESS: return { AcceptStatus::OperationInProgress };
case WSAEMFILE: return { AcceptStatus::NoMoreDescriptors };
case WSAENETDOWN: return { AcceptStatus::NetworkDown };
case WSAENOBUFS: return { AcceptStatus::NoBufferSpace };
case WSAENOTSOCK: return { AcceptStatus::NotASocket };
case WSAEOPNOTSUPP: return { AcceptStatus::NotSupported };
case WSAEWOULDBLOCK: return { AcceptStatus::WouldBlock };
default: return { AcceptStatus::Unknown };
}
}
WindowsSocket output{ r };
return { .status = AcceptStatus::Success, .socket = std::make_unique<Socket>(std::move(static_cast<BaseSocket&>(output))) };
}
SendResult Send(const char * buf, size_t length, int flags) const noexcept override
{
auto r = send(socket.Get(), buf, static_cast<int>(length), flags);
if (r == SOCKET_ERROR)
{
switch( WSAGetLastError())
{
case WSANOTINITIALISED: return { SendStatus::NotInitialized };
case WSAENETDOWN: return { SendStatus::NetworkDown };
case WSAEACCES: return { SendStatus::BroadcastAddressNotEnabled };
case WSAEINTR: return { SendStatus::Cancelled };
case WSAEINPROGRESS: return { SendStatus::OperationInProgress };
case WSAEFAULT: return { SendStatus::InvalidBufferParameter };
case WSAENETRESET: return { SendStatus::NetworkReset };
case WSAENOBUFS: return { SendStatus::NoBufferSpace };
case WSAENOTCONN: return { SendStatus::NotConnected };
case WSAENOTSOCK: return { SendStatus::NotASocket };
case WSAEOPNOTSUPP: return { SendStatus::NotSupported };
case WSAESHUTDOWN: return { SendStatus::Shutdown };
case WSAEWOULDBLOCK: return { SendStatus::WouldBlock };
case WSAEMSGSIZE: return { SendStatus::MessageTooLarge };
case WSAEHOSTUNREACH: return { SendStatus::HostUnreachable };
case WSAEINVAL: return { SendStatus::UnboundSocket };
case WSAECONNABORTED: return { SendStatus::ConnectionAborted };
case WSAECONNRESET: return { SendStatus::ConnectionReset };
case WSAETIMEDOUT: return { SendStatus::Timeout };
default: return { SendStatus::Unknown };
}
}
return { SendStatus::Success, static_cast<size_t>(r) };
}
ReceiveResult Receive(char * buf, size_t length, int flags) const noexcept override
{
auto r = recv(socket.Get(), buf, static_cast<int>(length), flags);
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return { ReceiveStatus::NotInitialized };
case WSAENETDOWN: return { ReceiveStatus::NetworkDown };
case WSAEFAULT: return { ReceiveStatus::InvalidBufferParameter };
case WSAENOTCONN: return { ReceiveStatus::NotConnected };
case WSAEINTR: return { ReceiveStatus::Cancelled };
case WSAEINPROGRESS: return { ReceiveStatus::OperationInProgress };
case WSAENETRESET: return { ReceiveStatus::ConnectionReset };
case WSAENOTSOCK: return { ReceiveStatus::NotASocket };
case WSAEOPNOTSUPP: return { ReceiveStatus::NotSupported };
case WSAESHUTDOWN: return { ReceiveStatus::Shutdown };
case WSAEWOULDBLOCK: return { ReceiveStatus::WouldBlock };
case WSAEMSGSIZE: return { ReceiveStatus::MessageTooLarge };
case WSAEINVAL: return { ReceiveStatus::UnboundSocket };
case WSAECONNABORTED: return { ReceiveStatus::ConnectionAborted };
case WSAETIMEDOUT: return { ReceiveStatus::Timeout };
case WSAECONNRESET: return { ReceiveStatus::RemoteConnectionReset };
default: return { ReceiveStatus::Unknown };
}
}
return { ReceiveStatus::Success, static_cast<size_t>(r) };
}
};
static int GetDomain(IpVersion version) noexcept
{
switch (version)
{
case IpVersion::Ipv4: return AF_INET;
case IpVersion::Ipv6: return AF_INET6;
default: return 0;
}
}
static int GetType(Type type) noexcept
{
switch (type)
{
case Type::TCP: return SOCK_STREAM;
case Type::UDP: return SOCK_DGRAM;
default: return 0;
}
}
static int GetProtocol(Type type) noexcept
{
switch (type)
{
case Type::TCP: return IPPROTO_TCP;
case Type::UDP: return IPPROTO_UDP;
default: return 0;
}
}
Socket::Socket(IpVersion ip_version, Type type) noexcept
: handle{ std::make_unique<WindowsSocket>(GetDomain(ip_version), GetType(type), GetProtocol(type)) }
{}
Socket::Socket(BaseSocket && socket) noexcept
: handle{ std::make_unique<WindowsSocket>(static_cast<WindowsSocket&&>(socket)) }
{}
Socket::~Socket(){}
BindStatus Socket::Bind(Ip const & ip, uint16_t port) const noexcept
{
return handle->Bind(ip, port);
}
BindStatus Socket::Bind(IpVersion ip_version, uint16_t port) const noexcept
{
return handle->Bind(ip_version, port);
}
ListenStatus Socket::Listen(size_t backlog) const noexcept
{
return handle->Listen(backlog);
}
AcceptResult Socket::Accept() const noexcept
{
return handle->Accept();
}
SendResult Socket::Send(const char * buf, size_t length, int flags) const noexcept
{
return handle->Send(buf, length, flags);
}
ReceiveResult Socket::Receive(char * buf, size_t length, int flags) const noexcept
{
return handle->Receive(buf, length, flags);
}
ConnectStatus Socket::Connect(Ip const & ip, uint16_t port) const noexcept
{
return handle->Connect(ip, port);
}
BaseSocket::~BaseSocket(){}
}
| 50.832016
| 422
| 0.755647
|
seppeon
|
e057dc6310154c57912c788292829909feffde5a
| 2,169
|
cpp
|
C++
|
pc/1.6.4_lcddisplay.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
pc/1.6.4_lcddisplay.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
pc/1.6.4_lcddisplay.cpp
|
aoibird/pc
|
b72c0b10117f95d45e2e7423614343b5936b260a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#define VERT 1
#define HOR 0
using namespace std;
const int MAXN = 8+2;
const int MAXS = 10+5;
const int MAXR = 2*MAXS+3;
const int MAXC = MAXN*(MAXS+2);
int S; // [1, 10] size
int N; // [0, 9999 9999] number
int digits[10][7] = {{1, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 0, 1},
{1, 1, 1, 1, 0, 0, 1},
{0, 1, 1, 0, 0, 1, 1},
{1, 0, 1, 1, 0, 1, 1},
{1, 0, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1}};
int segs[7][3] = {{HOR, 0, 0}, {VERT, 0, 1}, {VERT, 1, 1}, {HOR, 2, 0},
{VERT, 1, 0}, {VERT, 0, 0}, {HOR, 1, 0}};
int pad[MAXR][MAXC];
int R, C;
void draw(char s, int pos)
{
// for each segments draw it on pad
//printf("%d\n", s-'0');
for (int i = 0; i < 7; i++) {
if (digits[s-'0'][i] == 1) {
// draw the segment
int r = segs[i][1] * (S+1);
int c = pos + segs[i][2] * (S+1);
//printf("%d %d\n", r, c);
if (segs[i][0] == HOR) {
for (int i = 0; i < S; i++) pad[r][c+1+i] = '-';
}
else if (segs[i][0] == VERT) {
for (int i = 0; i < S; i++) pad[r+1+i][c] = '|';
}
else ;
}
}
}
void print()
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
printf("%c", pad[i][j]);
}
printf("\n");
}
}
int main()
{
int first = 1;
while (scanf("%d", &S) == 1) {
if (S == 0) break;
// init
char liter[MAXN];
int c = getchar();
int i = 0;
while (isdigit(c = getchar())) liter[i++] = c;
liter[i] = '\0';
R = 2*S+3;
C = strlen(liter)*(S+2);
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
pad[i][j] = ' ';
}
}
// for each digits draw it on pad
for (int i = 0; liter[i] != '\0'; i++) {
int pos = i * (S + 2);
draw(liter[i], pos);
//print();
}
if (first == 1) first = 0;
else printf("\n");
print();
}
}
| 23.576087
| 71
| 0.384509
|
aoibird
|
e05844649f727696eca04f4542aab71cbfe7031c
| 395
|
cc
|
C++
|
src/leetcode/palindromeNumber.cc
|
yuebanyishenqiu/my_repo
|
ecc05146eac9f85ccb1ba07717a36f3044652264
|
[
"MIT"
] | null | null | null |
src/leetcode/palindromeNumber.cc
|
yuebanyishenqiu/my_repo
|
ecc05146eac9f85ccb1ba07717a36f3044652264
|
[
"MIT"
] | null | null | null |
src/leetcode/palindromeNumber.cc
|
yuebanyishenqiu/my_repo
|
ecc05146eac9f85ccb1ba07717a36f3044652264
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
bool judge(int i){
if(i < 0 || ((i % 10 == 0 && i != 0)))
return false;
int j = 0;
while(i > j){
j = j*10 + i%10;
i /= 10;
}
return (i == j || i == j/10)? true:false;
}
int main(){
int i;
cin >> i;
if(judge(i))
cout << "true" <<endl;
else
cout << "false" <<endl;
return 0;
}
| 17.954545
| 45
| 0.425316
|
yuebanyishenqiu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.