hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
97020a69bca2dd711dad18ef03e181da5e4693af
4,535
hpp
C++
Source/src/ezcard/io/scribe/list_property_scribe.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
5
2019-10-30T06:10:10.000Z
2020-04-25T16:52:06.000Z
Source/src/ezcard/io/scribe/list_property_scribe.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
null
null
null
Source/src/ezcard/io/scribe/list_property_scribe.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
2
2019-11-27T23:47:54.000Z
2020-01-13T16:36:03.000Z
// // list_property_scribe.hpp // OpenPGP // // Created by Yanfeng Zhang on 6/23/17. // // The MIT License // // Copyright (c) 2019 Proton Technologies AG // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef list_property_scribe_hpp #define list_property_scribe_hpp #include <stdio.h> #include "vcard_property_scribe.hpp" #include "vobject_property_values.hpp" namespace ezvcard { /** * Marshals properties that contain a list of values. * @param <T> the property class * @author Michael Angstadt */ template <class T> class ListPropertyScribe : public VCardPropertyScribeWrapper<T> { static_assert(std::is_base_of<TextListProperty, T>::value, "ListPropertyScribe<T>: T must be extent of TextListProperty type :-("); public: ListPropertyScribe(const std::string& propertyName) : VCardPropertyScribeWrapper<T>(propertyName) { } protected: virtual std::shared_ptr<T> _newInstance() = 0; VCardDataType::Ptr _defaultDataType(const VCardVersion::Ptr& version) { return VCardDataType::TEXT; } std::string _writeText(const std::shared_ptr<T>& property, const WriteContext::Ptr& context) { return VObjectPropertyValues::writeList(property->getValues()); } std::shared_ptr<T> _parseText(const std::string& value, const VCardDataType::Ptr& dataType, const VCardVersion::Ptr& version, const VCardParameters::Ptr& parameters, std::list<std::string> warnings) { auto values = VObjectPropertyValues::parseList(value); return parse(values); } // @Override // protected void _writeXml(T property, XCardElement parent) { // parent.append(VCardDataType.TEXT.getName().toLowerCase(), property.getValues()); // } // // @Override // protected T _parseXml(XCardElement element, VCardParameters parameters, ParseContext context) { // List<String> values = element.all(VCardDataType.TEXT); // if (!values.isEmpty()) { // return parse(values); // } // // throw missingXmlElements(VCardDataType.TEXT); // } // // @Override // protected JCardValue _writeJson(T property) { // List<String> values = property.getValues(); // if (values.isEmpty()) { // return JCardValue.single(""); // } // // return JCardValue.multi(values); // } // // @Override // protected T _parseJson(JCardValue value, VCardDataType dataType, VCardParameters parameters, ParseContext context) { // List<String> values = value.asMulti(); // return parse(values); // } private: std::shared_ptr<T> parse(const std::vector<std::string>& values) { auto property = _newInstance(); property->addValues(values); return property; } }; } #endif /* list_property_scribe_hpp */
37.479339
139
0.587872
ProtonMail
9704beb9c7e8f67345dac4235bdce1d99220ae3a
173
hpp
C++
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
#pragma once #include "Treat.hpp" class MultiballTreat : public Treat { public: MultiballTreat(sf::Vector2f pos, float launchAngle); void AddAward(PlayState* state); };
15.727273
53
0.751445
FoxelCode
9704e258106af9ac50f95c6e1251955b8cb30194
544
hpp
C++
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
null
null
null
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
null
null
null
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
1
2021-11-11T12:35:09.000Z
2021-11-11T12:35:09.000Z
#ifndef __THROW_MESSAGE_NODE_HPP__ #define __THROW_MESSAGE_NODE_HPP__ #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/string.hpp> namespace executor_test { class ThrowMessageNode : public rclcpp::Node { public: explicit ThrowMessageNode(const rclcpp::NodeOptions &options); private: rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr msg_pub_; uint64_t publish_count_; void cyclic_send_message(); }; } #endif
22.666667
74
0.674632
hsgwa
970700f6e7502b8d1f5d358af3d6242ee8392dcc
2,608
cpp
C++
src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020 Huawei Technologies Co., Ltd // Copyright (c) 2019, Facebook CORPORATION. // All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ATen/native/npu/utils/CalcuOpUtil.h" #include "ATen/native/npu/utils/KernelNpuOutputSize.h" #include "ATen/native/npu/utils/NpuUtils.h" #include "ATen/native/npu/utils/OpAdapter.h" namespace at { namespace native { using namespace at::native::npu; Tensor& addmm_out_npu( Tensor& result, const Tensor& self, const Tensor& mat1, const Tensor& mat2, Scalar beta, Scalar alpha) { // mat1*alpha Tensor mulResult = at::mul(mat1, alpha); // mulmat1 mm mat2 Tensor mmResult = at::mm(mulResult, mat2); // matmul*alpha+self*beta at::add_out(result, mmResult, self, beta); return result; } Tensor addmm_npu( const Tensor& self, const Tensor& mat1, const Tensor& mat2, Scalar beta, Scalar alpha) { // calculate the output size auto outputSize = addmm_npu_output_size(self, mat1, mat2, beta, alpha); // add算子支持NZ与1维且该轴能被16整除的ND相加,直接得到NZ result int64_t resFormat = (self.dim() == 1 && self.size(0) % 16 == 0 && self.scalar_type() == at::kHalf) ? ACL_FORMAT_FRACTAL_NZ : ACL_FORMAT_ND; Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, self.options(), resFormat); // calculate the output result of the NPU addmm_out_npu(result, self, mat1, mat2, beta, alpha); return result; } Tensor& addmm_npu_( Tensor& self, const Tensor& mat1, const Tensor& mat2, Scalar beta, Scalar alpha) { SmallVector<Tensor, N> inputs = {self, mat1, mat2}; SmallVector<Tensor, N> outputs = {self}; CalcuOpUtil::check_memory_over_laps(inputs, outputs); if (!NpuUtils::check_match(&self)) { Tensor contiguousSelf = NpuUtils::format_contiguous(self); Tensor result = addmm_out_npu(contiguousSelf, contiguousSelf, mat1, mat2, beta, alpha); NpuUtils::format_fresh_view(self, result); } else { addmm_out_npu(self, self, mat1, mat2, beta, alpha); } return self; } } // namespace native } // namespace at
29.303371
103
0.704755
Ascend
8ccbe8b685149a575057a1fe2341f07029c38dec
4,255
cpp
C++
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
#include "ai.h" #include "engine.h" #include "state.h" #include <iostream> #include <stdlib.h> #include <unistd.h> using namespace ai; using namespace engine; using namespace state; using namespace std; int RandomIA::run (engine::Engine& engine){ // L'IA effectue ces actions uniquement si c'est son tour //sleep(5); State state = engine.getState(); if(state.getPlaying()->getIa()==true){ int randomAction; std::pair<int,int> randomPosition; int randomAttaque; bool premierEssai = true; bool actionPossible=true; bool attaquePossible=true; Player* bot =state.getPlaying(); int randomDirection; int X, Y, range; std::vector<int> attaquesValides; srand(time(NULL)); while ((bot->getHp() > 0) && actionPossible){ clock_t start_time = clock(); while(clock()<start_time+100000); //sleep(1); if(premierEssai == true){ cout<< "\t [Controle par le CPU] " << endl; premierEssai = false; } /* * randomAction: 0 = deplacemnt * 1 = attaque * 2 = fin de tour * */ //to do augementer proba d'action en fct des pm pa restant if (bot->getMovement()==0 && (bot->getSkillCount()==0 || !attaquePossible)){ randomAction = 2; } else if (bot->getMovement()==0 && bot->getSkillCount()>0 && attaquePossible){ randomAction = rand()%2+1 ; } else if (bot->getMovement()>0 && (bot->getSkillCount()==0 || !attaquePossible)){ randomAction = rand()%2; if(randomAction == 1){ randomAction = 2; } } else{randomAction = rand()%3;} //cout<<"Action selectionné :"; // 0 : Cas du deplacement if (randomAction == 0){ //cout<<" déplacement"<<endl; randomDirection=rand()%4; if(randomDirection==0){ randomPosition = {bot->getX(),bot->getY()-1}; }else if(randomDirection==1){ randomPosition = {bot->getX()+1,bot->getY()}; }else if(randomDirection==2){ randomPosition = {bot->getX(),bot->getY()+1}; }else if(randomDirection==3){ randomPosition = {bot->getX()-1,bot->getY()}; } Move* move = new Move(randomPosition); engine.executeCommand(move); } // 1 : Cas de l'attaque else if (randomAction == 1){ //cout<<" attaque"<<endl; std::vector<Skill*> listeAttaques = bot-> getSkills(); for(size_t a=0;a<listeAttaques.size();a++){ if(listeAttaques[a]->getCooldown()<=0){ attaquesValides.push_back(a); } } if (attaquesValides.size() !=0){ //cout<<"attaques valides"<<endl; //choix aléatoire de l'attaque parmi les attaques possibles randomAttaque = attaquesValides[rand()%attaquesValides.size()]; //cout<<"attaque selectionné :"<<listeAttaques[randomAttaque]->getName()<<endl; //choix de la direction aléatoire randomDirection=rand()%4; if(randomDirection==0){ X=0; Y=-1; //cout<<"Direction : Nord"<<endl; }else if(randomDirection==1){ X=1; Y=0; //cout<<"Direction : Est"<<endl; }else if(randomDirection==2){ X=0; Y=1; //cout<<"Direction : Sud"<<endl; }else if(randomDirection==3){ X=-1; Y=0; //cout<<"Direction : Ouest"<<endl; } //choix de la case attaqué (range) aléatoire range=rand()%(listeAttaques[randomAttaque]->getRange().second -listeAttaques[randomAttaque]->getRange().first+1)+listeAttaques[randomAttaque]->getRange().first; randomPosition={bot->getX()+X*range,bot->getY()+Y*range}; // Commande d'attaque Attack* attack = new Attack(randomPosition , randomAttaque); engine.executeCommand(attack); }else{ cout<<"Le CPU n'a pas d'attaque possible"<<endl; attaquePossible=false; } } // 2 : Cas de fin d'actions else if (randomAction == 2){ //cout<<" fin de tour"<<endl; EndActions* endactions = new EndActions(); engine.executeCommand(endactions); actionPossible=false; return 0; } engine.getState().notifyObservers(engine.getState()); } //test verification hors boucle if(actionPossible == false){ cout<< "\t\t-> Action impossible pour le CPU " << bot->getName() << " <-" << endl; } } return 0; }
26.93038
165
0.602115
StevenEnsea
8ccc20dd11a86c904eb27573405378b304d03922
1,915
cpp
C++
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.h" #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <system/collections/list.h> #include <PrimaveraXmlReader.h> #include <cstdint> #include "RunExamples.h" namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace WorkingWithProjects { namespace ImportingAndExporting { RTTI_INFO_IMPL_HASH(681918485u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::ImportingAndExporting::ReadProjectUIDsFromXMLFile, ThisTypeBaseTypesInfo); void ReadProjectUIDsFromXMLFile::Run() { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:ReadProjectUIDsFromXMLFile System::SharedPtr<PrimaveraXmlReader> reader = System::MakeObject<PrimaveraXmlReader>(dataDir + u"Project.xml"); System::SharedPtr<System::Collections::Generic::List<int32_t>> listOpProjectUids = reader->GetProjectUids(); // ExEnd:ReadProjectUIDsFromXMLFile } } // namespace ImportingAndExporting } // namespace WorkingWithProjects } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
36.826923
164
0.784856
aspose-tasks
8ccd54ac424e188603837c89770c80d54353d660
1,638
cpp
C++
Uncategorized/bts16p6.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/bts16p6.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/bts16p6.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; using ll = long long; using stt = pair<pair<int, ll>, pair<int, int>>; const ll mod = 1e9+7; const int MM = 505; int n, m, qt; ll v[MM][MM]; pair<int, ll> dis[MM][MM], ans; array<int, 2> mv[] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; priority_queue<stt> q; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>m>>qt; while(qt--){ ll a, b, c, d, k; cin>>a>>b>>c>>d>>k; v[a][b] += k; v[a][b+d] -= k*(d+1); v[a][b+d+1] += k*(d); v[a+c][b] -= k*(c+1); v[a+c+1][b] += k*(c); v[a+c][b+d] += k*(c+1)*(d+1); v[a+c+1][b+d] -= k*(c)*(d+1); v[a+c][b+d+1] -= k*(c+1)*(d); v[a+c+1][b+d+1] += k*(c)*(d); } for(int t = 0; t < 2; t++){ for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ v[i][j] += v[i-1][j] + v[i][j-1] - v[i-1][j-1]; } } } memset(dis, -0x3f, sizeof dis); int sx, sy; cin>>sx>>sy; q.push({dis[sx][sy] = {1, v[sx][sy]}, {sx, sy}}); while(size(q)){ auto [curd, p] = q.top(); q.pop(); auto [a, b] = p; if(curd < dis[a][b]) continue; ans = max(ans, curd); for(auto [x, y]: mv){ x += a, y += b; if(x and x <= n and y and y <= m and v[x][y] > v[a][b]){ auto nx = curd; nx.first++; nx.second += v[x][y]; if(nx > dis[x][y]){ q.push({dis[x][y] = nx, {x, y}}); } } } } cout<<ans.second%mod<<'\n'; } /* 1 0 0 -4 0 0 0 0 0 0 -3 0 0 12 0 0 0 0 0 0 1 1 1 -3 0 1 1 1 -3 0 -2 -2 -2 -6 0 0 0 0 0 0 1 2 3 0 0 2 4 6 0 0 0 0 0 0 0 0 0 0 0 0 */
18.827586
60
0.413919
crackersamdjam
8ccd7e504d55323da82c84b9662b782c3e668742
2,526
hpp
C++
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
/** * @file oglplus/object/bound.hpp * @brief Operations on currently bound objects * * @author Matus Chochlik * * Copyright 2010-2015 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OGLPLUS_OBJECT_BOUND_1405011014_HPP #define OGLPLUS_OBJECT_BOUND_1405011014_HPP #include <oglplus/object/name.hpp> namespace oglplus { template <typename ObjTag> class BoundObjOps { public: BoundObjOps(void) OGLPLUS_NOEXCEPT(true) { } template <typename X> BoundObjOps(X) OGLPLUS_NOEXCEPT(true) { } }; template <typename ObjTag> class ObjectOps<tag::CurrentBound, ObjTag> : public ObjZeroOps<tag::CurrentBound, ObjTag> , public BoundObjOps<ObjTag> { protected: ObjectOps(ObjectName<ObjTag> name) OGLPLUS_NOEXCEPT(true) : ObjZeroOps<tag::CurrentBound, ObjTag>(name) { } public: typedef typename BoundObjOps<ObjTag>::Target Target; #if !OGLPLUS_NO_DEFAULTED_FUNCTIONS ObjectOps(ObjectOps&&) = default; ObjectOps(const ObjectOps&) = default; ObjectOps& operator = (ObjectOps&&) = default; ObjectOps& operator = (const ObjectOps&) = default; #else typedef ObjZeroOps<tag::CurrentBound, ObjTag> _base1; typedef BoundObjOps<ObjTag> _base2; ObjectOps(ObjectOps&& temp) OGLPLUS_NOEXCEPT(true) : _base1(static_cast<_base1&&>(temp)) , _base2(static_cast<_base2&&>(temp)) { } ObjectOps(const ObjectOps& that) OGLPLUS_NOEXCEPT(true) : _base1(static_cast<const _base1&>(that)) , _base2(static_cast<const _base2&>(that)) { } ObjectOps& operator = (ObjectOps&& temp) OGLPLUS_NOEXCEPT(true) { _base1::operator = (static_cast<_base1&&>(temp)); _base2::operator = (static_cast<_base2&&>(temp)); return *this; } ObjectOps& operator = (const ObjectOps& that) OGLPLUS_NOEXCEPT(true) { _base1::operator = (static_cast<const _base1&>(that)); _base2::operator = (static_cast<const _base2&>(that)); return *this; } #endif }; template <typename ObjTag> class Reference<ObjectOps<tag::CurrentBound, ObjTag>> : public ObjectOps<tag::CurrentBound, ObjTag> { private: typedef ObjectOps<tag::CurrentBound, ObjTag> Base; public: Reference(void) : ObjectOps<tag::CurrentBound, ObjTag>( ObjBindingOps<ObjTag>::Binding() ) { } Reference(typename Base::Target init_tgt) : ObjectOps<tag::CurrentBound, ObjTag>( ObjBindingOps<ObjTag>::Binding(init_tgt) ) { this->target = init_tgt; } }; } // namespace oglplus #endif // include guard
22.756757
68
0.732779
Extrunder
8ccdc0abe43785e2014d73e8172ed2189027dbe4
4,964
cpp
C++
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
1
2019-10-10T12:30:14.000Z
2019-10-10T12:30:14.000Z
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
null
null
null
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
1
2019-10-10T12:52:08.000Z
2019-10-10T12:52:08.000Z
#include <bspch.h> #include "Vec3.h" namespace bs { const vec3 vec3::up(0.0f, 1.0f, 0.0f); const vec3 vec3::down(0.0f, -1.0f, 0.0f); const vec3 vec3::right(1.0f, 0.0f, 0.0f); const vec3 vec3::left(-1.0f, 0.0f, 0.0f); const vec3 vec3::back(0.0f, 0.0f, -1.0f); const vec3 vec3::forward(0.0f, 0.0f, 1.0f); const vec3 vec3::one(1.0f, 1.0f, 1.0f); const vec3 vec3::zero(0.0f, 0.0f, 0.0f); vec3::vec3(const float &x, const float &y, const float &z) : x(x), y(y), z(z) { } vec3::vec3() : x(0), y(0), z(0) { } vec3::~vec3() { } float vec3::magnitude() { return (float)sqrt(this->x * this->x + this->y * this->y + this->z * this->z); } float vec3::sqrMagnitude() { return (float) (this->x * this->x + this->y * this->y + this->z * this->z); } vec3 vec3::normalized() { return *this /= this->magnitude(); } bool vec3::equals(vec3& other) { return *this == other; } vec3& vec3::add(const vec3& other) { this->x += other.x; this->y += other.y; this->z += other.z; return *this; } vec3& vec3::sub(const vec3& other) { this->x -= other.x; this->y -= other.y; this->z -= other.z; return *this; } vec3& vec3::mult(const vec3& other) { this->x *= other.x; this->y *= other.y; this->z *= other.z; return *this; } vec3& vec3::div(const vec3& other) { this->x /= other.x; this->y /= other.y; this->z /= other.z; return *this; } vec3& vec3::add(const float& other) { this->x += other; this->y += other; this->z += other; return *this; } vec3& vec3::sub(const float& other) { this->x -= other; this->y -= other; this->z -= other; return *this; } vec3& vec3::mult(const float& other) { this->x *= other; this->y *= other; this->z *= other; return *this; } vec3& vec3::div(const float& other) { this->x /= other; this->y /= other; this->z /= other; return *this; } vec3& vec3::operator+=(const vec3& other) { return this->add(other); } vec3& vec3::operator-=(const vec3& other) { return this->sub(other); } vec3& vec3::operator*=(const vec3& other) { return this->mult(other); } vec3& vec3::operator/=(const vec3& other) { return this->div(other); } vec3& vec3::operator+=(const float& other) { return this->add(other); } vec3& vec3::operator-=(const float& other) { return this->sub(other); } vec3& vec3::operator*=(const float& other) { return this->mult(other); } vec3& vec3::operator/=(const float& other) { return this->div(other); } bool vec3::operator==(const vec3& other) { return (this->x == other.x && this->y == other.y && this->z == other.z); } bool vec3::operator!=(const vec3& other) { return !(this->x == other.x && this->y == other.y && this->z == other.z); } bool vec3::operator>(vec3& other) { return (this->sqrMagnitude() > other.sqrMagnitude()); } bool vec3::operator<(vec3& other) { return (this->sqrMagnitude() < other.sqrMagnitude()); } bool vec3::operator>=(vec3& other) { return (this->sqrMagnitude() >= other.sqrMagnitude()); } bool vec3::operator<=(vec3& other) { return (this->sqrMagnitude() <= other.sqrMagnitude()); } vec3 operator+(vec3 left, const vec3& right) { return left.add(right); } vec3 operator-(vec3 left, const vec3& right) { return left.sub(right); } vec3 operator*(vec3 left, const vec3& right) { return left.mult(right);; } vec3 operator/(vec3 left, const vec3& right) { return left.div(right);; } vec3 operator+(vec3 left, const float& right) { left.add(right); return left; } vec3 operator-(vec3 left, const float& right) { left.sub(right); return left; } vec3 operator*(vec3 left, const float& right) { left.mult(right); return left; } vec3 operator/(vec3 left, const float& right) { left.div(right); return left; } vec3 operator+(const float& left, vec3 right) { right.add(left); return right; } vec3 operator*(const float& left, vec3 right) { right.mult(left); return right; } std::ostream& operator<<(std::ostream& stream, vec3& vector) { stream << vector.toString(); return stream; } float vec3::dot(const vec3& left, const vec3& right) { return left.x * right.x + left.y * right.y + left.z * left.z; } vec3 vec3::cross(const vec3& left, const vec3& right) { return vec3(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); } float vec3::distance(const vec3& left, const vec3& right) { return (left - right).magnitude(); } float vec3::sqrDistance(const vec3& left, const vec3& right) { return (left - right).sqrMagnitude(); } vec3 vec3::lerp(const vec3& left, const vec3& right, const float& t) { return ((right - left) * t) + left; } std::string vec3::toString() { return "(" + std::to_string(this->x) + " | " + std::to_string(this->y) + " | " + std::to_string(this->z) + ")"; } }
15.368421
125
0.595085
GenTexX
8ccfbe147c1ddb00c6b36131edb47a96d2caf253
16,631
cp
C++
Std/Mod/Stamps.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Std/Mod/Stamps.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Std/Mod/Stamps.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE StdStamps; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) (* StdStamps are used to keep track of document changes, in particular program texts. StdStamps carry a sequence number and a fingerprint of the document with them. Each time the document (and therefore its fingerprint) is changed and stored, the sequence number is incremented. (When determining the fingerprint of the document, whitespace is ignored, except in string literals.) Each StdStamp also keeps track of the history of most recent changes. For the last maxHistoryEntries sequence numbers, the date and time, and an optional one-line comment is stored. To avoid too many entries in the history while working on a module, the most recent history entry is overwritten upon the generation of a new sequence number if the current date is the same as the date in the history entry. *) IMPORT SYSTEM, (* SYSTEM.ROT only, for fingerprint calculation *) Strings, Dates, StdCmds, Ports, Models, Stores, Containers, Properties, Views, Controllers, Fonts, TextModels, TextSetters, TextMappers, TextViews, TextRulers; CONST setCommentKey = "#Std:Set Comment"; maxHistoryEntries = 25; minVersion = 0; origStampVersion = 0; thisVersion = 2; TYPE History = ARRAY maxHistoryEntries OF RECORD fprint, snr: INTEGER; (* fingerprint, sequence number *) date: INTEGER; (* days since 1/1/1 *) time: INTEGER; (* min + 64 * hour *) comment: POINTER TO ARRAY OF CHAR; (* nil if no comment *) END; StdView = POINTER TO RECORD (Views.View) (*--snr: LONGINT;*) nentries: INTEGER; (* number of entries in history *) history: History; (* newest entry in history[0] *) cache: ARRAY 64 OF CHAR; END; SetCmtOp = POINTER TO RECORD (Stores.Operation) stamp: StdView; oldcomment: POINTER TO ARRAY OF CHAR; END; VAR comment*: RECORD s*: ARRAY 64 OF CHAR; END; PROCEDURE (op: SetCmtOp) Do; VAR temp: POINTER TO ARRAY OF CHAR; BEGIN temp := op.stamp.history[0].comment; op.stamp.history[0].comment := op.oldcomment; op.oldcomment := temp; END Do; PROCEDURE Format (v: StdView); VAR s: ARRAY 64 OF CHAR; d: Dates.Date; t: INTEGER; BEGIN t := v.history[0].time; Dates.DayToDate(v.history[0].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); v.cache := s$; Strings.IntToStringForm(v.history[0].snr, Strings.decimal, 4, "0", FALSE, s); v.cache := v.cache + " (" + s + ")" END Format; PROCEDURE FontContext (v: StdView): Fonts.Font; VAR c: Models.Context; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN RETURN c(TextModels.Context).Attr().font; ELSE RETURN Fonts.dir.Default() END; END FontContext; PROCEDURE CalcFP (t: TextModels.Model): INTEGER; CONST sglQuote = "'"; dblQuote = '"'; VAR fp: INTEGER; rd: TextModels.Reader; ch, quoteChar: CHAR; BEGIN quoteChar := 0X; fp := 0; rd := t.NewReader(NIL); rd.ReadChar(ch); WHILE ~rd.eot DO IF ch = quoteChar THEN quoteChar := 0X; ELSIF (quoteChar = 0X) & ((ch = dblQuote) OR (ch = sglQuote)) THEN quoteChar := ch; END; IF (quoteChar = 0X) & (21X <= ch) & (ch # 8BX) & (ch # 8FX) & (ch # 0A0X) (* not in string literal *) OR (quoteChar # 0X) & (20X <= ch) (* within string literal *) THEN fp := SYSTEM.ROT(fp, 1) + 13 * ORD(ch); END; rd.ReadChar(ch); END; RETURN fp; END CalcFP; PROCEDURE Update (v: StdView; forcenew: BOOLEAN); VAR fp: INTEGER; i: INTEGER; ndays: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN IF (v.context # NIL) & (v.context IS TextModels.Context) THEN fp := CalcFP(v.context(TextModels.Context).ThisModel()); IF (fp # v.history[0].fprint) OR forcenew THEN Dates.GetDate(d); Dates.GetTime(t); ndays := Dates.Day(d); IF (ndays # v.history[0].date) OR forcenew THEN (* move down entries in history list *) i := maxHistoryEntries-1; WHILE i > 0 DO v.history[i] := v.history[i-1]; DEC(i); END; v.history[0].comment := NIL; END; IF v.nentries < maxHistoryEntries THEN INC(v.nentries) END; INC(v.history[0].snr); v.history[0].fprint := fp; v.history[0].date := ndays; v.history[0].time := t.minute + t.hour*64; Format(v); Views.Update(v, Views.keepFrames); END; END; END Update; PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer); VAR i, len: INTEGER; BEGIN Update(v, FALSE); v.Externalize^(wr); wr.WriteVersion(thisVersion); (*--wr.WriteLInt(v.snr);*) wr.WriteXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO wr.WriteInt(v.history[i].fprint); wr.WriteInt(v.history[i].snr); wr.WriteInt(v.history[i].date); wr.WriteXInt(v.history[i].time); IF v.history[i].comment # NIL THEN len := LEN(v.history[i].comment$); wr.WriteXInt(len); wr.WriteXString(v.history[i].comment^); ELSE wr.WriteXInt(0); END END; END Externalize; PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader); VAR version: INTEGER; format: BYTE; i, len: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(minVersion, thisVersion, version); IF ~rd.cancelled THEN IF version = origStampVersion THEN (* deal with old StdStamp format *) (* would like to calculate fingerprint, but hosting model not available at this time *) v.history[0].fprint := 0; v.history[0].snr := 1; v.nentries := 1; rd.ReadXInt(d.year); rd.ReadXInt(d.month); rd.ReadXInt(d.day); rd.ReadXInt(t.hour); rd.ReadXInt(t.minute); rd.ReadXInt(t.second); rd.ReadByte(format); (* format not used anymore *) v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; ELSE IF version = 1 THEN rd.ReadInt(v.history[0].snr) END; (* red text: to be removed soon *) rd.ReadXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO rd.ReadInt(v.history[i].fprint); IF version > 1 THEN rd.ReadInt(v.history[i].snr) ELSIF (* (version = 1) & *) i > 0 THEN v.history[i].snr := v.history[i-1].snr - 1; END; (* red text: to be removed soon *) rd.ReadInt(v.history[i].date); rd.ReadXInt(v.history[i].time); rd.ReadXInt(len); IF len > 0 THEN NEW(v.history[i].comment, len + 1); rd.ReadXString(v.history[i].comment^); ELSE v.history[i].comment := NIL; END END; END; Format(v); END END END Internalize; PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View); VAR i: INTEGER; BEGIN (* v.CopyFrom^(source); *) WITH source: StdView DO (*--v.snr := source.snr;*) v.nentries := source.nentries; v.history := source.history; v.cache := source.cache; FOR i := 0 TO v.nentries - 1 DO IF source.history[i].comment # NIL THEN NEW(v.history[i].comment, LEN(source.history[i].comment$) + 1); v.history[i].comment^ := source.history[i].comment^$; END END END END CopyFromSimpleView; PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font; asc, dsc, fw: INTEGER; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := v.context(TextModels.Context).Attr(); font := a.font; color := a.color; ELSE font := Fonts.dir.Default(); color := Ports.black; END; font.GetBounds(asc, dsc, fw); f.DrawLine(f.l, asc + f.dot, f.r, asc + f.dot, 1, Ports.grey25 ); f.DrawString(0, asc, color, v.cache, font); END Restore; PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref); VAR font: Fonts.Font; asc, dsc, w: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; BEGIN font := FontContext(v); font.GetBounds(asc, dsc, w); d.day := 28; d.month := 1; d.year := 2222; p.w := 0; WHILE d.month <= 12 DO Dates.DateToString(d, Dates.plainAbbreviated, s); s := s + " (0000)"; w := font.StringWidth(s); IF w > p.w THEN p.w := w END; INC(d.month) END; p.h := asc + dsc; END SizePref; PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message); VAR font: Fonts.Font; asc, w: INTEGER; BEGIN WITH msg: Properties.Preference DO WITH msg: Properties.SizePref DO SizePref(v, msg) | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: TextSetters.Pref DO font := FontContext(v); font.GetBounds(asc, msg.dsc, w); ELSE END ELSE END END HandlePropMsg; PROCEDURE NewRuler (): TextRulers.Ruler; CONST mm = Ports.mm; VAR r: TextRulers.Ruler; BEGIN r := TextRulers.dir.New(NIL); TextRulers.SetRight(r, 140 * mm); TextRulers.AddTab(r, 15 * mm); TextRulers.AddTab(r, 35 * mm); TextRulers.AddTab(r, 75 * mm); RETURN r END NewRuler; PROCEDURE ShowHistory (v: StdView); VAR text: TextModels.Model; f: TextMappers.Formatter; i: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; tv: TextViews.View; attr: TextModels.Attributes; BEGIN text := TextModels.dir.New(); f.ConnectTo(text); attr := f.rider.attr; f.rider.SetAttr(TextModels.NewStyle(attr, {Fonts.italic})); f.WriteString("seq nr."); f.WriteTab; f.WriteString("fingerprint"); f.WriteTab; f.WriteString("date and time"); f.WriteTab; f.WriteString("comment"); f.WriteLn; f.rider.SetAttr(attr); f.WriteLn; (*--n := v.snr;*) FOR i := 0 TO v.nentries-1 DO f.WriteIntForm(v.history[i].snr, 10, 4, "0", FALSE); (*--DEC(n);*) f.WriteTab; f.WriteIntForm(v.history[i].fprint, TextMappers.hexadecimal, 8, "0", FALSE); f.WriteTab; Dates.DayToDate(v.history[i].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); f.WriteString(s); f.WriteString(" "); f.WriteIntForm(v.history[i].time DIV 64, 10, 2, "0", FALSE); f.WriteString(":"); f.WriteIntForm(v.history[i].time MOD 64, 10, 2, "0", FALSE); IF v.history[i].comment # NIL THEN f.WriteTab; f.WriteString( v.history[i].comment^); END; f.WriteLn; END; tv := TextViews.dir.New(text); tv.SetDefaults(NewRuler(), TextViews.dir.defAttr); tv.ThisController().SetOpts({Containers.noFocus, Containers.noCaret}); Views.OpenAux(tv, "History"); END ShowHistory; PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET); VAR c: Models.Context; w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET; BEGIN c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE; REPEAT IF in # in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in END; f.Input(x, y, m, isDown); in := (0 <= x) & (x < w) & (0 <= y) & (y < h) UNTIL ~isDown; IF in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide); IF Controllers.modify IN m THEN IF v.history[0].comment # NIL THEN comment.s := v.history[0].comment^$; ELSE comment.s := ""; END; StdCmds.OpenToolDialog("Std/Rsrc/Stamps", "Comment"); ELSE ShowHistory(v); END END END Track; PROCEDURE (v: StdView) HandleCtrlMsg ( f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Controllers.TrackMsg DO Track(v, f, msg.x, msg.y, msg.modifiers) | msg: Controllers.PollCursorMsg DO msg.cursor := Ports.refCursor ELSE END END HandleCtrlMsg; (* ------------ programming interface: ---------------------- *) PROCEDURE GetFirstInText* (t: TextModels.Model): Views.View; VAR r: TextModels.Reader; v: Views.View; BEGIN IF t # NIL THEN r := t.NewReader(NIL); REPEAT r.ReadView(v) UNTIL (v = NIL) OR (v IS StdView); RETURN v; ELSE RETURN NIL; END; END GetFirstInText; PROCEDURE IsStamp* (v: Views.View): BOOLEAN; BEGIN RETURN v IS StdView; END IsStamp; PROCEDURE GetInfo* (v: Views.View; VAR snr, historylen: INTEGER); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO snr := v.history[0].snr; historylen := v.nentries; END END GetInfo; PROCEDURE GetData* (v: Views.View; entryno: INTEGER; VAR fprint: INTEGER; VAR date: Dates.Date; VAR time: Dates.Time); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO IF entryno <= v.nentries THEN fprint := v.history[entryno].fprint; Dates.DayToDate(v.history[entryno].date, date); time.minute := v.history[entryno].time MOD 64; time.minute := v.history[entryno].time DIV 64; time.second := 0; END END END GetData; (** Insert new history entry with comment in v. *) PROCEDURE Stamp* (v: Views.View; comment: ARRAY OF CHAR); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO Update(v, TRUE); NEW(v.history[0].comment, LEN(comment$) + 1); v.history[0].comment^ := comment$; END END Stamp; PROCEDURE New* (): Views.View; VAR v: StdView; d: Dates.Date; t: Dates.Time; BEGIN NEW(v); v.history[0].snr := 0; v.nentries := 0; v.history[0].fprint := 0; Dates.GetDate(d); Dates.GetTime(t); v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; Format(v); RETURN v; END New; PROCEDURE SetComment*; VAR v: Views.View; op: SetCmtOp; BEGIN v := GetFirstInText(TextViews.FocusText()); IF v # NIL THEN WITH v: StdView DO NEW(op); op.stamp := v; NEW(op.oldcomment, LEN(comment.s$) + 1); op.oldcomment^ := comment.s$; Views.Do(v, setCommentKey, op); END END END SetComment; PROCEDURE Deposit*; BEGIN Views.Deposit(New()) END Deposit; END StdStamps.
37.373034
113
0.52793
romiras
8cd19462045c53dbfb213caad447eb6ab19d1fa9
305
hpp
C++
include/properties/properties.hpp
Voltra/CppProperties
fe63c7394d764ecafea17c570185139f5cb69a78
[ "MIT" ]
null
null
null
include/properties/properties.hpp
Voltra/CppProperties
fe63c7394d764ecafea17c570185139f5cb69a78
[ "MIT" ]
null
null
null
include/properties/properties.hpp
Voltra/CppProperties
fe63c7394d764ecafea17c570185139f5cb69a78
[ "MIT" ]
null
null
null
#pragma once /** * @namespace props * @brief Root namespace containing property classes */ namespace props{} #include <properties/property.h> #include <properties/readonly.h> #include <properties/Prop.h> #include <properties/ReadProp.h> #include <properties/WriteProp.h> #include <properties/utils.h>
21.785714
52
0.757377
Voltra
8cd1a5a4bf62b3720695a9a12beaaee08decda9d
1,357
cpp
C++
emulator/src/mame/video/tutankhm.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/video/tutankhm.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/video/tutankhm.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Mirko Buffoni /*************************************************************************** video.c Functions to emulate the video hardware of the machine. ***************************************************************************/ #include "emu.h" #include "includes/tutankhm.h" /************************************* * * Write handlers * *************************************/ WRITE_LINE_MEMBER(tutankhm_state::flip_screen_x_w) { m_flip_x = state; } WRITE_LINE_MEMBER(tutankhm_state::flip_screen_y_w) { m_flip_y = state; } /************************************* * * Video update * *************************************/ uint32_t tutankhm_state::screen_update_tutankhm(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xorx = m_flip_x ? 255 : 0; int xory = m_flip_y ? 255 : 0; for (int y = cliprect.min_y; y <= cliprect.max_y; y++) { uint32_t *dst = &bitmap.pix32(y); for (int x = cliprect.min_x; x <= cliprect.max_x; x++) { uint8_t effx = x ^ xorx; uint8_t yscroll = (effx < 192 && m_scroll.found()) ? *m_scroll : 0; uint8_t effy = (y ^ xory) + yscroll; uint8_t vrambyte = m_videoram[effy * 128 + effx / 2]; uint8_t shifted = vrambyte >> (4 * (effx % 2)); dst[x] = m_palette->pen_color(shifted & 0x0f); } } return 0; }
22.245902
119
0.512159
rjw57
8cd4fd710f3c18a8622b605dc0e595f513b4ca51
354
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
#using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Serialization; // <Snippet1> public ref class Car { public: [XmlAttributeAttribute(Namespace="Make")] String^ MakerName; [XmlAttributeAttribute(Namespace="Model")] String^ ModelName; }; // </Snippet1>
15.391304
45
0.723164
BaruaSourav
8cd69161a48a2981e3173a0b39c7f7fce5fbda19
28
cpp
C++
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
#include "FootCommander.hpp"
28
28
0.821429
amit1021
8cda95fd83e580f2cd1abf917f21598d4332a6a2
1,589
hpp
C++
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
1
2019-05-20T16:47:28.000Z
2019-05-20T16:47:28.000Z
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
#ifndef CONFIG_HPP #define CONFIG_HPP #include <QSettings> #include <QMap> #define CONFIG_SLEEP_STR "watcher_sleep_ms" #define CONFIG_START_MIN_STR "start_minimized" #define CONFIG_ENABLED_STR "enabled" #define CONFIG_AUTOHIDE_STR "autohide" #define CONFIG_TRAY_INFO_SHOWN "tray_icon_warning_shown" #define CONFIG_DEFAULT_PROFILE_STR "default" using DVC_map = QMap<int,int>; class Config : public QSettings { public: Config() noexcept; QVariant getValue(const QString &key, const QVariant &defaultValue = QVariant()) const noexcept; void setValue(const QString &key, const QVariant &value) noexcept; QStringList queryProfiles() noexcept; bool get_bool(const QString &attribute) { return getValue(attribute).toBool(); } bool set_bool(const QString &attribute, bool val) { setValue(attribute, val); return val; } bool toggle_bool(const QString &attribute) { return set_bool(attribute, !get_bool(attribute)); } QString queryIconPath(const QString &profile_name) noexcept; void setIconPath(const QString &profile_name, const QString &path) noexcept; DVC_map queryDVC(const QString &profile_name) noexcept; void setDVC(const QString &profile_name, DVC_map &map) noexcept; unsigned querySleepTime_ms(void) noexcept; void setSleepTime_ms(unsigned ms) noexcept; void removeProfile(const QString &key) noexcept; }; #endif // CONFIG_HPP
29.425926
104
0.674638
tpruzina
8cdb79234c0934d62035d0a852b2e11fc2917b3e
3,019
hpp
C++
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
9
2019-10-23T15:00:06.000Z
2021-04-02T01:45:26.000Z
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
null
null
null
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
5
2020-04-30T03:45:13.000Z
2021-11-25T05:28:16.000Z
// Copyright (c) 2019 AutonomouStuff, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef MESSAGE_HPP_ #define MESSAGE_HPP_ #include "common_defs.hpp" #include "bus_node.hpp" #include "comment.hpp" #include "signal.hpp" #include <memory> #include <string> #include <unordered_map> #include <vector> namespace AS { namespace CAN { namespace DbcLoader { class Message : public DbcObj, public AttrObj { public: Message(std::string && dbc_text); Message( unsigned int id, std::string && name, unsigned char dlc, BusNode && transmitting_node, std::vector<Signal> && signals); ~Message() = default; Message(const Message & other); Message(Message && other) = default; Message & operator=(const Message & other); Message & operator=(Message && other) = default; unsigned int getId() const; std::string getName() const; unsigned char getDlc() const; unsigned char getLength() const; BusNode getTransmittingNode() const; std::unordered_map<std::string, const Signal *> getSignals() const; const std::string * getComment() const; static unsigned char dlcToLength(const unsigned char & dlc); friend class Database; friend class MessageTranscoder; private: unsigned int id_; std::string name_; unsigned char dlc_; BusNode transmitting_node_; std::unordered_map<std::string, Signal> signals_; std::unique_ptr<std::string> comment_; void generateText() override; void parse() override; }; class MessageTranscoder { public: MessageTranscoder(Message * dbc_msg); const Message * getMessageDef(); void decode(std::vector<uint8_t> && raw_data, TranscodeError * err = nullptr); std::vector<uint8_t> encode(TranscodeError * err = nullptr); private: void decodeRawData(TranscodeError * err); Message * msg_def_; std::vector<uint8_t> data_; std::unordered_map<std::string, SignalTranscoder> signal_xcoders_; }; } // namespace DbcLoader } // namespace CAN } // namespace AS #endif // MESSAGE_HPP_
28.752381
80
0.735012
astuff
8ce13ff806babb1ef5d71e52db54a76d89500c3b
1,373
cpp
C++
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
6
2019-02-11T09:50:45.000Z
2021-07-31T03:27:11.000Z
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
null
null
null
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
1
2021-04-25T12:31:03.000Z
2021-04-25T12:31:03.000Z
#include "DropoutLayer.hpp" namespace mario { DropoutLayer::DropoutLayer(const int &_lastNeuronNum, const double &_p) { m_p = _p; m_in = matrix(1, _lastNeuronNum, 0); m_mul = matrix(1, _lastNeuronNum, 0); m_out = matrix(1, _lastNeuronNum, 0); m_dx = matrix(1, _lastNeuronNum, 0); } const matrix& DropoutLayer::forward(const matrix &_lastOut) { if (_lastOut.cols() != m_in.cols()) { throw "Error in DropoutLayer::forward(): _lastOut.cols() != m_in.cols()."; } m_in.release(); m_in = _lastOut; #if 1==TRAIN matrix deleteMul(1, m_in.cols(), 0); for (int c = 0; c < deleteMul.cols(); ++c) { if (isDelete()) { deleteMul.set(0, c, 0); } else { deleteMul.set(0, c, 1); } } #endif // 1==TRAIN #if 0==TRAIN matrix deleteMul(1, m_in.cols(), 1); #endif // 0==TRAIN m_mul.release(); m_mul = copyRow(deleteMul, _lastOut.rows()); m_out.release(); m_out = m_mul.mul(_lastOut); return m_out; } const matrix& DropoutLayer::backward(const matrix &_nextDerr) { if (m_dx.cols() != _nextDerr.cols()) { throw "Error in DropoutLayer::backward(): m_dx.cols() != _nextDerr.cols().\n"; } m_dx.release(); m_dx = m_mul.mul(_nextDerr); return m_dx; } bool DropoutLayer::isDelete() { double p = rand() / double(RAND_MAX); if (p < m_p) { return true; } return false; } }
16.152941
81
0.612527
xiaohuihuichao
8ce148dd152c96d19575fb5d72ab2552238fa455
3,835
cpp
C++
src/inference/src/check_network_batchable.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/inference/src/check_network_batchable.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/inference/src/check_network_batchable.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
#include "check_network_batchable.hpp" #include "dimension_tracker.hpp" #include "ie_ngraph_utils.hpp" #include "ngraph/opsets/opset.hpp" #include "openvino/op/detection_output.hpp" #include "openvino/op/ops.hpp" #include "openvino/pass/manager.hpp" #include "transformations/common_optimizations/dimension_tracking.hpp" #include "transformations/init_node_info.hpp" namespace InferenceEngine { namespace details { NetworkBatchAbility isNetworkBatchable(const CNNNetwork& orig_network, const std::string& deviceNameWithoutBatch, bool strictly_track_dims) { CNNNetwork clonedNetwork(cloneNetwork(orig_network)); auto function = clonedNetwork.getFunction(); // find the batch dim ov::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::pass::FindBatch>(true, strictly_track_dims); m.run_passes(function); bool any_batched_inputs = false; // do not reshape/re-batch originally batched networks and when there are no inputs with the N* layouts // input(s) should have the batch dim as the first dim or none (current limitation of the auto-batching impl) const auto& params = function->get_parameters(); for (size_t input_id = 0; input_id < params.size(); input_id++) { const auto& input = params[input_id]; const auto& shape = input->get_partial_shape(); // currently no plugin support batched execution for dynamic networks if (shape.is_dynamic()) return NetworkBatchAbility::NO; // check the batch dim: either 0th (and the original batch size of 1) or none if (shape.size() && ov::DimensionTracker::get_label(shape[0])) { const auto& static_shape = input->get_shape(); if (static_shape[0] != 1) return NetworkBatchAbility::NO; else any_batched_inputs = true; } else { // if the 0-th dim is not for the batch, then we support only the case when NONE dimension is batch for (size_t s = 1; s < shape.size(); s++) if (ov::DimensionTracker::get_label(shape[s])) return NetworkBatchAbility::NO; } } if (!any_batched_inputs) return NetworkBatchAbility::NO; for (auto&& node : orig_network.getFunction()->get_ops()) node->get_rt_info()["affinity"] = "BATCH"; // default affinity (ignored if HETERO is not triggered) // have to execute the DetectionOutput separately (without batching) // as this layer does mix-in the values from the different inputs (batch id) bool bDetectionOutput = false; for (auto& result_node : orig_network.getFunction()->get_results()) { auto do_node = result_node->input_value(0).get_node_shared_ptr(); std::shared_ptr<ov::Node> convert_node; if (ov::is_type<ov::opset1::Convert>(do_node)) { // cases with do->convert->result convert_node = do_node; do_node = convert_node->get_input_node_shared_ptr(0); } // the code below doesn't need to separate the versions (opsets) of the DetectionOutput // so base class check is enough auto detectionOutputBase = std::dynamic_pointer_cast<ov::op::util::DetectionOutputBase>(do_node); if (detectionOutputBase) { result_node->get_rt_info()["affinity"] = deviceNameWithoutBatch; do_node->get_rt_info()["affinity"] = deviceNameWithoutBatch; if (convert_node) convert_node->get_rt_info()["affinity"] = deviceNameWithoutBatch; bDetectionOutput = true; } } return bDetectionOutput ? NetworkBatchAbility::WITH_HETERO : NetworkBatchAbility::AS_IS; } } // namespace details } // namespace InferenceEngine
48.544304
113
0.663625
ryanloney
8ce6ba6e115cf9ff1876a9f7781287efc9c78fdc
7,398
cpp
C++
Labs/Puppeteer/src/main.cpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/Puppeteer/src/main.cpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/Puppeteer/src/main.cpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
#include "NeheGL.h" #include "app.h" #define WM_TOGGLEFULLSCREEN (WM_USER+1) // Application Define Message For Toggling static BOOL g_isProgramLooping; // Window Creation Loop, For FullScreen/Windowed Toggle // Between Fullscreen / Windowed Mode static BOOL g_createFullScreen; // If TRUE, Then Create Fullscreen App* g_App = NULL; LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) { case WM_DROPFILES: { if (g_App) { HDROP fDrop = (HDROP) wParam; int dropped_file_count = DragQueryFileA(fDrop, 0xFFFFFFFF, NULL, 0); char* fName = NULL; int buffer_size = 0; g_App->OnFilesDropped(dropped_file_count); for (int i=0; i<dropped_file_count; ++i) { UINT nBufSize = 1 + DragQueryFileA(fDrop, i, NULL, 0); if (nBufSize > buffer_size) { buffer_size = nBufSize; delete fName; fName = new char[buffer_size]; } DragQueryFileA(fDrop, i, fName, buffer_size); g_App->OnFileDropped(fName); } delete fName; DragFinish(fDrop); } return 0; } break; } return NeheGLWindowProc(hWnd,uMsg,wParam,lParam); } BOOL RegisterWindowClass (Application* application) // Register A Window Class For This Application. { // TRUE If Successful // Register A Window Class WNDCLASSEXA windowClass; // Window Class ZeroMemory (&windowClass, sizeof (WNDCLASSEXA)); // Make Sure Memory Is Cleared windowClass.cbSize = sizeof (WNDCLASSEXA); // Size Of The windowClass Structure windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraws The Window For Any Movement / Resizing windowClass.lpfnWndProc = (WNDPROC)(WndProc); // WindowProc Handles Messages windowClass.hInstance = application->hInstance; // Set The Instance windowClass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE); // Class Background Brush Color windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer windowClass.lpszClassName = application->className; // Sets The Applications Classname if (RegisterClassExA (&windowClass) == 0) // Did Registering The Class Fail? { // NOTE: Failure, Should Never Happen MessageBoxA (HWND_DESKTOP, "RegisterClassEx Failed!", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return False (Failure) } return TRUE; // Return True (Success) } int main() { Application application; // Application Structure GL_Window window; // Window Structure Keys keys; // Key Structure BOOL isMessagePumpActive; // Message Pump Active? MSG msg; // Window Message Structure DWORD tickCount; // Used For The Tick Counter // Fill Out Application Data application.className = "Puppeteer"; // Application Class Name application.hInstance = GetModuleHandle(NULL); // Application Instance // Fill Out Window ZeroMemory (&window, sizeof (GL_Window)); // Make Sure Memory Is Zeroed window.keys = &keys; // Window Key Structure window.init.application = &application; // Window Application window.init.title = "Puppeteer"; // Window Title window.init.width = 800; // Window Width window.init.height = 600; // Window Height window.init.bitsPerPixel = 32; // Bits Per Pixel window.init.isFullScreen = FALSE; // Fullscreen? (Set To TRUE) ZeroMemory (&keys, sizeof (Keys)); // Zero keys Structure // Ask The User If They Want To Start In FullScreen Mode? //if (MessageBoxA (HWND_DESKTOP, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) //{ // window.init.isFullScreen = FALSE; // If Not, Run In Windowed Mode //} // Register A Class For Our Window To Use if (RegisterWindowClass (&application) == FALSE) // Did Registering A Class Fail? { // Failure MessageBoxA (HWND_DESKTOP, "Error Registering Window Class!", "Error", MB_OK | MB_ICONEXCLAMATION); return -1; // Terminate Application } g_isProgramLooping = TRUE; // Program Looping Is Set To TRUE g_createFullScreen = window.init.isFullScreen; // g_createFullScreen Is Set To User Default App app; //while (g_isProgramLooping) // Loop Until WM_QUIT Is Received { // Create A Window window.init.isFullScreen = g_createFullScreen; // Set Init Param Of Window Creation To Fullscreen? if (CreateWindowGL (&window) == TRUE) // Was Window Creation Successful? { // At This Point We Should Have A Window That Is Setup To Render OpenGL if (!app.Load(&window)) // Call User Intialization { // Failure TerminateApplication (&window); // Close Window, This Will Handle The Shutdown } else // Otherwise (Start The Message Pump) { g_App = &app; DragAcceptFiles(window.hWnd, TRUE); // Initialize was a success isMessagePumpActive = TRUE; // Set isMessagePumpActive To TRUE while (isMessagePumpActive == TRUE) // While The Message Pump Is Active { // Success Creating Window. Check For Window Messages if (PeekMessage (&msg, window.hWnd, 0, 0, PM_REMOVE) != 0) { // Check For WM_QUIT Message if (msg.message != WM_QUIT) // Is The Message A WM_QUIT Message? { DispatchMessage (&msg); // If Not, Dispatch The Message } else // Otherwise (If Message Is WM_QUIT) { isMessagePumpActive = FALSE; // Terminate The Message Pump } } else // If There Are No Messages { //if (window.isVisible == FALSE) // If Window Is Not Visible //{ // WaitMessage (); // Application Is Minimized Wait For A Message //} //else // If Window Is Visible { // Process Application Loop tickCount = GetTickCount (); // Get The Tick Count app.Update (tickCount - window.lastTickCount); // Update The Counter window.lastTickCount = tickCount; // Set Last Count To Current Count app.Draw(); // Draw Our Scene SwapBuffers (window.hDC); // Swap Buffers (Double Buffering) } } } // Loop While isMessagePumpActive == TRUE } // If (Initialize (... // Application Is Finished app.End(); //Deinitialize (); // User Defined DeInitialization g_App = NULL; DestroyWindowGL (&window); // Destroy The Active Window } else // If Window Creation Failed { // Error Creating Window MessageBoxA (HWND_DESKTOP, "Error Creating OpenGL Window", "Error", MB_OK | MB_ICONEXCLAMATION); g_isProgramLooping = FALSE; // Terminate The Loop } } // While (isProgramLooping) UnregisterClassA (application.className, application.hInstance); // UnRegister Window Class return 0; }
37.744898
153
0.620843
jadnohra
8ce85cbe115c3eaf335aec9520d6771c5923f882
2,306
cpp
C++
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2009 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #include <vaca/vaca.h> #include "../resource.h" using namespace vaca; ////////////////////////////////////////////////////////////////////// class ScrollableTest : public ScrollableWidget { // true if we have to wait some milliseconds after update the // invalidated area bool m_sleep; public: ScrollableTest(Widget* parent) : ScrollableWidget(parent) , m_sleep(false) { setFullSize(Size(2000, 1500)); // the red color will be used to erase the background of // invalidated area, but in onPaint the red will be re-erased with // a white brush setBgColor(Color::Red); } void setSleep(bool sleep) { m_sleep = sleep; } protected: virtual void onPaint(PaintEvent& ev) { Graphics& g = ev.getGraphics(); // this sleep have the purpose to show the invalidated areas 100 // milliseconds (the background filled by default with the // getBgColor, that in this case is Color::Red) if (m_sleep) CurrentThread::sleep(100); // draw the (white) background Brush brush(Color::White); g.fillRect(brush, getClientBounds()); // draw the shapes (ellipses and round-rectangles) Pen pen(Color::Blue); Point offset = -getScrollPoint(); for (int r=0; r<10; ++r) { Rect rc(offset, getFullSize()); rc.shrink(50 * r); g.drawEllipse(pen, rc); g.drawRoundRect(pen, rc, Size(32, 32)); } } }; ////////////////////////////////////////////////////////////////////// void updateSleep(ScrollableTest* s, CheckBox* cb) { s->setSleep(cb->isSelected()); } int VACA_MAIN() { Application app; Frame frm(L"Scrolling"); ScrollableTest wgt(&frm); CheckBox sleep(L"Show invalidated areas for some milliseconds", &frm); sleep.Click.connect(Bind<void>(&updateSleep, &wgt, &sleep)); wgt.setConstraint(new BoxConstraint(true)); frm.setLayout(new BoxLayout(Orientation::Vertical, false)); frm.setIcon(ResourceId(IDI_VACA)); frm.setVisible(true); app.run(); return 0; }
24.531915
73
0.606678
picrap
8ce922f71f5ddd81ed293609b080050c360b16e3
708
cpp
C++
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <algorithm> #include <array> #include <iostream> using integer = long long; template <typename T, size_t N> std::istream& operator >>(std::istream& input, std::array<T, N>& v) { for (T& a : v) input >> a; return input; } void answer(integer v) { std::cout << v << '\n'; } void solve(std::array<integer, 3>& v) { std::sort(v.begin(), v.end()); const integer d = std::min(v[1] - v[0], v[2]); v[0] += d; v[2] -= d; answer(v[0] < v[1] ? v[0] : v[0] + v[2] / 2); } void test_case() { std::array<integer, 3> v; std::cin >> v; solve(v); } int main() { size_t t; std::cin >> t; while (t-- > 0) test_case(); return 0; }
14.16
67
0.507062
actium
8ce9b13579ba3a267f73417c070ea22855259089
19,164
cpp
C++
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
5
2016-04-18T23:12:51.000Z
2022-03-06T05:12:07.000Z
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
2
2015-10-09T19:13:25.000Z
2018-12-25T17:16:54.000Z
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
15
2015-02-23T16:35:28.000Z
2022-03-25T13:40:33.000Z
/* * vfspluginVP: Generic GUCEF VFS plugin for "Violation Pack" archives * Copyright (C) 2002 - 2008. Dinand Vanvelzen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #include <string.h> #ifndef GUCEF_CORE_DVMD5UTILS_H #include "dvmd5utils.h" #define GUCEF_CORE_DVMD5UTILS_H #endif /* GUCEF_CORE_DVMD5UTILS_H ? */ #ifndef GUCEF_CORE_CDYNAMICBUFFER_H #include "CDynamicBuffer.h" #define GUCEF_CORE_CDYNAMICBUFFER_H #endif /* GUCEF_CORE_CDYNAMICBUFFER_H ? */ #ifndef GUCEF_CORE_CDYNAMICBUFFERACCESS_H #include "CDynamicBufferAccess.h" #define GUCEF_CORE_CDYNAMICBUFFERACCESS_H #endif /* GUCEF_CORE_CDYNAMICBUFFERACCESS_H ? */ #ifndef GUCEF_CORE_CSUBFILEACCESS_H #include "gucefCORE_CSubFileAccess.h" #define GUCEF_CORE_CSUBFILEACCESS_H #endif /* GUCEF_CORE_CSUBFILEACCESS_H ? */ #ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H #include "dvcppstringutils.h" #define GUCEF_CORE_DVCPPSTRINGUTILS_H #endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */ #include "vfspluginVP_CVPArchive.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace VFSPLUGIN { namespace VP { /*-------------------------------------------------------------------------// // // // TYPES // // // //-------------------------------------------------------------------------*/ struct SVPFileIndexEntry { VFS::UInt32 offset; VFS::UInt32 size; char filename[ 32 ]; VFS::Int32 timestamp; }; typedef struct SVPFileIndexEntry TVPFileIndexEntry; /*-------------------------------------------------------------------------// // // // CONSTANTS // // // //-------------------------------------------------------------------------*/ #define VP_HEADER_SIZE 16 #define VP_INDEX_ENTRY_SIZE 44 /*-------------------------------------------------------------------------// // // // GLOBAL VARS // // // //-------------------------------------------------------------------------*/ const VFS::CString CVPArchive::VPArchiveTypeName = "vp"; /*-------------------------------------------------------------------------// // // // UTILITIES // // // //-------------------------------------------------------------------------*/ CVPArchive::CVPArchive( void ) : CArchive() , m_header() , m_index() , m_archiveName() , m_archivePath() {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ CVPArchive::~CVPArchive() {GUCEF_TRACE; UnloadArchive(); } /*-------------------------------------------------------------------------*/ VFS::CArchive::CVFSHandlePtr CVPArchive::GetFile( const VFS::CString& file , const char* mode , const VFS::UInt32 memLoadSize , const bool overwrite ) {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to get file: " + file ); // We only support read only modes if ( *mode != 'r' ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to support requested file access mode for file: " + file ); return CVFSHandlePtr(); } // load the file CORE::CIOAccess* fileAccess = LoadFile( file, memLoadSize ); if ( NULL != fileAccess ) { // create a handle for the file VFS::CString filePath = m_archivePath; CORE::AppendToPath( filePath, file ); VFS::CVFSHandle* fileHandle = new VFS::CVFSHandle( fileAccess , file , filePath ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: providing access to file: " + file ); return CVFSHandlePtr( fileHandle, this ); } GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to provide access to file: " + file ); return CVFSHandlePtr(); } /*-------------------------------------------------------------------------*/ bool CVPArchive::DeleteFile( const VFS::CString& filePath ) {GUCEF_TRACE; // Not implemented / supported at this time return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::StoreAsFile( const CORE::CString& filepath , const CORE::CDynamicBuffer& data , const CORE::UInt64 offset , const bool overwrite ) {GUCEF_TRACE; // Not implemented / supported at this time return false; } /*-------------------------------------------------------------------------*/ void CVPArchive::GetList( TStringSet& outputList , const VFS::CString& mountLocation , const VFS::CString& archiveLocation , bool recursive , bool includePathInFilename , const VFS::CString& filter , bool addFiles , bool addDirs ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.begin(); while ( i != m_index.end() ) { // Check if the starting path matches const VFS::CString& filePath = (*i).first; if ( filePath == archiveLocation ) { // Don't add the location itself to the list ++i; continue; } if ( 0 == filePath.HasSubstr( archiveLocation, true ) ) { const TVPIndexEntry& indexEntry = (*i).second; // Check if the entry is a directory if ( indexEntry.size == 0 || indexEntry.offset == 0 ) { if ( !addDirs ) { // Skip this item ++i; continue; } } else { if ( !addFiles ) { // Skip this item ++i; continue; } } if ( !recursive ) { // Check if we have multiple subdirs beyond the "location" to get to // the archive. If so then we cannot add this archive because recursive // searching is not allowed. if ( !CORE::IsFileInDir( archiveLocation, filePath ) ) { // The directory seperator was not the last character so we have multiple // sub-dirs which is not allowed, we cannot add this item ++i; continue; } } VFS::CString filename = CORE::ExtractFilename( filePath ); if ( filename != ".." ) { if ( includePathInFilename ) { outputList.insert( filePath ); } else { outputList.insert( filename ); } } } ++i; } } /*-------------------------------------------------------------------------*/ bool CVPArchive::FileExists( const VFS::CString& filePath ) const {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to check if file exists: " + filePath ); return m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ) != m_index.end(); } /*-------------------------------------------------------------------------*/ VFS::UInt32 CVPArchive::GetFileSize( const VFS::CString& filePath ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { return (*i).second.size; } return 0; } /*-------------------------------------------------------------------------*/ CORE::CIOAccess* CVPArchive::LoadFile( const VFS::CString& file , const VFS::UInt32 memLoadSize ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( file.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { const TVPIndexEntry& entry = (*i).second; if ( memLoadSize >= entry.size ) { FILE* fptr = fopen( m_archivePath.C_String(), "rb" ); if ( NULL == fptr ) return NULL; if ( 0 == fseek( fptr, entry.offset, SEEK_CUR ) ) { // prepare a memory buffer for the file CORE::CDynamicBuffer* fileBuffer = new CORE::CDynamicBuffer(); fileBuffer->SetDataSize( entry.size ); if ( 1 == fread( fileBuffer->GetBufferPtr(), entry.size, 1, fptr ) ) { // Successfully read file into memory fclose( fptr ); return new CORE::CDynamicBufferAccess( fileBuffer, true ); } // unable to read entire file delete fileBuffer; } fclose( fptr ); } else { CORE::CSubFileAccess* fileAccess = new CORE::CSubFileAccess(); if ( fileAccess->Load( m_archivePath , entry.offset , entry.size ) ) { return fileAccess; } delete fileAccess; } } return NULL; } /*-------------------------------------------------------------------------*/ VFS::CString CVPArchive::GetFileHash( const VFS::CString& file ) const {GUCEF_TRACE; CORE::CIOAccess* fileAccess = LoadFile( file.Lowercase().ReplaceChar( '/', '\\' ), 102400 ); if ( NULL != fileAccess ) { VFS::UInt8 digest[ 16 ]; if ( 0 != CORE::md5fromfile( fileAccess->CStyleAccess() , digest ) ) { delete fileAccess; char md5_str[ 48 ]; CORE::md5tostring( digest, md5_str ); VFS::CString md5Str; md5Str.Set( md5_str, 48 ); return md5Str; } delete fileAccess; } return VFS::CString(); } /*-------------------------------------------------------------------------*/ CORE::CDateTime CVPArchive::GetFileModificationTime( const VFS::CString& filePath ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { return CORE::CDateTime( (time_t) (*i).second.timestamp, true ); } return CORE::CDateTime(); } /*-------------------------------------------------------------------------*/ const VFS::CString& CVPArchive::GetArchiveName( void ) const {GUCEF_TRACE; return m_archiveName; } /*-------------------------------------------------------------------------*/ bool CVPArchive::IsWriteable( void ) const {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::LoadArchive( const VFS::CArchiveSettings& settings ) {GUCEF_TRACE; // We do not support writable VP archives if ( settings.GetWriteableRequested() ) return false; FILE* fptr = fopen( settings.GetActualArchivePath().C_String(), "rb" ); if ( NULL == fptr ) return false; if ( fread( &m_header, VP_HEADER_SIZE, 1, fptr ) == 1 ) { if ( ( memcmp( m_header.sig, "VPVP", 4 ) == 0 ) && ( m_header.version == 2 ) ) { // Move to the index location at the end of the file if ( 0 != fseek( fptr, m_header.indexoffset, SEEK_SET ) ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to archive header" ); fclose( fptr ); return false; } GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully read the archive header" ); // read the index VFS::CString path; TVPFileIndexEntry fileEntry; for ( VFS::UInt32 i=0; i<m_header.idxentries; ++i ) { if ( fread( &fileEntry, VP_INDEX_ENTRY_SIZE, 1, fptr ) != 1 ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to read index entry" ); m_header.idxentries = i; break; } if ( fileEntry.offset == 0 || fileEntry.size == 0 ) { // directory entry VFS::CString dirName; dirName.Scan( fileEntry.filename, 32 ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found directory entry: " + dirName); if ( dirName == ".." ) { path = CORE::StripLastSubDir( path ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Going up to directory: " + path ); } else { CORE::AppendToPath( path, dirName ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Entering directory: " + dirName ); } // Add the entry for the directory to our index TVPIndexEntry entry; entry.offset = 0; entry.size = 0; entry.timestamp = 0; m_index[ path.Lowercase().ReplaceChar( '/', '\\' ) ] = entry; } else { // file entry TVPIndexEntry entry; entry.offset = fileEntry.offset; entry.size = fileEntry.size; entry.timestamp = fileEntry.timestamp; VFS::CString filenameBuffer; filenameBuffer.Scan( fileEntry.filename, 32 ); VFS::CString filename = path; CORE::AppendToPath( filename, filenameBuffer ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found file entry: " + filenameBuffer ); m_index[ filename.Lowercase().ReplaceChar( '/', '\\' ) ] = entry; } } fclose( fptr ); m_archiveName = settings.GetArchiveName(); m_archivePath = settings.GetArchivePath(); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully finished reading the index" ); return true; } else { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: Archive header not recognized" ); fclose( fptr ); } } return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::LoadArchive( const VFS::CString& archiveName , CVFSHandlePtr vfsResource , const bool writeableRequest ) {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::UnloadArchive( void ) {GUCEF_TRACE; m_index.clear(); m_archiveName = NULL; m_archivePath = NULL; return true; } /*-------------------------------------------------------------------------*/ const VFS::CString& CVPArchive::GetType( void ) const {GUCEF_TRACE; return VPArchiveTypeName; } /*-------------------------------------------------------------------------*/ void CVPArchive::DestroyObject( VFS::CVFSHandle* objectToBeDestroyed ) {GUCEF_TRACE; delete objectToBeDestroyed; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace VP */ }; /* namespace VFSPLUGIN */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/
34.717391
128
0.412283
amvb
8cecb7820b8d7d4b2a52d3e4487f4d641983d2c9
3,356
cpp
C++
common_alg/src/surface_cps3_reader.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
7
2015-07-16T22:30:36.000Z
2020-02-06T10:16:42.000Z
common_alg/src/surface_cps3_reader.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
null
null
null
common_alg/src/surface_cps3_reader.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
3
2017-01-05T20:06:28.000Z
2021-12-20T16:19:10.000Z
/// @file surface_cps3_reader.cpp /// @brief Read surface in CPS-3 ASCII format /// @author uentity /// @version 1.0 /// @date 30.09.2015 /// @copyright This source code is released under the terms of /// the BSD License. See LICENSE for more details. #include "bs_kernel.h" #include "conf.h" #include <fstream> #include <sstream> #include <limits> namespace blue_sky { using namespace std; // hidden namespace namespace { /*----------------------------------------------------------------- * helper structure to get dx[i] when dim is given by one number *----------------------------------------------------------------*/ struct dim_subscript { dim_subscript(const double dim, const double offset = .0) : dim_(dim), offset_(offset), sum_(offset) {} void reset() { sum_ = offset_; } double operator[](t_ulong idx) { return offset_ + dim_ * idx; } private: const double dim_; const double offset_; double sum_; }; } /* eof hidden namespace */ ulong read_cps3_grid(std::ifstream& f, ulong* dims, spv_float& databuf) { std::string linebuf; std::istringstream line_s; // [x_min, x_max, y_min, y_max, z_min, z_max] t_float bounds[] = {0., 0., 0., 0., 0., 0.}; // increment in X and Y directions t_float D[] = {0., 0.}; // actually read file ulong n_points = 0; bool data_started = false, overflow = false; ulong i = 0, j = 0; while(std::getline(f, linebuf)) { line_s.clear(); // parse header if(!data_started) { size_t pos = linebuf.find("FSLIMI"); if(pos != string::npos) { line_s.str(linebuf.substr(pos + 6)); if(!(line_s >> bounds[0] >> bounds[1] >> bounds[2] >> bounds[3] >> bounds[4] >> bounds[5])) { BSERR << "Error reading limits from CPS-3 FSLIMI keyword" << bs_end; return 0; } } pos = linebuf.find("FSNROW"); if(pos != string::npos) { line_s.str(linebuf.substr(pos + 6)); if(!(line_s >> dims[1] >> dims[0])) { BSERR << "Error reading dimensions from CPS-3 FSNROW keyword" << bs_end; return 0; } // resize Z data buffer databuf->resize(dims[0] * dims[1] * 3); // TODO: enable NaN when GUI part will be fixed to support it //fill(databuf->begin(), databuf->end(), std::numeric_limits< double >::quiet_NaN()); fill(databuf->begin(), databuf->end(), 1e30); // data is read from upper left corner, i = 0, j = max i = 0; j = dims[1] - 1; } pos = linebuf.find("FSXINC"); if(pos != string::npos) { line_s.str(linebuf.substr(pos + 6)); if(!(line_s >> D[1] >> D[0])) { BSERR << "Error reading deltas from CPS-3 FSXINC keyword" << bs_end; return 0; } } // check if we reached actual data if(linebuf.find("->MSMODL") != string::npos) { data_started = true; } continue; } // if we are here, then we're in data section line_s.str(linebuf); t_float val; while(line_s >> val) { // store x, y, z surface value const v_float::iterator dest = databuf->begin() + (dims[1] * i + j) * 3; if(dest > databuf->end() - 3) { overflow = true; break; } dest[0] = bounds[0] + D[0] * i; dest[1] = bounds[2] + D[1] * j; if(val >= bounds[4] && val <= bounds[5]) dest[2] = val; // step to next surface point if(--j > dims[1]) { ++i; j = dims[1] - 1; } ++n_points; } } return n_points; } } /* namespace blue_sky */
25.424242
97
0.578069
bs-eagle
8cecd67c9170c77a95ca5206dfc6beeb4ff50153
46,408
cpp
C++
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
14
2016-11-08T19:06:52.000Z
2022-03-15T13:20:50.000Z
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
null
null
null
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
null
null
null
/* * MPU6050_Axis_MotionApps20.cpp * * Created on: 2016年1月10日 * Author: qq95538 */ // I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation // Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00) // 6/18/2012 by Jeff Rowberg <jeff@rowberg.net> // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib // // Changelog: // ... - ongoing debug release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ #include <iostream> #include <typeinfo> #include <math.h> #include <sys/time.h> #include "helper_3dmath4Edison.hpp" #include "MPU6050_4Edison.hpp" /* Source is from the InvenSense MotionApps v2 demo code. Original source is * unavailable, unless you happen to be amazing as decompiling binary by * hand (in which case, please contact me, and I'm totally serious). * * Also, I'd like to offer many, many thanks to Noah Zerkin for all of the * DMP reverse-engineering he did to help make this bit of wizardry * possible. */ #define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[] #define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[] #define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[] /* ================================================================================================ * | Default MotionApps v2.0 42-byte FIFO packet structure: | | | | [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] | | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | | | | [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] | | 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | * ================================================================================================ */ #define prog_uchar uint8_t #define PROGMEM /** * Instance DMP variables */ bool dmpDebug = true; bool dmpReady = false; // set true if DMP init was successful uint8_t dmpIntStatus = false; // holds actual interrupt status byte from MPU uint8_t dmpStatus; // return status after each device operation (0 = success, !0 = error) uint16_t dmpPacketSize; // expected DMP packet size (default is 42 bytes) uint16_t dmpFifoCount; // count of all bytes currently in FIFO uint8_t dmpFifoBuffer[64]; // FIFO storage buffer // orientation/motion vars Quaternion dmpQuat; // [w, x, y, z] quaternion container VectorInt16 dmpAccel; // [x, y, z] accel sensor measurements VectorInt16 dmpAccelReal; // [x, y, z] gravity-free accel sensor measurements VectorInt16 dmpAccelWorld; // [x, y, z] world-frame accel sensor measurements VectorFloat dmpGravity; // [x, y, z] gravity vector float dmpEuler[3]; // [psi, theta, phi] Euler angle container float dmpYawPitchRoll[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector //#define OUTPUT_READABLE_QUATERNION #define OUTPUT_READABLE_EULER #define OUTPUT_READABLE_YAWPITCHROLL //#define OUTPUT_READABLE_REALACCEL #define OUTPUT_READABLE_WORLDACCEL //#define OUTPUT_TEAPOT uint8_t dmpTeapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' }; // this block of memory gets written to the MPU on start-up, and it seems // to be volatile memory, so it has to be done each time (it only takes ~1 // second though) const prog_uchar dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = { // bank 0, 256 bytes 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82, 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC, 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4, 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10, // bank 1, 256 bytes 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8, 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C, 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0, // bank 2, 256 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bank 3, 256 bytes 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F, 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2, 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF, 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C, 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1, 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01, 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80, 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80, 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E, 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9, 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0, 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86, 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1, 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86, // bank 4, 256 bytes 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA, 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C, 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8, 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3, 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84, 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5, 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3, 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1, 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5, 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A, 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8, 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87, // bank 5, 256 bytes 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8, 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68, 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D, 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94, 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56, 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA, 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A, 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60, 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97, 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04, 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78, 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79, 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68, 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68, // bank 6, 256 bytes 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04, 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66, 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31, 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60, 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76, 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56, 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD, 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91, 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE, 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9, 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD, 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E, 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8, 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89, 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79, // bank 7, 138 bytes (remainder) 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA, 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB, 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3, 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3, 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC, 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF }; // DMP FIFO update rate: 0x09 drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz, // 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very // noisy data. DMP output frequency is calculated easily using this equation: // (200Hz / (1 + value)) // It is important to make sure the host processor can keep up with reading and // processing the FIFO output at the desired rate. Handling FIFO overflow // cleanly is also a good idea. thanks to Noah Zerkin for piecing this stuff // together! #ifndef DMP_FIFO_RATE #define DMP_FIFO_RATE 1 #endif const prog_uchar dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = { // BANK OFFSET LENGTH [DATA] 0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration 0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration 0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration 0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration 0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration 0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration 0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration 0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration 0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02 0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10 0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11 0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12 0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20 0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21 0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22 0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors 0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion 0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update 0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone // SPECIAL 0x01 = enable interrupts 0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION 0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt 0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion 0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer 0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro 0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo 0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo 0x02, 0x16, 0x02, 0x00, DMP_FIFO_RATE // D_0_22 inv_set_fifo_rate }; const prog_uchar dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = { 0x01, 0xB2, 0x02, 0xFF, 0xFF, 0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35, 0x01, 0x6A, 0x02, 0x06, 0x00, 0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00, 0x01, 0x62, 0x02, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00 }; long long timeLastCatch = 0; int timeAvg = 0; int timeAvgMax = 30; int timeCountTarget = 10; // Minimal measurement int timeCountCatch = 0; // Number of catching data double timeBalance = 0.9999; /** * Return the current time as milliseconds * @param print * @return */ long long MPU6050::getMilliTime(bool print) { timeval millitime; long long mtime, seconds, useconds; gettimeofday(&millitime, NULL); seconds = millitime.tv_sec; useconds = millitime.tv_usec; mtime = (seconds * 1000) + (useconds / 1000.0) + 0.5; if(print) printf("Seconds: %lld, Micro: %lld, Milli: %lld\n", seconds, useconds, mtime); return mtime; } /** * Check if is time to do a new request * @return */ long long MPU6050::timeCheck() { long long cur = getMilliTime(false); int interval = cur - timeLastCatch; if (interval >= timeAvg) { if(dmpDebug) printf("Interval\n"); return cur; }/* else if (timeCountCatch < timeCountTarget) { printf("Count\n"); return cur; }*/ else if(dmpDebug) printf("Pass %d >= %d and %d < %d - %lld\n", interval, timeAvg, timeCountCatch, timeCountTarget, cur); return 0; } /** * Recalculate average time with new time * @param time */ void MPU6050::timeCount(long long time) { // Balance use a range of tolerance to avoid fifo overflow and request overflow timeAvg = ((time - timeLastCatch + timeAvg) / 2) * timeBalance; if (timeAvg > timeAvgMax) timeAvg = timeAvgMax; timeLastCatch = time; timeCountCatch += 1; } /** * Reset average time measurement for interval of request data from MPU unit */ void MPU6050::timeReset() { timeAvg = 0; timeCountCatch = 0; timeLastCatch = getMilliTime(false); } /** * Start the device through address with offset's informed * @param address * @param xGyroOffset * @param yGyroOffset * @param zGyroOffset * @return boolean */ bool MPU6050::dmpStartDevice(uint8_t address, int xGyroOffset, int yGyroOffset, int zGyroOffset) { setAddress(address); initialize(); setXGyroOffset(xGyroOffset); setYGyroOffset(yGyroOffset); setZGyroOffset(zGyroOffset); if (testConnection()) { if(dmpDebug) printf("Connection OK\n"); // load and configure the DMP if (dmpInitialize() == 0) { if(dmpDebug) printf("DMP initialized\n"); // turn on the DMP, now that it's ready setDMPEnabled(true); dmpStatus = getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it dmpReady = true; // get expected DMP packet size for later comparison dmpPacketSize = dmpGetFIFOPacketSize(); timeReset(); resetFIFO(); return true; } } return false; } /** * Collect and process data from MPU unit, if this data is available * @return boolean */ bool MPU6050::dmpGetData() { long long time = timeCheck(); if(dmpDebug) printf("%lld ", time); if(dmpReady && time > 0) { if(dmpDebug) printf("\n %lld \n", time); // get current FIFO count dmpFifoCount = getFIFOCount(); if (dmpFifoCount == 1024) { // reset so we can continue cleanly resetFIFO(); timeReset(); if(dmpDebug) printf("FIFO overflow!\n"); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (dmpFifoCount >= 42) { timeCount(time); // read a packet from FIFO getFIFOBytes(dmpFifoBuffer, dmpPacketSize); // display quaternion values in easy matrix form: w x y z dmpGetQuaternion(&dmpQuat, dmpFifoBuffer); if(dmpDebug) printf("quat %7.2f %7.2f %7.2f %7.2f ", dmpQuat.w,dmpQuat.x,dmpQuat.y,dmpQuat.z); #ifdef OUTPUT_READABLE_EULER // display Euler angles in degrees dmpGetEuler(dmpEuler, &dmpQuat); dmpEuler[0] = dmpEuler[0] * 180/M_PI; dmpEuler[1] = dmpEuler[1] * 180/M_PI; dmpEuler[2] = dmpEuler[2] * 180/M_PI; if(dmpDebug) printf("euler %7.2f %7.2f %7.2f ", dmpEuler[0], dmpEuler[1], dmpEuler[2]); #endif #ifdef OUTPUT_READABLE_YAWPITCHROLL // display Euler angles in degrees dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetYawPitchRoll(dmpYawPitchRoll, &dmpQuat, &dmpGravity); dmpYawPitchRoll[0] = dmpYawPitchRoll[0] * 180/M_PI; dmpYawPitchRoll[1] = dmpYawPitchRoll[1] * 180/M_PI; dmpYawPitchRoll[2] = dmpYawPitchRoll[2] * 180/M_PI; if(dmpDebug) printf("ypr %7.2f %7.2f %7.2f ", dmpYawPitchRoll[0], dmpYawPitchRoll[1], dmpYawPitchRoll[2]); #endif #ifdef OUTPUT_READABLE_REALACCEL // display real acceleration, adjusted to remove gravity dmpGetAccel(&dmpAccel, dmpFifoBuffer); dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetLinearAccel(&dmpAccelReal, &dmpAccel, &dmpGravity); if(dmpDebug) printf("areal %6d %6d %6d ", dmpAccelReal.x, dmpAccelReal.y, dmpAccelReal.z); #endif #ifdef OUTPUT_READABLE_WORLDACCEL // display initial world-frame acceleration, adjusted to remove gravity // and rotated based on known orientation from quaternion dmpGetAccel(&dmpAccel, dmpFifoBuffer); dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetLinearAccelInWorld(&dmpAccelWorld, &dmpAccelReal, &dmpQuat); if(dmpDebug) printf("aworld %6d %6d %6d ", dmpAccelWorld.x, dmpAccelWorld.y, dmpAccelWorld.z); #endif #ifdef OUTPUT_TEAPOT // display quaternion values in InvenSense Teapot demo format: dmpTeapotPacket[2] = dmpFifoBuffer[0]; dmpTeapotPacket[3] = dmpFifoBuffer[1]; dmpTeapotPacket[4] = dmpFifoBuffer[4]; dmpTeapotPacket[5] = dmpFifoBuffer[5]; dmpTeapotPacket[6] = dmpFifoBuffer[8]; dmpTeapotPacket[7] = dmpFifoBuffer[9]; dmpTeapotPacket[8] = dmpFifoBuffer[12]; dmpTeapotPacket[9] = dmpFifoBuffer[13]; //Serial.write(dmpTeapotPacket, 14); dmpTeapotPacket[11]++; // packetCount, loops at 0xFF on purpose #endif printf("\n"); return true; } } return false; } /** * Quaternion * @return Quaternion[w, x, y, z] */ Quaternion getDmpQuaternion() { return dmpQuat; } /** * Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccel() { return dmpAccel; } /** * Gravity-free Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccelReal() { return dmpAccelReal; } /** * World-frame Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccelWorld() { return dmpAccelWorld; } /** * Gravity Vector * @return VectorFloat[x, y, z] */ VectorFloat getDmpGravity() { return dmpGravity; } /** * Euler Angle Container * @return Float[psi, theta, phi] */ float* getDmpEuler() { return dmpEuler; } /** * Yaw/Pitch/Roll container and gravity vector * @return Float[yaw, pitch, roll] */ float* getDmpYawPitchRoll() { return dmpYawPitchRoll; } /** * Initialize DMP inside MPU6050 * @return boolean */ uint8_t MPU6050::dmpInitialize() { //Resetting MPU6050... reset(); usleep(30000); // wait after reset //Disabling sleep mode... setSleepEnabled(false); // get MPU hardware revision //Selecting user bank 16... setMemoryBank(0x10, true, true); //Selecting memory byte 6... setMemoryStartAddress(0x06); //Checking hardware revision... uint8_t hwRevision __attribute__((__unused__)) = readMemoryByte(); //Revision @ user[16][6] = //hwRevision, HEX); //Resetting memory bank selection to 0... setMemoryBank(0, false, false); // check OTP bank valid //Reading OTP bank valid flag... uint8_t otpValid __attribute__((__unused__)) = getOTPBankValid(); //OTP bank is //otpValid ? F("valid!") : F("invalid! // get X/Y/Z gyro offsets //Reading gyro offset values... /* int8_t xgOffset = getXGyroOffset(); int8_t ygOffset = getYGyroOffset(); int8_t zgOffset = getZGyroOffset(); sleep(5); for(int cnt = 0; cnt < 1000; cnt = cnt + 1) { std::cout << "X: " << typeid(xgOffset).name() << "Y: " << typeid(ygOffset).name() << "Z: " << typeid(zgOffset).name() << "\n"; sleep(1); //xgOffset = (getXGyroOffset() + xgOffset)/2; //ygOffset = (getYGyroOffset() + ygOffset)/2; //zgOffset = (getZGyroOffset() + zgOffset)/2; } */ //X gyro offset = //xgOffset); //Y gyro offset = //ygOffset); //Z gyro offset = //zgOffset); // setup weird slave stuff (?) //Setting slave 0 address to 0x7F... setSlaveAddress(0, 0x7F); //Disabling I2C Master mode... setI2CMasterModeEnabled(false); //Setting slave 0 address to 0x68 (self)... setSlaveAddress(0, 0x68); /* if (addr == 104) { std::cout << "Address: 104"; setSlaveAddress(0, 0x68); } else { std::cout << "Address: 105"; setSlaveAddress(0, 0x69); } * */ //Resetting I2C Master control... resetI2CMaster(); usleep(20000); // load DMP code into memory banks //Writing DMP code to MPU memory banks ( // bytes) if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) { printf("Success! DMP code written and verified.\n"); // write DMP configuration //Writing DMP configuration to MPU memory banks ( // bytes in config def) if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) { printf("Success! DMP configuration written and verified.\n"); //Setting clock source to Z Gyro... setClockSource(MPU6050_CLOCK_PLL_ZGYRO); //Setting DMP and FIFO_OFLOW interrupts enabled... setIntEnabled(0x12); //Setting sample rate to 200Hz... setRate(4); // 1khz / (1 + 4) = 200 Hz //Setting external frame sync to TEMP_OUT_L[0]... setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); //Setting DLPF bandwidth to 42Hz... setDLPFMode(MPU6050_DLPF_BW_42); //Setting gyro sensitivity to +/- 2000 deg/sec... setFullScaleGyroRange(MPU6050_GYRO_FS_2000); //Setting DMP configuration bytes (function unknown)... setDMPConfig1(0x03); setDMPConfig2(0x00); //Clearing OTP Bank flag... setOTPBankValid(false); /* //Setting X/Y/Z gyro offsets to previous values... setXGyroOffset(xgOffset); setYGyroOffset(ygOffset); setZGyroOffset(zgOffset); //Setting X/Y/Z gyro user offsets to zero... setXGyroOffsetUser(0); setYGyroOffsetUser(0); setZGyroOffsetUser(0); */ //Writing final memory update 1/7 (function unknown)... uint8_t dmpUpdate[16], j; uint16_t pos = 0; for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 2/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Resetting FIFO... resetFIFO(); //Reading FIFO count... uint8_t fifoCount = getFIFOCount(); uint8_t fifoBuffer[128]; printf("Current FIFO count=%d\n", fifoCount); //fifoCount); if (fifoCount > 0) getFIFOBytes(fifoBuffer, fifoCount); //Setting motion detection threshold to 2... setMotionDetectionThreshold(2); //Setting zero-motion detection threshold to 156... setZeroMotionDetectionThreshold(156); //Setting motion detection duration to 80... setMotionDetectionDuration(80); //Setting zero-motion detection duration to 0... setZeroMotionDetectionDuration(0); //Resetting FIFO... resetFIFO(); //Enabling FIFO... setFIFOEnabled(true); //Enabling DMP... setDMPEnabled(true); //Resetting DMP... resetDMP(); //Writing final memory update 3/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 4/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 5/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); printf("Waiting for FIFO count > 2...\n"); while ((fifoCount = getFIFOCount()) < 3); printf("Current FIFO count=%d",fifoCount); //Reading FIFO data... getFIFOBytes(fifoBuffer, fifoCount); //Reading interrupt status... uint8_t mpuIntStatus __attribute__((__unused__)) = getIntStatus(); //Current interrupt status= mpuIntStatus, HEX //Reading final memory update 6/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Waiting for FIFO count > 2... while ((fifoCount = getFIFOCount()) < 3); //Current FIFO count= //fifoCount); //Reading FIFO data... getFIFOBytes(fifoBuffer, fifoCount); //Reading interrupt status... mpuIntStatus = getIntStatus(); //Current interrupt status= //mpuIntStatus, HEX //Writing final memory update 7/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //DMP is good to go! Finally. //Disabling DMP (you turn it on later)... setDMPEnabled(false); //Setting up internal 42-byte (default) DMP packet buffer... dmpPacketSize = 42; /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) { return 3; // TODO: proper error code for no memory }*/ //Resetting FIFO and clearing INT status one last time... resetFIFO(); getIntStatus(); } else { //ERROR! DMP configuration verification failed. return 2; // configuration block loading failed } } else { //ERROR! DMP code verification failed. return 1; // main binary block loading failed } return 0; // success } bool MPU6050::dmpPacketAvailable() { return getFIFOCount() >= dmpGetFIFOPacketSize(); } // uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate); // uint8_t MPU6050::dmpGetFIFORate(); // uint8_t MPU6050::dmpGetSampleStepSizeMS(); // uint8_t MPU6050::dmpGetSampleFrequency(); // int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg); //uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority); //uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func); //uint8_t MPU6050::dmpRunFIFORateProcesses(); // uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy); uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]); data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]); data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]); return 0; } uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[28] << 8) + packet[29]; data[1] = (packet[32] << 8) + packet[33]; data[2] = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; v -> x = (packet[28] << 8) + packet[29]; v -> y = (packet[32] << 8) + packet[33]; v -> z = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]); data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]); data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]); data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]); return 0; } uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 8) + packet[1]); data[1] = ((packet[4] << 8) + packet[5]); data[2] = ((packet[8] << 8) + packet[9]); data[3] = ((packet[12] << 8) + packet[13]); return 0; } uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) int16_t qI[4]; uint8_t status = dmpGetQuaternion(qI, packet); if (status == 0) { q -> w = (float)qI[0] / 16384.0f; q -> x = (float)qI[1] / 16384.0f; q -> y = (float)qI[2] / 16384.0f; q -> z = (float)qI[3] / 16384.0f; return 0; } return status; // int16 return value, indicates error if this line is reached } // uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]); data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]); data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]); return 0; } uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[16] << 8) + packet[17]; data[1] = (packet[20] << 8) + packet[21]; data[2] = (packet[24] << 8) + packet[25]; return 0; } // uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef); // uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) { // get rid of the gravity component (+1g = +4096 in standard DMP FIFO packet) v -> x = vRaw -> x - gravity -> x*4096; v -> y = vRaw -> y - gravity -> y*4096; v -> z = vRaw -> z - gravity -> z*4096; return 0; } // uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) { // rotate measured 3D acceleration vector into original state // frame of reference based on orientation quaternion memcpy(v, vReal, sizeof(VectorInt16)); v -> rotate(q); return 0; } // uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) { v -> x = 2 * (q -> x*q -> z - q -> w*q -> y); v -> y = 2 * (q -> w*q -> x + q -> y*q -> z); v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z; return 0; } // uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet); // uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) { data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi return 0; } uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) { // yaw: (about Z axis) data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // pitch: (nose up/down, about Y axis) data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z)); // roll: (tilt left/right, about X axis) data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z)); return 0; } // uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet); uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) { /*for (uint8_t k = 0; k < dmpPacketSize; k++) { if (dmpData[k] < 0x10) Serial.print("0"); Serial.print(dmpData[k], HEX); Serial.print(" "); } Serial.print("\n");*/ //Serial.println((uint16_t)dmpPacketBuffer); return 0; } uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) { uint8_t status; uint8_t buf[dmpPacketSize]; for (uint8_t i = 0; i < numPackets; i++) { // read packet from FIFO getFIFOBytes(buf, dmpPacketSize); // process packet if ((status = dmpProcessFIFOPacket(buf)) > 0) return status; // increment external process count variable, if supplied if (processed != 0) (*processed)++; } return 0; } // uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void)); // uint8_t MPU6050::dmpInitFIFOParam(); // uint8_t MPU6050::dmpCloseFIFO(); // uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source); // uint8_t MPU6050::dmpDecodeQuantizedAccel(); // uint32_t MPU6050::dmpGetGyroSumOfSquare(); // uint32_t MPU6050::dmpGetAccelSumOfSquare(); // void MPU6050::dmpOverrideQuaternion(long *q); uint16_t MPU6050::dmpGetFIFOPacketSize() { return dmpPacketSize; }
45.453477
134
0.618471
danielholanda
8cf02ef30bf559dd11e9df2d3d58fb0a749eac70
6,428
hpp
C++
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
#pragma once #include"State.hpp" class MarioStateMachine { public: MarioStateMachine() : _score(0) { //提前缓存各种状态 _normalMario = new NormalMario(this); _superMario = new SuperMario(this); _fireMario = new FireMario(this); _deadMario = new DeadMario(this); _state = _normalMario; } ~MarioStateMachine() { delete _normalMario, _superMario, _fireMario, _deadMario; } void getRevive(); //复活 void getMushroom(); //获得蘑菇 void getSunFlower(); //获得太阳花 void getHurt(); //受到伤害 int getScore() const; //获取当前分数 MarioState* getState() const; //获取当前状态 void setScore(int score); //获取当前分数 void setState(MarioState* state); //获取当前状态 MarioState* getNormalMario(); //获取缓存的状态 MarioState* getSuperMario(); MarioState* getFireMario(); MarioState* getDeadMario(); private: int _score; //当前分数 MarioState* _state; //当前状态 MarioState* _superMario; //缓存所有的状态 MarioState* _normalMario; MarioState* _fireMario; MarioState* _deadMario; private: class NormalMario : public MarioState { public: NormalMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); _stateMachine->setState(_stateMachine->getSuperMario()); std::cout << "获得蘑菇,由普通马里奥变为超级马里奥,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); _stateMachine->setState(_stateMachine->getFireMario()); std::cout << "获得太阳花,由普通马里奥变为火焰马里奥,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(0); _stateMachine->setState(_stateMachine->getDeadMario()); std::cout << "受到伤害,马里奥死亡,分数清空" << std::endl; } std::string getStateName() override { return "普通马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class SuperMario : public MarioState { public: SuperMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); std::cout << "获得蘑菇,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); _stateMachine->setState(_stateMachine->getFireMario()); std::cout << "获得太阳花,由超级马里奥变为火焰马里奥,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(_stateMachine->getScore() - 100); _stateMachine->setState(_stateMachine->getNormalMario()); std::cout << "受到伤害,由超级马里奥变为普通马里奥,扣一百分" << std::endl; } std::string getStateName() override { return "超级马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class FireMario : public MarioState { public: FireMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); std::cout << "获得蘑菇,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); std::cout << "获得太阳花,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(_stateMachine->getScore() - 100); _stateMachine->setState(_stateMachine->getSuperMario()); std::cout << "受到伤害,由火焰马里奥变为超级马里奥,扣一百分" << std::endl; } std::string getStateName() override { return "火焰马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class DeadMario : public MarioState { public: DeadMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { _stateMachine->setScore(0); _stateMachine->setState(_stateMachine->getNormalMario()); std::cout << "复活马里奥,会到普通状态,分数重新计算" << std::endl; } void getMushroom() override { std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl; } void getSunFlower() override { std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl; } void getHurt() override { std::cout << "死亡后不能受到伤害,不存在该逻辑" << std::endl; } std::string getStateName() override { return "死亡"; } private: MarioStateMachine* _stateMachine; //状态机 }; }; void MarioStateMachine::getRevive() { _state->getRevive(); } void MarioStateMachine::getMushroom() { _state->getMushroom(); } void MarioStateMachine::getSunFlower() { _state->getSunFlower(); } void MarioStateMachine::getHurt() { _state->getHurt(); } int MarioStateMachine::getScore() const { return _score; } MarioState* MarioStateMachine::getState() const { return _state; } void MarioStateMachine::setScore(int score) { _score = score; } void MarioStateMachine::setState(MarioState* state) { _state = state; } MarioState* MarioStateMachine::getNormalMario() { return _normalMario; } MarioState* MarioStateMachine::getSuperMario() { return _superMario; } MarioState* MarioStateMachine::getFireMario() { return _fireMario; } MarioState* MarioStateMachine::getDeadMario() { return _deadMario; }
23.807407
71
0.558027
HONGYU-LEE
8cf1cca6709f496c90b1ffcf3cbaa568ef803876
3,128
cpp
C++
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Say you have an array for which the ith element is the price of a given stock // on day i. // Design an algorithm to find the maximum profit. You may complete as many // transactions as you like (ie, buy one and sell one share of the stock // multiple times) with the following restrictions: // You may not engage in multiple transactions at the same time (ie, you // must sell the stock before you buy again). After you sell your stock, you // cannot buy stock on next day. (ie, cooldown 1 day) // Example: // prices = [1, 2, 3, 0, 2] // maxProfit = 3 // transactions = [buy, sell, cooldown, buy, sell] // correct thinking direction // finite state machine // ref: // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking) // 3 states (indicate net money we have, start at 0): // s0: can stay at s0, or buy and go to s1 // s1: can stay at s1, or sell and go to s2 (cooldown state, cannot buy) // s2: cannot stay at s2, after 1 day cooldown, go to s1 class Solution { public: int maxProfit(vector<int> &prices) { if (prices.size() < 2) return 0; int n = prices.size(); vector<int> s0(n), s1(n), s2(n); s0[0] = 0; s1[0] = -prices[0]; s2[0] = INT_MIN; // impossible to sell at first day for (int i = 1; i < n; ++i) { s0[i] = max(s0[i - 1], s2[i - 1]); s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); s2[i] = s1[i - 1] + prices[i]; } return max(s0[n - 1], s2[n - 1]); } }; // further optimized to O(1) space class Solution { public: int maxProfit(vector<int> &prices) { int s0 = 0, s1 = INT_MIN, s2 = 0; for (auto &&p : prices) { int pre_s2 = s2; s2 = s1 + p; s1 = max(s1, s0 - p); s0 = max(s0, pre_s2); } return max(s0, s2); } }; // my own analysis, seems to be wrong way // analysis // vector input, return a int // conditions // => dp // let dp[n] represents the max profit after the end of day n // not day n price is price[n-1] // if day n-1 must be selling transaction // i.e. dp[n-1] != dp[n-2] // dp[n] = max(dp[n-1], dp[n-1] + price[n-1] - price[n-2]) // if day n-1 can be a non-selling transaction // if day n-1 can be cooldown window // i.e. dp[n-1] == dp[n-2] // dp[n] = dp[n-1] // if day n-1 is not cooldown (n-2 is not selling) // i.e. dp[n-2] == dp[n-3] // dp[n] = dp[n-2] + max(0, price[n-1] - price[n-2]) // beginning cases: // dp[0] = 0, dp[1] = 0, dp[2] = max(0, price[1] - price[0]) // // code: // int n = prices.size(); // vector<int> dp(n + 1); // all 0s // dp[2] = max(0, prices[1] - prices[0]); // for (int i = 3; i <= n; ++i) { // if (dp[i - 1] != dp[i - 2]) // dp[i] = dp[i - 1] + max(0, prices[i - 1] - prices[i - 2]); // else { // // n-1 is cooldown // dp[i] = dp[i - 1]; // if (dp[i - 2] == dp[i - 3]) // dp[i] += max(0, prices[i - 1] - prices[i - 2]); // } // } // return dp[n];
31.59596
141
0.538683
ysmiles
8cf76e3a2f55f04ec658adbbce9fe0ea6b6b9d73
1,412
cpp
C++
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
1
2018-01-26T00:06:19.000Z
2018-01-26T00:06:54.000Z
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
#include "resources.hpp" #include <boost/dll/runtime_symbol_info.hpp> #include <fstream> #include <sstream> namespace MinIDE { //##################################################################################################################### path getResourcesDirectory() { auto program_path = boost::dll::program_location(); program_path = program_path.parent_path(); // for dev: auto fname = program_path.filename().string(); if (fname == "Debug" || fname == "Release") program_path = program_path.parent_path(); auto res = program_path.parent_path() / "resources"; return res; } //--------------------------------------------------------------------------------------------------------------------- path resource(path const& file) { return getResourcesDirectory() / file; } //--------------------------------------------------------------------------------------------------------------------- std::string loadResource(path const& file) { auto res = resource(file); std::ifstream reader{res, std::ios_base::binary}; std::stringstream buffer; buffer << reader.rdbuf(); return buffer.str(); } //##################################################################################################################### }
33.619048
120
0.386686
5cript
8cf8c764d68f0576d49cf9bbb33bd30b7e6a0e51
1,927
cc
C++
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
null
null
null
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
null
null
null
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
2
2020-12-02T13:04:29.000Z
2020-12-07T00:17:01.000Z
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @author F. de Sande * @date 7.nov.2020 * @brief Cada nuevo término de la serie de Fibonacci se genera sumando los dos anteriores. * Comenzando con 0 y 1, los primeros 10 términos serán: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 * Desarrolle en C++ un programa que calcule la suma de todos los términos de valor par * de la serie que sean menores que 1000. * @see https://docs.google.com/document/d/1-3hTIVf8tPrbn9u0vs0Cm2IGyX1XBgv8hReVU0KOSUQ/edit?usp=sharing * @see stoi http://www.cplusplus.com/reference/string/stoi/ * An Object Oriented Version of the program: * @see https://stackoverflow.com/questions/21360694/sum-of-even-fibonacci-numbers-under-1000 * */ #include <iostream> #include <cstdlib> // exit #include "fibonacci_sum.h" // Usage: the program requires a single numeric parameter void Usage(int argc, char *argv[]) { if (argc != 2) { std::cout << argv[0] << ": Falta un número natural como parámetro" << std::endl; std::cout << "Pruebe " << argv[0] << " --help para más información" << std::endl; exit(EXIT_SUCCESS); } std::string parameter{argv[1]}; if (parameter == "--help") { std::cout << kHelpText << std::endl; exit(EXIT_SUCCESS); } } size_t fibonacci_sum(const size_t kLimit) { size_t second_to_last{0}, // Second to last term last{1}, // Last term generated new_term; // New term of the serie size_t long sum{0}; // Accumulated sum of the terms do { new_term = last + second_to_last; if (new_term % 2 == 0) { sum += new_term; } // Uncomment for debug: print each new term // std::cout << "Term: " << new_term << std::endl; second_to_last = last; last = new_term; } while (new_term < kLimit); return sum; }
33.807018
104
0.646082
ULL-ESIT-IB-2020-2021
8cf90e7707c1f12d35fcd1633760e24ff715f571
3,984
cpp
C++
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T13:44:49.000Z
2021-01-19T10:39:48.000Z
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
null
null
null
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T16:03:20.000Z
2020-02-15T09:14:30.000Z
// ResourcesBar.cpp: implementation of the CResourcesBar class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResourcesBar.h" #include "..\GameClientGlobal.h" #include "..\DataObjects\CMap.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define RESOURCEBAR_ITEM_WIDTH 55 #define RESOURCEBAR_LINE_HEIGHT 18 #define RESOURCEBAR_TEXT_COLOR RGB32(255, 255, 255) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNAMIC(CResourcesBar, CWindow) BEGIN_OBSERVER_MAP(CResourcesBar, CWindow) case -1: break; END_OBSERVER_MAP(CResourcesBar, CWindow) CResourcesBar::CResourcesBar() { m_pFont = NULL; memset(m_aResources, 0, sizeof(int) * RESOURCE_COUNT); } CResourcesBar::~CResourcesBar() { ASSERT(m_pFont == NULL); } #ifdef _DEBUG void CResourcesBar::AssertValid() const { CWindow::AssertValid(); ASSERT(m_pFont != NULL); } void CResourcesBar::Dump(CDumpContext &dc) const { CWindow::Dump(dc); } #endif void CResourcesBar::Create(CWindow *pParent, CFontObject *pFont) { ASSERT(pParent != NULL); ASSERT(pFont != NULL); m_pFont = pFont; // First determine count of used resources DWORD dwCount = 0, i; for(i = 0; i < RESOURCE_COUNT; i++){ if(!g_pMap->GetResource(i)->GetName().IsEmpty()){ dwCount ++; } } // Compute the positioning CRect rcParent; rcParent = pParent->GetWindowPosition(); int nStartPosition, nRowCount = 1; while((int)((dwCount / nRowCount) * RESOURCEBAR_ITEM_WIDTH) > rcParent.Width()) nRowCount++; nStartPosition = rcParent.Width() - ((dwCount + (nRowCount / 2)) / nRowCount) * RESOURCEBAR_ITEM_WIDTH; int nPos = nStartPosition, nRow = 0; for(i = 0; i < RESOURCE_COUNT; i++){ if(g_pMap->GetResource(i)->GetName().IsEmpty()){ m_aPositions[i].x = -1; } else{ m_aPositions[i].x = nPos - nStartPosition; m_aPositions[i].y = nRow * RESOURCEBAR_LINE_HEIGHT; nPos += RESOURCEBAR_ITEM_WIDTH; if(nPos >= rcParent.Width()){ nPos = nStartPosition; nRow++; } } } // Comptute the position of the window CRect rcWnd; rcWnd.left = nStartPosition; rcWnd.right = rcParent.Width(); rcWnd.top = 0; rcWnd.bottom = nRowCount * RESOURCEBAR_LINE_HEIGHT; m_bTransparent = TRUE; CWindow::Create(&rcWnd, pParent); } void CResourcesBar::Delete() { CWindow::Delete(); m_pFont = NULL; } void CResourcesBar::SetResource(DWORD dwIndex, int nNewValue) { ASSERT(dwIndex < RESOURCE_COUNT); m_aResources[dwIndex] = nNewValue; CRect rc; rc.left = m_aPositions[dwIndex].x; if(rc.left == -1) return; rc.top = m_aPositions[dwIndex].y; rc.right = rc.left + RESOURCEBAR_ITEM_WIDTH; rc.bottom = rc.top + RESOURCEBAR_LINE_HEIGHT; UpdateRect(&rc); } void CResourcesBar::Draw(CDDrawSurface *pSurface, CRect *pRect) { DWORD i; CString str; int nVal; for(i = 0; i < RESOURCE_COUNT; i++){ if(m_aPositions[i].x == -1) continue; pSurface->Paste(m_aPositions[i], g_pMap->GetResource(i)->GetIcon()); nVal = m_aResources[i]; if(abs(nVal) > 99999){ // nVal / 1000 k if(abs(nVal) > 9999999){ // nVal / 1000000 M if(abs(nVal) > 9999999999){ // nVal / 1000000000 G str.Format("%dG", nVal / 1000000000); } else{ str.Format("%dM", nVal / 1000000); } } else{ str.Format("%dk", nVal / 1000); } } else{ str.Format("%d", nVal); } m_pFont->PaintText(m_aPositions[i].x + 17, m_aPositions[i].y + (RESOURCEBAR_LINE_HEIGHT - m_pFont->GetCharSize('A').cy) / 2, str, pSurface, RESOURCEBAR_TEXT_COLOR); } } // Returns the window from givven screen point // works only on subtree of windows CWindow * CResourcesBar::WindowFromPoint(CPoint &pt) { return NULL; }
23.298246
128
0.626255
vitek-karas
8cf9baba50c162a61a817c1d88bfc08028f7fe46
417
cpp
C++
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 21/7/19. // #include <iostream> #include <cmath> #define ACCURACY 0.001 int main() { int n; float sum,n1,m; n=1;sum=0; for(int i=1;;i++) { n1 = float(1) / n; m = pow(n1, i); std::cout<<m<<'\n'; sum +=m; std::cout<<"sum"<<sum<<'\n'; if (m <= ACCURACY) break; n++; } std::cout<<sum<<"\n"; return 0; }
16.68
36
0.434053
jattramesh
8cfcd4b41e0a05d8a7421905aaa8d3713f9c4f17
1,151
hpp
C++
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
#ifndef RSA_INPUT_HPP #define RSA_INPUT_HPP #include <vector> #include <string> //Forward declaration class Demand; class Vertex; class Edge; class RSA_Input { private: std::string file_Outputplacement_; std::vector<Demand *> requests_; std::vector<Vertex *> nodes_; std::vector<Edge *> edges_; public: //Constructors RSA_Input() {} //Getters const std::vector<Demand *> &getRequests() const { return requests_; } const std::vector<Vertex *> &getNodes() const { return nodes_; } const std::vector<Edge *> &getEdges() const { return edges_; } std::vector<Demand *> &getRequests() { return requests_; } std::vector<Vertex *> &getNodes() { return nodes_; } std::vector<Edge *> &getEdges() { return edges_; } //Functions void data_load_demand(const std::string filename); void data_load_edge(const std::string filename); void data_load_node(const std::string filename); //Shows void showRequests() const; //Destructors ~RSA_Input() {} }; #endif // RSA_INPUT_HPP
22.134615
78
0.612511
elie-wanko
8cfce37bdb0ee0541268171e2dad940d44557d5c
2,508
cpp
C++
frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* * Copyright 2012, The Android Open Source Project * * 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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "LinearRegression" #include <utils/Log.h> #include "LinearRegression.h" #include <math.h> #include <string.h> namespace android { LinearRegression::LinearRegression(size_t historySize) : mHistorySize(historySize), mCount(0), mHistory(new Point[mHistorySize]), mSumX(0.0), mSumY(0.0) { } LinearRegression::~LinearRegression() { delete[] mHistory; mHistory = NULL; } void LinearRegression::addPoint(float x, float y) { if (mCount == mHistorySize) { const Point &oldest = mHistory[0]; mSumX -= oldest.mX; mSumY -= oldest.mY; memmove(&mHistory[0], &mHistory[1], (mHistorySize - 1) * sizeof(Point)); --mCount; } Point *newest = &mHistory[mCount++]; newest->mX = x; newest->mY = y; mSumX += x; mSumY += y; } bool LinearRegression::approxLine(float *n1, float *n2, float *b) const { static const float kEpsilon = 1.0E-4; if (mCount < 2) { return false; } float sumX2 = 0.0f; float sumY2 = 0.0f; float sumXY = 0.0f; float meanX = mSumX / (float)mCount; float meanY = mSumY / (float)mCount; for (size_t i = 0; i < mCount; ++i) { const Point &p = mHistory[i]; float x = p.mX - meanX; float y = p.mY - meanY; sumX2 += x * x; sumY2 += y * y; sumXY += x * y; } float T = sumX2 + sumY2; float D = sumX2 * sumY2 - sumXY * sumXY; float root = sqrt(T * T * 0.25 - D); float L1 = T * 0.5 - root; if (fabs(sumXY) > kEpsilon) { *n1 = 1.0; *n2 = (2.0 * L1 - sumX2) / sumXY; float mag = sqrt((*n1) * (*n1) + (*n2) * (*n2)); *n1 /= mag; *n2 /= mag; } else { *n1 = 0.0; *n2 = 1.0; } *b = (*n1) * meanX + (*n2) * meanY; return true; } } // namespace android
22.594595
80
0.583333
touxiong88
ea0058484aadc9a76c9fa0d2bd09d9540088fd77
2,254
cpp
C++
cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
7
2020-07-20T12:11:35.000Z
2021-12-23T02:09:19.000Z
cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
null
null
null
cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
1
2020-08-29T16:36:48.000Z
2020-08-29T16:36:48.000Z
#ifdef OS_ANDROID #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "txWidestringWrapper.h" tx_wstring::tx_wstring(const wchar_t * wstr) : _wstring(wstr) { wcstombs(cbuf, wstr, BUF_SIZE); _astring.assign(cbuf); } tx_wstring::tx_wstring(const tx_wstring & other) : _wstring(other.c_str()) { wcstombs(cbuf, other.c_str(), BUF_SIZE); _astring.assign(cbuf); } void tx_wstring::assign(const wchar_t * wstr) { _wstring.assign(wstr); wcstombs(cbuf, wstr, BUF_SIZE); _astring.assign(cbuf); } void tx_wstring::assign(const tx_wstring & wstr) { _wstring.assign(wstr.c_str()); wcstombs(cbuf, wstr.c_str(), BUF_SIZE); _astring.assign(cbuf); } void tx_wstring::append(const tx_wstring & wstr) { wcstombs(cbuf, wstr.c_str(), BUF_SIZE); _astring.append(cbuf); mbstowcs(wbuf, _astring.c_str(), BUF_SIZE); _wstring.assign(wbuf); } tx_wstring & tx_wstring::operator=(const tx_wstring & other) { assign(other); return *this; } tx_wstring & tx_wstring::operator+=(const tx_wstring & other) { append(other); return *this; } tx_wstring & tx_wstring::operator+=(const wchar_t * wstr) { append(wstr); return *this; } tx_wstring tx_wstring::operator+(const tx_wstring & wstr) const { tx_wstring ans(_wstring.c_str()); ans.append(wstr); return ans; } tx_wstring tx_wstring::operator+(const wchar_t * wstr) const { tx_wstring ans(_wstring.c_str()); ans.append(wstr); return ans; } const wchar_t * tx_wstring::c_str() const { return _wstring.c_str(); } bool tx_wstring::empty() const { return _astring.empty(); } int tx_wstring::compare(const wchar_t * wstr) { wcstombs(cbuf, wstr, BUF_SIZE); return _astring.compare(cbuf); } dummyWString::dummyWString(const char * _str) { wchar_t buf[BUF_SIZE]; mbstowcs(buf, _str, BUF_SIZE); _wstr.assign(buf); } int tx_swprintf(wchar_t* ws, size_t len, const wchar_t* format, ...) { char cbuf[BUF_SIZE]; char fmt[BUF_SIZE]; wcstombs(fmt, format, BUF_SIZE); va_list ap; va_start(ap, format); int res = vsprintf(cbuf, fmt, ap); va_end(ap); mbstowcs(ws, cbuf, len); return res; } bool wccmp(const wchar_t* w1, const wchar_t* w2) { char cbuf1[16]; wcstombs(cbuf1, w1, 16); char cbuf2[16]; wcstombs(cbuf2, w2, 16); return cbuf1[0] == cbuf2[0]; } #endif // OS_ANDROID
18.783333
74
0.712067
wulfebw
ea017d4ceeb555ab858a441fe7c08b6fab504293
6,173
cpp
C++
WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp
achellies/WaterEveryDay
376b8a22b288a2b275861363a731a5054c43bf0a
[ "MIT" ]
5
2016-03-11T08:49:04.000Z
2019-07-19T02:18:02.000Z
WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp
achellies/WaterEveryDay
376b8a22b288a2b275861363a731a5054c43bf0a
[ "MIT" ]
null
null
null
WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp
achellies/WaterEveryDay
376b8a22b288a2b275861363a731a5054c43bf0a
[ "MIT" ]
4
2015-07-01T03:34:51.000Z
2019-12-25T18:21:38.000Z
// GDIImage.cpp : Implementation of CGDIImageOle #include "stdafx.h" #include "GDIImageOle.h" // CGDIImageOle //using namespace Gdiplus; const IID IID_IGDIImageDeleteNotify = {0xa991582, 0x6f1a, 0x4150, 0xbd, 0xcd, 0x25, 0x3b, 0xb7, 0x8c, 0xf9, 0xf}; CGDIImageOle::CGDIImageOle(): m_pImage(NULL), m_FrameCount(0), m_hCallbackWnd(NULL), m_dwUpdateMsg(WM_USER), m_bIsDeleting(false), m_bRegistered(false) { //m_bWindowOnly = TRUE; //CalcExtent(m_sizeExtent); } HRESULT CGDIImageOle::FinalConstruct() { //InitializeCriticalSection(&m_csAdviseSink); return S_OK; } void CGDIImageOle::FinalRelease() { if (m_pImage) { if (m_bRegistered) { m_pImage->UnregisterCallback(OnFrameChanged, (LPARAM)this); m_bRegistered = false; } m_pImage->Release(); } //DeleteCriticalSection(&m_csAdviseSink); } enum DefinedTestRectValue {TR_NOOVERLAP, TR_INTERSECT, TR_CONTAIN}; static DefinedTestRectValue TestRectInRect(RECT *pRect1, RECT *pRect2) { RECT rcIntersect; DefinedTestRectValue ret = TR_NOOVERLAP; if (IntersectRect(&rcIntersect, pRect1, pRect2)) { if (EqualRect(&rcIntersect, pRect2)) ret = TR_CONTAIN; else ret = TR_INTERSECT; } return ret; } HRESULT CGDIImageOle::FireViewChangeEx(BOOL bEraseBackground) { HRESULT Res = S_OK; if (m_bInPlaceActive) { // Active if (m_hWndCD != NULL) ::InvalidateRect(m_hWndCD, NULL, bEraseBackground); // Window based else if (m_bWndLess && m_spInPlaceSite != NULL) m_spInPlaceSite->InvalidateRect(NULL, bEraseBackground); // Windowless } else // Inactive { /* if (CComCompositeControl<CGDIImageOle>::m_hWnd) ::InvalidateRect(CComCompositeControl<CGDIImageOle>::m_hWnd, NULL, FALSE); else if (m_hCallbackWnd) { ::PostMessage(m_hCallbackWnd, m_dwUpdateMsg, 0, (LPARAM)this); } else { SendOnViewChange(DVASPECT_CONTENT); } */ if (m_spClientSite && !m_bIsDeleting) { /* IOleClientSite *pClientSite = m_spClientSite; pClientSite->AddRef(); ::PostMessage(m_hCallbackWnd, m_dwUpdateMsg, 0, (LPARAM)pClientSite); */ CComPtr<IOleInPlaceSite> spInPlaceSite; m_spClientSite->QueryInterface(__uuidof(IOleInPlaceSite), (void **)&spInPlaceSite); HWND hwndParent = NULL; if (spInPlaceSite && spInPlaceSite->GetWindow(&hwndParent) == S_OK && hwndParent && ::IsWindowVisible(hwndParent)) { OLEINPLACEFRAMEINFO frameInfo; IOleInPlaceFrame *pInPlaceFrame = NULL; IOleInPlaceUIWindow *pInPlaceUIWindow = NULL; RECT rcPos, rcClip; frameInfo.cb = sizeof(OLEINPLACEFRAMEINFO); if (spInPlaceSite->GetWindowContext(&pInPlaceFrame, &pInPlaceUIWindow, &rcPos, &rcClip, &frameInfo) == S_OK) { if (pInPlaceFrame) pInPlaceFrame->Release(); if (pInPlaceUIWindow) pInPlaceUIWindow->Release(); DefinedTestRectValue TestRect = TestRectInRect(&rcClip, &rcPos); if (TestRect == TR_CONTAIN) { // Object fully visible SendOnViewChange(DVASPECT_CONTENT); } else if (TestRect == TR_INTERSECT) { // Object partially visible // [!] brain-ripper // this implementation flickers smiles ::InvalidateRect(hwndParent, &rcPos, FALSE); /* // [!] brain-ripper // this implementation doesn't respect selection color HDC hDC = ::GetDC(hwndParent); m_pImage->Draw(hDC, rcPos.left, rcPos.top, min(m_dwW, DWORD(rcPos.right - rcPos.left)), min(m_dwH, DWORD(rcPos.bottom - rcPos.top)), 0, 0, m_hBackDC, 0, 0, min(m_dwW, DWORD(rcPos.right - rcPos.left)), min(m_dwH, DWORD(rcPos.bottom - rcPos.top))); ::ReleaseDC(hwndParent, hDC); //*/ } else { // Object hidden if (m_bRegistered) { // Returning S_FALSE on callback makes // pImage to unregister callback function. // This mechanism used because it is not allowed Register/Unregister // callback functions from inside callback functions Res = S_FALSE; m_bRegistered = false; } } } } } } return Res; } STDMETHODIMP CGDIImageOle::put_SetImage(CGDIImage *pImage, LPCWSTR pStrData, HWND hCallbackWnd, DWORD dwUpdateMsg) { if (m_pImage) return S_FALSE; m_pImage = pImage; if (!m_pImage) return S_FALSE; m_pImage->AddRef(); m_dwW = m_pImage->GetWidth(); m_dwH = m_pImage->GetHeight(); SIZEL szPix = {m_dwW, m_dwH}; SIZEL szHi; AtlPixelToHiMetric(&szPix, &szHi); m_sizeExtent.cx = szHi.cx; m_sizeExtent.cy = szHi.cy; m_hCallbackWnd = hCallbackWnd; m_dwUpdateMsg = dwUpdateMsg; m_pImage->RegisterCallback(OnFrameChanged, (LPARAM)this); m_bRegistered = true; SetUnicodeTextData(pStrData); return S_OK; } bool CGDIImageOle::OnFrameChanged(CGDIImage *pImage, LPARAM lParam) { CGDIImageOle *pGDIImage = (CGDIImageOle *)lParam; return pGDIImage->FireViewChangeEx(FALSE) == S_OK; } LRESULT CGDIImageOle::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { return S_OK; } HRESULT CGDIImageOle::IDataObject_GetData(FORMATETC* pFormatEtc, STGMEDIUM* pStgMedium) { ATLASSERT(pFormatEtc); ATLASSERT(pStgMedium); int iIndex = _FindFormat(pFormatEtc); if( iIndex < 0 ) return DV_E_FORMATETC; return _AddRefStgMedium(pStgMedium, &m_aObjects[iIndex].StgMed, &m_aObjects[iIndex].FmtEtc); } HRESULT CGDIImageOle::SetGlobalData(CLIPFORMAT cf, LPCVOID pData, DWORD dwSize) { FORMATETC fmtetc = { cf, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; STGMEDIUM stgmed = { TYMED_HGLOBAL, { 0 }, 0 }; stgmed.hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T) dwSize); if( stgmed.hGlobal == NULL ) return E_OUTOFMEMORY; memcpy(GlobalLock(stgmed.hGlobal), pData, (size_t) dwSize); GlobalUnlock(stgmed.hGlobal); return SetData(&fmtetc, &stgmed, TRUE); } HRESULT CGDIImageOle::SetUnicodeTextData(LPCWSTR pstrData) { return SetGlobalData(CF_UNICODETEXT, pstrData, (::lstrlenW(pstrData) + 1) * sizeof(WCHAR)); }
26.493562
118
0.672607
achellies
ea0208315cc3df4de2ecf683063501a8fc659c8f
6,987
hpp
C++
MsgWnd.hpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
5
2017-10-02T04:10:35.000Z
2021-07-26T04:45:35.000Z
MsgWnd.hpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
null
null
null
MsgWnd.hpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
null
null
null
/****************************************************************************** ** (C) Chris Oldwood ** ** MODULE: MSGWND.HPP ** COMPONENT: Windows C++ Library. ** DESCRIPTION: The CMsgWnd class declaration. ** ******************************************************************************* */ // Check for previous inclusion #ifndef MSGWND_HPP #define MSGWND_HPP #if _MSC_VER > 1000 #pragma once #endif #include "Wnd.hpp" // Forward declarations. class CPoint; class CDC; /****************************************************************************** ** ** This is a Wnd derived class that provides a base class for all message ** based windows. It provides the default handlers for all messages common to ** all windows. ** ******************************************************************************* */ class CMsgWnd : public CWnd /*, private NotCopyable*/ { public: // // Constructors/Destructor. // CMsgWnd(); // // Scroll bar methods. // int HorzScrollPos(int iPos, bool bRepaint = true); int VertScrollPos(int iPos, bool bRepaint = true); int HorzScrollPos(); int VertScrollPos(); void HorzScrollRange(int iMin, int iMax, bool bRepaint = true); void VertScrollRange(int iMin, int iMax, bool bRepaint = true); protected: ///////////////////////////////////////////////////////////////// // Structure to define an entry in the control message table. ///////////////////////////////////////////////////////////////// // Pointer to generic message handler. typedef LRESULT (CMsgWnd::*PFNMSGHANDLER)(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); // Pointer to WM_COMMAND style control message handler. typedef void (CMsgWnd::*PFNCMDMSGHANDLER)(); // Pointer to WM_NOTIFY style control message handler. typedef LRESULT (CMsgWnd::*PFNNFYMSGHANDLER)(NMHDR& rMsgHdr); struct CTRLMSG { uint m_iMsgType; // WM_COMMAND or WM_NOTIFY. uint m_iCtrlID; // ID of control. uint m_iMsgID; // Event message ID. PFNMSGHANDLER m_pfnMsgHandler; // Message handler method. }; // // Members. // CTRLMSG* m_pCtrlMsgTable; // // General message handlers. // virtual LRESULT WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); virtual LRESULT DefaultWndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) = 0; // // Message processors. // virtual void OnCreate(const CRect& rcClient); virtual void OnActivate(bool bActivating); virtual void OnEraseBackground(CDC& rDC); virtual void OnPaint(CDC& rDC); virtual void OnResize(WCL::ResizeFlags iFlag, const CSize& NewSize); virtual void OnTimer(WCL::TimerID iTimerID); virtual void OnShow(bool bShowing); virtual void OnDestroy(); virtual void OnNCDestroy(); virtual void OnHorizScroll(WCL::ScrollbarFlags iCode, uint iPos); virtual void OnVertScroll(WCL::ScrollbarFlags iCode, uint iPos); virtual void OnCmdMsg(uint iID); virtual void OnCtrlMsg(uint iID, uint iMsg, HWND hControl); virtual LRESULT OnCtrlMsg(NMHDR& rMsgHdr); virtual void OnReflectedCtrlMsg(uint iMsg); virtual void OnReflectedCtrlMsg(NMHDR& rMsgHdr); virtual void OnMeasureItem(uint iID, uint iItem, uint& iWidth, uint& iHeight); virtual void OnDrawItem(uint iID, uint iAction, uint iState, CDC& rDC, uint iItem, const CRect& rcItem); virtual void OnSetCursor(HWND hWnd, uint nHitCode, uint nMouseMsg); virtual void OnCtlColour(uint nCtlClrMsg, HDC hDC, HWND hCtlWnd); virtual HBRUSH OnReflectedCtlClr(uint nCtlClrMsg, HDC hDC); virtual void OnHelp(HELPINFO& oInfo); virtual void OnUserMsg(uint nMsg, WPARAM wParam, LPARAM lParam); virtual void OnAppMsg(uint nMsg, WPARAM wParam, LPARAM lParam); virtual void OnRegisteredMsg(uint nMsg, WPARAM wParam, LPARAM lParam); virtual void OnHitTest(const CPoint& ptCursor); // // Access to window data. // WNDPROC WindowProc(WNDPROC lpfnWndProc); // // Access to message result members. // void MsgHandled(BOOL bHandled); void MsgResult (LRESULT lResult); //! Set the result for the message. void SetMsgResult(BOOL bHandled, LRESULT lResult); BOOL* MsgHandledBuffer(BOOL* pbBuffer); LRESULT* MsgResultBuffer (LRESULT* plBuffer); private: // // Members. // BOOL* m_pbMsgHandled; // Was message handled? LRESULT* m_plMsgResult; // Message result code. // NotCopyable. CMsgWnd(const CMsgWnd&); CMsgWnd& operator=(const CMsgWnd&); }; /****************************************************************************** ** ** Macros used to ease the definition of the control message table. ** ******************************************************************************* */ #define DEFINE_CTRLMSG_TABLE static CTRLMSG CtrlMsgs[] = { #define CMD_CTRLMSG(id, msgid, fn) { (WM_COMMAND), (id), (msgid), (PFNMSGHANDLER) (fn) }, #define NFY_CTRLMSG(id, msgid, fn) { (WM_NOTIFY), (id), (msgid), (PFNMSGHANDLER) (fn) }, #define END_CTRLMSG_TABLE { 0, 0, 0, (PFNMSGHANDLER) (NULL) } }; \ m_pCtrlMsgTable = CtrlMsgs; /****************************************************************************** ** ** Implementation of inline functions. ** ******************************************************************************* */ inline int CMsgWnd::HorzScrollPos(int iPos, bool bRepaint) { return ::SetScrollPos(m_hWnd, SB_HORZ, iPos, bRepaint); } inline int CMsgWnd::VertScrollPos(int iPos, bool bRepaint) { return ::SetScrollPos(m_hWnd, SB_VERT, iPos, bRepaint); } inline int CMsgWnd::HorzScrollPos() { return ::GetScrollPos(m_hWnd, SB_HORZ); } inline int CMsgWnd::VertScrollPos() { return ::GetScrollPos(m_hWnd, SB_VERT); } inline void CMsgWnd::HorzScrollRange(int iMin, int iMax, bool bRepaint) { ::SetScrollRange(m_hWnd, SB_HORZ, iMin, iMax, bRepaint); } inline void CMsgWnd::VertScrollRange(int iMin, int iMax, bool bRepaint) { ::SetScrollRange(m_hWnd, SB_VERT, iMin, iMax, bRepaint); } inline WNDPROC CMsgWnd::WindowProc(WNDPROC lpfnWndProc) { return reinterpret_cast<WNDPROC>(::SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(lpfnWndProc))); } inline void CMsgWnd::MsgHandled(BOOL bHandled) { ASSERT(m_pbMsgHandled != NULL); *m_pbMsgHandled = bHandled; } inline void CMsgWnd::MsgResult(LRESULT lResult) { ASSERT(m_plMsgResult != NULL); *m_plMsgResult = lResult; } //////////////////////////////////////////////////////////////////////////////// //! Set the result for the message. This method replaces the need to make two //! calls - one to MsgHandled() and one to MsgResult() - with a single call. inline void CMsgWnd::SetMsgResult(BOOL bHandled, LRESULT lResult) { ASSERT(m_pbMsgHandled != NULL); ASSERT(m_plMsgResult != NULL); *m_pbMsgHandled = bHandled; *m_plMsgResult = lResult; } inline BOOL* CMsgWnd::MsgHandledBuffer(BOOL* pbBuffer) { BOOL* pbOldBuffer = m_pbMsgHandled; m_pbMsgHandled = pbBuffer; return pbOldBuffer; } inline LRESULT* CMsgWnd::MsgResultBuffer (LRESULT* plBuffer) { LRESULT* plOldBuffer = m_plMsgResult; m_plMsgResult = plBuffer; return plOldBuffer; } #endif //MSGWND_HPP
28.173387
117
0.642765
chrisoldwood
ea038c5120b075ddc7600e85808666bc4aaee631
552
cc
C++
Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc
abedeltawil/Licence3_Informatique
892b7b2cd74778539b534b57026bf8b4a3453c4f
[ "MIT" ]
1
2019-11-28T22:41:57.000Z
2019-11-28T22:41:57.000Z
Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc
abedeltawil/Licence3_Informatique
892b7b2cd74778539b534b57026bf8b4a3453c4f
[ "MIT" ]
null
null
null
Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc
abedeltawil/Licence3_Informatique
892b7b2cd74778539b534b57026bf8b4a3453c4f
[ "MIT" ]
7
2019-10-23T16:11:58.000Z
2019-12-14T12:27:27.000Z
#include "point.h" #include <iostream> #include <cstring> #include <cmath> using namespace std; Point::Point(){ this->x=0; this->y=0; } Point::Point(double x,double y){ this->x=x; this->y=y; } Point::Point(Point& p){ this->x=p.getX(); this->y=p.getY(); } double Point::getX(){ return this->x; } double Point::getY(){ return this->y; } void Point::affiche(){ cout<<"POINT ("<<this->x<<","<<this->y<<")"<<endl; } void Point::clone(const Point& p){ this->x=p.x; this->y=p.y; } Point::~Point(){ cout << "appel au destructeur Point"<<endl; }
15.333333
51
0.608696
abedeltawil
ea06bb35c1378bea013384c842221ae36d28d4c3
1,121
cpp
C++
src/dng_engine/XMLHelper.cpp
szczypiorofix/dungeon_engine
dd1db1c22a73eabd9ea18d44a133d71427957180
[ "MIT" ]
null
null
null
src/dng_engine/XMLHelper.cpp
szczypiorofix/dungeon_engine
dd1db1c22a73eabd9ea18d44a133d71427957180
[ "MIT" ]
null
null
null
src/dng_engine/XMLHelper.cpp
szczypiorofix/dungeon_engine
dd1db1c22a73eabd9ea18d44a133d71427957180
[ "MIT" ]
null
null
null
/* * Dungeon Engine * Copyright (C) 2020 szczypiorofix <szczypiorofix@o2.pl> */ #include "XMLHelper.h" int XMLHelper::xmlCharToInt(const xmlChar* a) { int c = 0, sign = 0, offset = 0, n = 0; if (a[0] == '-') { sign = -1; } if (sign == -1) { offset = 1; } else { offset = 0; } n = 0; for (c = offset; a[c] != '\0'; c++) { n = n * 10 + a[c] - '0'; } if (sign == -1) { n = -n; } return n; } short XMLHelper::xmlCharToShort(const xmlChar* a) { short c = 0, sign = 0, offset = 0, n = 0; if (a[0] == '-') { sign = -1; } if (sign == -1) { offset = 1; } else { offset = 0; } n = 0; for (c = offset; a[c] != '\0'; c++) { n = n * 10 + a[c] - '0'; } if (sign == -1) { n = -n; } return n; } int XMLHelper::readPropInt(xmlNodePtr node, const xmlChar* prop) { xmlChar* c = xmlGetProp(node, prop); int s = 0; if (c != NULL) { s = xmlCharToInt(c); xmlFree(c); } return s; } short XMLHelper::readPropShort(xmlNodePtr node, const xmlChar* prop) { xmlChar* c = xmlGetProp(node, prop); short s = 0; if (c != NULL) { s = xmlCharToShort(c); xmlFree(c); } return s; }
15.356164
70
0.522748
szczypiorofix
ea09432aabad0fc4950466ce982930d98fb37c09
5,518
cpp
C++
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
56
2017-02-14T13:19:52.000Z
2022-03-26T03:59:07.000Z
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
66
2017-04-22T01:02:04.000Z
2021-08-18T00:41:04.000Z
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
30
2017-02-16T09:07:31.000Z
2022-01-20T23:48:22.000Z
#include "hedgelib/io/hl_stream.h" #include <memory> namespace hl { stream::~stream() {} void stream::read_all(std::size_t size, void* buf) { const std::size_t readByteCount = read(size, buf); if (readByteCount != size) { // TODO: Throw a better error? HL_ERROR(error_type::unknown); } } void stream::write_all(std::size_t size, const void* buf) { const std::size_t writtenByteCount = write(size, buf); if (writtenByteCount != size) { // TODO: Throw a better error? HL_ERROR(error_type::unknown); } } static const u8 in_stream_nulls_static_buffer[1024] = { 0 }; void stream::write_nulls(std::size_t amount) { if (amount > sizeof(in_stream_nulls_static_buffer)) { // Allocate a buffer large enough to hold all of the nulls we want to write. std::unique_ptr<u8[]> nulls(new u8[amount]()); // Write the nulls to the stream. write_arr(amount, nulls.get()); } else { // Write the given amount of nulls to the stream using our static nulls buffer. write_arr(amount, in_stream_nulls_static_buffer); } } void stream::write_off32(std::size_t basePos, std::size_t offVal, bool doSwap, off_table& offTable) { // Compute offset. u32 off = static_cast<u32>(offVal - basePos); // Swap offset if necessary. if (doSwap) endian_swap(off); // Add offset position to offset table. offTable.push_back(tell()); // Write offset to stream. write_obj(off); } void stream::write_off64(std::size_t basePos, std::size_t offVal, bool doSwap, off_table& offTable) { // Compute offset. u64 off = static_cast<u64>(offVal - basePos); // Swap offset if necessary. if (doSwap) endian_swap(off); // Add offset position to offset table. offTable.push_back(tell()); // Write offset to stream. write_obj(off); } void stream::fix_off32(std::size_t basePos, std::size_t offPos, bool doSwap, off_table& offTable) { // Get end of stream position. const std::size_t endPos = tell(); // Jump to the given offset position. jump_to(offPos); // Fix the offset. write_off32(basePos, endPos, doSwap, offTable); // Jump back to end of stream. jump_to(endPos); } void stream::fix_off64(std::size_t basePos, std::size_t offPos, bool doSwap, off_table& offTable) { // Get end of stream position. const std::size_t endPos = tell(); // Jump to the given offset position. jump_to(offPos); // Fix the offset. write_off64(basePos, endPos, doSwap, offTable); // Jump back to end of stream. jump_to(endPos); } bool stream::read_str(std::size_t bufSize, char* buf) { constexpr std::size_t tmpBufSize = 20; char tmpBuf[tmpBufSize]; // Return early if bufSize == 0 if (!bufSize) return true; // Read string into buffer. while (true) { const std::size_t readByteCount = read(tmpBufSize, tmpBuf); const std::size_t safeWriteCount = std::min(readByteCount, bufSize); // Append a null terminator and return failure // if we've reached the end of the stream. if (readByteCount == 0) { *(buf++) = '\0'; return false; } // Otherwise, append all of the bytes we just read into the temporary buffer. for (std::size_t i = 0; i < safeWriteCount; ++i) { *(buf++) = tmpBuf[i]; // Jump to end of string and return success if we read a null terminator. if (tmpBuf[i] == '\0') { jump_behind(static_cast<long>(readByteCount - (i + 1))); return true; } } // Decrease writable buffer size. bufSize -= safeWriteCount; // Raise an error if we've exceeded the buffer size. if (!bufSize) { HL_ERROR(error_type::out_of_range); } } } std::string stream::read_str() { constexpr std::size_t tmpBufSize = 20; std::string str; char tmpBuf[tmpBufSize]; while (true) { const std::size_t readByteCount = read(tmpBufSize, tmpBuf); // Return if we've reached the end of the stream. if (readByteCount == 0) return str; // Otherwise, append all of the bytes we just read into the temporary buffer. for (std::size_t i = 0; i < readByteCount; ++i) { // Jump to end of string and return if we read a null terminator. if (tmpBuf[i] == '\0') { jump_behind(static_cast<long>(readByteCount - (i + 1))); return str; } // Append characters. str += tmpBuf[i]; } } } void stream::align(std::size_t stride) { std::size_t pos; // If stride is < 2, we don't need to align. if (stride-- < 2) return; /* Get the current stream position. */ pos = tell(); // Compute the closest position in the stream that's aligned // by the given stride, and jump to that position. jump_to(((pos + stride) & ~stride)); } void stream::pad(std::size_t stride) { std::size_t pos; // If stride is < 2, we don't need to pad. if (stride-- < 2) return; // Get the current stream position. pos = tell(); // Compute the amount of nulls we need to write to align the // stream with the given stride, and write that many nulls. write_nulls(((pos + stride) & ~stride) - pos); } } // hl
25.546296
87
0.600942
Radfordhound
ea0dfab3accb98ecb414c3727797d1580fc51380
1,529
cpp
C++
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
101
2017-08-08T12:08:01.000Z
2022-03-17T06:37:58.000Z
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
1,002
2018-01-09T10:33:07.000Z
2022-03-31T18:35:04.000Z
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
24
2018-01-05T20:16:36.000Z
2022-02-03T15:40:14.000Z
// // TM & (c) 2021 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXTest/Catch/catch.hpp> #include <MaterialXFormat/XmlExport.h> namespace mx = MaterialX; TEST_CASE("File Path Predicate", "[xmlexport]") { mx::FileSearchPath searchPath("libraries/stdlib"); mx::DocumentPtr doc = mx::createDocument(); mx::readFromXmlFile(doc, "resources/Materials/TestSuite/stdlib/export/export.mtlx", searchPath); mx::XmlExportOptions exportOptions; exportOptions.flattenFilenames = true; exportOptions.resolvedTexturePath = mx::FileSearchPath(mx::FilePath::getCurrentPath() / "resources" / "Materials" / "TestSuite" / "stdlib" / "export" ); mx::FileSearchPath textureSearchPath("resources"); exportOptions.skipFlattening = [textureSearchPath](const mx::FilePath& filePath) -> bool { return textureSearchPath.find(filePath) != filePath; }; std::stringstream ss; mx::exportToXmlStream(doc, ss, &exportOptions); mx::NodePtr node = doc->getNode("image_color3"); mx::NodePtr node2 = doc->getNode("image_color3_2"); REQUIRE(node); REQUIRE(node2); mx::InputPtr input = node->getInput("file"); mx::InputPtr input2 = node2->getInput("file"); REQUIRE(input->getValueString() == "Images/grid.png"); REQUIRE(mx::FileSearchPath(input2->getValueString()).asString() == exportOptions.resolvedTexturePath.find("black_image.png").asString()); }
36.404762
141
0.69261
jerrans
ea0f1967721cd8d30cf9086331dd8fd119eb2d3d
394
cpp
C++
solved/0-b/arrange-the-numbers/gen.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/arrange-the-numbers/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/arrange-the-numbers/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> #include <cstdlib> #include <ctime> #if 0 #define MAXT 1000 #define MAXN 1000 #endif #if 1 #define MAXT 20 #define MAXN 1000 #endif int T; void gen() { int N = rand() % MAXN + 1; int M = rand() % N + 1; int K = rand() % M + 1; printf("%d %d %d\n", N, M, K); --T; } int main() { srand(time(NULL)); T = MAXT; printf("%d\n", T); while (T) gen(); return 0; }
9.85
31
0.550761
abuasifkhan
ea157f15576755de1efd6ebc866056f8a9983480
111,373
cpp
C++
Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp
dphrygian/zeta
2b32760558cf2b20c626cf46fcf2a382924988fe
[ "Zlib", "Unlicense" ]
6
2022-01-22T02:18:07.000Z
2022-02-14T09:30:53.000Z
Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp
dphrygian/zeta
2b32760558cf2b20c626cf46fcf2a382924988fe
[ "Zlib", "Unlicense" ]
null
null
null
Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp
dphrygian/zeta
2b32760558cf2b20c626cf46fcf2a382924988fe
[ "Zlib", "Unlicense" ]
null
null
null
#include "core.h" #include "wbcomprosaplayer.h" #include "keyboard.h" #include "rosaworld.h" #include "rosaframework.h" #include "wbeventmanager.h" #include "wbcomprosatransform.h" #include "wbcomprosacollision.h" #include "wbcomprosacamera.h" #include "wbcomprosafootsteps.h" #include "wbcomprosahealth.h" #include "wbcomprosainventory.h" #include "wbcomprosaweapon.h" #include "wbcomprosafrobber.h" #include "wbcomprosafrobbable.h" #include "wbcomprosamesh.h" #include "Components/wbcompstatmod.h" #include "Components/wbcomplabel.h" #include "configmanager.h" #include "idatastream.h" #include "ray.h" #include "collisioninfo.h" #include "wbscene.h" #include "inputsystem.h" #include "configmanager.h" #include "mathcore.h" #include "rosagame.h" #include "rosasaveload.h" #include "reversehash.h" #include "matrix.h" #include "irenderer.h" #include "Common/uimanagercommon.h" #include "noise.h" #include "rosadifficulty.h" #include "rosacampaign.h" #if BUILD_DEV #if BUILD_WINDOWS #include "console.h" #endif #include "wbcomprosainventory.h" #include "wbcomprosarope.h" #include "wbcomprosavisible.h" #include "wbcomprosawallet.h" #include "wbcomprosakeyring.h" #include "wbcomprosalinkedentities.h" #include "wbcomponentarrays.h" #include "wbcomprosafaction.h" #include "fontmanager.h" #endif #define CAMERA_RELATIVE_CLIMBING 1 #define CAMERA_RELATIVE_CLIMBING_BIAS 1 WBCompRosaPlayer::WBCompRosaPlayer() : m_DeferMusic( false ) , m_InitialMusicTrackBits( 0 ) , m_RollingAutosaveDelay( 0.0f ) , m_RetryAutosaveDelay( 0.0f ) , m_AutosaveSuppRefsSerialized( 0 ) , m_AutosaveSuppRefsTransient( 0 ) , m_UnlandedForceFootstepWindow( 0.0f ) , m_UnlandedJumpWindow( 0.0f ) , m_UnlandedLeanWindow( 0.0f ) , m_LandAcceleration( 0.0f ) , m_AirAcceleration( 0.0f ) , m_TurnSpeed( 0.0f ) , m_JumpHeight( 0.0f ) , m_BackpedalScalar( 0.0f ) , m_UncrouchOnSprint( false ) , m_IsCrouched( false ) , m_IsUncrouching( false ) , m_IsForceCrouched( false ) , m_StandExtentsZ( 0.0f ) , m_CrouchExtentsZ( 0.0f ) , m_StandViewOffsetZ( 0.0f ) , m_CrouchViewOffsetZ( 0.0f ) , m_CrouchViewInterpTime( 0.0f ) , m_ViewOffsetZInterpolator() , m_PowerSlideRollInterpolator() , m_StepUpZInterpolator() , m_ViewBobOffsetInterpolator() , m_ViewBobAngleOffsetInterpolator() , m_ViewSwayOffsetInterpolator() , m_ViewSwayAngleOffsetInterpolator() , m_ViewHandsAcceleration() , m_ViewHandsVelocity() , m_ViewHandsRotationalAcceleration() , m_ViewHandsRotationalVelocity() , m_KickSpringK( 0.0f ) , m_KickDamperC( 0.0f ) , m_KickVelocity() , m_KickPosition() , m_ViewHandsSpringK( 0.0f ) , m_ViewHandsDamperC( 0.0f ) , m_PushToSprint( false ) , m_IsSprinting( false ) , m_IsSprintingWithMovement( false ) , m_SprintStartTime( 0.0f ) , m_SprintFOVScale( 0.0f ) , m_SprintFOVTime( 0.0f ) , m_DoubleJumpHeight( 0.0f ) , m_HasDoubleJumped( false ) , m_PowerJumpRatio( 0.0f ) , m_IsPowerSliding( false ) , m_PowerSlideDuration( 0.0f ) , m_PowerSlideEndTime( 0.0f ) , m_PowerSlideY() , m_PowerSlideInputContext() , m_PowerSlideReqVelocitySq( 0.0f ) , m_PowerSlideRoll( 0.0f ) , m_PowerSlideRollInterpTime( 0.0f ) , m_IsDragging( false ) , m_DragInputContext() , m_DragDropOffset() , m_DragDropOrientation() , m_DragDropSpawnImpulse( 0.0f ) , m_DragDropSpawnImpulseZ( 0.0f ) , m_DraggedEntity() , m_ClimbRefs( 0 ) , m_IsClimbing( false ) , m_ClimbInputContext() , m_ClimbOffImpulse( 0.0f ) , m_ClimbFacingBiasAngle( 0.0f ) , m_ClimbFacingBiasScale( 0.0f ) , m_IsMantling( false ) , m_MantleInputContext() , m_MantleVelocity( 0.0f ) , m_MantleVector() , m_MantleDestination() , m_CanMantle( false ) , m_AutoAimEnabled( false ) , m_AutoAimMaxTurn( 0.0f ) , m_SprintFOVEnabled( false ) , m_CurrentFOV() , m_CurrentFGFOV() , m_IsDisablingPause( false ) , m_HasSetSpawnPoint( false ) , m_SpawnLocation() , m_SpawnOrientation() , m_IsFlying( false ) , m_MaxViewBobOffset() , m_MaxViewBobAngleOffset() , m_UnlandedViewBobWindow( 0.0f ) , m_ViewBobAngleExponent( 0.0f ) , m_ViewBobInterpolateTime( 0.0f ) , m_MaxViewSwayOffset() , m_MaxViewSwayAngleOffset() , m_ViewSwayInterpolateTime( 0.0f ) , m_ViewSwayNoiseOctaves( 0 ) , m_ViewSwayNoiseScalars() , m_ViewSwayNoiseAngleScalars() #if BUILD_DEV , m_DEVHACKDebugTarget() , m_DEVHACKClockMultiplier( NULL ) , m_CAMHACKPathData() , m_CAMHACKCamActive( false ) , m_CAMHACKCamVelocity( 1.0f ) , m_CAMHACKCamLocation() , m_CAMHACKCamOrientation() , m_CAMHACKCamStartLocation() , m_CAMHACKCamEndLocation() , m_CAMHACKCamStartOrientation() , m_CAMHACKCamEndOrientation() , m_DebugSpawners() , m_DebugSpawnerIndex( 0 ) , m_CACHED_LastAINoiseSourceLocation() , m_CACHED_LastAINoiseRadius( 0.0f ) #endif { STATIC_HASHED_STRING( PreLevelTransition ); GetEventManager()->AddObserver( sPreLevelTransition, this ); STATIC_HASHED_STRING( PostLevelTransition ); GetEventManager()->AddObserver( sPostLevelTransition, this ); STATIC_HASHED_STRING( OnAINoise ); GetEventManager()->AddObserver( sOnAINoise, this ); GetFramework()->GetInputSystem()->AddInputSystemObserver( this ); } WBCompRosaPlayer::~WBCompRosaPlayer() { WBEventManager* const pEventManager = GetEventManager(); if( pEventManager ) { STATIC_HASHED_STRING( PreLevelTransition ); pEventManager->RemoveObserver( sPreLevelTransition, this ); STATIC_HASHED_STRING( PostLevelTransition ); pEventManager->RemoveObserver( sPostLevelTransition, this ); STATIC_HASHED_STRING( OnAINoise ); pEventManager->RemoveObserver( sOnAINoise, this ); } InputSystem* const pInputSystem = GetFramework()->GetInputSystem(); if( pInputSystem ) { pInputSystem->RemoveInputSystemObserver( this ); } } /*virtual*/ void WBCompRosaPlayer::InitializeFromDefinition( const SimpleString& DefinitionName ) { RosaCampaign* const pCampaign = RosaCampaign::GetCampaign(); Super::InitializeFromDefinition( DefinitionName ); MAKEHASH( DefinitionName ); STATICHASH( DeferMusic ); m_DeferMusic = ConfigManager::GetInheritedBool( sDeferMusic, false, sDefinitionName ); STATICHASH( InitialMusicTrackBits ); m_InitialMusicTrackBits = pCampaign->OverrideInt( sInitialMusicTrackBits, ConfigManager::GetInheritedInt( sInitialMusicTrackBits, 0, sDefinitionName ) ); STATICHASH( RollingAutosaveDelay ); m_RollingAutosaveDelay = ConfigManager::GetInheritedFloat( sRollingAutosaveDelay, 0.0f, sDefinitionName ); STATICHASH( RetryAutosaveDelay ); m_RetryAutosaveDelay = ConfigManager::GetInheritedFloat( sRetryAutosaveDelay, 0.0f, sDefinitionName ); STATICHASH( UnlandedForceFootstepWindow ); m_UnlandedForceFootstepWindow = ConfigManager::GetInheritedFloat( sUnlandedForceFootstepWindow, 0.0f, sDefinitionName ); STATICHASH( UnlandedJumpWindow ); m_UnlandedJumpWindow = ConfigManager::GetInheritedFloat( sUnlandedJumpWindow, 0.0f, sDefinitionName ); STATICHASH( UnlandedLeanWindow ); m_UnlandedLeanWindow = ConfigManager::GetInheritedFloat( sUnlandedLeanWindow, 0.0f, sDefinitionName ); STATICHASH( LandAcceleration ); m_LandAcceleration = ConfigManager::GetInheritedFloat( sLandAcceleration, 0.0f, sDefinitionName ); STATICHASH( AirAcceleration ); m_AirAcceleration = ConfigManager::GetInheritedFloat( sAirAcceleration, 0.0f, sDefinitionName ); STATICHASH( TurnSpeed ); m_TurnSpeed = ConfigManager::GetInheritedFloat( sTurnSpeed, 0.0f, sDefinitionName ); STATICHASH( JumpHeight ); m_JumpHeight = ConfigManager::GetInheritedFloat( sJumpHeight, 0.0f, sDefinitionName ); STATICHASH( BackpedalScalar ); m_BackpedalScalar = ConfigManager::GetInheritedFloat( sBackpedalScalar, 1.0f, sDefinitionName ); STATICHASH( DoubleJumpHeight ); m_DoubleJumpHeight = ConfigManager::GetInheritedFloat( sDoubleJumpHeight, 0.0f, sDefinitionName ); STATICHASH( PowerJumpRatio ); m_PowerJumpRatio = ConfigManager::GetInheritedFloat( sPowerJumpRatio, 0.0f, sDefinitionName ); STATICHASH( UncrouchOnSprint ); m_UncrouchOnSprint = ConfigManager::GetInheritedBool( sUncrouchOnSprint, false, sDefinitionName ); STATICHASH( SprintFOVScale ); m_SprintFOVScale = ConfigManager::GetInheritedFloat( sSprintFOVScale, 1.0f, sDefinitionName ); STATICHASH( SprintFOVTime ); m_SprintFOVTime = ConfigManager::GetInheritedFloat( sSprintFOVTime, 0.0f, sDefinitionName ); STATICHASH( StandExtentsZ ); m_StandExtentsZ = ConfigManager::GetInheritedFloat( sStandExtentsZ, 0.0f, sDefinitionName ); STATICHASH( CrouchExtentsZ ); m_CrouchExtentsZ = ConfigManager::GetInheritedFloat( sCrouchExtentsZ, 0.0f, sDefinitionName ); STATICHASH( StandViewOffsetZ ); m_StandViewOffsetZ = ConfigManager::GetInheritedFloat( sStandViewOffsetZ, 0.0f, sDefinitionName ); m_ViewOffsetZInterpolator.Reset( m_StandViewOffsetZ ); STATICHASH( CrouchViewOffsetZ ); m_CrouchViewOffsetZ = ConfigManager::GetInheritedFloat( sCrouchViewOffsetZ, 0.0f, sDefinitionName ); STATICHASH( CrouchViewInterpTime ); m_CrouchViewInterpTime = ConfigManager::GetInheritedFloat( sCrouchViewInterpTime, 0.0f, sDefinitionName ); STATICHASH( PushToSprint ); m_PushToSprint = ConfigManager::GetInheritedBool( sPushToSprint, false, sDefinitionName ); STATICHASH( PowerSlideDuration ); m_PowerSlideDuration = ConfigManager::GetInheritedFloat( sPowerSlideDuration, 0.0f, sDefinitionName ); STATICHASH( PowerSlideInputContext ); m_PowerSlideInputContext = ConfigManager::GetInheritedHash( sPowerSlideInputContext, HashedString::NullString, sDefinitionName ); STATICHASH( PowerSlideReqVelocity ); m_PowerSlideReqVelocitySq = Square( ConfigManager::GetInheritedFloat( sPowerSlideReqVelocity, 0.0f, sDefinitionName ) ); STATICHASH( PowerSlideRoll ); m_PowerSlideRoll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sPowerSlideRoll, 0.0f, sDefinitionName ) ); STATICHASH( PowerSlideRollInterpTime ); m_PowerSlideRollInterpTime = ConfigManager::GetInheritedFloat( sPowerSlideRollInterpTime, 0.0f, sDefinitionName ); STATICHASH( DragInputContext ); m_DragInputContext = ConfigManager::GetInheritedHash( sDragInputContext, HashedString::NullString, sDefinitionName ); STATICHASH( DragDropOffsetZ ); m_DragDropOffset.z = ConfigManager::GetInheritedFloat( sDragDropOffsetZ, 0.0f, sDefinitionName ); STATICHASH( DragDropOrientationYaw ); m_DragDropOrientation.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sDragDropOrientationYaw, 0.0f, sDefinitionName ) ); STATICHASH( DragDropSpawnImpulse ); m_DragDropSpawnImpulse = ConfigManager::GetInheritedFloat( sDragDropSpawnImpulse, 0.0f, sDefinitionName ); STATICHASH( DragDropSpawnImpulseZ ); m_DragDropSpawnImpulseZ = ConfigManager::GetInheritedFloat( sDragDropSpawnImpulseZ, 0.0f, sDefinitionName ); STATICHASH( ClimbInputContext ); m_ClimbInputContext = ConfigManager::GetInheritedHash( sClimbInputContext, HashedString::NullString, sDefinitionName ); STATICHASH( ClimbOffImpulse ); m_ClimbOffImpulse = ConfigManager::GetInheritedFloat( sClimbOffImpulse, 0.0f, sDefinitionName ); STATICHASH( ClimbFacingBiasAngle ); m_ClimbFacingBiasAngle = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sClimbFacingBiasAngle, 0.0f, sDefinitionName ) ); STATICHASH( ClimbFacingBiasScale ); m_ClimbFacingBiasScale = ConfigManager::GetInheritedFloat( sClimbFacingBiasScale, 0.0f, sDefinitionName ); STATICHASH( MantleInputContext ); m_MantleInputContext = ConfigManager::GetInheritedHash( sMantleInputContext, HashedString::NullString, sDefinitionName ); STATICHASH( MantleVelocity ); m_MantleVelocity = ConfigManager::GetInheritedFloat( sMantleVelocity, 0.0f, sDefinitionName ); // Not a config var of the component! STATICHASH( AutoAim ); m_AutoAimEnabled = ConfigManager::GetBool( sAutoAim ); STATICHASH( AutoAimMaxTurn ); m_AutoAimMaxTurn = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sAutoAimMaxTurn, 0.0f, sDefinitionName ) ); // Not a config var of the component! STATICHASH( SprintFOV ); m_SprintFOVEnabled = ConfigManager::GetBool( sSprintFOV ); STATICHASH( MaxViewBobOffsetX ); m_MaxViewBobOffset.x = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetX, 0.0f, sDefinitionName ); STATICHASH( MaxViewBobOffsetY ); m_MaxViewBobOffset.y = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetY, 0.0f, sDefinitionName ); STATICHASH( MaxViewBobOffsetZ ); m_MaxViewBobOffset.z = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetZ, 0.0f, sDefinitionName ); STATICHASH( MaxViewBobAngleOffsetPitch ); m_MaxViewBobAngleOffset.Pitch = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetPitch, 0.0f, sDefinitionName ) ); STATICHASH( MaxViewBobAngleOffsetRoll ); m_MaxViewBobAngleOffset.Roll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetRoll, 0.0f, sDefinitionName ) ); STATICHASH( MaxViewBobAngleOffsetYaw ); m_MaxViewBobAngleOffset.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetYaw, 0.0f, sDefinitionName ) ); STATICHASH( UnlandedViewBobWindow ); m_UnlandedViewBobWindow = ConfigManager::GetInheritedFloat( sUnlandedViewBobWindow, 0.0f, sDefinitionName ); STATICHASH( ViewBobAngleExponent ); m_ViewBobAngleExponent = ConfigManager::GetInheritedFloat( sViewBobAngleExponent, 0.0f, sDefinitionName ); STATICHASH( ViewBobInterpolateTime ); m_ViewBobInterpolateTime = ConfigManager::GetInheritedFloat( sViewBobInterpolateTime, 0.0f, sDefinitionName ); STATICHASH( MaxViewSwayOffsetX ); m_MaxViewSwayOffset.x = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetX, 0.0f, sDefinitionName ); STATICHASH( MaxViewSwayOffsetY ); m_MaxViewSwayOffset.y = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetY, 0.0f, sDefinitionName ); STATICHASH( MaxViewSwayOffsetZ ); m_MaxViewSwayOffset.z = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetZ, 0.0f, sDefinitionName ); STATICHASH( MaxViewSwayAngleOffsetPitch ); m_MaxViewSwayAngleOffset.Pitch = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetPitch, 0.0f, sDefinitionName ) ); STATICHASH( MaxViewSwayAngleOffsetRoll ); m_MaxViewSwayAngleOffset.Roll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetRoll, 0.0f, sDefinitionName ) ); STATICHASH( MaxViewSwayAngleOffsetYaw ); m_MaxViewSwayAngleOffset.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetYaw, 0.0f, sDefinitionName ) ); STATICHASH( ViewSwayInterpolateTime ); m_ViewSwayInterpolateTime = ConfigManager::GetInheritedFloat( sViewSwayInterpolateTime, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseOctaves ); m_ViewSwayNoiseOctaves = ConfigManager::GetInheritedInt( sViewSwayNoiseOctaves, 0, sDefinitionName ); STATICHASH( ViewSwayNoiseScalarsX ); m_ViewSwayNoiseScalars.x = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsX, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseScalarsY ); m_ViewSwayNoiseScalars.y = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsY, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseScalarsZ ); m_ViewSwayNoiseScalars.z = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsZ, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseAngleScalarsPitch ); m_ViewSwayNoiseAngleScalars.x = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsPitch, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseAngleScalarsRoll ); m_ViewSwayNoiseAngleScalars.y = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsRoll, 0.0f, sDefinitionName ); STATICHASH( ViewSwayNoiseAngleScalarsYaw ); m_ViewSwayNoiseAngleScalars.z = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsYaw, 0.0f, sDefinitionName ); STATICHASH( KickSpringK ); m_KickSpringK = ConfigManager::GetInheritedFloat( sKickSpringK, 0.0f, sDefinitionName ); STATICHASH( KickDamperC ); m_KickDamperC = ConfigManager::GetInheritedFloat( sKickDamperC, 0.0f, sDefinitionName ); STATICHASH( ViewHandsSpringK ); m_ViewHandsSpringK = ConfigManager::GetInheritedFloat( sViewHandsSpringK, 0.0f, sDefinitionName ); STATICHASH( ViewHandsDamperC ); m_ViewHandsDamperC = ConfigManager::GetInheritedFloat( sViewHandsDamperC, 0.0f, sDefinitionName ); #if BUILD_DEV const uint NumActiveContexts = GetFramework()->GetInputSystem()->GetNumActiveContexts(); const bool IsInTitleScreen = GetGame()->IsInTitleScreen(); // This isn't really the player component's domain, it's just a convenient place to validate this. // Title screen has a null input context, so it is excepted. DEVASSERT( NumActiveContexts == 0 || IsInTitleScreen ); #endif // BUILD_DEV #if BUILD_DEV STATICHASH( RosaPlayer_DebugSpawner ); STATICHASH( NumEntities ); const uint NumEntities = ConfigManager::GetInt( sNumEntities, 0, sRosaPlayer_DebugSpawner ); for( uint EntityIndex = 0; EntityIndex < NumEntities; ++EntityIndex ) { SDebugSpawner& Spawner = m_DebugSpawners.PushBack(); Spawner.m_Entity = ConfigManager::GetSequenceString( "Entity%d", EntityIndex, "", sRosaPlayer_DebugSpawner ); Spawner.m_Offset.x = ConfigManager::GetSequenceFloat( "Entity%dX", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner ); Spawner.m_Offset.y = ConfigManager::GetSequenceFloat( "Entity%dY", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner ); Spawner.m_Offset.z = ConfigManager::GetSequenceFloat( "Entity%dZ", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner ); Spawner.m_NormalDistance = ConfigManager::GetSequenceFloat( "Entity%dN", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner ); } #endif } void WBCompRosaPlayer::TickViewBobAndSway() { XTRACE_FUNCTION; PROFILE_FUNCTION; WBEntity* const pEntity = GetEntity(); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); WBCompRosaHealth* const pHealth = WB_GETCOMP( pEntity, RosaHealth ); WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); // NOTE: This uses the transform's *default* speed limit, not the modded speed limit. // Which is what I want here, because then it saturates while running even if speed limit is increased. const bool DoViewBob = pHealth->IsAlive() && pCollision->IsRecentlyLanded( m_UnlandedViewBobWindow ) && !m_IsPowerSliding && !m_IsClimbing && !m_IsMantling; const float ViewBobScalar = Saturate( pTransform->GetVelocity().Length2D() / pTransform->GetSpeedLimit() ); const float ViewBobAngleScalar = Pow( ViewBobScalar, m_ViewBobAngleExponent ); const float ViewBobAlphaX = pFootsteps ? pFootsteps->GetStepPhaseSignedAlpha() : 0.0f; // [-1, 1] const float ViewBobAlphaYZ = Abs( ViewBobAlphaX ); // [0, 1] const Vector ViewBobAlpha = Vector( ViewBobAlphaX, ViewBobAlphaYZ, ViewBobAlphaYZ ); const Angles ViewBobAngleAlpha = Angles( ViewBobAlphaYZ, ViewBobAlphaX, ViewBobAlphaX ); const Vector ViewBobOffset = ( ViewBobScalar * ViewBobAlpha * m_MaxViewBobOffset ) * pTransform->GetOrientation().ToMatrix(); const Angles ViewBobAngleOffset = ( ViewBobAngleScalar * ViewBobAngleAlpha * m_MaxViewBobAngleOffset ); const bool DoViewSway = true; const Vector ViewSwayAlpha = Vector( Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.x, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ), Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.y, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ), Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.z, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ) ); const Angles ViewSwayAngleAlpha = Angles( Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.x, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ), Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.y, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ), Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.z, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ) ); WB_MODIFY_FLOAT( ViewSwayOffsetScalar, 1.0f, pStatMod ); const float ViewSwayOffsetScalar = WB_MODDED( ViewSwayOffsetScalar ); WB_MODIFY_FLOAT( ViewSwayAngleOffsetScalar, 1.0f, pStatMod ); const float ViewSwayAngleOffsetScalar = WB_MODDED( ViewSwayAngleOffsetScalar ); const Vector ViewSwayOffset = ViewSwayOffsetScalar * ( ( ViewSwayAlpha * m_MaxViewSwayOffset ) * pTransform->GetOrientation().ToMatrix() ); const Angles ViewSwayAngleOffset = ViewSwayAngleOffsetScalar * ( ViewSwayAngleAlpha * m_MaxViewSwayAngleOffset ); // Constantly resetting from current value produces an ease-out effect m_ViewBobOffsetInterpolator.Reset( Interpolator<Vector>::EIT_Linear, m_ViewBobOffsetInterpolator.GetValue(), DoViewBob ? ViewBobOffset : Vector(), m_ViewBobInterpolateTime ); m_ViewBobAngleOffsetInterpolator.Reset( Interpolator<Angles>::EIT_Linear, m_ViewBobAngleOffsetInterpolator.GetValue(), DoViewBob ? ViewBobAngleOffset : Angles(), m_ViewBobInterpolateTime ); m_ViewSwayOffsetInterpolator.Reset( Interpolator<Vector>::EIT_Linear, m_ViewSwayOffsetInterpolator.GetValue(), DoViewSway ? ViewSwayOffset : Vector(), m_ViewSwayInterpolateTime ); m_ViewSwayAngleOffsetInterpolator.Reset( Interpolator<Angles>::EIT_Linear, m_ViewSwayAngleOffsetInterpolator.GetValue(), DoViewSway ? ViewSwayAngleOffset : Angles(), m_ViewSwayInterpolateTime ); } WBCompRosaWeapon* WBCompRosaPlayer::GetWeapon() const { WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaInventory* const pInventory = WB_GETCOMP( pEntity, RosaInventory ); DEVASSERT( pInventory ); WBEntity* const pWeaponEntity = pInventory->GetCycleItem(); WBCompRosaWeapon* const pWeapon = WB_GETCOMP_SAFE( pWeaponEntity, RosaWeapon ); return pWeapon; } void WBCompRosaPlayer::TickKick( const float DeltaTime ) { WBCompRosaWeapon* const pWeapon = GetWeapon(); const float SpringK = ( pWeapon && pWeapon->GetKickSpringK() > 0.0f ) ? pWeapon->GetKickSpringK() : m_KickSpringK; const float DamperC = ( pWeapon && pWeapon->GetKickDamperC() > 0.0f ) ? pWeapon->GetKickDamperC() : m_KickDamperC; // Spring-damping system (ignoring mass because it's just a multiple of this equation) const Angles KickAcceleration = ( -SpringK * m_KickPosition ) + ( -DamperC * m_KickVelocity ); m_KickVelocity += KickAcceleration * DeltaTime; m_KickPosition += m_KickVelocity * DeltaTime; } void WBCompRosaPlayer::TickHandsVelocity( const float DeltaTime, const Vector& TargetVelocity, const Angles& TargetRotationalVelocity ) { // Here, the velocity *is* the position for the spring system; so "velocity" becomes acceleration, and "acceleration" becomes jerk. // This system typically tries to center at the origin instead of a target; // so subtract to get our "position" (velocity). const Vector CurrentVelocity = m_ViewHandsVelocity - TargetVelocity; const Angles CurrentRotationalVelocity = m_ViewHandsRotationalVelocity - TargetRotationalVelocity; const Vector ViewHandsJerk = ( -m_ViewHandsSpringK * CurrentVelocity ) + ( -m_ViewHandsDamperC * m_ViewHandsAcceleration ); const Angles ViewHandsRotationalJerk = ( -m_ViewHandsSpringK * CurrentRotationalVelocity ) + ( -m_ViewHandsDamperC * m_ViewHandsRotationalAcceleration ); m_ViewHandsAcceleration += ViewHandsJerk * DeltaTime; m_ViewHandsRotationalAcceleration += ViewHandsRotationalJerk * DeltaTime; m_ViewHandsVelocity += m_ViewHandsAcceleration * DeltaTime; m_ViewHandsRotationalVelocity += m_ViewHandsRotationalAcceleration * DeltaTime; } // Sticky targeting (lock-on, auto aim, aim assist, whatever) // Orient to face aim target, if any; only if we're using the controller. // This isn't dependent on input per se, but it's probably best // if we only do it in cases where turning isn't suppressed. // ROSATODO: This should probably still be an option, even if it's controller-only. void WBCompRosaPlayer::TickAutoAim( const float DeltaTime ) { if( !m_AutoAimEnabled ) { return; } STATIC_HASHED_STRING( TurnX ); STATIC_HASHED_STRING( TurnY ); InputSystem* const pInputSystem = GetFramework()->GetInputSystem(); if( !pInputSystem->IsUsingControllerExclusively() || pInputSystem->IsSuppressed( sTurnX ) || pInputSystem->IsSuppressed( sTurnY ) ) { return; } WBCompRosaWeapon* const pWeapon = GetWeapon(); if( !pWeapon || !pWeapon->CanAutoAim() ) { return; } WBEntity* const pEntity = GetEntity(); WBCompRosaFrobber* const pFrobber = WB_GETCOMP( pEntity, RosaFrobber ); WBEntity* pAimTarget; HashedString AimTargetBone; pFrobber->GetAimTarget( pAimTarget, AimTargetBone ); if( !pAimTarget ) { return; } WBCompRosaFrobbable* const pFrobbable = WB_GETCOMP( pAimTarget, RosaFrobbable ); DEVASSERT( pFrobbable ); if( !pFrobbable->CanBeAutoAimedAt() ) { return; } WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera ); WBCompRosaMesh* const pAimTargetMesh = WB_GETCOMP( pAimTarget, RosaMesh ); const Vector BoneLocation = pAimTargetMesh->GetBoneLocation( pAimTargetMesh->GetBoneIndex( AimTargetBone ) ); const Vector CameraLocation = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); const Angles OldOrientation = pTransform->GetOrientation(); const Vector AimOffset = BoneLocation - CameraLocation; const Angles AimOrientation = AimOffset.ToAngles(); Angles TurnOffset = ( AimOrientation - pTransform->GetOrientation() ).GetShortestRotation(); const float MaxTurn = DeltaTime * m_AutoAimMaxTurn; TurnOffset.Yaw = Clamp( TurnOffset.Yaw, -MaxTurn, MaxTurn ); TurnOffset.Pitch = Clamp( TurnOffset.Pitch, -MaxTurn, MaxTurn ); const Angles NewOrientation = WBCompRosaTransform::ClampPitch( OldOrientation + TurnOffset ); pTransform->SetOrientation( NewOrientation ); } /*virtual*/ void WBCompRosaPlayer::Tick( const float DeltaTime ) { XTRACE_FUNCTION; PROFILE_FUNCTION; WBEntity* const pEntity = GetEntity(); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera ); WBCompRosaHealth* const pHealth = WB_GETCOMP( pEntity, RosaHealth ); WBCompRosaInventory* const pInventory = WB_GETCOMP( pEntity, RosaInventory ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); WBCompRosaWeapon* const pWeapon = GetWeapon(); WBEventManager* const pEventManager = GetEventManager(); InputSystem* const pInputSystem = GetFramework()->GetInputSystem(); #if BUILD_DEV if( m_CAMHACKCamActive ) { m_CAMHACKCamLocation.Tick( DeltaTime ); m_CAMHACKCamOrientation.Tick( DeltaTime ); WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps ); pTransform->SetLocation( m_CAMHACKCamLocation.GetValue() ); pTransform->SetOrientation( m_CAMHACKCamOrientation.GetValue() ); if( m_CAMHACKCamLocation.GetT() == 1.0f ) { m_CAMHACKCamActive = false; pCollision->ResetCollisionFlags(); pTransform->SetDefaultGravity(); if( pFootsteps ) { pFootsteps->SetFootstepsDisabled( false ); } WB_MAKE_EVENT( ShowHands, GetEntity() ); WB_DISPATCH_EVENT( pEventManager, ShowHands, GetEntity() ); STATIC_HASHED_STRING( HUD ); WB_MAKE_EVENT( RepushUIScreen, NULL ); WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD ); WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL ); } } #endif // BUILD_DEV TickViewBobAndSway(); TickKick( DeltaTime ); TickHandsVelocity( DeltaTime, pTransform->GetVelocity(), pTransform->GetRotationalVelocity() ); if( pHealth->IsAlive() ) { m_ViewOffsetZInterpolator.Tick( DeltaTime ); pCamera->SetViewOffsetZ( m_ViewOffsetZInterpolator.GetValue() ); m_PowerSlideRollInterpolator.Tick( DeltaTime ); pCamera->SetSlideRoll( m_PowerSlideRollInterpolator.GetValue() ); m_StepUpZInterpolator.Tick( DeltaTime ); pCamera->SetStepUpZ( m_StepUpZInterpolator.GetValue() ); // Stat mod kick at the last minute instead of for each impulse WB_MODIFY_FLOAT( KickScalar, 1.0f, pStatMod ); pCamera->SetKickAngleOffset( m_KickPosition * WB_MODDED( KickScalar ) ); } else { pCamera->SetKickAngleOffset( Angles() ); } // Do this part regardless of being alive, I guess { m_ViewBobOffsetInterpolator.Tick( DeltaTime ); pCamera->SetViewBobOffset( m_ViewBobOffsetInterpolator.GetValue() ); m_ViewBobAngleOffsetInterpolator.Tick( DeltaTime ); pCamera->SetViewBobAngleOffset( m_ViewBobAngleOffsetInterpolator.GetValue() ); m_ViewSwayOffsetInterpolator.Tick( DeltaTime ); pCamera->SetViewSwayOffset( m_ViewSwayOffsetInterpolator.GetValue() ); m_ViewSwayAngleOffsetInterpolator.Tick( DeltaTime ); pCamera->SetViewSwayAngleOffset( m_ViewSwayAngleOffsetInterpolator.GetValue() ); pCamera->SetHandsVelocity( m_ViewHandsVelocity, m_ViewHandsRotationalVelocity ); } // Update FOVs, factoring in weapon aim and any other stat mods // Weapon aim FOV takes priority, then fall back to sprint/normal, then apply stat mods const bool UseSprintFOV = m_SprintFOVEnabled && ( m_IsSprintingWithMovement || m_IsPowerSliding ); const float BaseFOVScale = ( pWeapon && pWeapon->IsAiming() ) ? pWeapon->GetAimZoom() : ( UseSprintFOV ? m_SprintFOVScale : 1.0f ); const float BaseFGFOVScale = ( pWeapon && pWeapon->IsAiming() ) ? pWeapon->GetAimZoomFG() : 1.0f; const float BaseFOVTime = ( pWeapon && pWeapon->IsAimChanging() ) ? pWeapon->GetAimTime() : m_SprintFOVTime; WB_MODIFY_FLOAT( FOVScale, BaseFOVScale, pStatMod ); WB_MODIFY_FLOAT( FGFOVScale, BaseFGFOVScale, pStatMod ); WB_MODIFY_FLOAT( FOVTime, BaseFOVTime, pStatMod ); STATICHASH( FOV ); STATICHASH( ForegroundFOV ); TickScaleFOV( m_CurrentFOV, ConfigManager::GetFloat( sFOV ), WB_MODDED( FOVScale ), WB_MODDED( FOVTime ), DeltaTime ); TickScaleFOV( m_CurrentFGFOV, ConfigManager::GetFloat( sForegroundFOV ), WB_MODDED( FGFOVScale ), WB_MODDED( FOVTime ), DeltaTime ); GetFramework()->SetFOV( m_CurrentFOV.GetValue() ); GetFramework()->SetFGFOV( m_CurrentFGFOV.GetValue() ); if( m_IsUncrouching ) { TryUncrouch(); } if( m_IsPowerSliding ) { if( GetTime() >= m_PowerSlideEndTime ) { EndPowerSlide(); } } // ********************************************************************************************* // ********************************************************************************************* // ********************************************************************************************* // // Everything before this point is independent of current input and must be done every tick. // Everything after this point is dependent on input and should be done only when we have focus. // // ********************************************************************************************* // ********************************************************************************************* // ********************************************************************************************* if( !GetFramework()->HasFocus() ) { return; } TickAutoAim( DeltaTime ); DEVASSERT( pTransform ); DEVASSERT( pCollision ); DEVASSERT( pCamera ); DEVASSERT( pStatMod ); // Get 2D orientation; we don't want to move as if we're flying. Angles PlayerOrientation; Vector X, Y, Z; const Vector UpVector = Vector( 0.0f, 0.0f, 1.0f ); const Vector PlayerFacing = pTransform->GetOrientation().ToVector(); const Vector PlayerRight = PlayerFacing.Cross( UpVector ).GetNormalized(); // DLP 8 Nov 2019: This didn't used to be normalized, not sure if it could've been a problem if( m_IsFlying ) { PlayerOrientation = pTransform->GetOrientation(); } else { PlayerOrientation.Yaw = pTransform->GetOrientation().Yaw; } PlayerOrientation.GetAxes( X, Y, Z ); Vector MovementVector; Angles TurnAngles; Vector ImpulseVector; STATIC_HASHED_STRING( Right ); STATIC_HASHED_STRING( Left ); STATIC_HASHED_STRING( Forward ); STATIC_HASHED_STRING( Back ); STATIC_HASHED_STRING( MoveX ); STATIC_HASHED_STRING( MoveY ); STATIC_HASHED_STRING( Jump ); STATIC_HASHED_STRING( Heal ); STATIC_HASHED_STRING( UseWeapon ); STATIC_HASHED_STRING( Shove ); STATIC_HASHED_STRING( Reload ); STATIC_HASHED_STRING( Zoom ); STATIC_HASHED_STRING( Light ); STATIC_HASHED_STRING( CycleMag ); STATIC_HASHED_STRING( Radial ); STATIC_HASHED_STRING( CycleSlot0 ); STATIC_HASHED_STRING( CycleSlot1 ); STATIC_HASHED_STRING( CycleSlot2 ); STATIC_HASHED_STRING( CycleSlot3 ); STATIC_HASHED_STRING( CyclePrev ); STATIC_HASHED_STRING( CycleNext ); STATIC_HASHED_STRING( Frob ); STATIC_HASHED_STRING( LeanLeft ); STATIC_HASHED_STRING( LeanRight ); STATIC_HASHED_STRING( TurnX ); STATIC_HASHED_STRING( TurnY ); STATIC_HASHED_STRING( Run ); STATIC_HASHED_STRING( Crouch ); STATIC_HASHED_STRING( ClimbForward ); STATIC_HASHED_STRING( ClimbBack ); STATIC_HASHED_STRING( ClimbDown ); STATIC_HASHED_STRING( ClimbY ); STATIC_HASHED_STRING( ClimbJump ); STATIC_HASHED_STRING( Mantle ); if( pInputSystem->IsHigh( sRight ) ) { MovementVector += X; } if( pInputSystem->IsHigh( sLeft ) ) { MovementVector -= X; } if( pInputSystem->IsHigh( sForward ) ) { MovementVector += Y; } if( pInputSystem->IsHigh( sBack ) ) { MovementVector -= Y * m_BackpedalScalar; } if( m_IsFlying ) { // TODO: Maybe do this with an input context? It's really just a borrowed hack from Acid for ghosting right now, whatever. if( pInputSystem->IsHigh( sJump ) ) { MovementVector += UpVector; } if( pInputSystem->IsHigh( sCrouch ) ) { MovementVector -= UpVector; } } const float MoveX = pInputSystem->GetPosition( sMoveX ); const float MoveY = pInputSystem->GetPosition( sMoveY ); MovementVector += X * MoveX; MovementVector += Y * MoveY * ( ( MoveY < 0.0f ) ? m_BackpedalScalar : 1.0f ); const bool HasMovementInput = MovementVector.LengthSquared() >= 0.1f || pInputSystem->IsHigh( sMantle ); // HACKHACK to keep spring on during mantle, since the input context disabled MoveX/Y const bool WasSprinting = m_IsSprinting; if( m_PushToSprint ) { // In this mode, latch the sprinting flag until movement stops. if( pInputSystem->IsHigh( sRun ) ) { m_IsSprinting = true; } else if( !HasMovementInput ) { m_IsSprinting = false; } } else { m_IsSprinting = pInputSystem->IsHigh( sRun ); } m_IsSprintingWithMovement = m_IsSprinting && HasMovementInput; if( !WasSprinting && m_IsSprinting ) { m_SprintStartTime = GetTime(); } // If we're crouched and we start sprinting, even if we don't have any movement input, then uncrouch. // (Surprisingly, this feels more correct than requiring movement input. Feels weird to be crouched, // press shift, start moving, and not be sprinting.) // Note: This behavior doesn't change for push-to-sprint. if( m_UncrouchOnSprint && m_IsCrouched && pInputSystem->OnRise( sRun ) ) { BeginUncrouch(); } if( m_IsPowerSliding ) { MovementVector += m_PowerSlideY; } float LeanTarget = 0.0f; const bool CanLean = pCollision->IsRecentlyLanded( m_UnlandedLeanWindow ); if( m_IsFlying ) { // Don't lean } else if( CanLean ) { if( pInputSystem->IsHigh( sLeanLeft ) ) { LeanTarget -= 1.0f; } if( pInputSystem->IsHigh( sLeanRight ) ) { LeanTarget += 1.0f; } } float StrafeRollTarget = 0.0f; if( pInputSystem->IsHigh( sLeft ) ) { StrafeRollTarget -= 1.0f; } if( pInputSystem->IsHigh( sRight ) ) { StrafeRollTarget += 1.0f; } StrafeRollTarget += pInputSystem->GetPosition( sMoveX ); if( pInputSystem->OnRise( sHeal ) ) { WB_MAKE_EVENT( TryUseBandage, pEntity ); WB_DISPATCH_EVENT( pEventManager, TryUseBandage, pEntity ); } // NOTE: Always send weapon input, even when it's low. This way, we // untrigger automatic weapons even if the OnFall edge is missed. const uint UseWeaponInput = pInputSystem->OnInput( sUseWeapon ); { WB_MAKE_EVENT( UseWeapon, pEntity ); WB_SET_AUTO( UseWeapon, Int, Input, UseWeaponInput ); WB_DISPATCH_EVENT( pEventManager, UseWeapon, pEntity ); } if( pInputSystem->OnRise( sShove ) ) { WB_MAKE_EVENT( TryShove, pEntity ); WB_DISPATCH_EVENT( pEventManager, TryShove, pEntity ); } if( pInputSystem->OnRise( sReload ) ) { WB_MAKE_EVENT( TryReload, pEntity ); WB_DISPATCH_EVENT( pEventManager, TryReload, pEntity ); } if( pInputSystem->OnRise( sLight ) ) { WB_MAKE_EVENT( ToggleFlashlight, NULL ); WB_DISPATCH_EVENT( pEventManager, ToggleFlashlight, NULL ); } if( pInputSystem->OnRise( sCycleMag ) ) { WB_MAKE_EVENT( TryCycleMagazine, pEntity ); WB_DISPATCH_EVENT( pEventManager, TryCycleMagazine, pEntity ); } // NOTE: TryAim/TryUnAim are sent continuously, to make sure they aren't missed // during weapon transitional states and stuff. if( pInputSystem->IsHigh( sZoom ) ) { WB_MAKE_EVENT( TryAim, pEntity ); WB_SET_AUTO( TryAim, Float, ZoomTime, WB_MODDED( FOVTime ) ); WB_DISPATCH_EVENT( pEventManager, TryAim, pEntity ); } else { WB_MAKE_EVENT( TryUnAim, pEntity ); WB_SET_AUTO( TryUnAim, Float, ZoomTime, WB_MODDED( FOVTime ) ); WB_DISPATCH_EVENT( pEventManager, TryUnAim, pEntity ); } // Only accept radial input if we have any cycle items if( pInputSystem->OnRise( sRadial ) && pInventory->GetNumCycleItems() > 0 ) { STATIC_HASHED_STRING( RadialScreen ); WB_MAKE_EVENT( PushUIScreen, NULL ); WB_SET_AUTO( PushUIScreen, Hash, Screen, sRadialScreen ); WB_DISPATCH_EVENT( GetEventManager(), PushUIScreen, NULL ); } #define HANDLE_CYCLESLOT_INPUT( slot ) \ if( pInputSystem->OnRise( sCycleSlot##slot ) ) \ { \ STATIC_HASHED_STRING( WeaponSlot##slot ); \ WB_MAKE_EVENT( RequestCycleToSlot, pEntity ); \ WB_SET_AUTO( RequestCycleToSlot, Hash, Slot, sWeaponSlot##slot ); \ WB_DISPATCH_EVENT( pEventManager, RequestCycleToSlot, pEntity ); \ } HANDLE_CYCLESLOT_INPUT( 0 ); HANDLE_CYCLESLOT_INPUT( 1 ); HANDLE_CYCLESLOT_INPUT( 2 ); HANDLE_CYCLESLOT_INPUT( 3 ); #undef HANDLE_CYCLESLOT_INPUT if( pInputSystem->OnRise( sCyclePrev ) ) { WB_MAKE_EVENT( RequestCyclePrev, pEntity ); WB_DISPATCH_EVENT( pEventManager, RequestCyclePrev, pEntity ); } if( pInputSystem->OnRise( sCycleNext ) ) { WB_MAKE_EVENT( RequestCycleNext, pEntity ); WB_DISPATCH_EVENT( pEventManager, RequestCycleNext, pEntity ); } const uint FrobInput = pInputSystem->OnInput( sFrob ); if( FrobInput ) { WB_MAKE_EVENT( OnFrob, pEntity ); WB_SET_AUTO( OnFrob, Int, Input, FrobInput ); WB_DISPATCH_EVENT( pEventManager, OnFrob, pEntity ); } bool IsDoubleJumping = false; const bool IsRecentlyLanded = pCollision->IsRecentlyLanded( m_UnlandedJumpWindow ); const bool ShouldDoubleJump = !IsRecentlyLanded && CanDoubleJump(); if( m_IsFlying ) { // Don't jump } else if( ( pInputSystem->OnRise( sJump ) && IsRecentlyLanded ) || ( pInputSystem->OnRise( sJump ) && ShouldDoubleJump ) || ( pInputSystem->IsHigh( sJump ) && ShouldDoubleJump && pTransform->GetVelocity().z < 0.0f ) ) { if( ShouldDoubleJump ) { IsDoubleJumping = true; m_HasDoubleJumped = true; } WB_MAKE_EVENT( OnJumped, pEntity ); WB_SET_AUTO( OnJumped, Bool, DoubleJump, IsDoubleJumping ); WB_DISPATCH_EVENT( pEventManager, OnJumped, pEntity ); ImpulseVector.z += 1.0f; if( CanPowerJump() ) { ImpulseVector += ( Y * m_PowerJumpRatio ); // HACKHACK: Power jump should always uncrouch you if( m_IsCrouched ) { BeginUncrouch(); } // HACKHACK: Land out of the jump in a sprint (for push-to-sprint mode) m_IsSprinting = true; m_IsSprintingWithMovement = true; } if( m_IsPowerSliding ) { EndPowerSlide(); } } if( m_IsMantling && pInputSystem->IsLow( sMantle ) ) { EndMantle( false ); } if( m_IsFlying ) { // Don't crouch, and uncrouch if we are if( m_IsCrouched ) { BeginUncrouch(); } } else if( pInputSystem->OnRise( sCrouch ) ) { if( m_IsUncrouching ) { CancelUncrouch(); } else if( m_IsCrouched ) { BeginUncrouch(); } else { if( CanCrouch() ) { Crouch(); if( CanPowerSlide() && ( pInputSystem->IsHigh( sForward ) || pInputSystem->GetPosition( sMoveY ) > 0.0f ) ) { BeginPowerSlide( Y ); } } } } // CAMTODO: Is this still something we want? How will missions in Zeta end? Going to an exit might make more sense... // Send the Return to Hub message if we've completed the mission if( pInputSystem->OnHold( sHeal ) && RosaCampaign::GetCampaign()->IsScenarioCompleted() ) { WB_MAKE_EVENT( ActiveReturnToHub, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), ActiveReturnToHub, GetEntity() ); } const bool IsClimbForward = pInputSystem->IsHigh( sClimbForward ); const bool IsClimbBack = pInputSystem->IsHigh( sClimbBack ); const bool IsClimbDown = pInputSystem->IsHigh( sClimbDown ); const float ClimbY = pInputSystem->GetPosition( sClimbY ); const bool IsClimbY = Abs( ClimbY ) > EPSILON; #if CAMERA_RELATIVE_CLIMBING // Camera-relative climbing motion (how I prefer). if( IsClimbForward || IsClimbBack || IsClimbDown || IsClimbY ) { #if CAMERA_RELATIVE_CLIMBING_BIAS const Matrix ClimbFacingMatrix = Matrix::CreateRotation( PlayerRight, m_ClimbFacingBiasAngle ); const Vector ClimbFacing = PlayerFacing * ClimbFacingMatrix; const float ClimbMagnitude = ClimbFacing.z; const float ScaledClimbMagnitude = Clamp( ClimbMagnitude * m_ClimbFacingBiasScale, -1.0f, 1.0f ); const Vector ClimbVector = UpVector * ScaledClimbMagnitude; #else const Vector ClimbVector = PlayerFacing.ProjectionOnto( UpVector ); #endif ASSERT( ClimbVector.x == 0.0f && ClimbVector.y == 0.0f ); if( IsClimbForward ) { MovementVector += ClimbVector; } if( IsClimbBack ) { MovementVector -= ClimbVector; } if( IsClimbDown ) { MovementVector -= UpVector; } if( IsClimbY ) { MovementVector += ClimbVector * ClimbY; } } #else if( IsClimbForward || IsClimbBack || IsClimbDown || IsClimbY ) { if( IsClimbForward ) { MovementVector += UpVector; } if( IsClimbBack ) { MovementVector -= UpVector; } if( IsClimbDown ) { MovementVector -= UpVector; } if( IsClimbY ) { MovementVector += UpVector * ClimbY; } } #endif if( pInputSystem->OnRise( sClimbJump ) && !pInputSystem->OnFall( sJump ) ) // This prevents jumping off when we've just switched to the climb context { ZeroClimbRefs(); WB_MAKE_EVENT( OnJumped, pEntity ); WB_DISPATCH_EVENT( pEventManager, OnJumped, pEntity ); ImpulseVector.z += 1.0f; MovementVector = Vector(); if( IsClimbForward ) { ImpulseVector += Y; } if( IsClimbBack ) { ImpulseVector -= Y; } if( IsClimbY ) { ImpulseVector += Y * ClimbY; } } ConditionalApplyRunningStatMods(); TurnAngles.Yaw -= pInputSystem->GetPosition( sTurnX ); TurnAngles.Pitch -= pInputSystem->GetPosition( sTurnY ); float MoveSpeed = 0.0f; if( m_IsClimbing || pCollision->IsLanded() || m_IsFlying ) // ACIDHACK: Use land acceleration in the air if we're flying, because that's how it's tuned { WB_MODIFY_FLOAT( LandAcceleration, m_LandAcceleration, pStatMod ); MoveSpeed = WB_MODDED( LandAcceleration ); } else { MoveSpeed = m_AirAcceleration; } if( m_IsClimbing ) { const float Mu = pCollision->GetFrictionCoefficient(); pTransform->SetVelocity( pTransform->GetVelocity() * Mu ); } // Don't let movement input exceed 1.0 (run + strafe doesn't double speed!), // but do allow it to be less than 1.0 for camera-relative climbing or analog input. Vector MovementVectorDirection; float MovementVectorLength; float MovementVectorLengthOverOne; MovementVector.GetNormalized( MovementVectorDirection, MovementVectorLength, MovementVectorLengthOverOne ); const float AppliedMovementLength = Min( MovementVectorLength, 1.0f ); MovementVector = MovementVectorDirection * AppliedMovementLength * MoveSpeed; TurnAngles *= m_TurnSpeed * WB_MODDED( FOVScale ); // Apply FOV scale here so zoomed view has slower turn speed if( m_IsMantling ) { // Check if we're past the destination and end the mantle if so const Vector CurrentLocation = pTransform->GetLocation(); const Vector ToDestination = ( m_MantleDestination - CurrentLocation ); const float CosAngle = ToDestination.Dot( m_MantleVector ); if( CosAngle < 0.0f ) { EndMantle( true ); } else { const Vector MantleVelocity = m_MantleVector * m_MantleVelocity; pTransform->SetVelocity( MantleVelocity ); } } pTransform->SetAcceleration( MovementVector ); pTransform->SetRotationalVelocity( TurnAngles ); if( !ImpulseVector.IsZero() ) { const float BaseJumpHeight = IsDoubleJumping ? m_DoubleJumpHeight : m_JumpHeight; WB_MODIFY_FLOAT( JumpHeight, BaseJumpHeight, pStatMod ); const float JumpImpulse = SqRt( -2.0f * pTransform->GetGravity() * WB_MODDED( JumpHeight ) ); ImpulseVector = ImpulseVector.GetFastNormalized() * JumpImpulse; // HACKHACK: Negate velocity along impulse vector, so double jumps work as expected. // DLP 29 Dec 2018: For power jumps, I've realized I only want to negate velocity in Z. //const Vector ImpulseDirectionVelocity = pTransform->GetVelocity().ProjectionOnto( ImpulseVector ); const Vector ImpulseDirectionVelocity = pTransform->GetVelocity().ProjectionOnto( Vector::Up ); pTransform->ApplyImpulse( -ImpulseDirectionVelocity ); pTransform->ApplyImpulse( ImpulseVector ); } pCamera->SetLeanPosition( LeanTarget ); pCamera->SetStrafeRollPosition( StrafeRollTarget ); if( m_IsSprintingWithMovement || m_IsPowerSliding ) { pCamera->ZoomMinimapOut(); } else { pCamera->ZoomMinimapIn(); } #if BUILD_DEV DEVHACKInput(); #endif } void WBCompRosaPlayer::SetCrouchOverlayHidden( const bool Hidden ) { STATIC_HASHED_STRING( HUD ); STATIC_HASHED_STRING( CrouchOverlay ); WB_MAKE_EVENT( SetWidgetHidden, GetEntity() ); WB_SET_AUTO( SetWidgetHidden, Hash, Screen, sHUD ); WB_SET_AUTO( SetWidgetHidden, Hash, Widget, sCrouchOverlay ); WB_SET_AUTO( SetWidgetHidden, Bool, Hidden, Hidden ); WB_DISPATCH_EVENT( GetEventManager(), SetWidgetHidden, GetFramework()->GetUIManager() ); } void WBCompRosaPlayer::Crouch() { ASSERT( !m_IsCrouched ); ASSERT( !m_IsUncrouching ); DEBUGASSERT( CanCrouch() ); m_IsCrouched = true; WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); Vector Extents = pCollision->GetExtents(); ASSERT( m_CrouchExtentsZ < Extents.z ); Extents.z = m_CrouchExtentsZ; pCollision->SetExtents( Extents ); // DLP 22 Dec 2020: If we're on the ground, immediately assume the crouched height location. // This fixes the long standing issue of falling to the ground which I'd papered over with // view interpolation and stuff. It was revealed again with the view hands velocity stuff, // so I'm finally just doing the thing I should've always done and setting the location // (after setting the smaller extents). I don't do this in the air because it jerks the // camera and might affect the ability to reach high ledges during crouch jumps. if( pCollision->IsLanded() ) { Vector CrouchLocation = pTransform->GetLocation(); CrouchLocation.z = ( CrouchLocation.z - m_StandExtentsZ ) + m_CrouchExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground pTransform->SetLocation( CrouchLocation ); } m_ViewOffsetZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, m_StandViewOffsetZ, m_CrouchViewOffsetZ, m_CrouchViewInterpTime ); SetCrouchOverlayHidden( false ); STATIC_HASHED_STRING( Crouching ); pStatMod->TriggerEvent( sCrouching ); } void WBCompRosaPlayer::BeginUncrouch() { ASSERT( m_IsCrouched ); m_IsUncrouching = true; m_IsForceCrouched = false; if( m_IsPowerSliding ) { EndPowerSlide(); } } void WBCompRosaPlayer::CancelUncrouch() { ASSERT( m_IsCrouched ); ASSERT( m_IsUncrouching ); m_IsUncrouching = false; } void WBCompRosaPlayer::TryUncrouch() { ASSERT( m_IsCrouched ); ASSERT( m_IsUncrouching ); if( CanUncrouch() ) { Uncrouch(); } } bool WBCompRosaPlayer::CanCrouch() { DEVASSERT( !m_IsCrouched ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); RosaWorld* const pWorld = GetWorld(); ASSERT( pWorld ); CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = GetEntity(); Info.m_In_UserFlags = EECF_BlockerCollision; if( pWorld->CheckClearance( pTransform->GetLocation(), pCollision->GetExtents(), Info ) ) { // We're inside collision (a valid case when seated at a table, for example); don't crouch return false; } else { return true; } } bool WBCompRosaPlayer::CanUncrouch() { ASSERT( m_IsCrouched ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); RosaWorld* const pWorld = GetWorld(); ASSERT( pWorld ); Vector StandLocation = pTransform->GetLocation(); // DLP 22 Dec 2020: I used to always check the standing location because I was always // moving the location on Uncrouch. Not anymore, this corresponds to what Uncrouch does. if( pCollision->IsLanded() ) { StandLocation.z = ( StandLocation.z - m_CrouchExtentsZ ) + m_StandExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground } Vector CheckExtents = pCollision->GetExtents(); CheckExtents.z = m_StandExtentsZ; CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = GetEntity(); Info.m_In_UserFlags = EECF_BlockerCollision; if( pWorld->CheckClearance( StandLocation, CheckExtents, Info ) ) { // Something is blocking the uncrouch return false; } else { return true; } } void WBCompRosaPlayer::Uncrouch() { ASSERT( m_IsCrouched ); ASSERT( m_IsUncrouching ); DEBUGASSERT( CanUncrouch() ); m_IsUncrouching = false; m_IsCrouched = false; WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); // If we're on land, transform back up. // DLP 22 Dec 2020: I used to always do this, which could be used to boost higher during a jump. // This introduces the possibility that you won't be able to uncrouch if you're airborne // just above the ground (a case I'm handling in CanUncrouch), but that's probably fine. if( pCollision->IsLanded() ) { Vector StandLocation = pTransform->GetLocation(); StandLocation.z = ( StandLocation.z - m_CrouchExtentsZ ) + m_StandExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground pTransform->SetLocation( StandLocation ); } Vector Extents = pCollision->GetExtents(); ASSERT( m_StandExtentsZ > Extents.z ); Extents.z = m_StandExtentsZ; pCollision->SetExtents( Extents ); m_ViewOffsetZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, m_CrouchViewOffsetZ, m_StandViewOffsetZ, m_CrouchViewInterpTime ); SetCrouchOverlayHidden( true ); STATIC_HASHED_STRING( Crouching ); pStatMod->UnTriggerEvent( sCrouching ); } void WBCompRosaPlayer::RestoreCrouch() { // Fix up view offset and stat mod from state. // Other crouch properties (collision extents, transform location) are serialized. WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera ); ASSERT( pCamera ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); const float ViewOffsetZ = m_IsCrouched ? m_CrouchViewOffsetZ : m_StandViewOffsetZ; m_ViewOffsetZInterpolator.Reset( ViewOffsetZ ); pCamera->SetViewOffsetZ( ViewOffsetZ ); SetCrouchOverlayHidden( !m_IsCrouched ); STATIC_HASHED_STRING( Crouching ); pStatMod->SetEventActive( sCrouching, m_IsCrouched ); } void WBCompRosaPlayer::OnSteppedUp( const float StepHeight ) { WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera ); ASSERT( pCamera ); const float NewViewOffsetZ = m_StepUpZInterpolator.GetEndValue(); const float OldViewOffsetZ = NewViewOffsetZ - StepHeight; m_StepUpZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, OldViewOffsetZ, NewViewOffsetZ, m_CrouchViewInterpTime ); pCamera->SetStepUpZ( OldViewOffsetZ ); } bool WBCompRosaPlayer::CanPowerJump() const { if( !m_IsPowerSliding ) { return false; } WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod ); WB_MODIFY_FLOAT( PowerJump, 0.0f, pStatMod ); const bool PowerJump = ( WB_MODDED( PowerJump ) != 0.0f ); return PowerJump; } bool WBCompRosaPlayer::CanPowerSlide() const { if( !m_IsSprinting ) { return false; } WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>(); if( pTransform->GetVelocity().LengthSquared2D() < m_PowerSlideReqVelocitySq ) { return false; } WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod ); WB_MODIFY_FLOAT( PowerSlide, 0.0f, pStatMod ); const bool PowerSlide = ( WB_MODDED( PowerSlide ) != 0.0f ); return PowerSlide; } bool WBCompRosaPlayer::CanDoubleJump() const { if( m_HasDoubleJumped ) { return false; } if( m_IsMantling ) { return false; } WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod ); WB_MODIFY_FLOAT( DoubleJump, 0.0f, pStatMod ); const bool DoubleJump = ( WB_MODDED( DoubleJump ) != 0.0f ); return DoubleJump; } void WBCompRosaPlayer::BeginPowerSlide( const Vector& PowerSlideY ) { ASSERT( !m_IsPowerSliding ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); DEVASSERT( pStatMod ); WB_MODIFY_FLOAT( PowerSlideDuration, m_PowerSlideDuration, pStatMod ); m_IsPowerSliding = true; m_PowerSlideEndTime = GetTime() + WB_MODDED( PowerSlideDuration ); m_PowerSlideY = PowerSlideY; m_PowerSlideRollInterpolator.Reset( Interpolator<float>::EIT_Linear, 0.0f, m_PowerSlideRoll, m_PowerSlideRollInterpTime ); STATIC_HASHED_STRING( PowerSliding ); pStatMod->TriggerEvent( sPowerSliding ); GetFramework()->GetInputSystem()->PushContext( m_PowerSlideInputContext ); WB_MAKE_EVENT( OnBeginPowerSlide, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), OnBeginPowerSlide, pEntity ); } void WBCompRosaPlayer::EndPowerSlide() { ASSERT( m_IsPowerSliding ); m_IsPowerSliding = false; InputSystem* const pInputSystem = GetFramework()->GetInputSystem(); ASSERT( pInputSystem ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); // DLP 13 Oct 2021: This used to use m_PowerSlideRoll as the StartValue, but it seems better to blend back // from whatever it was at, in case the roll hadn't finished interpolating when the player stopped sliding? m_PowerSlideRollInterpolator.Reset( Interpolator<float>::EIT_Linear, m_PowerSlideRollInterpolator.GetValue(), 0.0f, m_PowerSlideRollInterpTime ); STATIC_HASHED_STRING( PowerSliding ); pStatMod->UnTriggerEvent( sPowerSliding ); pInputSystem->PopContext( m_PowerSlideInputContext ); STATIC_HASHED_STRING( Run ); if( pInputSystem->IsHigh( sRun ) ) { BeginUncrouch(); } } void WBCompRosaPlayer::RestorePowerSlide() { WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); const float ViewAngleOffsetRoll = m_IsPowerSliding ? m_PowerSlideRoll : 0.0f; m_PowerSlideRollInterpolator.Reset( ViewAngleOffsetRoll ); STATIC_HASHED_STRING( PowerSliding ); pStatMod->SetEventActive( sPowerSliding, m_IsPowerSliding ); if( m_IsPowerSliding ) { GetFramework()->GetInputSystem()->PushContext( m_PowerSlideInputContext ); } } void WBCompRosaPlayer::BeginDrag( WBEntity* const pDraggedEntity ) { DEVASSERT( !m_IsDragging ); m_IsDragging = true; m_DraggedEntity = pDraggedEntity; WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); DEVASSERT( pStatMod ); STATIC_HASHED_STRING( Dragging ); pStatMod->TriggerEvent( sDragging ); GetFramework()->GetInputSystem()->PushContext( m_DragInputContext ); } // HACKHACK: Move the dragged entity and give it an impulse. // I'm calling this a hack because all the other behavior (e.g., showing/hiding it) is scripted. void WBCompRosaPlayer::DropDraggedEntity() { WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBEntity* const pDraggedEntity = m_DraggedEntity.Get(); DEVASSERT( pDraggedEntity ); WBCompRosaTransform* const pDraggedTransform = pDraggedEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pDraggedTransform ); WBCompRosaCollision* const pDraggedCollision = WB_GETCOMP( pDraggedEntity, RosaCollision ); DEVASSERT( pDraggedCollision ); Vector DropLocation = pTransform->GetLocation() + m_DragDropOffset; const Angles Orientation = pTransform->GetOrientation().Get2D(); const Angles DropOrientation = Orientation + m_DragDropOrientation; Vector DropImpulse = Orientation.ToVector(); DropImpulse.z += m_DragDropSpawnImpulseZ; DropImpulse.FastNormalize(); DropImpulse *= m_DragDropSpawnImpulse; CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = pEntity; // Using the player, not the dragged entity Info.m_In_UserFlags = EECF_EntityCollision; const bool FoundSpot = GetWorld()->FindSpot( DropLocation, pDraggedCollision->GetExtents(), Info ); Unused( FoundSpot ); DEVASSERT( FoundSpot ); pDraggedTransform->SetLocation( DropLocation ); pDraggedTransform->SetVelocity( pTransform->GetVelocity() ); pDraggedTransform->SetOrientation( DropOrientation ); pDraggedTransform->ApplyImpulse( DropImpulse ); pDraggedTransform->OnTeleport(); } void WBCompRosaPlayer::EndDrag() { DEVASSERT( m_IsDragging ); DropDraggedEntity(); m_IsDragging = false; m_DraggedEntity = static_cast<WBEntity*>( NULL ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); DEVASSERT( pStatMod ); STATIC_HASHED_STRING( Dragging ); pStatMod->UnTriggerEvent( sDragging ); GetFramework()->GetInputSystem()->PopContext( m_DragInputContext ); } void WBCompRosaPlayer::RestoreDrag() { WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); DEVASSERT( pStatMod ); STATIC_HASHED_STRING( Dragging ); pStatMod->SetEventActive( sDragging, m_IsDragging ); if( m_IsDragging ) { GetFramework()->GetInputSystem()->PushContext( m_DragInputContext ); } } bool WBCompRosaPlayer::ShouldAttachToClimbable( const WBEvent& ClimbEvent ) { if( m_ClimbRefs > 0 ) { // If we're already climbing, always attach to any further climbables. return true; } STATIC_HASHED_STRING( UseSnapPlane ); const bool UseSnapPlane = ClimbEvent.GetBool( sUseSnapPlane ); if( !UseSnapPlane ) { // We have no snap plane, always attach. return true; } WBEntity* const pEntity = GetEntity(); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); if( !pCollision->IsLanded() ) { // Always attach if jumping or falling. return true; } WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); const Vector Orientation = pTransform->GetOrientation().ToVector(); const Vector VelocityNormal = pTransform->GetVelocity().GetFastNormalized(); STATIC_HASHED_STRING( SnapPlaneNormal ); const Vector SnapPlaneNormal = ClimbEvent.GetVector( sSnapPlaneNormal ); // Cheap 90 degree rotation to get facing plane from snap plane ASSERT( SnapPlaneNormal.z == 0.0f ); const Vector FacingPlaneNormal = Vector( -SnapPlaneNormal.y, SnapPlaneNormal.x, 0.0f ); // TODO: Configurate if needed. static const float kCos90 = 0.0f; // Climbing angle const float FacingDot = Orientation.Dot( FacingPlaneNormal ); const float MovingDot = VelocityNormal.Dot( FacingPlaneNormal ); if( FacingDot < kCos90 && MovingDot < kCos90 ) { // We're facing the snap plane and moving toward the snap plane, so we should attach. return true; } // All cases failed, don't attach. return false; } void WBCompRosaPlayer::IncrementClimbRefs( const WBEvent& ClimbEvent ) { if( ++m_ClimbRefs == 1 ) { if( !m_IsMantling && !m_IsDragging ) { BeginClimb( ClimbEvent ); } } } void WBCompRosaPlayer::DecrementClimbRefs( const bool AddClimbOffImpulse ) { if( m_ClimbRefs > 0 ) { if( --m_ClimbRefs == 0 ) { if( m_IsClimbing ) { EndClimb( AddClimbOffImpulse ); } } } } void WBCompRosaPlayer::ZeroClimbRefs() { if( m_ClimbRefs > 0 ) { m_ClimbRefs = 0; if( m_IsClimbing ) { EndClimb( false ); } } } void WBCompRosaPlayer::BeginClimb( const WBEvent& ClimbEvent ) { if( m_IsPowerSliding ) { EndPowerSlide(); } if( m_IsCrouched ) { BeginUncrouch(); } ASSERT( !m_IsClimbing ); m_HasDoubleJumped = false; m_IsClimbing = true; WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); STATIC_HASHED_STRING( UseSnapPlane ); const bool UseSnapPlane = ClimbEvent.GetBool( sUseSnapPlane ); if( UseSnapPlane ) { STATIC_HASHED_STRING( SnapPlaneDistance ); const float SnapPlaneDistance = ClimbEvent.GetFloat( sSnapPlaneDistance ); STATIC_HASHED_STRING( SnapPlaneNormal ); const Vector SnapPlaneNormal = ClimbEvent.GetVector( sSnapPlaneNormal ); const Plane SnapPlane = Plane( SnapPlaneNormal, SnapPlaneDistance ); const Vector Location = pTransform->GetLocation(); const Vector SnappedLocation = SnapPlane.ProjectPoint( Location ); pTransform->SetLocation( SnappedLocation ); } pTransform->SetGravity( 0.0f ); pTransform->SetVelocity( Vector() ); pTransform->SetAcceleration( Vector() ); pTransform->SetRotationalVelocity( Angles() ); STATIC_HASHED_STRING( Climbing ); pStatMod->TriggerEvent( sClimbing ); GetFramework()->GetInputSystem()->PushContext( m_ClimbInputContext ); WB_MAKE_EVENT( HideHands, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), HideHands, pEntity ); } void WBCompRosaPlayer::EndClimb( const bool AddClimbOffImpulse ) { ASSERT( m_IsClimbing ); m_IsClimbing = false; GetFramework()->GetInputSystem()->PopContext( m_ClimbInputContext ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); pTransform->SetDefaultGravity(); if( AddClimbOffImpulse ) { pTransform->ApplyImpulse( Vector( 0.0f, 0.0f, m_ClimbOffImpulse ) ); } STATIC_HASHED_STRING( Climbing ); pStatMod->UnTriggerEvent( sClimbing ); WB_MAKE_EVENT( ShowHands, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), ShowHands, pEntity ); } void WBCompRosaPlayer::RestoreClimb() { m_IsClimbing = ( m_ClimbRefs > 0 ); WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); ASSERT( pStatMod ); STATIC_HASHED_STRING( Climbing ); pStatMod->SetEventActive( sClimbing, m_IsClimbing ); if( m_IsClimbing ) { GetFramework()->GetInputSystem()->PushContext( m_ClimbInputContext ); } } void WBCompRosaPlayer::TryBeginMantle( const Vector& CollisionNormal ) { if( m_IsMantling || !m_CanMantle || m_ClimbRefs > 0 ) { return; } WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); InputSystem* const pInputSystem = GetFramework()->GetInputSystem(); ASSERT( pInputSystem ); STATIC_HASHED_STRING( Jump ); // TODO: Configurate if needed. static const float kCos45 = 0.707107f; // Mantle angle const Vector Facing = pTransform->GetOrientation().ToVector2D(); // If we're facing the collision surface and falling and holding the jump button, try to mantle. if( pCollision->IsRecentlyLanded( 0.0f ) || pTransform->GetVelocity().z >= 0.0f || Facing.Dot( CollisionNormal ) >= -kCos45 || !pInputSystem->IsHigh( sJump ) ) { return; } RosaWorld* const pWorld = GetWorld(); DEVASSERT( pWorld ); const Vector MantleDestination = GetMantleDestination( CollisionNormal, pTransform->GetLocation(), pCollision->GetExtents() ); CollisionInfo ClearanceInfo; ClearanceInfo.m_In_CollideWorld = true; ClearanceInfo.m_In_CollideEntities = true; ClearanceInfo.m_In_CollidingEntity = pEntity; // Historically, this was always EECF_BlockerCollision (same as below but also colliding with dynamic entities); // now I'm choosing to not collide with dynamic entities so the player can smash through windows. Potentially // this means it could try to mantel the player up into an enemy or something, but that won't cause stuck bugs. ClearanceInfo.m_In_UserFlags = EECF_CollideAsBlocker | EECF_CollideStaticEntities; // Check that we still have room at our destination. if( !pWorld->CheckClearance( MantleDestination, pCollision->GetExtents(), ClearanceInfo ) ) { BeginMantle( MantleDestination ); return; } // Something is blocking the mantle; crouch and retry if( m_IsCrouched || !CanCrouch() ) { return; } Vector CrouchExtents = pCollision->GetExtents(); CrouchExtents.z = m_CrouchExtentsZ; const Vector CrouchMantleDestination = GetMantleDestination( CollisionNormal, pTransform->GetLocation(), CrouchExtents ); if( !pWorld->CheckClearance( CrouchMantleDestination, CrouchExtents, ClearanceInfo ) ) { Crouch(); m_IsForceCrouched = true; BeginMantle( CrouchMantleDestination ); return; } } Vector WBCompRosaPlayer::GetMantleDestination( const Vector& CollisionNormal, const Vector& Location, const Vector& Extents ) const { const float MantleDestinationZ = Location.z + ( Extents.z * 1.5f ); // We can climb up to 1.5x our height (TODO: configurate? might require a sweep down to be sure we don't overshoot) const Vector MantleDestinationXY = Location - ( CollisionNormal * Extents.x * 1.414f ); // Multiply by 1.414 to be sure we'll have clearance on any angle const Vector MantleDestination = Vector( MantleDestinationXY.x, MantleDestinationXY.y, MantleDestinationZ ); return MantleDestination; } void WBCompRosaPlayer::BeginMantle( const Vector& MantleDestination ) { ASSERT( !m_IsMantling ); m_IsMantling = true; m_HasDoubleJumped = true; // HACKHACK: We don't want to double jump during the pop off a mantel WBEntity* const pEntity = GetEntity(); DEVASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); GetFramework()->GetInputSystem()->PushContext( m_MantleInputContext ); m_MantleDestination = MantleDestination; // Make sure m_MantleVector has a significant component in both X/Y and Z. // As such, it does *not* indicate the actual direction to the mantle point. m_MantleVector = ( MantleDestination - pTransform->GetLocation() ).GetNormalized().Get2D(); m_MantleVector.z = 1.0f; m_MantleVector.FastNormalize(); m_CanMantle = false; WB_MAKE_EVENT( OnBeginMantle, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), OnBeginMantle, pEntity ); } void WBCompRosaPlayer::EndMantle( const bool AllowMantle ) { ASSERT( m_IsMantling ); m_IsMantling = false; // DLP 18 May 2020: This used to only become true on landing; // I'm now making it so you can continue to mantle into any // other surface you encounter before landing, which feels // a lot better because you keep holding the inputs and keep // mantling as long as there's space to do so. I haven't seen // any issues with it yet, just leaving this note here as a // reminder in case anything wonky happens later. // (Addendum: I added the AllowMantle flag so this does *not* // get enabled if EndMantle is called because the input was // released during mantling; this fixes odd repeat mantling // if spamming the space bar to bunny hop.) m_CanMantle = AllowMantle; GetFramework()->GetInputSystem()->PopContext( m_MantleInputContext ); if( m_IsForceCrouched ) { BeginUncrouch(); } } void WBCompRosaPlayer::TickScaleFOV( Interpolator<float>& FOVInterpolator, const float BaseFOVDegrees, const float Scale, const float Time, const float DeltaTime ) { const float HalfFOVRadians = DEGREES_TO_RADIANS( 0.5f * BaseFOVDegrees ); const float HalfScaledFOVRadians = ATan( Scale * Tan( HalfFOVRadians ) ); const float ScaledFOVDegrees = 2.0f * RADIANS_TO_DEGREES( HalfScaledFOVRadians ); if( FOVInterpolator.GetValue() == 0.0f ) { // Instantly reset FOV to the target if we don't have a valid current value. FOVInterpolator.Reset( ScaledFOVDegrees ); } if( FOVInterpolator.GetEndValue() != ScaledFOVDegrees ) { // If the target FOV changes, restart the lerp. FOVInterpolator.Reset( Interpolator<float>::EIT_Linear, FOVInterpolator.GetValue(), ScaledFOVDegrees, Time ); } FOVInterpolator.Tick( DeltaTime ); } void WBCompRosaPlayer::SetSpawnPoint() { ASSERT( !m_HasSetSpawnPoint ); WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); m_SpawnLocation = pTransform->GetLocation(); m_SpawnOrientation = pTransform->GetOrientation(); m_HasSetSpawnPoint = true; } void WBCompRosaPlayer::RestoreSpawnPoint() { ASSERT( m_HasSetSpawnPoint ); WBEntity* const pEntity = GetEntity(); ASSERT( pEntity ); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); ASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); ASSERT( pCollision ); RosaWorld* const pWorld = GetWorld(); DEVASSERT( pWorld ); CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = pEntity; Info.m_In_UserFlags = EECF_BlockerCollision; Vector SpawnLocation = m_SpawnLocation; const bool FoundSpot = pWorld->FindSpot( SpawnLocation, pCollision->GetExtents(), Info ); ASSERT( FoundSpot ); pTransform->SetLocation( SpawnLocation ); pTransform->SetVelocity( Vector() ); pTransform->SetAcceleration( Vector() ); pTransform->SetOrientation( m_SpawnOrientation ); if( m_IsCrouched ) { BeginUncrouch(); } } void WBCompRosaPlayer::TeleportTo( const HashedString& TeleportLabel ) { if( TeleportLabel == HashedString::NullString ) { return; } WBEntity* const pTeleportTarget = WBCompLabel::GetEntityByLabel( TeleportLabel ); if( !pTeleportTarget ) { return; } WBCompRosaTransform* pTeleportTransform = pTeleportTarget->GetTransformComponent<WBCompRosaTransform>(); if( !pTeleportTransform ) { return; } WBCompRosaTransform* pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>(); ASSERT( pTransform ); pTransform->SetLocation( pTeleportTransform->GetLocation() ); pTransform->SetVelocity( Vector() ); pTransform->SetAcceleration( Vector() ); pTransform->SetOrientation( pTeleportTransform->GetOrientation() ); } #if BUILD_DEV /*virtual*/ void WBCompRosaPlayer::Report() const { Super::Report(); PRINTF( WBPROPERTY_REPORT_PREFIX "Autosave Suppression Refcount: %d/%d\n", m_AutosaveSuppRefsSerialized, m_AutosaveSuppRefsTransient ); } /*virtual*/ void WBCompRosaPlayer::DebugRender( const bool GroupedRender ) const { Super::DebugRender( GroupedRender ); RosaFramework* const pFramework = GetFramework(); IRenderer* const pRenderer = pFramework->GetRenderer(); View* const pView = pFramework->GetMainView(); Display* const pDisplay = pFramework->GetDisplay(); WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>(); DEVASSERT( pTransform ); const Vector Location = pTransform->GetLocation(); const float ClockMultiplier = m_DEVHACKClockMultiplier ? m_DEVHACKClockMultiplier->m_Multiplier : 1.0f; pRenderer->DEBUGPrint( SimpleString::PrintF( "%s Clock multiplier: %.2f", DebugRenderLineFeed().CStr(), ClockMultiplier ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) ); pRenderer->DEBUGPrint( SimpleString::PrintF( "%s Fixed time scalar: %.2f", DebugRenderLineFeed().CStr(), pFramework->DEV_GetFixedTimeScalar() ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) ); // (These are going to be the previous frame's stats, obviously.) const IRenderer::SDEV_RenderStats& RenderStats = pRenderer->DEV_GetStats(); // Print renderer stats in the top left, not on the player entity. // TODO: I don't feel like writing a whole system to display real-time stats from multiple sources right now. But I should. pRenderer->DEBUGPrint( SimpleString::PrintF( "Avg FPS: %d\nAvg frame time: %.3fms\nRender time: %.3fms\nRendered meshes: %d\nRendered draw calls: %d\n" "Rendered shadow lights: %d\nRendered shadow meshes: %d\nShadow time: %.3fms\n" "TickSim time: %.3fms (min %.3fms / max %.3fms)\n" "TickRender time: %.3fms (min %.3fms / max %.3fms)", RoundToUInt( RenderStats.m_AvgFPS ), 1000.0f / RenderStats.m_AvgFPS, GET_CLOCK_MS( RenderStats.m_RenderTime ), RenderStats.m_NumMeshes, RenderStats.m_NumDrawCalls, RenderStats.m_NumShadowLights, RenderStats.m_NumShadowMeshes, GET_CLOCK_MS( RenderStats.m_ShadowTime ), GET_CLOCK_MS( pFramework->DEV_GetSimTime() ), GET_CLOCK_MS( pFramework->DEV_GetSimTimeMin() ), GET_CLOCK_MS( pFramework->DEV_GetSimTimeMax() ), GET_CLOCK_MS( pFramework->DEV_GetRenderTime() ), GET_CLOCK_MS( pFramework->DEV_GetRenderTimeMin() ), GET_CLOCK_MS( pFramework->DEV_GetRenderTimeMax() ) ), SRect( 100.0f, 100.0f, 0.0f, 0.0f ), DEFAULT_MONOSPACED_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) ); // Display relevant shadow-casting lights and the number of meshes drawn for each. // It makes sense to do this here instead of a debug display on the light component, // because we want to see all lights, and also we don't have rendered numbers on the // light components. I might comment this out too. FOR_EACH_ARRAY( ShadowLightIter, RenderStats.m_ShadowLights, IRenderer::SDEV_RenderStats::SDEV_ShadowLight ) { const IRenderer::SDEV_RenderStats::SDEV_ShadowLight& ShadowLight = ShadowLightIter.GetValue(); //pRenderer->DEBUGDrawSphere( ShadowLight.m_Location, ShadowLight.m_Radius, ARGB_TO_COLOR( 255, 255, 255, 255 ), false ); pRenderer->DEBUGDrawCross( ShadowLight.m_Location, 1.0f, ARGB_TO_COLOR( 255, 255, 255, 255 ), false ); pRenderer->DEBUGPrint( SimpleString::PrintF( "%d", ShadowLight.m_NumMeshes ), ShadowLight.m_Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 0 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) ); } const uint NumPathSteps = m_CAMHACKPathData.m_Path.Size(); for( uint PathIndex = 1; PathIndex < NumPathSteps; ++PathIndex ) { const Vector& PrevStep = m_CAMHACKPathData.m_Path[ PathIndex - 1 ]; const Vector& NextStep = m_CAMHACKPathData.m_Path[ PathIndex ]; pRenderer->DEBUGDrawLine( PrevStep, NextStep, ARGB_TO_COLOR( 255, 255, 0, 0 ) ); } uint NavNodeIndex; if( GetWorld()->FindNavNodeUnder( Location, NavNodeIndex ) ) { static const Vector skNavNodeOffset = Vector( 0.0f, 0.0f, 0.01f ); const SNavNode& NavNode = GetWorld()->GetNavNode( NavNodeIndex ); // Draw the tri raised slightly and with each vert moved slightly toward centroid so it doesn't z-fight geo pRenderer->DEBUGDrawTriangle( NavNode.m_Tri.m_Vec1 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec1 ).GetFastNormalized(), NavNode.m_Tri.m_Vec2 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec2 ).GetFastNormalized(), NavNode.m_Tri.m_Vec3 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec3 ).GetFastNormalized(), ARGB_TO_COLOR( 255, 255, 128, 0 ) ); if( NavNode.m_Props != ENP_None ) { pRenderer->DEBUGPrint( SimpleString::PrintF( "%sNav node props: 0x%08X", DebugRenderLineFeed().CStr(), NavNode.m_Props ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 128, 0 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) ); } } for( float Radius = m_CACHED_LastAINoiseRadius; Radius > 0.0f; Radius -= 1.0f ) { pRenderer->DEBUGDrawCircleXY( m_CACHED_LastAINoiseSourceLocation, Radius, ARGB_TO_COLOR( 255, 255, 255, 0 ) ); } } #endif // BUILD_DEV #if BUILD_DEV void WBCompRosaPlayer::DEVHACKInput() { WBEntity* const pEntity = GetEntity(); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera ); WBCompRosaKeyRing* const pKeyRing = WB_GETCOMP( pEntity, RosaKeyRing ); WBCompRosaVisible* const pVisible = WB_GETCOMP( pEntity, RosaVisible ); WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps ); RosaWorld* const pWorld = GetWorld(); RosaFramework* const pFramework = GetFramework(); Keyboard* const pKeyboard = pFramework->GetKeyboard(); // G (no Alt): Hide hands and HUD, Shift + G: re-show if( pKeyboard->IsLow( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_G ) ) { if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) ) { WB_MAKE_EVENT( ForceShowHands, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), ForceShowHands, pEntity ); STATIC_HASHED_STRING( HUD ); WB_MAKE_EVENT( RepushUIScreen, NULL ); WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD ); WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL ); } else { WB_MAKE_EVENT( HideHands, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), HideHands, pEntity ); STATIC_HASHED_STRING( HUD ); WB_MAKE_EVENT( RemoveUIScreen, NULL ); WB_SET_AUTO( RemoveUIScreen, Hash, Screen, sHUD ); WB_DISPATCH_EVENT( GetEventManager(), RemoveUIScreen, NULL ); } } #if BUILD_WINDOWS if( pKeyboard->OnRise( Keyboard::EB_Grave ) ) { Console::Toggle(); } #endif if( pKeyboard->OnRise( Keyboard::EB_LeftBrace ) ) { m_DebugSpawnerIndex = ( m_DebugSpawnerIndex + m_DebugSpawners.Size() - 1 ) % m_DebugSpawners.Size(); PRINTF( "Next entity: %s\n", m_DebugSpawners[ m_DebugSpawnerIndex ].m_Entity.CStr() ); } if( pKeyboard->OnRise( Keyboard::EB_RightBrace ) ) { m_DebugSpawnerIndex = ( m_DebugSpawnerIndex + 1 ) % m_DebugSpawners.Size(); PRINTF( "Next entity: %s\n", m_DebugSpawners[ m_DebugSpawnerIndex ].m_Entity.CStr() ); } // Numpad +/-: time dilation (use Ctrl to test clock multiplier instead of fixed frame time hack; ideal for slowing the game instead of speeding it up) if( pKeyboard->OnRise( Keyboard::EB_NumAdd ) || pKeyboard->OnRise( Keyboard::EB_NumSubtract ) ) { const float Scalar = pKeyboard->OnRise( Keyboard::EB_NumAdd ) ? 2.0f : 0.5f; if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Control ) ) { const float NewMultiplier = m_DEVHACKClockMultiplier ? ( Scalar * m_DEVHACKClockMultiplier->m_Multiplier ) : Scalar; if( m_DEVHACKClockMultiplier ) { pFramework->GetClock()->RemoveMultiplierRequest( &m_DEVHACKClockMultiplier ); } if( NewMultiplier != 1.0f ) { m_DEVHACKClockMultiplier = pFramework->GetClock()->AddMultiplierRequest( 0.0f, NewMultiplier ); } } else { pFramework->DEV_SetFixedTimeScalar( Scalar * pFramework->DEV_GetFixedTimeScalar() ); } } // Right shift: debug render targeted entity // (This is pretty basic, but it works to debug enemies, which is the main purpose) if( pKeyboard->OnRise( Keyboard::EB_RightShift ) ) { WBEntityRef OldTarget = m_DEVHACKDebugTarget; m_DEVHACKDebugTarget = NULL; // DLP 5 Dec 2021: First try the frob and aim targets, then trace if needed WBCompRosaFrobber* const pFrobber = WB_GETCOMP( pEntity, RosaFrobber ); DEVASSERT( pFrobber ); m_DEVHACKDebugTarget = pFrobber->GetFrobTarget(); if( !m_DEVHACKDebugTarget ) { m_DEVHACKDebugTarget = pFrobber->GetAimTarget(); } if( !m_DEVHACKDebugTarget ) { const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector(); const Ray TraceRay = Ray( EyeLoc, EyeDir ); CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = GetEntity(); Info.m_In_UserFlags = EECF_Trace | EECF_CollideBones; if( pWorld->Trace( TraceRay, Info ) ) { WBEntity* const pHitEntity = static_cast<WBEntity*>( Info.m_Out_HitEntity ); m_DEVHACKDebugTarget = pHitEntity; } } // Targeting nothing; focus on self, then unfocus if( !m_DEVHACKDebugTarget ) { if( OldTarget == GetEntity() ) { // Do nothing (unfocus) } else { m_DEVHACKDebugTarget = GetEntity(); } } if( OldTarget != m_DEVHACKDebugTarget ) { if( OldTarget.Get() ) { OldTarget.Get()->SetShouldDebugRender( false ); } if( m_DEVHACKDebugTarget ) { m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true ); } } } if( pKeyboard->OnRise( Keyboard::EB_PageDown ) ) { if( m_DEVHACKDebugTarget ) { m_DEVHACKDebugTarget.Get()->GoToNextDebugRenderComponent(); } else { m_DEVHACKDebugTarget = GetEntity(); m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true ); } } if( pKeyboard->OnRise( Keyboard::EB_PageUp ) ) { if( m_DEVHACKDebugTarget ) { m_DEVHACKDebugTarget.Get()->GoToPrevDebugRenderComponent(); } else { m_DEVHACKDebugTarget = GetEntity(); m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true ); m_DEVHACKDebugTarget.Get()->GoToPrevDebugRenderComponent(); } } // X: Teleport to trace destination if( pKeyboard->OnRise( Keyboard::EB_X ) ) { const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector(); const Ray TraceRay = Ray( EyeLoc, EyeDir ); CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_CollideEntities = true; Info.m_In_CollidingEntity = GetEntity(); Info.m_In_UserFlags = EECF_BlockerCollision; if( pWorld->Trace( TraceRay, Info ) ) { Vector Destination = Info.m_Out_Intersection + Info.m_Out_Plane.m_Normal * 0.1f; if( pWorld->FindSpot( Destination, pCollision->GetExtents(), Info ) ) { pTransform->SetLocation( Destination ); } } } // Alt + K: Kill all enemies if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_K ) && !pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) && !pKeyboard->IsHigh( Keyboard::EB_V ) ) { Array<WBEntity*> AllEntities; WBScene::GetDefault()->GetAllEntities( AllEntities ); FOR_EACH_ARRAY( EntityIter, AllEntities, WBEntity* ) { WBEntity* const pIterEntity = EntityIter.GetValue(); if( pIterEntity == pEntity ) { continue; } if( WBCompRosaFaction::GetCon( pEntity, pIterEntity ) != RosaFactions::EFR_Hostile ) { continue; } WB_MAKE_EVENT( Kill, pIterEntity ); WB_SET_AUTO( Kill, Entity, Damager, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), Kill, pIterEntity ); } } // Alt + L: Print player location and heading to log if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_L ) && !pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) ) { PRINTF( "Player location: %s\n", pTransform->GetLocation().GetString().CStr() ); PRINTF( "Player direction: %s\n", pTransform->GetOrientation().ToVector().GetString().CStr() ); } // Alt + M: Give master key if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_M ) ) { STATIC_HASHED_STRING( Keycard_MASTER ); pKeyRing->AddKeycard( sKeycard_MASTER, true ); } // Alt + O: Toggle invisible, silent, noclip if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_O ) ) { const bool CheatOn = pVisible->IsVisible(); pVisible->SetVisible( !CheatOn ); if( pFootsteps ) { pFootsteps->SetFootstepsDisabled( CheatOn ); } } // V: Spawn entity if( !pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_V ) ) { const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector(); const Ray TraceRay( EyeLoc, EyeDir ); CollisionInfo TraceInfo; TraceInfo.m_In_CollideWorld = true; TraceInfo.m_In_UserFlags = EECF_CollideAsEntity; if( pWorld->Trace( TraceRay, TraceInfo ) ) { const SDebugSpawner& Spawner = m_DebugSpawners[ m_DebugSpawnerIndex ]; WBEntity* pSpawnedEntity = WBWorld::GetInstance()->CreateEntity( Spawner.m_Entity ); WBCompRosaTransform* pSpawnedTransform = pSpawnedEntity->GetTransformComponent<WBCompRosaTransform>(); if( pSpawnedTransform ) { Vector SpawnLocation = TraceInfo.m_Out_Intersection + TraceInfo.m_Out_Plane.m_Normal * Spawner.m_NormalDistance * pSpawnedTransform->GetScale() + Spawner.m_Offset; WBCompRosaCollision* pSpawnedCollision = WB_GETCOMP( pSpawnedEntity, RosaCollision ); if( pSpawnedCollision ) { CollisionInfo FindSpotInfo; FindSpotInfo.m_In_CollideWorld = true; FindSpotInfo.m_In_CollideEntities = true; FindSpotInfo.m_In_CollidingEntity = pSpawnedEntity; FindSpotInfo.m_In_UserFlags = EECF_EntityCollision; pWorld->FindSpot( SpawnLocation, pSpawnedCollision->GetExtents(), FindSpotInfo ); } pSpawnedTransform->SetInitialTransform( SpawnLocation, Angles() ); } } } // Alt+LMB: Test pathfinding from current loc to wherever we're aiming if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_Mouse_Left ) ) { const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector(); const Ray TraceRay( EyeLoc, EyeDir ); CollisionInfo Info; Info.m_In_CollideWorld = true; Info.m_In_UserFlags = EECF_CollideAsEntity; if( pWorld->Trace( TraceRay, Info ) ) { const Vector HitLoc = Info.m_Out_Intersection + Info.m_Out_Plane.m_Normal * 0.1f; m_CAMHACKPathData.m_Params.m_PathMode = RosaNav::EPM_Search; m_CAMHACKPathData.m_Params.m_Start = pTransform->GetLocation(); m_CAMHACKPathData.m_Params.m_Destination = HitLoc; m_CAMHACKPathData.m_Params.m_AgentHeight = pCollision->GetExtents().z * 2.0f; m_CAMHACKPathData.m_Params.m_AgentRadius = pCollision->GetExtents().x * 1.414f; m_CAMHACKPathData.m_Params.m_MotionType = RosaNav::EMT_Walking; m_CAMHACKPathData.m_Params.m_CanOpenDoors = true; m_CAMHACKPathData.m_Params.m_MaxSteps = 1000; m_CAMHACKPathData.m_Params.m_UsePartialPath = true; #if BUILD_DEBUG m_CAMHACKPathData.m_Params.m_Verbose = true; #endif RosaNav::GetInstance()->FindPath( m_CAMHACKPathData ); } } // Alt + G: ghost (no collision, no gravity), Shift + Alt + G: disable ghost if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_G ) ) { if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) ) { pCollision->ResetCollisionFlags(); WB_MAKE_EVENT( StopFlying, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), StopFlying, GetEntity() ); } else { pCollision->SetCollisionFlags( 0 ); WB_MAKE_EVENT( StartFlying, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), StartFlying, GetEntity() ); } } // Camera hacks: Alt + V + ... (Used to be Shift + C + ...) if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->IsHigh( Keyboard::EB_V ) ) { //WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>(); //WBCompRosaCollision* const pCollision = WB_GETCOMP( GetEntity(), RosaCollision ); //WBCompRosaHealth* const pHealth = WB_GETCOMP( GetEntity(), RosaHealth ); //WBCompRosaWallet* const pWallet = WB_GETCOMP( GetEntity(), RosaWallet ); //WBCompRosaKeyRing* const pKeyRing = WB_GETCOMP( GetEntity(), RosaKeyRing ); if( pKeyboard->OnRise( Keyboard::EB_U ) ) { m_CAMHACKCamVelocity *= 0.8f; PRINTF( "m_CAMHACKCamVelocity: %f\n", m_CAMHACKCamVelocity ); } if( pKeyboard->OnRise( Keyboard::EB_P ) ) { m_CAMHACKCamVelocity *= 1.25f; PRINTF( "m_CAMHACKCamVelocity: %f\n", m_CAMHACKCamVelocity ); } if( pKeyboard->OnRise( Keyboard::EB_J ) ) { m_CAMHACKCamStartLocation = pTransform->GetLocation(); m_CAMHACKCamStartOrientation = pTransform->GetOrientation(); PRINTF( "Start point set\n" ); } if( pKeyboard->OnRise( Keyboard::EB_K ) ) { m_CAMHACKCamEndLocation = pTransform->GetLocation(); m_CAMHACKCamEndOrientation = pTransform->GetOrientation(); PRINTF( "End point set\n" ); } if( pKeyboard->OnRise( Keyboard::EB_L ) ) { PRINTF( "Toggled\n" ); m_CAMHACKCamActive = !m_CAMHACKCamActive; if( m_CAMHACKCamActive ) { if( m_CAMHACKCamStartLocation.IsZero() || m_CAMHACKCamEndLocation.IsZero() ) { // Don't interpolate, it will cause problems. m_CAMHACKCamActive = false; } else { pCollision->SetCollisionFlags( 0 ); pTransform->SetGravity( 0.0f ); if( pFootsteps ) { pFootsteps->SetFootstepsDisabled( true ); } WB_MAKE_EVENT( HideHands, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), HideHands, GetEntity() ); const float Distance = ( m_CAMHACKCamStartLocation - m_CAMHACKCamEndLocation ).Length(); const float Duration = Distance / m_CAMHACKCamVelocity; m_CAMHACKCamLocation.Reset( Interpolator<Vector>::EIT_Linear, m_CAMHACKCamStartLocation, m_CAMHACKCamEndLocation, Duration ); m_CAMHACKCamOrientation.Reset( Interpolator<Angles>::EIT_Linear, m_CAMHACKCamStartOrientation, m_CAMHACKCamEndOrientation, Duration ); STATIC_HASHED_STRING( HUD ); WB_MAKE_EVENT( RemoveUIScreen, NULL ); WB_SET_AUTO( RemoveUIScreen, Hash, Screen, sHUD ); WB_DISPATCH_EVENT( GetEventManager(), RemoveUIScreen, NULL ); } } else { pCollision->ResetCollisionFlags(); pTransform->SetDefaultGravity(); if( pFootsteps ) { pFootsteps->SetFootstepsDisabled( false ); } WB_MAKE_EVENT( ShowHands, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), ShowHands, GetEntity() ); STATIC_HASHED_STRING( HUD ); WB_MAKE_EVENT( RepushUIScreen, NULL ); WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD ); WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL ); } } } } #endif // BUILD_DEV /*virtual*/ void WBCompRosaPlayer::HandleEvent( const WBEvent& Event ) { XTRACE_FUNCTION; Super::HandleEvent( Event ); // Forward all events the player receives to the game and world GetGame()->HandleEvent( Event ); GetWorld()->HandleEvent( Event ); STATIC_HASHED_STRING( OnSpawned ); STATIC_HASHED_STRING( OnLoaded ); STATIC_HASHED_STRING( CycleMenuDifficulty ); STATIC_HASHED_STRING( SetMenuDifficulty ); STATIC_HASHED_STRING( OnInitialized ); STATIC_HASHED_STRING( OnAutosave ); STATIC_HASHED_STRING( AddAutosaveSuppression ); STATIC_HASHED_STRING( RemoveAutosaveSuppression ); STATIC_HASHED_STRING( StartDrag ); STATIC_HASHED_STRING( StopDrag ); STATIC_HASHED_STRING( OnTouchedClimbable ); STATIC_HASHED_STRING( OnUntouchedClimbable ); STATIC_HASHED_STRING( OnJumped ); STATIC_HASHED_STRING( OnLanded ); STATIC_HASHED_STRING( OnCollided ); STATIC_HASHED_STRING( OnSteppedUp ); STATIC_HASHED_STRING( OnKickImpulse ); STATIC_HASHED_STRING( PreLevelTransition ); STATIC_HASHED_STRING( PostLevelTransition ); STATIC_HASHED_STRING( PushInputContext ); STATIC_HASHED_STRING( PopInputContext ); STATIC_HASHED_STRING( DisablePause ); STATIC_HASHED_STRING( EnablePause ); STATIC_HASHED_STRING( PushPersistence ); STATIC_HASHED_STRING( PullPersistence ); STATIC_HASHED_STRING( OnAINoise ); STATIC_HASHED_STRING( OnFOVChanged ); STATIC_HASHED_STRING( SlamFOVScale ); STATIC_HASHED_STRING( SetInitialMusicTrackBits ); STATIC_HASHED_STRING( StartFlying ); STATIC_HASHED_STRING( StopFlying ); STATIC_HASHED_STRING( OnDied ); const HashedString EventName = Event.GetEventName(); if( EventName == sOnSpawned ) { SetCrouchOverlayHidden( true ); QueueAutosave( m_RollingAutosaveDelay ); // Update from difficulty system RosaDifficulty::PushMenuToGame(); } else if( EventName == sOnLoaded ) { RestoreCrouch(); RestorePowerSlide(); RestoreDrag(); RestoreClimb(); // Notify difficulty system (if we're traveling with persistence, we pull that later) RosaDifficulty::PushGameToMenu(); } else if( EventName == sCycleMenuDifficulty || EventName == sSetMenuDifficulty ) { // Update from difficulty system RosaDifficulty::PushMenuToGame(); } else if( EventName == sOnInitialized ) { // In case user switches away from game and we end up paused // before playing new music, stop the old music (and ambience!) immediately. WB_MAKE_EVENT( StopMusicAndAmbience, NULL ); WB_DISPATCH_EVENT( GetEventManager(), StopMusicAndAmbience, GetGame() ); // HACKHACK: The grossest hack. Since I'm (currently!) only using this to defer // music in RosaIntro, ignore it on subsequent initializations so returning to // the title will play music the usual way. Gross! static bool CanDeferMusic = true; if( m_DeferMusic && CanDeferMusic ) { CanDeferMusic = false; // Do nothing, something else will play music later } else { WB_MAKE_EVENT( PlayMusicAndAmbience, NULL ); WB_SET_AUTO( PlayMusicAndAmbience, Int, TrackBits, m_InitialMusicTrackBits ); WB_DISPATCH_EVENT( GetEventManager(), PlayMusicAndAmbience, GetGame() ); // ROSANOTE: Since Eldritch, this had always been delayed by one tick. Can't remember why. } } else if( EventName == sOnAutosave ) { if( CanAutosave() ) { // Queue the next one *before* autosaving so the queued event gets saved. QueueAutosave( m_RollingAutosaveDelay ); GetGame()->Autosave(); } else { QueueAutosave( m_RetryAutosaveDelay ); } } else if( EventName == sAddAutosaveSuppression ) { STATIC_HASHED_STRING( Serialize ); const bool Serialize = Event.GetBool( sSerialize ); AddAutosaveSuppression( Serialize ); } else if( EventName == sRemoveAutosaveSuppression ) { STATIC_HASHED_STRING( Serialize ); const bool Serialize = Event.GetBool( sSerialize ); RemoveAutosaveSuppression( Serialize ); } else if( EventName == sStartDrag ) { STATIC_HASHED_STRING( DraggedEntity ); WBEntity* const pDraggedEntity = Event.GetEntity( sDraggedEntity ); DEVASSERT( pDraggedEntity ); BeginDrag( pDraggedEntity ); } else if( EventName == sStopDrag ) { #if BUILD_DEV // Validate that we're stopping the actual dragged entity STATIC_HASHED_STRING( DraggedEntity ); WBEntity* const pDraggedEntity = Event.GetEntity( sDraggedEntity ); DEVASSERT( pDraggedEntity ); DEVASSERT( pDraggedEntity == m_DraggedEntity.Get() ); #endif EndDrag(); } else if( EventName == sOnTouchedClimbable ) { if( ShouldAttachToClimbable( Event ) ) { IncrementClimbRefs( Event ); } } else if( EventName == sOnUntouchedClimbable ) { const bool AddClimbOffImpulse = true; DecrementClimbRefs( AddClimbOffImpulse ); } else if( EventName == sOnLanded ) { if( !m_HasSetSpawnPoint ) { SetSpawnPoint(); } m_HasDoubleJumped = false; m_CanMantle = true; ZeroClimbRefs(); // Force a footstep on landed, with a timeout to prevent relanded events from making more footsteps WBEntity* const pEntity = GetEntity(); WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision ); if( !pCollision->IsRecentlyLanded( m_UnlandedForceFootstepWindow ) ) { // Pass landed magnitude through as additional speed STATIC_HASHED_STRING( LandedMagnitude ); const float LandedMagnitude = Event.GetFloat( sLandedMagnitude ); WB_MAKE_EVENT( ForceFootstep, GetEntity() ); WB_SET_AUTO( ForceFootstep, Float, AdditionalSpeed, LandedMagnitude ); WB_DISPATCH_EVENT( GetEventManager(), ForceFootstep, GetEntity() ); } if( m_IsForceCrouched ) { BeginUncrouch(); } } else if( EventName == sOnCollided ) { if( m_IsPowerSliding ) { EndPowerSlide(); } STATIC_HASHED_STRING( CollidedEntity ); WBEntity* const pCollidedEntity = Event.GetEntity( sCollidedEntity ); WBCompRosaCollision* const pCollidedCollision = WB_GETCOMP_SAFE( pCollidedEntity, RosaCollision ); if( pCollidedCollision && pCollidedCollision->IsDynamicBlocker() ) { // Collided entity is a blocker (a dynamic entity that blocks other entities). Do not attempt to mantle onto it. } else { STATIC_HASHED_STRING( CollisionNormal ); const Vector CollisionNormal = Event.GetVector( sCollisionNormal ); TryBeginMantle( CollisionNormal ); } } else if( EventName == sOnSteppedUp ) { STATIC_HASHED_STRING( StepHeight ); const float StepHeight = Event.GetFloat( sStepHeight ); OnSteppedUp( StepHeight ); } else if( EventName == sOnKickImpulse ) { STATIC_HASHED_STRING( KickImpulse ); const Angles KickImpulse = Event.GetAngles( sKickImpulse ); m_KickVelocity += KickImpulse; } else if( EventName == sPreLevelTransition ) { WB_MAKE_EVENT( PushPersistence, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), PushPersistence, GetEntity() ); } else if( EventName == sPostLevelTransition ) { const TPersistence& Persistence = RosaGame::StaticGetTravelPersistence(); if( Persistence.Size() ) { WB_MAKE_EVENT( PullPersistence, GetEntity() ); WB_DISPATCH_EVENT( GetEventManager(), PullPersistence, GetEntity() ); } STATIC_HASHED_STRING( RestoreSpawnPoint ); const bool ShouldRestoreSpawnPoint = Event.GetBool( sRestoreSpawnPoint ); STATIC_HASHED_STRING( TeleportLabel ); const HashedString TeleportLabel = Event.GetHash( sTeleportLabel ); if( TeleportLabel != HashedString::NullString ) { TeleportTo( TeleportLabel ); } else if( ShouldRestoreSpawnPoint && m_HasSetSpawnPoint ) { RestoreSpawnPoint(); } } else if( EventName == sPushInputContext ) { STATIC_HASHED_STRING( InputContext ); const HashedString InputContext = Event.GetHash( sInputContext ); GetFramework()->GetInputSystem()->PushContext( InputContext ); } else if( EventName == sPopInputContext ) { STATIC_HASHED_STRING( InputContext ); const HashedString InputContext = Event.GetHash( sInputContext ); GetFramework()->GetInputSystem()->PopContext( InputContext ); } else if( EventName == sDisablePause ) { m_IsDisablingPause = true; } else if( EventName == sEnablePause ) { m_IsDisablingPause = false; } else if( EventName == sPushPersistence ) { PushPersistence(); } else if( EventName == sPullPersistence ) { PullPersistence(); } else if( EventName == sOnAINoise ) { #if BUILD_DEV STATIC_HASHED_STRING( EventOwner ); WBEntity* const pEventOwner = Event.GetEntity( sEventOwner ); ASSERT( pEventOwner ); STATIC_HASHED_STRING( NoiseEntity ); WBEntity* const pNoiseEntity = Event.GetEntity( sNoiseEntity, pEventOwner ); if( pNoiseEntity == GetEntity() ) { STATIC_HASHED_STRING( NoiseLocation ); const Vector NoiseEntityLocation = pEventOwner->GetTransformComponent<WBCompRosaTransform>()->GetLocation(); const Vector NoiseLocation = Event.GetVector( sNoiseLocation, NoiseEntityLocation ); DEVASSERT( !NoiseLocation.IsZero() ); STATIC_HASHED_STRING( NoiseSourceLocation ); const Vector NoiseSourceLocation = Event.GetVector( sNoiseSourceLocation ); m_CACHED_LastAINoiseSourceLocation = NoiseSourceLocation.IsZero() ? NoiseLocation : NoiseSourceLocation; STATIC_HASHED_STRING( NoiseRadius ); m_CACHED_LastAINoiseRadius = Event.GetFloat( sNoiseRadius ); } #endif } else if( EventName == sOnFOVChanged ) { STATICHASH( FOV ); m_CurrentFOV.Reset( ConfigManager::GetFloat( sFOV ) ); } else if( EventName == sSlamFOVScale ) { // HACKHACK for Intro hub wake-up moment, mainly STATICHASH( FOVScale ); const float FOVScale = Event.GetFloat( sFOVScale ); STATICHASH( FOV ); STATICHASH( ForegroundFOV ); TickScaleFOV( m_CurrentFOV, ConfigManager::GetFloat( sFOV ), FOVScale, 0.0f, 0.0f ); TickScaleFOV( m_CurrentFGFOV, ConfigManager::GetFloat( sForegroundFOV ), FOVScale, 0.0f, 0.0f ); GetFramework()->SetFOV( m_CurrentFOV.GetValue() ); GetFramework()->SetFGFOV( m_CurrentFGFOV.GetValue() ); } else if( EventName == sSetInitialMusicTrackBits ) { STATIC_HASHED_STRING( InitialMusicTrackBits ); const uint InitialMusicTrackBits = Event.GetInt( sInitialMusicTrackBits ); m_InitialMusicTrackBits = InitialMusicTrackBits; } else if( EventName == sStartFlying ) { // Adapted from Acid flying scripts m_IsFlying = true; WBEntity* const pEntity = GetEntity(); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); pTransform->SetGravity( 0.0f ); WB_MAKE_EVENT( EnableAirFriction, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), EnableAirFriction, pEntity ); WB_MAKE_EVENT( DisableFootsteps, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), DisableFootsteps, pEntity ); } else if( EventName == sStopFlying ) { // Adapted from Acid flying scripts m_IsFlying = false; WBEntity* const pEntity = GetEntity(); WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>(); pTransform->SetDefaultGravity(); WB_MAKE_EVENT( DisableAirFraction, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), DisableAirFraction, pEntity ); WB_MAKE_EVENT( EnableFootsteps, pEntity ); WB_DISPATCH_EVENT( GetEventManager(), EnableFootsteps, pEntity ); } else if( EventName == sOnDied ) { if( m_IsCrouched ) { BeginUncrouch(); } } } /*virtual*/ void WBCompRosaPlayer::AddContextToEvent( WBEvent& Event ) const { Super::AddContextToEvent( Event ); WBCompRosaWeapon* const pWeapon = GetWeapon(); const bool IsAiming = pWeapon && pWeapon->IsAiming(); WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod ); WB_MODIFY_FLOAT( CanUnlockDoors, 0.0f, pStatMod ); const bool CanUnlockDoors = ( WB_MODDED( CanUnlockDoors ) != 0.0f ); { WB_SET_CONTEXT( Event, Bool, CanOpenDoors, true ); WB_SET_CONTEXT( Event, Bool, CanUnlockDoors, CanUnlockDoors ); WB_SET_CONTEXT( Event, Bool, IsSprinting, m_IsSprinting && !m_IsCrouched ); WB_SET_CONTEXT( Event, Float, SprintTime, GetTime() - m_SprintStartTime ); WB_SET_CONTEXT( Event, Bool, IsPowerSliding, m_IsPowerSliding ); WB_SET_CONTEXT( Event, Bool, IsMantling, m_IsMantling ); WB_SET_CONTEXT( Event, Bool, IsAiming, IsAiming ); } // OLDVAMP: Replace with an equivalent for Zeta campaign? //// Add some campaign context so we can easily query this stuff without special PEs //// (as long as we're querying it *after* the player has spawned!) //RosaCampaign* const pCampaign = RosaCampaign::GetCampaign(); //if( pCampaign ) //{ // WB_SET_CONTEXT( Event, Int, Campaign_Legacy, pCampaign->GetLegacy() ); // WB_SET_CONTEXT( Event, Int, Campaign_Season, pCampaign->GetSeason() ); // WB_SET_CONTEXT( Event, Int, Campaign_Episode, pCampaign->GetEpisode() ); //} } // Manage difficulty persistence here, since there's no difficulty component void WBCompRosaPlayer::PushPersistence() const { TPersistence& Persistence = RosaGame::StaticGetTravelPersistence(); const uint GameDifficulty = RosaDifficulty::GetGameDifficulty(); STATIC_HASHED_STRING( GameDifficulty ); Persistence.SetInt( sGameDifficulty, GameDifficulty ); } void WBCompRosaPlayer::PullPersistence() { TPersistence& Persistence = RosaGame::StaticGetTravelPersistence(); STATIC_HASHED_STRING( GameDifficulty ); const uint GameDifficulty = Persistence.GetInt( sGameDifficulty ); RosaDifficulty::SetGameDifficulty( GameDifficulty ); RosaDifficulty::PushGameToMenu(); } void WBCompRosaPlayer::AddAutosaveSuppression( const bool Serialize ) { if( Serialize ) { ++m_AutosaveSuppRefsSerialized; } else { ++m_AutosaveSuppRefsTransient; } } void WBCompRosaPlayer::RemoveAutosaveSuppression( const bool Serialize ) { if( Serialize ) { if( m_AutosaveSuppRefsSerialized > 0 ) { --m_AutosaveSuppRefsSerialized; } #if BUILD_DEV else { WARNDESC( "Autosave: Suppression refcount mismatch, trying to decrement past zero." ); } #endif } else { if( m_AutosaveSuppRefsTransient > 0 ) { --m_AutosaveSuppRefsTransient; } #if BUILD_DEV else { WARNDESC( "Autosave: Transient suppression refcount mismatch, trying to decrement past zero." ); } #endif } } bool WBCompRosaPlayer::CanAutosave() { if( m_AutosaveSuppRefsSerialized > 0 || m_AutosaveSuppRefsTransient > 0 ) { DEVPRINTF( "CanAutosave: false because suppression refcount is %d/%d\n", m_AutosaveSuppRefsSerialized, m_AutosaveSuppRefsTransient ); return false; } WBCompRosaCollision* const pCollision = WB_GETCOMP( GetEntity(), RosaCollision ); if( !pCollision->IsLanded() ) { DEVPRINTF( "CanAutosave: false because player is unlanded\n" ); return false; } DEVPRINTF( "CanAutosave: true\n" ); return true; } void WBCompRosaPlayer::QueueAutosave( const float AutosaveDelay ) { WB_MAKE_EVENT( OnAutosave, NULL ); WB_QUEUE_EVENT_DELAY( GetEventManager(), OnAutosave, GetEntity(), AutosaveDelay ); } /*virtual*/ void WBCompRosaPlayer::OnInputContextsChanged() { ConditionalApplyRunningStatMods(); } void WBCompRosaPlayer::ConditionalApplyRunningStatMods() { WBEntity* const pEntity = GetEntity(); WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod ); STATIC_HASHED_STRING( Running ); if( m_IsSprinting && !m_IsCrouched ) { pStatMod->SetEventActive( sRunning, true ); } else { pStatMod->SetEventActive( sRunning, false ); } } #define VERSION_EMPTY 0 #define VERSION_CROUCHING 1 #define VERSION_CLIMBING 2 #define VERSION_UNCLIMBINGGRAVITY 3 #define VERSION_SPAWNPOINT 4 #define VERSION_POWERSLIDE 5 #define VERSION_POWERSLIDEY 6 #define VERSION_ISDISABLINGPAUSE 7 #define VERSION_DRAG 8 #define VERSION_AUTOSAVESUPPRESSION 9 #define VERSION_HASDOUBLEJUMPED 10 #define VERSION_INITIALMUSICTRACKBITS 11 #define VERSION_ISFORCEDCROUCHED 12 #define VERSION_UNCLIMBINGGRAVITY_DEPR 13 #define VERSION_ISFLYING 14 #define VERSION_CURRENT 14 uint WBCompRosaPlayer::GetSerializationSize() { uint Size = 0; Size += 4; // Version Size += 1; // m_IsCrouched Size += 1; // m_IsUncrouching Size += 1; // m_IsForceCrouched Size += 4; // m_ClimbRefs Size += 1; // m_HasSetSpawnPoint Size += sizeof( Vector ); // m_SpawnLocation Size += sizeof( Angles ); // m_SpawnOrientation Size += 1; // m_HasDoubleJumped Size += 1; // m_IsPowerSliding Size += 4; // Power slide time remaining Size += sizeof( Vector ); // m_PowerSlideY Size += 1; // m_IsDisablingPause Size += 1; // m_IsDragging Size += sizeof( WBEntityRef ); // m_DraggedEntity Size += 4; // m_AutosaveSuppRefsSerialized Size += 4; // m_InitialMusicTrackBits Size += 1; // m_IsFlying return Size; } void WBCompRosaPlayer::Save( const IDataStream& Stream ) { Stream.WriteUInt32( VERSION_CURRENT ); Stream.WriteBool( m_IsCrouched ); Stream.WriteBool( m_IsUncrouching ); Stream.WriteBool( m_IsForceCrouched ); Stream.WriteInt32( m_ClimbRefs ); Stream.WriteBool( m_HasSetSpawnPoint ); Stream.Write( sizeof( Vector ), &m_SpawnLocation ); Stream.Write( sizeof( Angles ), &m_SpawnOrientation ); Stream.WriteBool( m_HasDoubleJumped ); Stream.WriteBool( m_IsPowerSliding ); Stream.WriteFloat( m_PowerSlideEndTime - GetTime() ); Stream.Write( sizeof( Vector ), &m_PowerSlideY ); Stream.WriteBool( m_IsDisablingPause ); Stream.WriteBool( m_IsDragging ); Stream.Write( sizeof( WBEntityRef ), &m_DraggedEntity ); Stream.WriteUInt32( m_AutosaveSuppRefsSerialized ); Stream.WriteUInt32( m_InitialMusicTrackBits ); Stream.WriteBool( m_IsFlying ); } void WBCompRosaPlayer::Load( const IDataStream& Stream ) { XTRACE_FUNCTION; const uint Version = Stream.ReadUInt32(); if( Version >= VERSION_CROUCHING ) { m_IsCrouched = Stream.ReadBool(); m_IsUncrouching = Stream.ReadBool(); } if( Version >= VERSION_ISFORCEDCROUCHED ) { m_IsForceCrouched = Stream.ReadBool(); } if( Version >= VERSION_CLIMBING ) { m_ClimbRefs = Stream.ReadInt32(); } if( Version >= VERSION_UNCLIMBINGGRAVITY && Version < VERSION_UNCLIMBINGGRAVITY_DEPR ) { Stream.ReadFloat(); } if( Version >= VERSION_SPAWNPOINT ) { m_HasSetSpawnPoint = Stream.ReadBool(); Stream.Read( sizeof( Vector ), &m_SpawnLocation ); Stream.Read( sizeof( Angles ), &m_SpawnOrientation ); } if( Version >= VERSION_HASDOUBLEJUMPED ) { m_HasDoubleJumped = Stream.ReadBool(); } if( Version >= VERSION_POWERSLIDE ) { m_IsPowerSliding = Stream.ReadBool(); m_PowerSlideEndTime = GetTime() + Stream.ReadFloat(); } if( Version >= VERSION_POWERSLIDEY ) { Stream.Read( sizeof( Vector ), &m_PowerSlideY ); } if( Version >= VERSION_ISDISABLINGPAUSE ) { m_IsDisablingPause = Stream.ReadBool(); } if( Version >= VERSION_DRAG ) { m_IsDragging = Stream.ReadBool(); Stream.Read( sizeof( WBEntityRef ), &m_DraggedEntity ); } if( Version >= VERSION_AUTOSAVESUPPRESSION ) { m_AutosaveSuppRefsSerialized = Stream.ReadUInt32(); } if( Version >= VERSION_INITIALMUSICTRACKBITS ) { m_InitialMusicTrackBits = Stream.ReadUInt32(); } if( Version >= VERSION_ISFLYING ) { m_IsFlying = Stream.ReadBool(); } }
33.375187
261
0.743044
dphrygian
ea1661eda603cd1b755ed6abeda67e0793b7072c
3,283
hpp
C++
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
1
2019-11-09T07:12:56.000Z
2019-11-09T07:12:56.000Z
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
1
2015-12-19T10:53:53.000Z
2015-12-19T17:58:20.000Z
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and * * Martin Renou * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_COMMON_MATH_HPP #define XSIMD_COMMON_MATH_HPP #include <limits> #include <type_traits> namespace xsimd { /********************************************* * Some utility math operations shared * * across scalar versio and fallback * * versions * *********************************************/ namespace detail { template <class T0, class T1> inline T0 ipow(const T0& t0, const T1& t1) { static_assert(std::is_integral<T1>::value, "second argument must be an integer"); T0 a = t0; T1 b = t1; bool const recip = b < 0; T0 r{static_cast<T0>(1)}; while (1) { if (b & 1) { r *= a; } b /= 2; if (b == 0) { break; } a *= a; } return recip ? 1 / r : r; } template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type> T sadd(const T& lhs, const T& rhs) { if (std::numeric_limits<T>::is_signed) { if ((lhs > 0) && (rhs > std::numeric_limits<T>::max() - lhs)) { return std::numeric_limits<T>::max(); } else if ((lhs < 0) && (rhs < std::numeric_limits<T>::lowest() - lhs)) { return std::numeric_limits<T>::lowest(); } else { return lhs + rhs; } } else { if (rhs > std::numeric_limits<T>::max() - lhs) { return std::numeric_limits<T>::max(); } else { return lhs + rhs; } } } template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type> T ssub(const T& lhs, const T& rhs) { if (std::numeric_limits<T>::is_signed) { return sadd(lhs, (T)-rhs); } else { if (lhs < rhs) { return std::numeric_limits<T>::lowest(); } else { return lhs - rhs; } } } } } #endif
31.266667
93
0.335364
jeanlaroche
ea1a1a4ad651a8413789e171ef860cd2d745c0e6
107
cpp
C++
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
#include "Liber_pch.h" #include "InputComponent.h" void Libero::InputComponent::HandleEvent(IEvent& ) { }
15.285714
50
0.747664
Kair0z
ea1e97576f585169d98fd8f01f696db032199934
10,874
cpp
C++
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2013 Vladislav Tyulbashev * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include <QVBoxLayout> #include <QPushButton> #include <QTime> #include <QMouseEvent> #include <QWidget> #include <QTime> #include <QTimer> #include <QSizePolicy> #include <QEventLoop> #include <QTimeLine> #include <QDir> #include <QDebug> #include "vlcplayer.h" namespace { QTime convertTime (libvlc_time_t t) { return QTime (t / 1000 / 60 / 60, t / 1000 / 60 % 60, t / 1000 % 60, t % 1000); } void sleep (int ms) { QEventLoop loop; QTimer::singleShot (ms, &loop, SLOT (quit ())); loop.exec (); } const int DVD_IS_MORE_THAN = 10 * 60 * 1000; // in ms const int MAX_TIMEOUT = 1000; // in ms } namespace LeechCraft { namespace vlc { VlcPlayer::VlcPlayer (QWidget *parent) : QObject (parent) , M_ (nullptr) , Parent_ (parent) , DVD_ (false) { VlcInstance_ = std::shared_ptr<libvlc_instance_t> (libvlc_new (0, nullptr), libvlc_release); Mp_ = std::shared_ptr<libvlc_media_player_t> (libvlc_media_player_new (VlcInstance_.get ()), libvlc_media_player_release); libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ()); } VlcPlayer::~VlcPlayer() { libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::Init (QWidget *parent) { libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ()); Parent_ = parent; } void VlcPlayer::setUrl (const QUrl& url) { Subtitles_.clear (); libvlc_media_player_stop (Mp_.get ()); DVD_ = url.scheme () == "dvd"; M_.reset (libvlc_media_new_location (VlcInstance_.get (), url.toEncoded ()), libvlc_media_release); libvlc_media_player_set_media (Mp_.get (), M_.get ()); libvlc_media_player_play (Mp_.get ()); } void VlcPlayer::addUrl (const QUrl& url) { const QUrl &lastMedia = QUrl::fromEncoded (libvlc_media_get_meta (libvlc_media_player_get_media (Mp_.get ()), libvlc_meta_URL)); Freeze (); M_.reset (libvlc_media_new_location (VlcInstance_.get (), lastMedia.toEncoded ()), libvlc_media_release); libvlc_media_add_option (M_.get (), ":input-slave=" + url.toEncoded ()); libvlc_media_player_set_media (Mp_.get (), M_.get ()); UnFreeze (); } bool VlcPlayer::NowPlaying () const { return libvlc_media_player_is_playing (Mp_.get ()); } double VlcPlayer::GetPosition () const { return libvlc_media_player_get_position (Mp_.get ()); } void VlcPlayer::togglePlay () { bool subtitlesRequired = false; if (libvlc_media_player_get_state (Mp_.get ()) == libvlc_Stopped || libvlc_media_player_get_state (Mp_.get ()) == libvlc_Ended) subtitlesRequired = true; if (NowPlaying ()) libvlc_media_player_pause (Mp_.get ()); else libvlc_media_player_play (Mp_.get ()); if (subtitlesRequired) ReloadSubtitles (); } void VlcPlayer::stop () { libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::pause () { libvlc_media_player_pause (Mp_.get ()); } void VlcPlayer::changePosition (double pos) { if (libvlc_media_player_get_media (Mp_.get ())) libvlc_media_player_set_position (Mp_.get (), pos); } QTime VlcPlayer::GetFullTime () const { if (libvlc_media_player_get_media (Mp_.get ())) return convertTime (libvlc_media_player_get_length (Mp_.get ())); else return convertTime (0); } QTime VlcPlayer::GetCurrentTime () const { if (libvlc_media_player_get_media (Mp_.get ())) return convertTime (libvlc_media_player_get_time (Mp_.get ())); else return convertTime (0); } void VlcPlayer::SetCurrentTime (libvlc_time_t time) { if (libvlc_media_player_is_playing (Mp_.get ())) libvlc_media_player_set_time (Mp_.get (), time); else { libvlc_media_player_play (Mp_.get ()); WaitForPlaying (); libvlc_media_player_set_time (Mp_.get (), time); libvlc_media_player_pause (Mp_.get ()); } } void VlcPlayer::Freeze () { emit unstable (); FreezePlayingMedia_ = libvlc_media_player_get_media (Mp_.get ()); if (FreezePlayingMedia_) { FreezeCur_ = libvlc_media_player_get_time (Mp_.get ()); FreezeAudio_ = GetCurrentAudioTrack (); FreezeSubtitle_ = GetCurrentSubtitle (); } FreezeIsPlaying_ = libvlc_media_player_is_playing (Mp_.get ()); FreezeDVD_ = DVD_ && libvlc_media_player_get_length (Mp_.get ()) > DVD_IS_MORE_THAN; libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::switchWidget (QWidget *widget) { Freeze (); libvlc_media_player_set_xwindow (Mp_.get (), widget->winId ()); UnFreeze (); } void VlcPlayer::UnFreeze () { libvlc_media_player_play (Mp_.get ()); WaitForPlaying (); if (FreezeDVD_) { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate); WaitForDVDPlaying (); } if (FreezePlayingMedia_ && (!DVD_ || FreezeDVD_)) { libvlc_media_player_set_time (Mp_.get (), FreezeCur_); setAudioTrack (FreezeAudio_); setSubtitle (FreezeSubtitle_); } if (!FreezeIsPlaying_) libvlc_media_player_pause (Mp_.get ()); ReloadSubtitles (); emit stable (); } void VlcPlayer::ReloadSubtitles () { for (int i = 0; i < Subtitles_.size (); i++) libvlc_video_set_subtitle_file (Mp_.get (), Subtitles_ [i].toUtf8 ()); } QWidget* VlcPlayer::GetParent () const { return Parent_; } std::shared_ptr<libvlc_media_player_t> VlcPlayer::GetPlayer () const { return Mp_; } int VlcPlayer::GetAudioTracksNumber () const { return libvlc_audio_get_track_count (Mp_.get ()); } int VlcPlayer::GetCurrentAudioTrack () const { return libvlc_audio_get_track (Mp_.get ()); } void VlcPlayer::setAudioTrack (int track) { libvlc_audio_set_track (Mp_.get (), track); } QString VlcPlayer::GetAudioTrackDescription (int track) const { libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track); return QString (t->psz_name); } int VlcPlayer::GetAudioTrackId(int track) const { libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track); return t->i_id; } int VlcPlayer::GetSubtitlesNumber () const { return libvlc_video_get_spu_count (Mp_.get ()); } void VlcPlayer::AddSubtitles (const QString& file) { libvlc_video_set_subtitle_file (Mp_.get (), file.toUtf8 ()); Subtitles_ << file; } int VlcPlayer::GetCurrentSubtitle () const { return libvlc_video_get_spu (Mp_.get ()); } QString VlcPlayer::GetSubtitleDescription (int track) const { libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track); return QString (t->psz_name); } int VlcPlayer::GetSubtitleId(int track) const { libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track); return t->i_id; } void VlcPlayer::setSubtitle (int track) { libvlc_video_set_spu (Mp_.get (), track); } libvlc_track_description_t* VlcPlayer::GetTrack(libvlc_track_description_t *t, int track) const { for (int i = 0; i < track; i++) t = t->p_next; return t; } void VlcPlayer::DVDNavigate (unsigned nav) { libvlc_media_player_navigate (Mp_.get (), nav); } void VlcPlayer::dvdNavigateDown () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_down); } void VlcPlayer::dvdNavigateUp () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_up); } void VlcPlayer::dvdNavigateRight () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_right); } void VlcPlayer::dvdNavigateLeft () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_left); } void VlcPlayer::dvdNavigateEnter () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate); } void VlcPlayer::WaitForPlaying () const { QTimeLine line; line.start (); while (!NowPlaying ()) { sleep (5); if (line.currentTime () > MAX_TIMEOUT) { qWarning () << Q_FUNC_INFO << "timeout"; break; } } } void VlcPlayer::WaitForDVDPlaying () const { QTimeLine line; line.start (); while (libvlc_media_player_get_length (Mp_.get ()) < DVD_IS_MORE_THAN) { sleep (5); if (line.currentTime () > MAX_TIMEOUT) { qWarning () << Q_FUNC_INFO << "timeout"; break; } } WaitForPlaying (); } libvlc_instance_t* VlcPlayer::GetInstance () const { return VlcInstance_.get (); } void VlcPlayer::plus3percent () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + libvlc_media_player_get_length (Mp_.get ()) * 0.03); } void VlcPlayer::minus3percent () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - libvlc_media_player_get_length (Mp_.get ()) * 0.03); } void VlcPlayer::plus10seconds () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + 10 * 1000); } void VlcPlayer::minus10seconds () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - 10 * 1000); } void VlcPlayer::setAspectRatio (const QByteArray& ratio) { libvlc_video_set_aspect_ratio (Mp_.get (), ratio); } void VlcPlayer::setRealZoom (const QByteArray& zoom) { libvlc_video_set_crop_geometry (Mp_.get (), zoom.constData ()); } QString VlcPlayer::GetAspectRatio () const { return libvlc_video_get_aspect_ratio (Mp_.get ()); } } }
26.014354
140
0.697995
MellonQ
ea1facd474872ae296f836d868e0b674e4ccedc0
787
hpp
C++
src/CacheClient.hpp
mostynb/tundra
4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1
[ "MIT" ]
null
null
null
src/CacheClient.hpp
mostynb/tundra
4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1
[ "MIT" ]
null
null
null
src/CacheClient.hpp
mostynb/tundra
4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1
[ "MIT" ]
null
null
null
#pragma once #include "Hash.hpp" namespace Frozen { struct DagNode; struct Dag; } struct StatCache; struct Mutex; struct ThreadState; namespace CacheResult { enum Enum { DidNotTry, Failure, CacheMiss, Success, }; } struct CacheClient { static CacheResult::Enum AttemptRead(const Frozen::Dag* dag, const Frozen::DagNode* dagNode, HashDigest signature, StatCache* stat_cache, Mutex* queue_lock, ThreadState* thread_state); static CacheResult::Enum AttemptWrite(const Frozen::Dag* dag, const Frozen::DagNode* dagNode, HashDigest signature, StatCache* stat_cache, Mutex* queue_lock, ThreadState* thread_state, const char* ingredients_file); }; void GetCachingBehaviourSettingsFromEnvironment(bool* attemptReads, bool* attemptWrites);
28.107143
219
0.7446
mostynb
ea221a48a43ed4ee332d6f60ac6fd941bf9321f2
5,515
cpp
C++
server.cpp
Stykk-Gruppen/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
null
null
null
server.cpp
Stykk-Gruppen/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
2
2020-06-03T10:03:48.000Z
2020-08-24T13:58:34.000Z
server.cpp
Feqzz/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
null
null
null
#include "server.h" #include <string> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <iostream> /** * Initializes the openssl library, creates SSL context, configures it * and creates a socket using the portnumber supplied * @param int port * @return Server object */ Server::Server(int port) { initOpenSSL(); ctx = createContext(); configureContect(ctx); sock = createSocket(port); } /** * Creates a Secure TCP socket server and starts listening. * It does not very if the certificate is valid only that is exists. * The function also creates a new thread for each incoming request. */ void Server::start() { /* Handle connections */ while(1) { struct sockaddr_in addr; uint len = sizeof(addr); SSL *ssl; int client = accept(sock, (struct sockaddr*)&addr, &len); if (client < 0) { perror("Unable to accept"); exit(EXIT_FAILURE); } pid=fork(); if(pid==0) { ssl = SSL_new(ctx); SSL_set_fd(ssl, client); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); } else { handleClient(ssl); /*const char reply[] = "1"; char readBuffer[10]; SSL_read(ssl,readBuffer,10); SSL_write(ssl, reply, strlen(reply));*/ signal(SIGCHLD,SIG_IGN); SSL_shutdown(ssl); SSL_free(ssl); exit(0); } } else { close(client); } } close(sock); SSL_CTX_free(ctx); cleanupSSL(); } /** * Read and parses the buffer from the socket connection and creates a Email object. * Depending on the email sending success, a 0 or 1 is returned back to the TCP connection. * @param ssl Secure Socket connection pointer */ void Server::handleClient(SSL* ssl) { //buffer size can be changed to whatever int bufferSize = 255; std::string reply = ""; char readBuffer[bufferSize]; SSL_read(ssl,readBuffer,bufferSize); std::vector<std::string> variables; variables = parseBuffer(readBuffer,bufferSize); Email email(variables); int emailSuccess = email.send(); //emailSuccess = -1 means the system call failed if(emailSuccess >= 0) { reply = "1"; } else { reply = "0"; } SSL_write(ssl,&reply[0],1); /*const char asd[] = "1"; int test = SSL_write(ssl, asd, strlen(asd)); std::cout << test << "\n";*/ } /** * Iterates through the buffer to build strings, if a '\n' char is found a variable is finished * and added to the return vector. * @param buffer * @param length * @return std::vector<std::string> parsed data from buffer */ std::vector<std::string> Server::parseBuffer(char* buffer,int length) { std::vector<std::string> stringVector; std::string tempString = ""; //0 is invite, 1 is forgotten password //int code = (int)buffer[0]-48; for(int i=0;i<length;i++) { char tempChar = buffer[i]; if(tempChar=='\n') { stringVector.push_back(tempString); tempString = ""; } else { tempString += tempChar; } } return stringVector; } /** * Creates a TCP socket with the port number 'port' * @param port * @return int socket */ int Server::createSocket(int port) { int s; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("Unable to create socket"); exit(EXIT_FAILURE); } if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("Unable to bind"); exit(EXIT_FAILURE); } if (listen(s, 1) < 0) { perror("Unable to listen"); exit(EXIT_FAILURE); } return s; } /** * @brief Server::initOpenSSL */ void Server::initOpenSSL() { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); } /** * @brief Server::cleanupSSL */ void Server::cleanupSSL() { EVP_cleanup(); } /** * @brief Server::createContext * @return SSL_CTX* */ SSL_CTX* Server::createContext() { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (!ctx) { perror("Unable to create SSL context"); ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } return ctx; } /** * @brief Server::configureContect * @param SSL_CTX* */ void Server::configureContect(SSL_CTX *ctx) { SSL_CTX_set_ecdh_auto(ctx, 1); /* Set the key and cert */ if (SSL_CTX_use_certificate_file(ctx, "cert.pem", SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } }
22.789256
96
0.553218
Stykk-Gruppen
ea2948783dfe546548f7937329adac5262413e9c
550
cpp
C++
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/SPLASH
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
12
2019-09-11T15:52:31.000Z
2021-11-14T20:33:35.000Z
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
2
2020-10-26T02:35:18.000Z
2020-10-26T02:36:01.000Z
#include "pch.h" #include "RagdollComponent.h" RagdollComponent::RagdollComponent() { localCenterOfMass = {0.f, 0.f, 0.f}; wireframeModel = nullptr; } RagdollComponent::RagdollComponent(Model* wireframe) { localCenterOfMass = { 0.f, 0.f, 0.f }; wireframeModel = wireframe; } RagdollComponent::~RagdollComponent() { } void RagdollComponent::addContactPoint(glm::vec3 localOffset, glm::vec3 halfSize) { contactPoints.emplace_back(); contactPoints.back().boundingBox.setHalfSize(halfSize); contactPoints.back().localOffSet = localOffset; }
22.916667
83
0.752727
BTH-StoraSpel-DXR
ea2a6ec0c8c1518fd2627ff467f0bcd2f715cfd0
572
cc
C++
zircon/kernel/phys/panic.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
zircon/kernel/phys/panic.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
zircon/kernel/phys/panic.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <zircon/assert.h> #include "main.h" // This is what ZX_ASSERT calls. // TODO(mcgrathr): print message, backtrace PHYS_SINGLETHREAD void __zx_panic(const char* format, ...) { __builtin_trap(); } // The compiler generates calls to this for -fstack-protector. extern "C" [[noreturn]] PHYS_SINGLETHREAD void __stack_chk_fail() { __zx_panic("stack canary corrupted!\n"); }
30.105263
80
0.736014
casey
ea2ca5a2a95fc6632a25d457d167b0d36980f8f3
5,820
cpp
C++
bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
null
null
null
bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
null
null
null
bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp
MosHumanoid/bitbots_thmos_meta
f45ccc362dc689b69027be5b0d000d2a08580de4
[ "MIT" ]
null
null
null
#include <bitbots_local_planner/bitbots_local_planner.h> #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(bitbots_local_planner::BBPlanner, nav_core::BaseLocalPlanner) namespace bitbots_local_planner { BBPlanner::BBPlanner() { } void BBPlanner::initialize(std::string name, tf2_ros::Buffer *tf_buffer, costmap_2d::Costmap2DROS *costmap_ros) { ros::NodeHandle private_nh("~/" + name); local_plan_publisher_ = private_nh.advertise<nav_msgs::Path>("local_plan", 1); tf_buffer_ = tf_buffer; goal_reached_ = false; costmap_ros_ = costmap_ros; //Parameter for dynamic reconfigure dsrv_ = new dynamic_reconfigure::Server<BBPlannerConfig>(private_nh); dynamic_reconfigure::Server<BBPlannerConfig>::CallbackType cb = boost::bind(&BBPlanner::reconfigureCB, this, _1, _2); dsrv_->setCallback(cb); ROS_DEBUG("BBPlanner: Version 2 Init."); } void BBPlanner::reconfigureCB(BBPlannerConfig &config, uint32_t level) { config_ = config; } bool BBPlanner::setPlan(const std::vector<geometry_msgs::PoseStamped> &plan) { global_plan_ = plan; int carrot_distance = 10; if (global_plan_.size() > 10) { carrot_distance = 10; } else { carrot_distance = global_plan_.size() - 1; } // Querys the pose of our carrot which we want to follow bitbots_local_planner::getXPose( *tf_buffer_, global_plan_, costmap_ros_->getGlobalFrameID(), goal_pose_, carrot_distance); // Query the final pose of our robot at the end of the global plan bitbots_local_planner::getXPose( *tf_buffer_, global_plan_, costmap_ros_->getGlobalFrameID(), end_pose_, global_plan_.size() - 1); old_goal_pose_ = goal_pose_; goal_reached_ = false; return true; } bool BBPlanner::computeVelocityCommands(geometry_msgs::Twist &cmd_vel) { ros::Time begin = ros::Time::now(); tf2::Stamped<tf2::Transform> current_pose; geometry_msgs::PoseStamped msg; costmap_ros_->getRobotPose(msg); current_pose.setData( tf2::Transform( tf2::Quaternion( msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z, msg.pose.orientation.w), tf2::Vector3( msg.pose.position.x, msg.pose.position.y, msg.pose.position.z))); double walk_angle = std::fmod( std::atan2( goal_pose_.getOrigin().y() - current_pose.getOrigin().y(), goal_pose_.getOrigin().x() - current_pose.getOrigin().x()), 2 * M_PI); double final_walk_angle = std::fmod( std::atan2( end_pose_.getOrigin().y() - current_pose.getOrigin().y(), end_pose_.getOrigin().x() - current_pose.getOrigin().x()), 2 * M_PI); double distance = sqrt( pow(end_pose_.getOrigin().y() - current_pose.getOrigin().y(), 2) + pow(end_pose_.getOrigin().x() - current_pose.getOrigin().x(), 2)); double walk_vel = std::min(distance * config_.translation_slow_down_factor, config_.max_vel_x); double diff = 0; if (distance > config_.orient_to_goal_distance) { diff = final_walk_angle - tf2::getYaw(current_pose.getRotation()); } else { diff = tf2::getYaw(end_pose_.getRotation()) - tf2::getYaw(current_pose.getRotation()); } double min_angle = (std::fmod(diff + M_PI, 2 * M_PI) - M_PI); double vel = std::max(std::min( config_.rotation_slow_down_factor * min_angle, config_.max_rotation_vel), -config_.max_rotation_vel); if (distance < config_.position_accuracy && abs(min_angle) < config_.rotation_accuracy) { cmd_vel.linear.x = 0; cmd_vel.linear.y = 0; cmd_vel.angular.z = 0; goal_reached_ = true; } else { cmd_vel.linear.x = std::cos(walk_angle - tf2::getYaw(current_pose.getRotation())) * walk_vel; cmd_vel.linear.y = std::sin(walk_angle - tf2::getYaw(current_pose.getRotation())) * walk_vel; cmd_vel.angular.z = vel; goal_reached_ = false; } publishPlan(0); ros::Time end = ros::Time::now(); ros::Duration duration = end - begin; ROS_DEBUG("BBPlanner: Calculation time: %f seconds", duration.toSec()); return true; } bool BBPlanner::isGoalReached() { if (goal_reached_) { ROS_DEBUG("BBPlanner: Goal reached."); } return goal_reached_; } void BBPlanner::publishPlan(int max_point) { std::vector<geometry_msgs::PoseStamped> path; path = transformed_global_plan_; //given an empty path we won't do anything if (path.empty()) return; //create a path message nav_msgs::Path gui_path; gui_path.poses.resize(path.size()); gui_path.header.frame_id = path[0].header.frame_id; gui_path.header.stamp = path[0].header.stamp; // Extract the plan in world co-ordinates, we assume the path is all in the same frame for (unsigned int i = 0; i < path.size(); i++) { gui_path.poses[i] = path[i]; } local_plan_publisher_.publish(gui_path); } BBPlanner::~BBPlanner() { } }
31.290323
125
0.576632
MosHumanoid
ea2f9e99d5b76a029fb58104b9313e546e674578
576
hpp
C++
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2017-10-11T13:48:30.000Z
2020-06-04T05:30:13.000Z
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
null
null
null
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2018-10-05T15:37:29.000Z
2021-12-20T15:25:48.000Z
#ifndef PX_CG_OBJECT_GEOMETRY_HPP #define PX_CG_OBJECT_GEOMETRY_HPP #include "object/geometry/base_geometry.hpp" #include "object/geometry/box.hpp" #include "object/geometry/cone.hpp" #include "object/geometry/cylinder.hpp" #include "object/geometry/disk.hpp" #include "object/geometry/ellipsoid.hpp" #include "object/geometry/normal_triangle.hpp" #include "object/geometry/plane.hpp" #include "object/geometry/quadric.hpp" #include "object/geometry/ring.hpp" #include "object/geometry/sphere.hpp" #include "object/geometry/triangle.hpp" #endif // PX_CG_OBJECT_GEOMETRY_HPP
32
46
0.809028
xupei0610
ea317fbca3e28c10b4b0e577e351cf6a6bbd06c9
6,197
cpp
C++
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
#include "Utility.hpp" #define TINYOBJLOADER_IMPLEMENTATION #include <tiny_obj_loader.h> #include <SFML/Graphics.hpp> #include <iostream> #include <string> #include <fstream> #include <streambuf> #define ASSERT(expr) assert(expr) std::string Utility::LoadTextFile(const std::string& filepath) { std::ifstream t(filepath); return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); } bool LoadObj(const std::string& directory, const std::string& filename, tinyobj::attrib_t& attrib, std::vector<tinyobj::shape_t>& shapes, std::vector<tinyobj::material_t>& materials) { std::string warn; std::string err; std::string& filepath = directory.size() > 0 ? directory + "/" + filename : filename; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filepath.c_str(), directory.c_str()); if (!warn.empty()) std::cout << warn << std::endl; if (!err.empty()) std::cerr << err << std::endl; return ret; } void ParseVertex(VertexPNCT& vertex, const tinyobj::index_t& idx, const tinyobj::attrib_t& attrib) { // access to vertex vertex.position.x = attrib.vertices[(3 * idx.vertex_index) + 0]; vertex.position.y = attrib.vertices[(3 * idx.vertex_index) + 1]; vertex.position.z = attrib.vertices[(3 * idx.vertex_index) + 2]; vertex.normal.x = attrib.normals[(3 * idx.normal_index) + 0]; vertex.normal.y = attrib.normals[(3 * idx.normal_index) + 1]; vertex.normal.z = attrib.normals[(3 * idx.normal_index) + 2]; vertex.texcoord.x = attrib.texcoords[(2 * idx.texcoord_index) + 0]; vertex.texcoord.y = attrib.texcoords[(2 * idx.texcoord_index) + 1]; vertex.color.r = attrib.colors[3 * idx.vertex_index + 0]; vertex.color.g = attrib.colors[3 * idx.vertex_index + 1]; vertex.color.b = attrib.colors[3 * idx.vertex_index + 2]; vertex.color.a = 1.0f; } Model Utility::LoadModel(const std::string& directory, const std::string& filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!LoadObj(directory, filename, attrib, shapes, materials)) throw; Model model; if (materials.size() > 0) { Material& material = model.material; material.diffuse = glm::vec3(materials[0].diffuse[0], materials[0].diffuse[1], materials[0].diffuse[2]); sf::Image image; if (image.loadFromFile((directory + "/" + materials[0].diffuse_texname).c_str())) { sf::Vector2u imageSize = image.getSize(); material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true); Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR); } material.attributeFormat = VertexPNCT::format; } std::vector<VertexPNCT> meshData; // Loop over shapes for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { int fv = shapes[s].mesh.num_face_vertices[f]; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { VertexPNCT vertex; tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; ParseVertex(vertex, idx, attrib); meshData.emplace_back(vertex); } index_offset += fv; } } Mesh& mesh = model.mesh; mesh.vBuffer = Graphics::CreateBuffer(1, meshData.size() * (sizeof(VertexPNCT) / sizeof(float)), &meshData[0], false, false); mesh.count = meshData.size(); return model; } std::vector<Model> Utility::LoadScene(const std::string& directory, const std::string& filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!LoadObj(directory, filename, attrib, shapes, materials)) throw; std::vector<Model> models(materials.size()); for (size_t i = 0; i < materials.size(); i++) { Material& material = models[i].material; material.diffuse = glm::vec3(materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]); sf::Image image; if (image.loadFromFile((directory + "/" + materials[i].diffuse_texname).c_str())) { sf::Vector2u imageSize = image.getSize(); material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true); Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR); } material.attributeFormat = VertexPNCT::format; } std::vector<std::vector<VertexPNCT>> meshData(materials.size()); // Loop over shapes for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { // per-face material int matId = shapes[s].mesh.material_ids[f]; std::vector<VertexPNCT>& data = meshData[matId]; int fv = shapes[s].mesh.num_face_vertices[f]; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { VertexPNCT vertex; tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; ParseVertex(vertex, idx, attrib); data.emplace_back(vertex); } index_offset += fv; } } for (size_t i = 0; i < materials.size(); i++) { std::vector<VertexPNCT>& data = meshData[i]; Mesh& mesh = models[i].mesh; mesh.vBuffer = Graphics::CreateBuffer(1, data.size() * (sizeof(VertexPNCT) / sizeof(float)), &data[0], false, false); mesh.count = data.size(); } return models; }
35.210227
182
0.616589
Belfer
ea31ecc3290c6e3646cb56c0b0742d4a0f278456
83
hpp
C++
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
15
2017-09-12T14:54:16.000Z
2021-09-21T23:28:57.000Z
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
67
2017-10-31T02:04:44.000Z
2022-03-28T01:02:25.000Z
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
48
2017-09-28T23:47:17.000Z
2022-01-08T18:30:40.000Z
#ifndef RSSI_HPP #define RSSI_HPP bool CommsFailed(); void RSSI_Check(); #endif
9.222222
19
0.746988
YashrajN
ea32bfeb3470f003807075e55be23f2238848833
2,542
cpp
C++
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright © 2018 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <unity/server/unity_server_control.hpp> #include <unity/server/unity_server_options.hpp> #include <unity/server/unity_server.hpp> #include <capi/impl/capi_initialization.hpp> #include <capi/impl/capi_initialization_internal.hpp> #include <capi/impl/capi_error_handling.hpp> // All the functions related to the initialization of the server. namespace turi { // Create and return the server options. static unity_server_options& _get_server_options() { static std::unique_ptr<turi::unity_server_options> _server_options; if (_server_options == nullptr) { _server_options.reset(new unity_server_options); _server_options->log_file = "/var/log/"; _server_options->root_path = ""; _server_options->daemon = false; _server_options->log_rotation_interval = 0; _server_options->log_rotation_truncate = 0; } return *_server_options; } /////////////////////////////////////////////////////////////////////////////// // // The server is initialized on demand. bool capi_server_initialized = false; static std::mutex _capi_server_initializer_lock; EXPORT void _tc_initialize() { std::lock_guard<std::mutex> lg(_capi_server_initializer_lock); if (capi_server_initialized) { return; } turi::start_server(_get_server_options(), *capi_server_initializer()); capi_server_initialized = true; // Set up the progress logger to log progress to stdout. global_logger().add_observer(LOG_PROGRESS, [](int, const char* buf, size_t len) { for (; len != 0; --len) { std::cout << *buf; ++buf; } std::cout << std::flush; }); } } // namespace turi // The user facing components of the server initialization extern "C" { EXPORT void tc_setup_log_location(const char* log_file, tc_error** error) { ERROR_HANDLE_START(); std::lock_guard<std::mutex> lg(turi::_capi_server_initializer_lock); if (turi::capi_server_initialized) { set_error(error, "CAPI server is already initialized; call setup functions before all other functions."); return; } turi::_get_server_options().log_file = log_file; ERROR_HANDLE_END(error); } }
29.905882
109
0.651849
meiwanlanjun
ea3498abc15747fdba49966c1e4ee69294837816
22,249
cpp
C++
Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Serialization/PropertyLocalizationDataGathering.h" #include "UObject/Script.h" #include "UObject/ObjectMacros.h" #include "UObject/UObjectHash.h" #include "UObject/Class.h" #include "UObject/Package.h" #include "UObject/UnrealType.h" #include "UObject/TextProperty.h" #include "UObject/PropertyPortFlags.h" #include "HAL/UnrealMemory.h" #include "Internationalization/TextNamespaceUtil.h" #include "Internationalization/TextPackageNamespaceUtil.h" FPropertyLocalizationDataGatherer::FPropertyLocalizationDataGatherer(TArray<FGatherableTextData>& InOutGatherableTextDataArray, const UPackage* const InPackage, EPropertyLocalizationGathererResultFlags& OutResultFlags) : GatherableTextDataArray(InOutGatherableTextDataArray) , Package(InPackage) , ResultFlags(OutResultFlags) , AllObjectsInPackage() { // Build up the list of objects that are within our package - we won't follow object references to things outside of our package { TArray<UObject*> AllObjectsInPackageArray; GetObjectsWithOuter(Package, AllObjectsInPackageArray, true, RF_Transient, EInternalObjectFlags::PendingKill); AllObjectsInPackage.Reserve(AllObjectsInPackageArray.Num()); for (UObject* Object : AllObjectsInPackageArray) { AllObjectsInPackage.Add(Object); } } TArray<UObject*> RootObjectsInPackage; GetObjectsWithOuter(Package, RootObjectsInPackage, false, RF_Transient, EInternalObjectFlags::PendingKill); // Iterate over each root object in the package for (const UObject* Object : RootObjectsInPackage) { GatherLocalizationDataFromObjectWithCallbacks(Object, EPropertyLocalizationGathererTextFlags::None); } } bool FPropertyLocalizationDataGatherer::ShouldProcessObject(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) const { if (Object->HasAnyFlags(RF_Transient)) { // Transient objects aren't saved, so skip them as part of the gather return false; } // Skip objects that we've already processed to avoid repeated work and cyclic chains const bool bAlreadyProcessed = ProcessedObjects.Contains(FObjectAndGatherFlags(Object, GatherTextFlags)); return !bAlreadyProcessed; } void FPropertyLocalizationDataGatherer::MarkObjectProcessed(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { ProcessedObjects.Add(FObjectAndGatherFlags(Object, GatherTextFlags)); } void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObjectWithCallbacks(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { // See if we have a custom handler for this type FLocalizationDataGatheringCallback* CustomCallback = nullptr; for (const UClass* Class = Object->GetClass(); Class != nullptr; Class = Class->GetSuperClass()) { CustomCallback = GetTypeSpecificLocalizationDataGatheringCallbacks().Find(Class); if (CustomCallback) { break; } } if (CustomCallback) { checkf(IsObjectValidForGather(Object), TEXT("Cannot gather for objects outside of the current package! Package: '%s'. Object: '%s'."), *Package->GetFullName(), *Object->GetFullName()); if (ShouldProcessObject(Object, GatherTextFlags)) { MarkObjectProcessed(Object, GatherTextFlags); (*CustomCallback)(Object, *this, GatherTextFlags); } } else if (ShouldProcessObject(Object, GatherTextFlags)) { MarkObjectProcessed(Object, GatherTextFlags); GatherLocalizationDataFromObject(Object, GatherTextFlags); } } void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObject(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { checkf(IsObjectValidForGather(Object), TEXT("Cannot gather for objects outside of the current package! Package: '%s'. Object: '%s'."), *Package->GetFullName(), *Object->GetFullName()); const FString Path = Object->GetPathName(); // Gather text from our fields. GatherLocalizationDataFromObjectFields(Path, Object, GatherTextFlags); // Also gather from the script data on UStruct types. { if (!!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceHasScript)) { ResultFlags |= EPropertyLocalizationGathererResultFlags::HasScript; } const UStruct* Struct = Cast<UStruct>(Object); if (Struct) { GatherScriptBytecode(Path, Struct->Script, !!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceEditorOnlyScriptData)); } } // Gather from anything that has us as their outer, as not all objects are reachable via a property pointer. if (!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::SkipSubObjects)) { TArray<UObject*> ChildObjects; GetObjectsWithOuter(Object, ChildObjects, false, RF_Transient, EInternalObjectFlags::PendingKill); for (const UObject* ChildObject : ChildObjects) { GatherLocalizationDataFromObjectWithCallbacks(ChildObject, GatherTextFlags); } } } void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObjectFields(const FString& PathToParent, const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { const UObject* ArchetypeObject = Object->GetArchetype(); for (TFieldIterator<const UField> FieldIt(Object->GetClass(), EFieldIteratorFlags::IncludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::IncludeInterfaces); FieldIt; ++FieldIt) { // Gather text from the property data { const UProperty* PropertyField = Cast<UProperty>(*FieldIt); if (PropertyField) { const void* ValueAddress = PropertyField->ContainerPtrToValuePtr<void>(Object); const void* DefaultValueAddress = nullptr; if (ArchetypeObject) { const UProperty* ArchetypePropertyField = FindField<UProperty>(ArchetypeObject->GetClass(), *PropertyField->GetName()); if (ArchetypePropertyField && ArchetypePropertyField->IsA(PropertyField->GetClass())) { DefaultValueAddress = ArchetypePropertyField->ContainerPtrToValuePtr<void>(ArchetypeObject); } } GatherLocalizationDataFromChildTextProperties(PathToParent, PropertyField, ValueAddress, DefaultValueAddress, GatherTextFlags | (PropertyField->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None)); } } // Gather text from the script bytecode { const UStruct* StructField = Cast<UStruct>(*FieldIt); if (StructField && IsObjectValidForGather(StructField) && ShouldProcessObject(StructField, GatherTextFlags)) { MarkObjectProcessed(StructField, GatherTextFlags); GatherLocalizationDataFromObject(StructField, GatherTextFlags); } } } } void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromStructFields(const FString& PathToParent, const UStruct* Struct, const void* StructData, const void* DefaultStructData, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { const UStruct* ArchetypeStruct = Cast<UStruct>(Struct->GetArchetype()); for (TFieldIterator<const UField> FieldIt(Struct, EFieldIteratorFlags::IncludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::IncludeInterfaces); FieldIt; ++FieldIt) { // Gather text from the property data { const UProperty* PropertyField = Cast<UProperty>(*FieldIt); if (PropertyField) { const void* ValueAddress = PropertyField->ContainerPtrToValuePtr<void>(StructData); const void* DefaultValueAddress = nullptr; if (ArchetypeStruct && DefaultStructData) { const UProperty* ArchetypePropertyField = FindField<UProperty>(ArchetypeStruct, *PropertyField->GetName()); if (ArchetypePropertyField && ArchetypePropertyField->IsA(PropertyField->GetClass())) { DefaultValueAddress = ArchetypePropertyField->ContainerPtrToValuePtr<void>(DefaultStructData); } } GatherLocalizationDataFromChildTextProperties(PathToParent, PropertyField, ValueAddress, DefaultValueAddress, GatherTextFlags | (PropertyField->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None)); } } // Gather text from the script bytecode { const UStruct* StructField = Cast<UStruct>(*FieldIt); if (StructField && IsObjectValidForGather(StructField) && ShouldProcessObject(StructField, GatherTextFlags)) { MarkObjectProcessed(StructField, GatherTextFlags); GatherLocalizationDataFromObject(StructField, GatherTextFlags); } } } } void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromChildTextProperties(const FString& PathToParent, const UProperty* const Property, const void* const ValueAddress, const void* const DefaultValueAddress, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { if (Property->HasAnyPropertyFlags(CPF_Transient)) { // Transient properties aren't saved, so skip them as part of the gather return; } const UTextProperty* const TextProperty = Cast<const UTextProperty>(Property); const UArrayProperty* const ArrayProperty = Cast<const UArrayProperty>(Property); const UMapProperty* const MapProperty = Cast<const UMapProperty>(Property); const USetProperty* const SetProperty = Cast<const USetProperty>(Property); const UStructProperty* const StructProperty = Cast<const UStructProperty>(Property); const UObjectPropertyBase* const ObjectProperty = Cast<const UObjectPropertyBase>(Property); const EPropertyLocalizationGathererTextFlags ChildPropertyGatherTextFlags = GatherTextFlags | (Property->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None); // Handles both native, fixed-size arrays and plain old non-array properties. const bool IsFixedSizeArray = Property->ArrayDim > 1; for(int32 i = 0; i < Property->ArrayDim; ++i) { const FString PathToElement = FString(PathToParent.IsEmpty() ? TEXT("") : PathToParent + TEXT(".")) + (IsFixedSizeArray ? Property->GetName() + FString::Printf(TEXT("[%d]"), i) : Property->GetName()); const void* const ElementValueAddress = reinterpret_cast<const uint8*>(ValueAddress) + Property->ElementSize * i; const void* const DefaultElementValueAddress = DefaultValueAddress ? (reinterpret_cast<const uint8*>(DefaultValueAddress) + Property->ElementSize * i) : nullptr; const bool bIsDefaultValue = DefaultElementValueAddress && Property->Identical(ElementValueAddress, DefaultElementValueAddress, PPF_None); if (bIsDefaultValue) { // Skip any properties that have the default value, as those will be gathered from the default instance continue; } // Property is a text property. if (TextProperty) { const FText* const TextElementValueAddress = static_cast<const FText*>(ElementValueAddress); UPackage* const PropertyPackage = TextProperty->GetOutermost(); if (FTextInspector::GetFlags(*TextElementValueAddress) & ETextFlag::ConvertedProperty) { PropertyPackage->MarkPackageDirty(); } GatherTextInstance(*TextElementValueAddress, PathToElement, !!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceEditorOnlyProperties) || TextProperty->HasAnyPropertyFlags(CPF_EditorOnly)); } // Property is a DYNAMIC array property. else if (ArrayProperty) { // Iterate over all elements of the array. FScriptArrayHelper ScriptArrayHelper(ArrayProperty, ElementValueAddress); const int32 ElementCount = ScriptArrayHelper.Num(); for(int32 j = 0; j < ElementCount; ++j) { GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d)"), j), ArrayProperty->Inner, ScriptArrayHelper.GetRawPtr(j), nullptr, ChildPropertyGatherTextFlags); } } // Property is a map property. else if (MapProperty) { // Iterate over all elements of the map. FScriptMapHelper ScriptMapHelper(MapProperty, ElementValueAddress); const int32 ElementCount = ScriptMapHelper.Num(); for(int32 j = 0, ElementIndex = 0; ElementIndex < ElementCount; ++j) { if (!ScriptMapHelper.IsValidIndex(j)) { continue; } const uint8* MapPairPtr = ScriptMapHelper.GetPairPtr(j); GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d - Key)"), ElementIndex), MapProperty->KeyProp, MapPairPtr + MapProperty->MapLayout.KeyOffset, nullptr, ChildPropertyGatherTextFlags); GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d - Value)"), ElementIndex), MapProperty->ValueProp, MapPairPtr + MapProperty->MapLayout.ValueOffset, nullptr, ChildPropertyGatherTextFlags); ++ElementIndex; } } // Property is a set property. else if (SetProperty) { // Iterate over all elements of the Set. FScriptSetHelper ScriptSetHelper(SetProperty, ElementValueAddress); const int32 ElementCount = ScriptSetHelper.Num(); for(int32 j = 0, ElementIndex = 0; ElementIndex < ElementCount; ++j) { if (!ScriptSetHelper.IsValidIndex(j)) { continue; } const uint8* ElementPtr = ScriptSetHelper.GetElementPtr(j); GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d)"), ElementIndex), SetProperty->ElementProp, ElementPtr + SetProperty->SetLayout.ElementOffset, nullptr, ChildPropertyGatherTextFlags); ++ElementIndex; } } // Property is a struct property. else if (StructProperty) { GatherLocalizationDataFromStructFields(PathToElement, StructProperty->Struct, ElementValueAddress, DefaultElementValueAddress, ChildPropertyGatherTextFlags); } // Property is an object property. else if (ObjectProperty && !(GatherTextFlags & EPropertyLocalizationGathererTextFlags::SkipSubObjects)) { const UObject* InnerObject = ObjectProperty->GetObjectPropertyValue(ElementValueAddress); if (InnerObject && IsObjectValidForGather(InnerObject)) { GatherLocalizationDataFromObjectWithCallbacks(InnerObject, ChildPropertyGatherTextFlags); } } } } void FPropertyLocalizationDataGatherer::GatherTextInstance(const FText& Text, const FString& Description, const bool bIsEditorOnly) { auto AddGatheredText = [this, &Description](const FString& InNamespace, const FString& InKey, const FTextSourceData& InSourceData, const bool InIsEditorOnly) { FGatherableTextData* GatherableTextData = GatherableTextDataArray.FindByPredicate([&](const FGatherableTextData& Candidate) { return Candidate.NamespaceName.Equals(InNamespace, ESearchCase::CaseSensitive) && Candidate.SourceData.SourceString.Equals(InSourceData.SourceString, ESearchCase::CaseSensitive) && Candidate.SourceData.SourceStringMetaData == InSourceData.SourceStringMetaData; }); if (!GatherableTextData) { GatherableTextData = &GatherableTextDataArray[GatherableTextDataArray.AddDefaulted()]; GatherableTextData->NamespaceName = InNamespace; GatherableTextData->SourceData = InSourceData; } // We might attempt to add the same text multiple times if we process the same object with slightly different flags - only add this source site once though. { static const FLocMetadataObject DefaultMetadataObject; const bool bFoundSourceSiteContext = GatherableTextData->SourceSiteContexts.ContainsByPredicate([&](const FTextSourceSiteContext& InSourceSiteContext) -> bool { return InSourceSiteContext.KeyName.Equals(InKey, ESearchCase::CaseSensitive) && InSourceSiteContext.SiteDescription.Equals(Description, ESearchCase::CaseSensitive) && InSourceSiteContext.IsEditorOnly == InIsEditorOnly && InSourceSiteContext.IsOptional == false && InSourceSiteContext.InfoMetaData == DefaultMetadataObject && InSourceSiteContext.KeyMetaData == DefaultMetadataObject; }); if (!bFoundSourceSiteContext) { FTextSourceSiteContext& SourceSiteContext = GatherableTextData->SourceSiteContexts[GatherableTextData->SourceSiteContexts.AddDefaulted()]; SourceSiteContext.KeyName = InKey; SourceSiteContext.SiteDescription = Description; SourceSiteContext.IsEditorOnly = InIsEditorOnly; SourceSiteContext.IsOptional = false; } } }; FString Namespace; FString Key; const FTextDisplayStringRef DisplayString = FTextInspector::GetSharedDisplayString(Text); const bool bFoundNamespaceAndKey = FTextLocalizationManager::Get().FindNamespaceAndKeyFromDisplayString(DisplayString, Namespace, Key); if (!bFoundNamespaceAndKey || !Text.ShouldGatherForLocalization()) { return; } ResultFlags |= EPropertyLocalizationGathererResultFlags::HasText; FTextSourceData SourceData; { const FString* SourceString = FTextInspector::GetSourceString(Text); SourceData.SourceString = SourceString ? *SourceString : FString(); } #if USE_STABLE_LOCALIZATION_KEYS // Make sure the namespace is what we expect for this package // This would usually be done when the text is loaded, but we also gather text when saving packages so we need to make sure things are consistent { const FString PackageNamespace = TextNamespaceUtil::GetPackageNamespace(Package); if (!PackageNamespace.IsEmpty()) { Namespace = TextNamespaceUtil::BuildFullNamespace(Namespace, PackageNamespace); } } #endif // USE_STABLE_LOCALIZATION_KEYS // Always include the text without its package localization ID const FString CleanNamespace = TextNamespaceUtil::StripPackageNamespace(Namespace); AddGatheredText(CleanNamespace, Key, SourceData, bIsEditorOnly); } struct FGatherTextFromScriptBytecode { public: FGatherTextFromScriptBytecode(const TCHAR* InSourceDescription, const TArray<uint8>& InScript, FPropertyLocalizationDataGatherer& InPropertyLocalizationDataGatherer, const bool InTreatAsEditorOnlyData) : SourceDescription(InSourceDescription) , Script(const_cast<TArray<uint8>&>(InScript)) // We won't change the script, but we have to lie so that the code in ScriptSerialization.h will compile :( , PropertyLocalizationDataGatherer(InPropertyLocalizationDataGatherer) , bTreatAsEditorOnlyData(InTreatAsEditorOnlyData) , bIsParsingText(false) { const int32 ScriptSizeBytes = Script.Num(); int32 iCode = 0; while (iCode < ScriptSizeBytes) { SerializeExpr(iCode, DummyArchive); } } private: FLinker* GetLinker() { return nullptr; } EExprToken SerializeExpr(int32& iCode, FArchive& Ar) { #define XFERSTRING() SerializeString(iCode, Ar) #define XFERUNICODESTRING() SerializeUnicodeString(iCode, Ar) #define XFERTEXT() SerializeText(iCode, Ar) #define SERIALIZEEXPR_INC #define SERIALIZEEXPR_AUTO_UNDEF_XFER_MACROS #include "ScriptSerialization.h" return Expr; #undef SERIALIZEEXPR_INC #undef SERIALIZEEXPR_AUTO_UNDEF_XFER_MACROS } void SerializeString(int32& iCode, FArchive& Ar) { if (bIsParsingText) { LastParsedString.Reset(); do { LastParsedString += (char)(Script[iCode]); iCode += sizeof(uint8); } while (Script[iCode-1]); } else { do { iCode += sizeof(uint8); } while (Script[iCode-1]); } } void SerializeUnicodeString(int32& iCode, FArchive& Ar) { if (bIsParsingText) { LastParsedString.Reset(); do { uint16 UnicodeChar = 0; #ifdef REQUIRES_ALIGNED_INT_ACCESS FMemory::Memcpy(&UnicodeChar, &Script[iCode], sizeof(uint16)); #else UnicodeChar = *((uint16*)(&Script[iCode])); #endif LastParsedString += (TCHAR)UnicodeChar; iCode += sizeof(uint16); } while (Script[iCode-1] || Script[iCode-2]); } else { do { iCode += sizeof(uint16); } while (Script[iCode-1] || Script[iCode-2]); } } void SerializeText(int32& iCode, FArchive& Ar) { // What kind of text are we dealing with? const EBlueprintTextLiteralType TextLiteralType = (EBlueprintTextLiteralType)Script[iCode++]; switch (TextLiteralType) { case EBlueprintTextLiteralType::Empty: // Don't need to gather empty text break; case EBlueprintTextLiteralType::LocalizedText: { bIsParsingText = true; SerializeExpr(iCode, Ar); const FString SourceString = MoveTemp(LastParsedString); SerializeExpr(iCode, Ar); const FString TextKey = MoveTemp(LastParsedString); SerializeExpr(iCode, Ar); const FString TextNamespace = MoveTemp(LastParsedString); bIsParsingText = false; const FText TextInstance = FInternationalization::ForUseOnlyByLocMacroAndGraphNodeTextLiterals_CreateText(*SourceString, *TextNamespace, *TextKey); PropertyLocalizationDataGatherer.GatherTextInstance(TextInstance, FString::Printf(TEXT("%s [Script Bytecode]"), SourceDescription), bTreatAsEditorOnlyData); } break; case EBlueprintTextLiteralType::InvariantText: // Don't need to gather invariant text, but we do need to walk over the string in the buffer SerializeExpr(iCode, Ar); break; case EBlueprintTextLiteralType::LiteralString: // Don't need to gather literal strings, but we do need to walk over the string in the buffer SerializeExpr(iCode, Ar); break; case EBlueprintTextLiteralType::StringTableEntry: // Don't need to gather string table entries, but we do need to walk over the strings in the buffer iCode += sizeof(ScriptPointerType); // String Table asset (if any) SerializeExpr(iCode, Ar); SerializeExpr(iCode, Ar); break; default: checkf(false, TEXT("Unknown EBlueprintTextLiteralType! Please update FGatherTextFromScriptBytecode::SerializeText to handle this type of text.")); break; } } const TCHAR* SourceDescription; TArray<uint8>& Script; FPropertyLocalizationDataGatherer& PropertyLocalizationDataGatherer; bool bTreatAsEditorOnlyData; FArchive DummyArchive; bool bIsParsingText; FString LastParsedString; }; void FPropertyLocalizationDataGatherer::GatherScriptBytecode(const FString& PathToScript, const TArray<uint8>& ScriptData, const bool bIsEditorOnly) { if (ScriptData.Num() > 0) { ResultFlags |= EPropertyLocalizationGathererResultFlags::HasScript; } FGatherTextFromScriptBytecode(*PathToScript, ScriptData, *this, bIsEditorOnly); } FPropertyLocalizationDataGatherer::FLocalizationDataGatheringCallbackMap& FPropertyLocalizationDataGatherer::GetTypeSpecificLocalizationDataGatheringCallbacks() { static FLocalizationDataGatheringCallbackMap TypeSpecificLocalizationDataGatheringCallbacks; return TypeSpecificLocalizationDataGatheringCallbacks; }
39.378761
291
0.779046
windystrife
ea3b9a0fde1686640ccbd54de121d3eef0fca70c
23,497
cpp
C++
pepnovo/src/main.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/main.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/main.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
#include "AdvancedScoreModel.h" #include "FileManagement.h" #include "Fragmentation.h" #include "DeNovoDp.h" #include "QuickClustering.h" #include "EdgeModel.h" #include "FragmentSelection.h" #include "MSBlast.h" #include "PMCSQS.h" #include "PeakRankStats.h" #include "PeptideRankScorer.h" #include "DeNovoSolutions.h" #include "auxfun.h" #include "includes.h" int main() { Config *config=NULL; FileManager fm; FileSet fs; AdvancedScoreModel model; EdgeModel edge_model; PeptideRankScorer drs; rand_seed(112233); // train_all(); model.read_model("CID_IT_TRYP"); config = model.get_config(); config->apply_selected_PTMs("C+57:M+16:Q-17"); // fm.init_from_file(config,"C:\\Work\\msms5\\DnvScore\\all_ds\\HEK_98_3_unique_30.mgf"); fs.select_files_in_mz_range(fm,300,2000,3); fs.randomly_reduce_ssfs(100); vector<int> cc(4,0); cc[3]=100; fs.create_mgf_file(fm,config,"HEK_4_30e.mgf",cc); exit(0); // model.get_config()->apply_selected_PTMs("C+57:M+16:Q-17"); PMCSQS_Scorer *pmcsqs = (PMCSQS_Scorer *)model.get_pmcsqs_ptr(); fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\train3.txt"); pmcsqs->benchmark_pm_selection(config,fm,0.3); exit(0); /* benchmark_shew(model,"C:\\Work\\msms5\\PepNovoHQ\\Shew_test_10.mgf"); exit(0); drs.set_model_type(0); drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt"); drs.give_de_novo_and_peak_match_examples("C:\\Work\\msms5\\DnvScore\\all_db_hits", "C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences", "C:\\Work\\msms5\\DnvScore\\dnv_full_parts", "C:\\Work\\msms5\\DnvScore\\dicty2_all.txt", 2,2); exit(0); drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt"); drs.rescore_inspect_results("C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.mzXML", "C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.txt", "C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08_new.txt"); exit(0); // test_denovo_integrity(model,"C:\\Work\\msms5\\DnvScore\\all_ds\\Dicty_98_2_unique_8.mgf", 20000, 8); // benchmark_ranking_on_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSCORE5\\DNVSCORE5_rank_model.txt", // "C:\\Work\\msms5\\DnvScore\\test\\DNVSCORE4_test_10.mgf",400,10); // // benchmark_ranking_on_full_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVFULL\\DNVFULL_rank_model.txt", // "C:\\Work\\msms5\\DnvScore\\test\\FULL_test_10.mgf",1000); // exit(0); fm.init_from_list_file(config,//"C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt"); "C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt"); // "C:\\Work\\msms5\\NewScore\\lists\\Shew_98_3_unique_mgf_list.txt"); fs.select_files(fm,0,2500,-1,-1,2); find_special_PTM_frags_using_offset_counts("S",fm,fs.get_ssf_pointers(),&model,2); exit(0); drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSC_RANK\\LTQ_DNVRANK_model.txt"); drs.test_model("C:\\Work\\msms5\\DnvScore\\test_sets\\LTQ_DNVRANK_test_10.mgf",2000); drs.train_denovo_partition_model("C:\\Work\\msms5\\DnvScore\\all_db_hits", "C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences", "C:\\Work\\msms5\\DnvScore\\comp_all_parts", // "C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt", "C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt", 2, 1, 30000, 5); // model.read_model("ETD"); // config = model.get_config(); // config->apply_selected_PTMs("M+16:Q-17:N+1:C+57"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_unique_train.txt"); // model.full_train_model("ETD",fm,0.5); // model.train_pmc_rank_models("C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_all_train.txt"); // model.write_model(); exit(0); // train_all(); // create_training_sets(); // exit(0); // generate_size_reports(); // test_sims(); // data_set_stats(); // convert_list_to_trianing_peptide_file( // "C:\\Work\\msms5\\NewScore\\lists\\Dicty_98_3_unique_mgf_list.txt", // "C:\\Work\\msms5\\NewScore\\tps\\Dicty_98_3_unique_tps.txt"); // proline_cleavage_reports("b",2); // exit(0); // center_cleavage_reports("y",3); // n_terminal_cleavage_reports("y",2); // c_terminal_cleavage_reports("y",-2); // find_best_similar_pairs("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf",8); // find_self_similarity("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf"); // find_similar_pairs_ditrib("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf"); // find_homeometric_similarity_distrib("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf"); // find_self_similarity_ranges("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\SHEW18.mgf"); // peptide_distances(); // find_matches_similarity_distrib("LTQ_LOW_TRYP", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf", // "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf"); // match_sim_exp(); // exit(0); // edge_model.train_all_edge_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); // saa.train_saa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); // saa.train_saancd_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); // daa.train_daa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2,0.25); // daa.train_daancd_model("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2); // dot_prod_exp(); // qc_exp(); // qc_ann_exp("64068",true); // exit(0); config = model.get_config(); config->init_with_defaults(); config->apply_selected_PTMs("M+16:Q-17:N+1:C+57"); fm.init_from_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD\\train_etd.mgf"); model.full_train_model("ETD",fm,0.5); exit(0); if (1) { model.read_model("LTQ_LOW_TRYP"); // model.get_config()->apply_selected_PTMs("C+57:M+16"); // model.get_config()->init_with_defaults(); model.get_config()->apply_selected_PTMs("M+16:C+57:Q-17"); // model.test_pmc("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs_train_1.mgf",1); // model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt"); // model.compute_sqs_cum_stats_for_crap("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt"); // model.write_model(); model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40good\\H40good_mgf_list.txt"); /// model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\small_list.txt", // "C:\\Work\\msms5\\PepNovoHQ\\small_anns.txt"); // model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\tmp\\H40ul_0_list.txt", // "C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt"); // "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt"); exit(0); DAT_Converter dat; dat.create_dat_files_for_anns(model.get_config(), "C:\\Work\\Data\\Briggs\\HEK293\\40ul_list.txt", // "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt", "C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt", "C:\\Work\\msms5\\PepNovoHQ\\tmp\\", "H4055"); // // model.train_pmc_rank_models( // "C:\\Work\\msms5\\NewScore\\lists\\HEK_98_1_unique_mgf_list.txt",0); // "C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt",0); // "C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt",0); // model.write_model(); // make_before_and_after_matrices(model.get_config(),"C:\\Work\\msms5\\lists\\mgf10.txt",3,"y"); exit(0); FileManager fm; fm.init_from_list_file(model.get_config(),"C:\\Work\\msms5\\lists\\LTQ_train_list.txt"); model.full_train_model("LTQ_IT_TRYP",fm,0.45); model.write_model(); // model.train_pmc("C:\\Work\\msms5\\lists\\pos_sqs_list.txt"); vector< vector<float> > weights; weights.resize(4); weights[1].resize(3,0); weights[2].resize(3,0); weights[3].resize(3,0); weights[1][0] = 0.1; weights[1][1] = 0.1; weights[1][2] = 0.4; weights[2][0] = 0.6; weights[2][1] = 0.75; weights[2][2] = 0.5; weights[3][0] = 0.3; weights[3][1] = 0.15; weights[3][2] = 0.1; // model.train_sqs("C:\\Work\\msms5\\lists\\pos_sqs_list.txt", // "C:\\Work\\msms5\\lists\\neg_sqs_list.txt",&weights); // model.train_sqs("C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt", // "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt",&weights); // config = model.get_config(); // config->set_tolerance(0.5); // // find_pair_similarities(config,"C:/Work/clust_exp/Results/Shew_bm/ShewBM40_0_1.mgf", // "C:/Work/clust_exp/Results/Shew_bm/ShewBM40_pairs.txt"); exit(0); } // make_y_vectors("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs10_train_2.mgf",&model); // create_training_files(config); // exit(0); if (0) { PMCSQS_Scorer sqs; // exit(0); // create_training_files(config); exit(0); } if (1) { // fm.init_from_file(model.get_config(),"C:\\Work\\msms5\\PepNovoHQ\\orbi_ann.mgf"); // create_MSB_query_for_file_list(fm,&model); vector< vector<int> > annotation_idxs; vector<mzXML_annotation> annotations; read_mzXML_annotations("C:/Work/Data/Briggs/HEK293_mzxml_list.txt", "C:/Work/ClusterAnn/mzxml_anns3.txt", annotation_idxs, annotations, 35000); // read_mzXML_annotations("C:/Work/ClusterAnn/H40ul_mgf_list.txt", // "C:/Work/ClusterAnn/mgf_anns.txt", annotation_idxs, annotations, 35000); cout << "Read annotations: " << annotations.size() << endl; fm.init_from_list_file_and_add_annotations(config,"C:/Work/Data/Briggs/HEK293_mzxml_list.txt", annotation_idxs, annotations,true); // fm.init_from_list_file_and_add_annotations(config,"C:/Work/ClusterAnn/H40ul_mgf_list.txt",annotation_idxs, // annotations,true); FileSet all_spec_fs; all_spec_fs.select_all_files(fm,true); // config->set_need_to_normalize(0); // all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mgf_spectra.mgf"); // exit(0); ofstream mgf_stream("C:/Work/ClusterAnn/mzxml_spectra3.mgf",ios::out); BasicSpecReader bsr; const vector<SingleSpectrumFile *>& ssfs = all_spec_fs.get_ssf_pointers(); int i; for (i=0; i<ssfs.size(); i++) { static QCPeak peaks[5000]; BasicSpectrum bs; MZXML_single *ssf = (MZXML_single *)ssfs[i]; bs.peaks = peaks; bs.ssf = ssf; ostringstream oss; oss << ssf->file_idx << " " << ssf->scan_number; ssf->single_name = oss.str(); bs.num_peaks = bsr.read_basic_spec(config,fm,ssf,peaks); if (ssf->scan_number<0) { cout << "Error: no scan number read from mzXML!!!" << endl; exit(1); } cout << "scan: " << ssf->scan_number << " " << bs.num_peaks << endl; bs.output_to_mgf(mgf_stream,config); // bs.output_to_mgf(cout,&config); } //all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mzxml_spectra.mgf"); // extractMZFromFiles(model.get_config(),,"C:/Work/Data/Briggs/HEK293/H29340ul_mz.txt"); // exit(0); } if (1) { model.read_model("LTQ_LOW_TRYP"); config = model.get_config(); config->apply_selected_PTMs("C+57 M+16"); config->set_tolerances(0.5); config->set_pm_tolerance(2.5); config->set_digest_type(TRYPSIN_DIGEST); config->set_max_number_peaks_per_local_window(15); // fm.init_from_list_file(config,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\LTQ_train_list.txt"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\orbi_train.txt"); // edge_model.train_all_edge_models(fm,&model); // tm.train_models(fm,&model); // fm.init_from_list_file(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt"); // make_frag_rank_histogram(fm,config); // exit(0); // benchmark_k_value(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt"); // make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt", // 600, 750, false, "C:\\Work\\clust_exp\\ShewMGF\\", "BMNEW"); // exit(0); benchmark_clustering_performance(config, "C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt",15); // print_dataset_spectra_by_stats(config,"C:\\Work\\clust_exp\\ann_mgf\\Sings_1.mgf"); // benchmark_top7_and_sim_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt", // "C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt"); // benchmark_heuristic_filtering(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt"); // benchmark_retention_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt", // "C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt"); exit(0); FileManager fm; // fm.init_from_mgf(config,"C:\\Work\\clust_exp\\ShewMGF\\OnlyAnn_1.mgf"); // make_specified_benchmark_clustering_dataset(config,"C:\\Work\\clust_exp\\ShewMGF\\both_list.txt",400,1000, // "C:\\Work\\clust_exp\\ShewMGF\\","BM3000",3000,10,0); make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt", 800, 1200, true, "C:\\Work\\clust_exp\\ShewMGF\\", "AnnOnly"); exit(0); ann_mgf_and_create_mgf_with_sim_masses(config,"K:\\Work\\Data\\Shewenella\\FT_anns.txt", "K:\\Work\\Data\\Shewenella\\FT_mgf_list.txt", "K:\\Work\\Data\\Shewenella\\FT_peptides.txt", "C:\\Work\\clust_exp\\ShewMGF\\", "AnnsPlus"); exit(0); ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_single_anns.txt", "C:\\Work\\Data\\FT_mgf\\FT_single_mgf.txt", "C:\\Work\\clust_exp\\ShewMGF\\", "Single",true); exit(0); ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_anns.txt", "C:\\Work\\Data\\FT_mgf\\FT_mgf_list.txt", "C:\\Work\\clust_exp\\ShewMGF\\", "OnlyAnn",true); exit(0); // create_16O_18O_dataset("C:\\Work\\msms5\\lists\\p19_list.txt",config); // exit(0); // config->set_need_to_estimate_pm(0); model.clone_charge_model(2,1); model.clone_charge_model(2,3); model.clone_charge_model(2,4); model.clone_charge_model(2,5); // dataset_eval(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.05); // dataset_eval(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1); // dataset_eval(&model,"C:\\Work\\msms5\\lists\\list280_mgf.txt",0.6); vector<int> set_sizes; vector<float> probs; denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\m280_list.txt", set_sizes,probs,2); // denovo_sequencing_and_aa_probs(&model,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt", // set_sizes,probs,2); // // output_denovo_results(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt"); // denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt", // set_sizes,probs, 2); exit(0); // print_specs(model.get_config(), "C:\\Work\\msms5\\lists\\one_mzxml.txt"); // check_m_over_z(&model,"C:\\Work\\msms5\\lists\\CoCl345sann_ann_list.txt"); // calc_parent_mass_tolerance_distribution(&model, "C:\\Work\\msms5\\lists\\ann_mgf_list.txt" , 0.6, 0.98); // calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_mgf_list.txt", 0.6, 0.95); // perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_mgf_list.txt",0.5,2,0.05); // denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt" ,0.0075); // denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1); // denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.008); // perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.2,2,0.05); // perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.025,2,0.05); // calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.95); // calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.95); // calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.95); // calc_tolerance_distribution(&model,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt",0.75,0.95); // calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.975); // calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.975); // calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.975); exit(0); // fm.init_from_mgf(config,"C:\\Work\\msms4\\PepNovo\\test\\m280.mgf"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\good_list2.txt"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\p215.txt"); // fm.init_from_list_file(config,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt"); // fm.init_from_mgf(config,"C:\\Work\\msms5\\PepNovoHQ\\Omics04Spectra.mgf"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics02_dta.txt"); // FileSet fs; // fs.select_all_files(fm); // fs.sort_according_to_m_over_z(); // fs.create_MGF_file(fm,config,"Omics02Spectra.mgf"); // exit(0); // collect_denovo_statistics(fm,&model); // denovo_histograms(fm,&model); // config->set_tolerance(0.0075); // random_check_homemorphic(config,50000,25); // create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Drosophila_list.txt",".","cc",0,5E6,0,1E6); // create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Dros_short.txt",".","cc",0,1E6,0,1E6); // create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\all_clust.txt","clust_out","ikkb",0,5E6,0,1E6); // create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt","clust_out", // "Omics04b",0,5E6,0,1E6); // create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics02_mgf_list.txt","clust_out", // "Omics02",0,5E6,0,1E6); // create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out2\\h293_dat_list.txt", // "clust_out2","H293b_2nd_digest_abd3",0,5E6,1938.76,1E6,2); // create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out\\h29s_list.txt","clust_out", // "xxxx",0,5E6,835.397,1E6,2); exit(0); DAT_Converter dat; dat.init_DAT_Converter(2000,25,1048576); exit(0); } // config->add_selected_PTMs("C+57 M+16 S+80 T+80 Y+80 N+1 Q+1 K+42 D+16 K+16 P+16 N+16"); // config->set_tolerances(0.0075); // config->set_pm_tolerance(0.011); // fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\contaminants.fasta",config); // fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\Homo_sapiens.NCBI35.dec.pep.fa",config); // fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa50mb.fa",config,true,5,6); // fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo_pos.fa",config); // fdb.print_protein_names(); // fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo.dat"); // fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo.dat",config); // fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\qqq.dat",config); // fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa500k.dat",config); // fdb.print_protein_names(); // fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa5--0mb.dat"); // exit(0); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_seq_list.txt"); // fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_u_list.txt"); fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_376.txt"); // make_bin_histograms(fm,config); // calc_avg_rand(fm,config); // explore_fragment_set(fm,config); // show_occurences(fm,config,"p-25.0"); // find_internal_offset_counts(fm,config); // make_frag_rank_histogram(fm,config); // exit(0); // internal_fragment_annotation(fm,model.get_config()); // find_internal_offset_counts(fm,model.get_config()); // exit(0); FileSet fs; fs.select_all_files(fm); fstream ofs("true_seq.txt",ios::out); fs.make_fasta_from_file_seqs(fm,config,45,ofs); // dbsm.train_regression_models(fm,fdb,12,&model); // analyze_cad_spec(fm,config); // make_rank_histograms(fm,&model); // dbsm.read_model("DBS.txt"); // CAD_histograms(fm,&model,fdb,&dbsm); // rand_db_stats(fm,&model,&dbsm); // db_search_stats(fm,&model,&dbsm); // neg_db_search_stats(fm,&model,&dbsm); // CAD_edge_stats(fm,&model); // CAD_denovo_histograms(fm,&model,fdb); // CAD_edge_stats(fm,&model); // collect_denovo_statistics(fm,&model); exit(0); // int *arr; // int t_size; // read_fasta("cshort.fasta",&arr,&t_size,&config); // read_fasta("C:\\Work\\msms4\\PepNovo\\Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config); // homeomorphic_levels(&config,arr,t_size,1000.0,1001,"hp_res.txt"); config->set_tolerance(0.0075); // full_exp(config,0,arr,t_size,"hp_res_dis_a0.txt"); // full_exp(config,1,arr,t_size,"hp_res_dis_a1.txt"); // full_exp(config,2,arr,t_size,"hp_res_dis_a2.txt"); // full_exp(config,3,arr,t_size,"hp_res_dis_a3.txt"); // full_exp(config,4,arr,t_size,"hp_res_dis_a4.txt"); // homeomorphic_exp3(&config,100); // exit(0); // config.print_supported_PTMs(); // config.print_session_aas(); string p; // ifstream fs("D:\\msms4\\PepNovo\\test\\C25A19_IP_01.mgf",ios::in); // ifstream fs("D:\\msms4\\PepNovo\\test\\m280.mgf",ios::in); // fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\test\\m280.mgf"); // fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\mgf_2600.2.mgf"); // fm.init_from_list_file(&config,"D:\\msms4\\lists\\unique_good2.txt"); // fm.init_from_list_file(&config,"D:\\msms4\\lists\\short2.txt"); // fm.init_from_list_file(&config,"D:\\Data2\\ikkb_unmod_list.txt"); // rand_seed(1111); rand_seed(1426347); // model.read_model("ESI_RANKS"); // model.get_config()->add_selected_PTMs("C+57"); // SpectrumScore sqs; // sqs.learn_score_params(&model,"D:\\msms4\\lists\\sqs2_short.txt", // "D:\\msms4\\lists\\sqs_neg1.txt"); // exit(0); // model.set_model_name(string("ESI2")); // random_peak_match_exp(model.get_config(),fm,800,1200,10000000); // model.print_joint_scores(); // me_reg_exp(); // me_exp(); // exit(0); // fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\test\\m280.mgf"); // fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\hpep.mgf"); fm.init_from_list_file(config,"c:\\Work\\msms4\\lists\\efast2.txt"); // fm.init_from_list_file(&config,"D:\\msms4\\lists\\charge2.txt"); //m.init_from_list_file(model.get_config(),"C:\\Work\\msms4\\PepNovo\\lll.txt"); //m.init_from_list_file(model.get_config(),"D:\\msms4\\lists\\l1.txt"); */ return 0; }
35.122571
111
0.675831
compomics
ea3bf7111be855d397152194b602065d6a61b0b0
107
hpp
C++
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
null
null
null
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
4
2020-08-09T20:33:04.000Z
2021-02-07T04:02:39.000Z
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
null
null
null
#pragma once #if defined(_WIN32) # define EXPORT __declspec(dllexport) #else # define EXPORT #endif
13.375
40
0.719626
RealKC
ea3edce689c621c537745fbce640c7806ef286c5
457
cc
C++
ast/location.cc
asilha/hilti
ebfffc7dad31059b43a02eb26abcf7a25f742eb8
[ "BSD-3-Clause" ]
46
2015-01-21T13:31:25.000Z
2020-10-27T10:18:03.000Z
ast/location.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
29
2015-03-30T08:23:04.000Z
2019-05-03T13:11:35.000Z
ast/location.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
20
2015-01-27T12:59:38.000Z
2020-10-28T21:40:47.000Z
#include <util/util.h> #include "location.h" using namespace ast; const Location Location::None("<no location>"); Location::operator string() const { if ( this == &None ) return "<no location>"; string s = _file.size() ? _file : "<no filename>"; s += ":"; if ( _from >= 0 ) { if ( _to >= 0 ) s += util::fmt("%d-%d", _from, _to); else s += util::fmt("%d", _from); } return s; }
16.925926
54
0.49453
asilha
ea3f18a9f2941f8de6e6ad85de09584ffa021e61
3,040
cpp
C++
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
/******************************************************************************* * Copyright (c) 2020 Matthew Krueger * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgment in the product documentation would * * be appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not * * be misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source * * distribution. * * * *******************************************************************************/ #include "SubTexture2D.hpp" namespace GEOGL{ SubTexture2D::SubTexture2D(const Ref <Texture2D> &textureAtlas, const glm::vec2 &minBound, const glm::vec2 &maxBound) : m_Texture(textureAtlas){ m_TextureCoords[0] = {minBound.x, minBound.y}; m_TextureCoords[1] = {maxBound.x, minBound.y}; m_TextureCoords[2] = {maxBound.x, maxBound.y}; m_TextureCoords[3] = {minBound.x, maxBound.y}; } Ref <SubTexture2D> SubTexture2D::createFromCoords(const Ref<Texture2D>& textureAtlas, const glm::vec2 &spritePosition, const glm::vec2& cellSize, const glm::vec2& spriteDimensions) { glm::vec2 minBounds = { (spritePosition.x * cellSize.x)/(float)textureAtlas->getWidth(), (spritePosition.y * cellSize.y)/(float)textureAtlas->getHeight()}; glm::vec2 maxBounds = { ((spritePosition.x + spriteDimensions.x) * cellSize.x) / (float)textureAtlas->getWidth(), ((spritePosition.y + spriteDimensions.y) * cellSize.y) / (float)textureAtlas->getHeight()}; return createRef<SubTexture2D>(textureAtlas, minBounds, maxBounds); } }
55.272727
186
0.471382
Matthew-Krueger
ea405f6f53b65abdb821e58f9bf4bb40b9deefa4
1,715
cpp
C++
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
1
2018-01-16T18:55:31.000Z
2018-01-16T18:55:31.000Z
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
null
null
null
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
null
null
null
#include "PerspectiveCamera.h" PerspectiveCamera::PerspectiveCamera(const Vector3& e, const Vector3& look, const Vector3& u, unsigned int height, unsigned int width, float pixSize, const std::shared_ptr<AdaptiveSampler>& sampler, float field) : Camera(e, look, u, height, width, pixSize, sampler) { fieldOfView = field; // if distance is default -> calculate from field(ofView) calculateViewDistance(); zoom = 4.0f; } EngineImage PerspectiveCamera::RenderScene(LightIntensity &background, std::unique_ptr<Tracer> const &tracer) { LightIntensity color; std::string name = tracer->sceneName(); EngineImage image = EngineImage(viewHeight, viewWidth, background, name); image.resetPixels(background); float x, y; float d; Ray ray; Vector3 vo; ray.setOrigin(eye); for(unsigned int r = 0; r < viewHeight; r++){ //up for(unsigned int c = 0; c < viewWidth; c++){ //horizontal x = pixelSize * (c - 0.5f *(viewWidth - 1.0f)); y = pixelSize * (r - 0.5f *(viewHeight - 1.0f)); vo = Vector3(x, y, viewDistance) - eye; d = vo.length(); ray.setDirection(Vector3(x, y, d)); color = sampler->AdaptiveSampling(ray, tracer, pixelSize, 0, false); image.setPixel((int)r, (int)c, color); } } return image; } PerspectiveCamera::PerspectiveCamera(const PerspectiveCamera& cam) : Camera(cam), fieldOfView(cam.fieldOfView){ } void PerspectiveCamera::calculateViewDistance(){ viewDistance = 400.0f;//viewWidth / (2.0f * tanf(Utility::degToRad(fieldOfView) * 0.5f)); }
36.489362
111
0.61516
drobnik
ea423eb3e36b05cb5a4e48631ce07d29b8cf4308
3,091
cpp
C++
src/api/button/b_skill.cpp
geoo89/Lix
47dfd2317509ed5cb39b7b230b2de138dc613a6d
[ "CC0-1.0" ]
1
2015-08-29T05:22:40.000Z
2015-08-29T05:22:40.000Z
src/api/button/b_skill.cpp
carvalhomb/AdaptiveLix
d7054c5f96fae54dccef23e48760851b4981a109
[ "CC0-1.0" ]
null
null
null
src/api/button/b_skill.cpp
carvalhomb/AdaptiveLix
d7054c5f96fae54dccef23e48760851b4981a109
[ "CC0-1.0" ]
null
null
null
#include <sstream> #include "b_skill.h" #include "../../graphic/gra_lib.h" #include "../../other/help.h" #include "../../other/language.h" // Lix-Bildname namespace Api { SkillButton::SkillButton(const int nx, const int ny, const int nxl) : Button (nx, ny, nxl, 60), icon(GraLib::get_lix(LixEn::GARDEN), get_ground(), get_x_here() + get_xl()/2 - 17, get_y_here() + 23) { set_skill(LixEn::NOTHING); } SkillButton::~SkillButton() { } void SkillButton::set_skill(const LixEn::Ac ac) { set_draw_required(); skill = ac; icon.set_y_frame(skill - 1); if (skill == LixEn::NOTHING) set_number(0); } void SkillButton::set_number(const int nr) { set_draw_required(); number = (skill != LixEn::NOTHING ? nr : 0); if (number != 0 ) { icon.set_x_frame(0); } else { set_off(); icon.set_x_frame(1); } } void SkillButton::set_style(const LixEn::Style st) { set_draw_required(); icon.set_cutbit(GraLib::get_lix(st)); } void SkillButton::set_hotkey_label(const std::string& s) { hotkey_label = s; if (ustrlen(hotkey_label.c_str()) > 3) { hotkey_label.resize(uoffset(hotkey_label.c_str(), 3)); } // note: if the hotkey label text has an initial non-ASCII // character we won't be able to capitalize it. Oh well. // Not sure that ever happens for real? // Anyway, this allows us to work below as if the first // character only takes one byte. if (hotkey_label.size() > 0) { int c = hotkey_label[0]; if (c >= 'a' && c <= 'z') hotkey_label[0] = c + 'A' - 'a'; } set_draw_required(); } void SkillButton::draw_self() { Button::draw_self(); if (skill != LixEn::NOTHING) { icon.set_x(get_x_here() + get_xl()/2 - 17); icon.set_y(get_y_here() + 23); icon.draw(); // draw the number // note: some calculations below assume all chars in s // are ASCII which is currently the case. std::ostringstream s; if (number == LixEn::infinity) s << "*"; else if (number == 0); // write nothing else if (number >= 0 && number <= LixEn::skill_nr_max) s << number; else s << "?"; // for the horizontal position, we subtract 1 in case of 3 digits // because they weren't properly centered otherwise. Help::draw_shadow_centered_text(get_ground(), (s.str().size() > 2 ? font_nar : font_big), s.str().c_str(), get_x_here() + get_xl()/2 + (s.str().size()>2?-1:0), get_y_here() + 4, color[COL_TEXT_ON], color[COL_API_SHADOW]); // draw the hotkey if (! hotkey_label.empty() && ! s.str().empty()) { Help::draw_shadow_text(get_ground(), font_sml, hotkey_label.c_str(), get_x_here() + get_xl() - 3 - ::text_length(font_sml, hotkey_label.c_str()), get_y_here() + get_yl() - 15, color[COL_TEXT], color[COL_API_SHADOW] ); } // end drawing hotkey } } } // Ende Namensraum
25.758333
78
0.57813
geoo89
ea45370865a076b0520fb580ba48176e80bfcee7
5,629
cc
C++
easyeye/tests/FilesTest.cc
mike10004/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
4
2017-01-27T16:38:53.000Z
2018-09-07T14:02:39.000Z
easyeye/tests/FilesTest.cc
superchao1982/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
1
2018-07-25T18:19:43.000Z
2018-07-25T18:19:43.000Z
easyeye/tests/FilesTest.cc
superchao1982/easyeye
d9996cab2edcedbc1eb78ab6366866423c6be023
[ "MIT" ]
11
2015-02-20T05:28:22.000Z
2021-07-27T03:57:27.000Z
/* * File: FilesTest.cc * Author: mike * * Created on Jan 31, 2014, 10:25:33 AM */ #include "FilesTest.h" #include <vector> #include <string> #include "../src/easyeye/common/easyeye_utils.h" using namespace easyeye; using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION(FilesTest); static bool Eq(const string& a, const string& b) { return a.compare(b) == 0; } // format: // {"path", "dirname", "basename", "extension", "nameWithoutExtension"}, //vector< vector<string> > get_test_cases() { // // {"/usr/lib", "/usr", "lib", "", ""}, // {"/usr/", "/", "usr", "", ""}, // {"usr", ".", "usr", "", ""}, // {"/", "/", "/", "", ""}, // {".", ".", ".", "", ""}, // {"..", ".", "..", "", ""}, // {0, 0, 0, 0, 0, 0} //}; static vector<PathInfo> GetTestCases() { // format: path, dirname, basename, stem, extension PathInfo a("/usr/lib", "/usr", "lib", "lib", ""); PathInfo b("/usr/", "/", "usr", "usr", ""); PathInfo c("usr", ".", "usr", "usr", ""); PathInfo d("/", "/", "/", "/", ""); PathInfo e("a/b/c.txt", "a/b", "c.txt", "c", "txt"); PathInfo f("a.txt", ".", "a.txt", "a", "txt"); PathInfo g("a/b/c", "a/b", "c", "c", ""); PathInfo h("a/b/c/", "a/b", "c", "c", ""); PathInfo l("a/b/c.jpg", "a/b", "c.jpg", "c", "jpg"); PathInfo m("a/b.txt/c", "a/b.txt", "c", "c", ""); PathInfo n("/a/b/c.txt", "/a/b", "c.txt", "c", "txt"); PathInfo q("a/b/.c", "a/b", ".c", ".c", ""); PathInfo r("a/b/c.", "a/b", "c.", "c", ""); PathInfo s(".", ".", ".", ".", ""); PathInfo t("..", ".", "..", "..", ""); PathInfo u("........", ".", "........", "........", ""); // {".", ".", ".", "", ""}, // {"..", ".", "..", "", ""}, vector<PathInfo> test_cases; test_cases.push_back(a); test_cases.push_back(b); test_cases.push_back(c); test_cases.push_back(d); test_cases.push_back(e); test_cases.push_back(f); test_cases.push_back(g); test_cases.push_back(h); test_cases.push_back(l); test_cases.push_back(m); test_cases.push_back(n); test_cases.push_back(q); test_cases.push_back(r); test_cases.push_back(s); test_cases.push_back(t); test_cases.push_back(u); return test_cases; } //Filename //a/b/c.txt --> c.txt // a.txt --> a.txt // a/b/c --> c // a/b/c/ --> "" // Name without extension //a/b/c.txt --> c // a.txt --> a // a/b/c --> c // a/b/c/ --> "" //foo.txt --> "txt" // a/b/c.jpg --> "jpg" // a/b.txt/c --> "" // a/b/c --> "" FilesTest::FilesTest() { } FilesTest::~FilesTest() { } void FilesTest::setUp() { } void FilesTest::tearDown() { } void FilesTest::testExtension() { vector<PathInfo> test_cases = GetTestCases(); int num_diff = 0; for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) { PathInfo& expected = *it; cerr << endl << "filename_extension of \"" << expected.path << "\"" << endl; cerr << "expected: " << expected.filename_extension << endl; PathInfo actual; Files::ParsePathInfo(expected.path, actual); cerr << " actual: " << actual.filename_extension << endl; bool equiv = Eq(expected.filename_extension, actual.filename_extension); cerr << " equal: " << equiv << endl; if (!equiv) num_diff++; } CPPUNIT_ASSERT_EQUAL(0, num_diff); } void FilesTest::testNameWithoutExtension() { vector<PathInfo> test_cases = GetTestCases(); int num_diff = 0; for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) { PathInfo& expected = *it; cerr << endl << "filename_stem of \"" << expected.path << "\"" << endl; cerr << "expected: " << expected.filename_stem << endl; PathInfo actual; Files::ParsePathInfo(expected.path, actual); cerr << " actual: " << actual.filename_stem << endl; bool equiv = Eq(expected.filename_stem, actual.filename_stem); cerr << " equal: " << equiv << endl; if (!equiv) num_diff++; } CPPUNIT_ASSERT_EQUAL(0, num_diff); } void FilesTest::testAbsolute() { CPPUNIT_ASSERT(true); } void FilesTest::testDirname() { vector<PathInfo> test_cases = GetTestCases(); int num_diff = 0; for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) { PathInfo& expected = *it; cerr << endl << "dirname of \"" << expected.path << "\"" << endl; cerr << "expected: " << expected.dirname << endl; PathInfo actual; Files::ParsePathInfo(expected.path, actual); cerr << " actual: " << actual.dirname << endl; bool equiv = Eq(expected.dirname, actual.dirname); cerr << " equal: " << equiv << endl; if (!equiv) num_diff++; } CPPUNIT_ASSERT_EQUAL(0, num_diff); } void FilesTest::testBasename() { vector<PathInfo> test_cases = GetTestCases(); int num_diff = 0; for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) { PathInfo& expected = *it; cerr << endl << "filename of \"" << expected.path << "\"" << endl; cerr << "expected: " << expected.filename << endl; PathInfo actual; Files::ParsePathInfo(expected.path, actual); cerr << " actual: " << actual.filename << endl; bool equiv = Eq(expected.filename, actual.filename); cerr << " equal: " << equiv << endl; if (!equiv) num_diff++; } CPPUNIT_ASSERT_EQUAL(0, num_diff); }
30.101604
92
0.52798
mike10004
3569f3f4b1ed81bd76a4a9f74daff5d730c69b77
748
cpp
C++
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
1
2020-12-09T06:12:43.000Z
2020-12-09T06:12:43.000Z
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
null
null
null
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
null
null
null
/* Runtime: 4 ms, faster than 98.81% of C++ online submissions for Trapping Rain Water. Memory Usage: 14.4 MB, less than 96.32% of C++ online submissions for Trapping Rain Water. */ class Solution { public: int trap(vector<int> &height) { int i = 0; int j = height.size() - 1; int vol = 0; int lmax = 0; int rmax = 0; while (i < j) { lmax = max(lmax, height[i]); rmax = max(rmax, height[j]); if (lmax < rmax) { vol += lmax - height[i]; i++; } else { vol += rmax - height[j]; j--; } } return vol; } };
20.777778
90
0.417112
rohith-bare-on
356e66a8717a03e14994d0f5362993c17eab363d
918
cpp
C++
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
Chaphlagical/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
13
2020-05-21T03:12:48.000Z
2022-01-20T01:25:02.000Z
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
lyf7115/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
null
null
null
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
lyf7115/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
4
2020-06-13T13:14:14.000Z
2021-12-15T07:36:05.000Z
#include "Curve.h" using namespace minidraw; Curve::Curve() { type_ = kCurve; finish = false; polygon.push_back(start); } Curve::~Curve() { } void Curve::update(int mode) { switch (mode) { case 0: finish = true; break; case 1: if (polygon.size() > 0) { polygon.back() = end; points.push_back(end); } polygon.push_back(polygon.back()); break; default: break; } } void Curve::Draw(QPainter& painter) { if (finish) { QPainterPath path(points[0]); for (int i = 0; i < points.size() - 1; i++) { QPoint sp = points[i]; QPoint ep = points[i + 1]; QPoint c1 = QPoint((sp.x() + ep.x()) / 2, sp.y()); QPoint c2 = QPoint((sp.x() + ep.x()) / 2, ep.y()); //QPoint c2 = QPoint(ep.x(), (sp.y() + ep.y()) / 2); path.cubicTo(c1, c2, ep); //path.quadTo(c1, ep); } painter.drawPath(path); } //painter.drawPolygon(polygon); else painter.drawPolyline(polygon); }
15.827586
55
0.58061
Chaphlagical
356fe67569b3e8efd7d30b4e41ead2f716705f08
24,565
cpp
C++
inetsrv/iis/svcs/smtp/adminsso/admin.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/smtp/adminsso/admin.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/smtp/adminsso/admin.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// admin.cpp : Implementation of CsmtpadmApp and DLL registration. #include "stdafx.h" #include "metautil.h" #include "smtpadm.h" #include "smtpcmn.h" #include "smtpprop.h" #include "admin.h" #include "version.h" #include "oleutil.h" #include "metakey.h" #define SMTP_DEF_SERVICE_VERSION ( 0 ) // MCIS // Must define THIS_FILE_* macros to use NntpCreateException() #define THIS_FILE_HELP_CONTEXT 0 #define THIS_FILE_PROG_ID _T("Smtpadm.Admin.1") #define THIS_FILE_IID IID_ISmtpAdmin ///////////////////////////////////////////////////////////////////////////// // CSmtpAdmin::CSmtpAdmin () : m_dwServiceInstance ( 0 ) // CComBSTR's are initialized to NULL by default. { m_dwServiceVersion = SMTP_DEF_SERVICE_VERSION; } CSmtpAdmin::~CSmtpAdmin () { // All CComBSTR's are freed automatically. } STDMETHODIMP CSmtpAdmin::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_ISmtpAdmin, }; for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } STDMETHODIMP CSmtpAdmin::get_ServiceAdmin ( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminService> pISmtpAdminService; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminService, IID_ISmtpAdminService, &pISmtpAdminService, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminService->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminService } STDMETHODIMP CSmtpAdmin::get_VirtualServerAdmin ( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminVirtualServer> pISmtpAdminVirtualServer; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminVirtualServer, IID_ISmtpAdminVirtualServer, &pISmtpAdminVirtualServer, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminVirtualServer->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminVirtualServer->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminVirtualServer } STDMETHODIMP CSmtpAdmin::get_SessionsAdmin ( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminSessions> pISmtpAdminSessions; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminSessions, IID_ISmtpAdminSessions, &pISmtpAdminSessions, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminSessions->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminSessions->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminSessions } STDMETHODIMP CSmtpAdmin::get_AliasAdmin( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminAlias> pISmtpAdminAlias; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminAlias, IID_ISmtpAdminAlias, &pISmtpAdminAlias, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminAlias->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminAlias->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminAlias } STDMETHODIMP CSmtpAdmin::get_UserAdmin( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminUser> pISmtpAdminUser; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminUser, IID_ISmtpAdminUser, &pISmtpAdminUser, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminUser->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminUser->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminUser } STDMETHODIMP CSmtpAdmin::get_DLAdmin( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminDL> pISmtpAdminDL; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminDL, IID_ISmtpAdminDL, &pISmtpAdminDL, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminDL->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminDL->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminDL } STDMETHODIMP CSmtpAdmin::get_DomainAdmin( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminDomain> pISmtpAdminDomain; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminDomain, IID_ISmtpAdminDomain, &pISmtpAdminDomain, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminDomain->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminDomain->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminDomain } STDMETHODIMP CSmtpAdmin::get_VirtualDirectoryAdmin( IDispatch ** ppIDispatch ) { HRESULT hr = NOERROR; CComBSTR bstrT = _T(""); CComPtr<ISmtpAdminVirtualDirectory> pISmtpAdminVirtualDirectory; if (!bstrT) { hr = E_OUTOFMEMORY; goto Error; } hr = StdPropertyHandoffIDispatch ( CLSID_CSmtpAdminVirtualDirectory, IID_ISmtpAdminVirtualDirectory, &pISmtpAdminVirtualDirectory, ppIDispatch ); if ( FAILED(hr) ) { goto Error; } // Set default properties: hr = pISmtpAdminVirtualDirectory->put_Server ( m_strServer ? m_strServer : bstrT ); if ( FAILED (hr) ) { goto Error; } hr = pISmtpAdminVirtualDirectory->put_ServiceInstance ( m_dwServiceInstance ); if ( FAILED (hr) ) { goto Error; } return hr; Error: SAFE_RELEASE ( *ppIDispatch ); *ppIDispatch = NULL; return hr; // Destructor releases pISmtpAdminVirtualDirectory } // Which service to configure: STDMETHODIMP CSmtpAdmin::get_Server ( BSTR * pstrServer ) { return StdPropertyGet ( m_strServer, pstrServer ); } STDMETHODIMP CSmtpAdmin::put_Server ( BSTR strServer ) { return StdPropertyPutServerName ( &m_strServer, strServer ); } STDMETHODIMP CSmtpAdmin::get_ServiceInstance ( long * plServiceInstance ) { return StdPropertyGet ( m_dwServiceInstance, plServiceInstance ); } STDMETHODIMP CSmtpAdmin::put_ServiceInstance ( long lServiceInstance ) { return StdPropertyPut ( &m_dwServiceInstance, lServiceInstance ); } // Versioning: STDMETHODIMP CSmtpAdmin::get_HighVersion ( long * plHighVersion ) { *plHighVersion = HIGH_VERSION; return NOERROR; } STDMETHODIMP CSmtpAdmin::get_LowVersion ( long * plLowVersion ) { *plLowVersion = LOW_VERSION; return NOERROR; } STDMETHODIMP CSmtpAdmin::get_BuildNum ( long * plBuildNumber ) { *plBuildNumber = BUILD_NUM; return NOERROR; } STDMETHODIMP CSmtpAdmin::get_ServiceVersion ( long * plServiceVersion ) { *plServiceVersion = m_dwServiceVersion; return NOERROR; } ////////////////////////////////////////////////////////////////////// // Methods: ////////////////////////////////////////////////////////////////////// //$------------------------------------------------------------------- // // CSmtpAdmin::EnumerateInstances // // Description: // // Returns a list of the virtual servers on the given machine. // // Parameters: // // ppsaInstances - Returned SAFEARRAY of instance IDs. // Must be freed by caller. // // Returns: // // //-------------------------------------------------------------------- STDMETHODIMP CSmtpAdmin::EnumerateInstances ( SAFEARRAY ** ppsaInstances ) { TraceFunctEnter ( "CSmtpAdmin::EnumerateInstances" ); HRESULT hr = NOERROR; CComPtr<IMSAdminBase> pMetabase; SAFEARRAY * psaEmpty = NULL; SAFEARRAYBOUND sabound[1]; // Check parameters: _ASSERT ( ppsaInstances != NULL ); _ASSERT ( IS_VALID_OUT_PARAM ( ppsaInstances ) ); if ( ppsaInstances == NULL ) { FatalTrace ( 0, "Bad return pointer" ); hr = E_POINTER; goto Exit; } // Zero the out parameters: *ppsaInstances = NULL; // Set the return array to an empty array: sabound[0].lLbound = 0; sabound[0].cElements = 0; psaEmpty = SafeArrayCreate ( VT_I4, 1, sabound ); if ( psaEmpty == NULL ) { FatalTrace ( (LPARAM) this, "Out of memory" ); hr = E_OUTOFMEMORY; goto Exit; } *ppsaInstances = psaEmpty; // Get the metabase pointer: hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase ); BAIL_ON_FAILURE(hr); // Enumerate the instances: hr = QueryMetabaseInstances ( pMetabase, ppsaInstances ); Exit: if ( FAILED(hr) ) { _VERIFY ( SUCCEEDED (SafeArrayDestroy ( psaEmpty )) ); if (ppsaInstances) *ppsaInstances = NULL; } TraceFunctLeave (); return hr; } STDMETHODIMP CSmtpAdmin::EnumerateInstancesVariant ( SAFEARRAY ** ppsaInstances ) { TraceFunctEnter ( "CSmtpAdmin::EnumerateInstancesVariant" ); HRESULT hr; SAFEARRAY * psaInstances = NULL; hr = EnumerateInstances ( &psaInstances ); BAIL_ON_FAILURE(hr); hr = LongArrayToVariantArray ( psaInstances, ppsaInstances ); BAIL_ON_FAILURE(hr); Exit: TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::CreateInstance // // Description: // // Creates a new SMTP virtual server on the given machine. // // Parameters: // // plInstanceId - The new virtual server ID. // // Returns: // // //-------------------------------------------------------------------- STDMETHODIMP CSmtpAdmin::CreateInstance ( BSTR pstrMailRoot, long * plInstanceId ) { TraceFunctEnter ( "CSmtpAdmin::CreateInstance" ); HRESULT hr = NOERROR; CComPtr<IMSAdminBase> pMetabase; // Check parameters: _ASSERT ( plInstanceId != NULL ); _ASSERT ( IS_VALID_OUT_PARAM ( plInstanceId ) ); if ( plInstanceId == NULL ) { FatalTrace ( 0, "Bad return pointer" ); hr = E_POINTER; goto Exit; } // Zero the out parameter: *plInstanceId = 0; // Get the metabase pointer: hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase ); if ( FAILED(hr) ) { goto Exit; } // Create a new instance: hr = CreateNewInstance ( pMetabase, plInstanceId, pstrMailRoot ); Exit: TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::DestroyInstance // // Description: // // Removes the given virtual server. // // Parameters: // // lInstanceId - The ID of the virtual server to delete. // // Returns: // // //-------------------------------------------------------------------- STDMETHODIMP CSmtpAdmin::DestroyInstance ( long lInstanceId ) { TraceFunctEnter ( "CSmtpAdmin::DestroyInstance" ); HRESULT hr = NOERROR; CComPtr<IMSAdminBase> pMetabase; // Get the metabase pointer: hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase ); if ( FAILED(hr) ) { goto Exit; } // Delete the instance: hr = DeleteInstance ( pMetabase, lInstanceId ); Exit: TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::ErrorToString // // Description: // // Translates an SMTP_ERROR_CODE to a readable string. // // Parameters: // // lErrorCode - Win32 error code. // pstrError - the readable error string. // // Returns: // // The error string in *pstrError. // //-------------------------------------------------------------------- STDMETHODIMP CSmtpAdmin::ErrorToString ( DWORD lErrorCode, BSTR * pstrError ) { TraceFunctEnter ( "CSmtpAdmin::ErrorToString" ); _ASSERT ( IS_VALID_OUT_PARAM ( pstrError ) ); HRESULT hr = NOERROR; DWORD dwFormatFlags; WCHAR wszError [ 1024 ]; if ( pstrError == NULL ) { FatalTrace ( (LPARAM) this, "Bad return pointer" ); TraceFunctLeave (); return E_POINTER; } //---------------------------------------------------------------- // // Map error codes here: // // //---------------------------------------------------------------- dwFormatFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; if ( !FormatMessage ( dwFormatFlags, NULL, lErrorCode, 0, // Lang ID - Should be nonzero? wszError, 1024, NULL ) ) { // Didn't work, so put in a default message: WCHAR wszFormat [ 256 ]; wszFormat[0] = L'\0'; if ( !LoadStringW ( _Module.GetResourceInstance (), IDS_UNKNOWN_ERROR, wszFormat, 256 ) || !*wszFormat ) { wcscpy ( wszFormat, L"Unknown Error (%1!d!)" ); } FormatMessage ( FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, wszFormat, IDS_UNKNOWN_ERROR, 0, wszError, 1024, (va_list *) &lErrorCode ); } // // We need to strip out any " from the string, because // Javascript will barf. // LPWSTR pch; for ( pch = wszError; *pch; pch++ ) { if ( *pch == L'\"' ) { *pch = L'\''; } } // // Strip off any trailing control characters. // for (pch = &wszError[wcslen(wszError) - 1]; pch >= wszError && iswcntrl(*pch); pch --) { *pch = 0; } *pstrError = ::SysAllocString( wszError ); if ( *pstrError == NULL ) { hr = E_OUTOFMEMORY; goto Exit; } Exit: TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::Tokenize // // Description: // // Makes the given string safe for HTML & Javascript // // Parameters: // // strIn - the input string // strOut - the resulting string with appropriate escape sequences. // //-------------------------------------------------------------------- STDMETHODIMP CSmtpAdmin::Tokenize ( BSTR strIn, BSTR * pstrOut ) { TraceFunctEnter ( "CSmtpAdmin::Tokenize" ); _ASSERT ( IS_VALID_STRING ( strIn ) ); _ASSERT ( IS_VALID_OUT_PARAM ( pstrOut ) ); HRESULT hr = NOERROR; PWCHAR pSrc = strIn; PWCHAR pSrcCur = NULL; PWCHAR pDstCur = NULL; PWCHAR pDst = NULL; *pstrOut = NULL; pDst = new WCHAR [ 3 * lstrlen ( strIn ) + 1 ]; if ( pDst == NULL ) { FatalTrace ( (LPARAM) this, "Out of memory" ); hr = E_OUTOFMEMORY; goto Exit; } for ( pSrcCur = pSrc, pDstCur = pDst; *pSrcCur; pSrcCur++ ) { switch ( *pSrcCur ) { case L'\\': *(pDstCur++) = L'%'; *(pDstCur++) = L'5'; *(pDstCur++) = L'c'; break; case L' ': *(pDstCur++) = L'+'; break; case L':': *(pDstCur++) = L'%'; *(pDstCur++) = L'3'; *(pDstCur++) = L'a'; break; case L'/': *(pDstCur++) = L'%'; *(pDstCur++) = L'2'; *(pDstCur++) = L'f'; break; default: *(pDstCur++) = *pSrcCur; } } *pDstCur = L'\0'; *pstrOut = ::SysAllocString ( pDst ); if ( *pstrOut == NULL ) { FatalTrace ( (LPARAM) this, "Out of memory" ); hr = E_OUTOFMEMORY; goto Exit; } Exit: delete pDst; if ( FAILED(hr) && hr != DISP_E_EXCEPTION ) { hr = SmtpCreateExceptionFromHresult ( hr ); } TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::QueryMetabaseInstances // // Description: // // Retrieves the list of virtual servers from the metabase // // Parameters: // // pMetabase - the metabase object // ppsaInstances - resulting array of instance ids. // // Returns: // // //-------------------------------------------------------------------- HRESULT CSmtpAdmin::QueryMetabaseInstances ( IMSAdminBase * pMetabase, SAFEARRAY ** ppsaInstances ) { TraceFunctEnter ( "CSmtpAdmin::QueryMetabaseInstances" ); _ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) ); _ASSERT ( IS_VALID_OUT_PARAM ( ppsaInstances ) ); HRESULT hr = NOERROR; CMetabaseKey mkeySmtp ( pMetabase ); SAFEARRAY * psaResult = NULL; DWORD cValidInstances = 0; SAFEARRAYBOUND rgsaBound[1]; DWORD i; TCHAR szName[ METADATA_MAX_NAME_LEN ]; long index[1]; DWORD dwInstance; hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH ); if ( FAILED(hr) ) { goto Exit; } // pickup the service version number: hr = mkeySmtp.GetDword ( _T(""), MD_SMTP_SERVICE_VERSION, &m_dwServiceVersion ); if ( FAILED(hr) ) { m_dwServiceVersion = SMTP_DEF_SERVICE_VERSION; } hr = mkeySmtp.GetIntegerChildCount ( &cValidInstances ); if ( FAILED(hr) ) { goto Exit; } // Allocate the array: rgsaBound[0].lLbound = 0; rgsaBound[0].cElements = cValidInstances; psaResult = SafeArrayCreate ( VT_I4, 1, rgsaBound ); if ( psaResult == NULL ) { FatalTrace ( 0, "Out of memory" ); hr = E_OUTOFMEMORY; goto Exit; } mkeySmtp.BeginChildEnumeration (); for ( i = 0; i < cValidInstances; i++ ) { hr = mkeySmtp.NextIntegerChild ( &dwInstance, szName ); _ASSERT ( SUCCEEDED(hr) ); index[0] = i; hr = SafeArrayPutElement ( psaResult, index, &dwInstance ); _ASSERT ( SUCCEEDED(hr) ); } *ppsaInstances = psaResult; _ASSERT ( SUCCEEDED(hr) ); Exit: if ( FAILED (hr) ) { SafeArrayDestroy ( psaResult ); } TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::CreateNewInstance // // Description: // // Creates a new virtual server in the metabase. // // Parameters: // // pMetabase - The metabase object // plInstanceId - The new instance ID. // // Returns: // // //-------------------------------------------------------------------- HRESULT CSmtpAdmin::CreateNewInstance ( IMSAdminBase * pMetabase, long * plInstanceId, BSTR bstrMailRoot ) { TraceFunctEnter ( "CSmtpAdmin::CreateNewInstance" ); _ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) ); _ASSERT ( IS_VALID_OUT_PARAM ( plInstanceId ) ); HRESULT hr = NOERROR; CMetabaseKey mkeySmtp ( pMetabase ); DWORD dwInstance; TCHAR szInstance [ METADATA_MAX_NAME_LEN ]; TCHAR szPath [ METADATA_MAX_NAME_LEN ]; TCHAR szDir [512]; DWORD cb; // Zero the out parameters: *plInstanceId = NULL; hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH, METADATA_PERMISSION_WRITE ); if ( FAILED(hr) ) { ErrorTraceX ( (LPARAM) this, "Failed to open SmtpSvc key, %x", GetLastError() ); goto Exit; } hr = mkeySmtp.CreateIntegerChild ( &dwInstance, szInstance ); if ( FAILED (hr) ) { goto Exit; } wsprintf( szPath, _T("%s/Root"), szInstance ); hr = mkeySmtp.CreateChild( szPath ); if ( FAILED (hr) ) { goto Exit; } wsprintf( szPath, _T("%s/Root/MailRoot"), szInstance ); hr = mkeySmtp.CreateChild( szPath ); if ( FAILED (hr) ) { goto Exit; } // create mail root virtual directory if( bstrMailRoot && bstrMailRoot[0] ) { // get rid of '\' at the end cb = lstrlen( bstrMailRoot ); if( cb > 0 && bstrMailRoot[cb-1] == _T('\\') ) bstrMailRoot[cb-1] = _T('\0'); wsprintf( szPath, _T("%s/Root/MailRoot"), szInstance ); cb = wsprintf( szDir, _T("%s\\Mailbox"), bstrMailRoot ); mkeySmtp.SetString( szPath, MD_VR_PATH, szDir); // set badmail, drop, pickup, queue keys wsprintf( szPath, _T("%s"), szInstance ); cb = wsprintf( szDir, _T("%s\\Badmail"), bstrMailRoot ); mkeySmtp.SetString( szPath, MD_BAD_MAIL_DIR, szDir); // K2 only has drop doamin if( SERVICE_IS_K2(m_dwServiceVersion) ) { cb = wsprintf( szDir, _T("%s\\Drop"), bstrMailRoot ); mkeySmtp.SetString( szPath, MD_MAIL_DROP_DIR, szDir ); } cb = wsprintf( szDir, _T("%s\\Pickup"), bstrMailRoot ); mkeySmtp.SetString( szPath, MD_MAIL_PICKUP_DIR, szDir ); cb = wsprintf( szDir, _T("%s\\Queue"), bstrMailRoot ); mkeySmtp.SetString( szPath, MD_MAIL_QUEUE_DIR, szDir ); // set the routing sources, it's MultiSZ cb = wsprintf( szDir, _T("szDataDirectory=%s\\Route"), bstrMailRoot ); szDir[cb] = szDir[cb+1] = _T('\0'); mkeySmtp.SetMultiSz( szPath, MD_ROUTING_SOURCES, szDir, (cb+2) * sizeof(TCHAR) ); // MCIS needs SendNDRTo and SendBadTo as "Postmaster", setup should set it on service level if( SERVICE_IS_MCIS(m_dwServiceVersion) ) { mkeySmtp.SetString( szPath, MD_SEND_NDR_TO, TSTR_POSTMASTR_NAME ); mkeySmtp.SetString( szPath, MD_SEND_BAD_TO, TSTR_POSTMASTR_NAME ); } } // // Initialize the server state: // mkeySmtp.SetDword ( szInstance, MD_SERVER_COMMAND, MD_SERVER_COMMAND_STOP ); mkeySmtp.SetDword ( szInstance, MD_SERVER_STATE, MD_SERVER_STATE_STOPPED ); mkeySmtp.SetDword ( szInstance, MD_SERVER_AUTOSTART, FALSE ); // hr = mkeySmtp.Close(); // BAIL_ON_FAILURE(hr); mkeySmtp.Close(); hr = pMetabase->SaveData ( ); if ( FAILED (hr) ) { goto Exit; } *plInstanceId = dwInstance; Exit: TraceFunctLeave (); return hr; } //$------------------------------------------------------------------- // // CSmtpAdmin::DeleteInstance // // Description: // // Removes a virtual server from the metabase // // Parameters: // // pMetabase - The metabase object // lInstanceId - The ID of the virtual server to delete. // // Returns: // // //-------------------------------------------------------------------- HRESULT CSmtpAdmin::DeleteInstance ( IMSAdminBase * pMetabase, long lInstanceId ) { TraceFunctEnter ( "CSmtpAdmin::CreateNewInstance" ); _ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) ); HRESULT hr = NOERROR; CMetabaseKey mkeySmtp ( pMetabase ); // // Tell U2 to delete any mappings associated with this virtual server: // ::DeleteMapping ( m_strServer, (BSTR) MD_SERVICE_NAME, lInstanceId ); // // Delete the virtual server from the metabase: // hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH, METADATA_PERMISSION_WRITE ); if ( FAILED(hr) ) { ErrorTraceX ( (LPARAM) this, "Failed to open SmtpSvc key, %x", GetLastError() ); goto Exit; } hr = mkeySmtp.DestroyIntegerChild ( (DWORD) lInstanceId ); if ( FAILED (hr) ) { goto Exit; } // hr = mkeySmtp.Close(); // BAIL_ON_FAILURE(hr); mkeySmtp.Close(); hr = pMetabase->SaveData ( ); if ( FAILED (hr) ) { goto Exit; } Exit: TraceFunctLeave (); return hr; }
21.91347
100
0.596173
npocmaka
3573fb7d5e9ca7e52ba4fdd797c30dc406b3ff22
1,402
hpp
C++
modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
1
2022-03-24T03:35:10.000Z
2022-03-24T03:35:10.000Z
modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
/******************************************************************************* * Copyright 2003-2010 LASMEA UMR 6602 CNRS/U.B.P * Copyright 2009-2010 LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #ifndef NT2_SDK_DSL_PROTO_EXTENDS_HPP #define NT2_SDK_DSL_PROTO_EXTENDS_HPP #include <nt2/sdk/details/preprocessor.hpp> //////////////////////////////////////////////////////////////////////////////// // BOOST_PROTO_BASIC_EXTENDS working with template Domain //////////////////////////////////////////////////////////////////////////////// #define BOOST_PROTO_BASIC_EXTENDS_TPL(Expr, Derived, Domain) \ BOOST_PROTO_BASIC_EXTENDS_( NT2_PP_STRIP(Expr) \ , NT2_PP_STRIP(Derived) \ , NT2_PP_STRIP(Domain) \ ) \ typedef void proto_is_aggregate_; \ typedef typename NT2_PP_STRIP(Domain)::proto_generator proto_generator; \ /**/ #endif
53.923077
80
0.413695
brycelelbach
35740d60fbccfa21c6ab923e38c28c5debb9e38d
940
cpp
C++
third_party/mexconv3d/mex_maxpool3d.cpp
janelia-flyem/flymatlib
63fab6b2deca8996d31b379a38a860ef3e751466
[ "BSD-3-Clause" ]
4
2016-04-02T17:58:47.000Z
2020-02-13T18:19:31.000Z
third_party/mexconv3d/mex_maxpool3d.cpp
janelia-flyem/flymatlib
63fab6b2deca8996d31b379a38a860ef3e751466
[ "BSD-3-Clause" ]
null
null
null
third_party/mexconv3d/mex_maxpool3d.cpp
janelia-flyem/flymatlib
63fab6b2deca8996d31b379a38a860ef3e751466
[ "BSD-3-Clause" ]
2
2019-12-19T01:09:53.000Z
2022-01-03T21:17:48.000Z
#include "mex.h" #include "src/maxpool3d.h" #include "src/wrapperMx.h" // [Y,ind] = MEX_MAXPOOL3D(X); forward pass // dZdX = MEX_MAXPOOL3D(dZdY, ind); backward pass // MEX_MAXPOOL3D(..., 'pool',pool, 'stride',s, 'pad',pad); options void mexFunction(int no, mxArray *vo[], int ni, mxArray const *vi[]) { #ifdef WITHCUDNN factory_mp3d_withcudnn factory; #else factory_mp3d_homebrew factory; #endif maxpool3d* h = 0; // TODO: consider unique_ptr? try { h = factory.parse_and_create(no, vo, ni, vi); assert( h != 0 ); // do the job and set output if (h->ct == maxpool3d::FPROP) { h->fprop(); vo[0] = h->Y.getMxArray(); vo[1] = h->ind.getMxArray(); } if (h->ct == maxpool3d::BPROP) { h->bprop(); vo[0] = h->dX.getMxArray(); } // done: cleanup safe_delete(h); } catch (const mp3d_ex e) { safe_delete(h); mexErrMsgTxt(e.what()); } }
23.5
66
0.584043
janelia-flyem
35751cf78578591ccfa8a90510839623b78c9628
493
hpp
C++
platform/platform.hpp
Peefy/ArkLightCpp
d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5
[ "Apache-2.0" ]
1
2018-05-03T14:12:17.000Z
2018-05-03T14:12:17.000Z
platform/platform.hpp
Peefy/ArkLightCpp
d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5
[ "Apache-2.0" ]
null
null
null
platform/platform.hpp
Peefy/ArkLightCpp
d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5
[ "Apache-2.0" ]
null
null
null
#include <string> #include "../core/basic.h" #include "./osplatformutil.h" enum class Platform { Unknown = 0, Windows = 1, Linux = 2, MacOS = 3, Android = 4, iOS = 5, FreeBSD = 6, OpenBSD = 7, Sun = 8 }; inline Platform GetPlatfom() { #if defined ARK_MSVC return Platform::Windows; #elif defined ARK_GCC return Platform::Linux; #elif defined ARK_APPLE return Platform::MacOS; #else return Platform::Unknown; #endif }
16.433333
30
0.602434
Peefy
3576d34fd65a8bcf6ffb78c50761890d9945b668
10,370
cpp
C++
silkopter/rc/src/main.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
silkopter/rc/src/main.cpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
silkopter/rc/src/main.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#include "Comms.h" #include "Video_Decoder.h" //#include "Menu_System.h" //#include "Splash_Menu_Page.h" //#include "Main_Menu_Page.h" #include "utils/Clock.h" #include "IHAL.h" #ifdef RASPBERRY_PI # include "PI_HAL.h" #else # include "GLFW_HAL.h" #endif #include "imgui.h" #include "HUD.h" namespace silk { int s_version_major = 1; int s_version_minor = 0; std::string s_program_path; std::unique_ptr<silk::IHAL> s_hal; } /////////////////////////////////////////////////////////////////////////////////////////////////// //This prints an "Assertion failed" message and aborts. void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function) { QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion); } /////////////////////////////////////////////////////////////////////////////////////////////////// void signal_callback_handler(int signum) { printf("Caught signal %d\n", signum); if (silk::s_hal) { silk::s_hal->shutdown(); } exit(signum); } /////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger())); q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC)); // boost::shared_ptr<asio::io_service::work> work(new asio::io_service::work(s_async_io_service)); // std::thread_group worker_threads; // for(int x = 0; x < 4; ++x) // { // worker_threads.create_thread(boost::bind(&asio::io_service::run, &s_async_io_service)); // } signal(SIGHUP, signal_callback_handler); signal(SIGINT, signal_callback_handler); signal(SIGCONT, signal_callback_handler); signal(SIGTERM, signal_callback_handler); silk::s_program_path = argv[0]; size_t off = silk::s_program_path.find_last_of('/'); if (off != std::string::npos) { silk::s_program_path = silk::s_program_path.substr(0, off); } QLOGI("Program path: {}.", silk::s_program_path); #ifdef RASPBERRY_PI silk::s_hal.reset(new silk::PI_HAL()); #else silk::s_hal.reset(new silk::GLFW_HAL()); #endif silk::IHAL& hal = *silk::s_hal; ts::Result<void> result = hal.init(); if (result != ts::success) { QLOGE("Cannot init hal: {}.", result.error().what()); exit(1); } silk::HUD hud(hal); math::vec2u32 display_size = hal.get_display_size(); ImGuiStyle& style = ImGui::GetStyle(); style.ScrollbarSize = display_size.x / 80.f; style.TouchExtraPadding = ImVec2(style.ScrollbarSize * 2.f, style.ScrollbarSize * 2.f); //style.ItemSpacing = ImVec2(size.x / 200, size.x / 200); //style.ItemInnerSpacing = ImVec2(style.ItemSpacing.x / 2, style.ItemSpacing.y / 2); ImGuiIO& io = ImGui::GetIO(); io.FontGlobalScale = 2.f; Video_Decoder decoder; decoder.init(); Clock::time_point last_tp = Clock::now(); hal.get_comms().on_video_data_received = [&decoder](void const* data, size_t size, math::vec2u16 const& res) { decoder.decode_data(data, size, res); }; float temperature = 0.f; Clock::time_point last_comms_history_tp = Clock::now(); std::vector<float> tx_rssi_history; std::vector<float> rx_rssi_history; std::vector<float> packets_dropped_history; std::vector<float> packets_received_history; std::vector<float> packets_sent_history; float brightness = 80.f; float fan_speed = 100.f; hal.set_backlight(brightness / 100.f); hal.set_fan_speed(fan_speed / 100.f); bool single_phy = false; silk::stream::ICamera_Commands::Value camera_commands; while (hal.process()) { decoder.release_buffers(); Clock::time_point now = Clock::now(); Clock::duration dt = now - last_tp; last_tp = now; io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(dt).count(); ImGui::NewFrame(); ImGui::SetNextWindowPos(ImVec2(0, 0)); ImGui::SetNextWindowSize(ImVec2(display_size.x, display_size.y)); ImGui::SetNextWindowBgAlpha(0); ImGui::Begin("", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs); ImGui::Image((void*)(decoder.get_video_texture_id() | 0x80000000), ImVec2(display_size.x, display_size.y), ImVec2(0, 1), ImVec2(1, 0)); hud.draw(); ImGui::Begin("HAL"); { static int counter = 0; ImGui::Text("Hello, world!"); // Display some text (you can use a format string too) if (ImGui::SliderFloat("Brightness", &brightness, 10.f, 100.f, "%.0f%%")) { hal.set_backlight(brightness / 100.f); } if (ImGui::SliderFloat("Fan", &fan_speed, 10.f, 100.f, "%.0f%%")) { hal.set_fan_speed(fan_speed / 100.f); } temperature = hal.get_temperature(); ImGui::Text("Temperature = %.2f'C", temperature); if (now - last_comms_history_tp >= std::chrono::milliseconds(100)) { last_comms_history_tp = now; silk::Comms::Stats stats = hal.get_comms().get_stats(); tx_rssi_history.push_back(stats.tx_rssi); while (tx_rssi_history.size() > 10 * 5) { tx_rssi_history.erase(tx_rssi_history.begin()); } rx_rssi_history.push_back(stats.rx_rssi); while (rx_rssi_history.size() > 10 * 5) { rx_rssi_history.erase(rx_rssi_history.begin()); } packets_dropped_history.push_back(stats.packets_dropped_per_second); while (packets_dropped_history.size() > 10 * 5) { packets_dropped_history.erase(packets_dropped_history.begin()); } packets_received_history.push_back(stats.packets_received_per_second); while (packets_received_history.size() > 10 * 5) { packets_received_history.erase(packets_received_history.begin()); } packets_sent_history.push_back(stats.packets_sent_per_second); while (packets_sent_history.size() > 10 * 5) { packets_sent_history.erase(packets_sent_history.begin()); } } if (!tx_rssi_history.empty()) { ImGui::Text("TX = %ddBm", (int)tx_rssi_history.back()); ImGui::PlotLines("History", tx_rssi_history.data(), tx_rssi_history.size(), 0, NULL, -128.f, 128.f, ImVec2(0, display_size.y / 20)); } if (!rx_rssi_history.empty()) { ImGui::Text("RX = %ddBm", (int)rx_rssi_history.back()); ImGui::PlotLines("History", rx_rssi_history.data(), rx_rssi_history.size(), 0, NULL, -128.f, 128.f, ImVec2(0, display_size.y / 20)); } if (!packets_dropped_history.empty()) { ImGui::Text("Dropped = %.2f", packets_dropped_history.back()); auto minmax = std::minmax_element(packets_dropped_history.begin(), packets_dropped_history.end()); ImGui::PlotLines("History", packets_dropped_history.data(), packets_dropped_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } if (!packets_received_history.empty()) { ImGui::Text("Received = %.2f", packets_received_history.back()); auto minmax = std::minmax_element(packets_received_history.begin(), packets_received_history.end()); ImGui::PlotLines("History", packets_received_history.data(), packets_received_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } if (!packets_sent_history.empty()) { ImGui::Text("Sent = %.2f", packets_sent_history.back()); auto minmax = std::minmax_element(packets_sent_history.begin(), packets_sent_history.end()); ImGui::PlotLines("History", packets_sent_history.data(), packets_sent_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } bool hq = camera_commands.quality == silk::stream::ICamera_Commands::Quality::HIGH; ImGui::Checkbox("HQ Video", &hq); camera_commands.quality = hq ? silk::stream::ICamera_Commands::Quality::HIGH : silk::stream::ICamera_Commands::Quality::LOW; ImGui::SameLine(); ImGui::Checkbox("Record Video", &camera_commands.recording); hal.get_comms().send_camera_commands_value(camera_commands); ImGui::Checkbox("Single Phy", &single_phy); hal.get_comms().set_single_phy(single_phy); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } ImGui::End(); ImGui::End(); //std::this_thread::sleep_for(std::chrono::microseconds(1)); ImGui::Render(); } hal.shutdown(); return 0; }
39.429658
155
0.542816
jeanleflambeur
35780e67403f1502578682eb387b94c80863e5cd
3,850
cpp
C++
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-07-29T04:27:22.000Z
2021-10-11T01:27:43.000Z
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
null
null
null
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-08-03T03:29:28.000Z
2020-08-03T08:01:14.000Z
/** * ================================================== * _____ * __|___ |__ __ __ _ ____ ____ _ * | ___| | _| |_ | |_| || \ | \ | | * | ___| ||_ _|| _ || \ | \| | * |______| __| |__| |__| |_||__|\__\|__/\____| * |_____| * * Game Engine * ================================================== * * @file gl_buffers.cpp * @author Nghia Lam <nghialam12795@gmail.com> * * @brief * * @license Copyright 2020 Nghia Lam * * 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 "ethan/opengl/gl_buffers.h" #include "ethan/opengl/gl_assert.h" #include <glad/glad.h> namespace Ethan { static unsigned int BufferDataUsageToOpenGL(BufferDataUsage usage) { switch(usage) { case BufferDataUsage::STATIC: return GL_STATIC_DRAW; case BufferDataUsage::DYNAMIC: return GL_DYNAMIC_DRAW; } } /// --- GLVertexBuffer GLVertexBuffer::GLVertexBuffer(BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile Here GLCALL(glGenBuffers(1, &vertexbufferID_)); } GLVertexBuffer::GLVertexBuffer(uint32_t size, BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile Here GLCALL(glGenBuffers(1, &vertexbufferID_)); GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, nullptr, BufferDataUsageToOpenGL(usage))); } GLVertexBuffer::GLVertexBuffer(const void* data, uint32_t size, BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile here GLCALL(glGenBuffers(1, &vertexbufferID_)); GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(usage))); } GLVertexBuffer::~GLVertexBuffer() { GLCALL(glDeleteBuffers(1, &vertexbufferID_)); } void GLVertexBuffer::Bind() const { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); } void GLVertexBuffer::UnBind() const { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); } void GLVertexBuffer::SetData(const void* data, uint32_t size) { // NOTE(Nghia Lam): Bind Buffer to make sure we set data to the right vertex buffer // Will this impact the performace ? GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(data_usage_))); } void GLVertexBuffer::SetSubData(const void* data, uint32_t size, uint32_t offset) { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferSubData(GL_ARRAY_BUFFER, offset, size, data)); } /// --- GLIndexBuffer GLIndexBuffer::GLIndexBuffer(uint32_t* indices, uint32_t &count) : count_(count) { GLCALL(glGenBuffers(1, &indexbufferID_)); GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_)); GLCALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint32_t), indices, GL_STATIC_DRAW)); } GLIndexBuffer::~GLIndexBuffer() { GLCALL(glDeleteBuffers(1, &indexbufferID_)); } void GLIndexBuffer::Bind() const { GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_)); } void GLIndexBuffer::UnBind() const { GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); } } // namespace Ethan
32.627119
101
0.670909
zZnghialamZz
357aacf63c7d9f507c2fc9dfb197f5d474f336a4
351
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise5.22.cpp // Ad // Rewrite the last example in this section using a loop. #include <iostream> using std::cin; using std::cout; using std::endl; int get_size(); int main() { int sz = get_size(); while (sz <= 0) { sz = get_size(); } // pause cin.get(); return 0; } int get_size() { return -1; }
12.535714
58
0.555556
alaxion
357e438ac93c4bb905bdeb3833a77bd60233f590
2,788
cpp
C++
containers/list/c++/list.cpp
nonkr/cat
754372d0f1a20de5d88aa54f489034478ab61444
[ "MIT" ]
null
null
null
containers/list/c++/list.cpp
nonkr/cat
754372d0f1a20de5d88aa54f489034478ab61444
[ "MIT" ]
null
null
null
containers/list/c++/list.cpp
nonkr/cat
754372d0f1a20de5d88aa54f489034478ab61444
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018, Billie Soong <nonkr@hotmail.com> * All rights reserved. * * This file is under MIT, see LICENSE for details. * * Author: Billie Soong <nonkr@hotmail.com> * Datetime: 2018/3/9 15:11 * */ #include <string> #include <list> #include <iostream> #include <algorithm> using namespace std; void PrintIt(string &StringToPrint) { cout << StringToPrint << endl; } int main() { list<string> lst; if (lst.empty()) { cout << "empty list" << endl; } lst.push_back("b"); lst.push_back("c"); lst.push_front("a"); cout << "list size: " << lst.size() << endl; cout << "list max_size: " << lst.max_size() << endl; cout << "========" << endl; // 遍历方式一 for (auto n : lst) { cout << n << endl; } cout << "========" << endl; // 遍历方式二 list<string>::iterator lstIterator; for (lstIterator = lst.begin(); lstIterator != lst.end(); lstIterator++) { cout << *lstIterator << endl; } cout << "========" << endl; string s = lst.front(); cout << "first: " << s << endl; cout << "========" << endl; lst.pop_front(); string s2 = lst.front(); cout << "first after pop_front: " << s2 << endl; cout << "========" << endl; // 把list的元素倒转 lst.reverse(); // 遍历方式三 for_each(lst.begin(), lst.end(), PrintIt); cout << "========" << endl; list<int> Scores; Scores.push_back(15); Scores.push_back(100); Scores.push_back(5); Scores.push_back(25); Scores.push_back(10); Scores.push_back(100); Scores.push_back(25); Scores.push_back(30); Scores.push_back(20); cout << count(Scores.begin(), Scores.end(), 100) << endl; cout << count_if(Scores.begin(), Scores.end(), [](int i) { return i % 10 == 0; }) << endl; cout << "========" << endl; for (auto n : Scores) { cout << n << endl; } Scores.sort(); cout << "==== after sort() ====" << endl; for (auto n : Scores) { cout << n << endl; } Scores.erase(Scores.begin()); cout << "==== after erase(Scores.begin()) ====" << endl; for (auto n : Scores) { cout << n << endl; } cout << "========" << endl; Scores.remove(25); cout << "==== after remove(25) ====" << endl; for (auto n : Scores) { cout << n << endl; } cout << "========" << endl; Scores.unique(); cout << "==== after unique() ====" << endl; for (auto n : Scores) { cout << n << endl; } cout << "========" << endl; Scores.erase(Scores.begin(), Scores.end()); cout << "==== after erase() ====" << endl; for (auto n : Scores) { cout << n << endl; } cout << "========" << endl; return 0; }
20.651852
94
0.48637
nonkr
357f2fc5c895bbe88e01755584290087338ea20c
3,816
cpp
C++
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt #include "StdAfx.h" #include "FilePickerDialog.h" #include "QtUtil.h" #include "Project.h" #include "QtUtil.h" namespace Armed { ////////////////////////////////////////////////////////////////////////// FilePickerDialog::FilePickerDialog(QWidget* parent) : QDialog(parent) { m_Ui.setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); connect(m_Ui.OkButton, SIGNAL(clicked()), this, SLOT(accept())); connect(m_Ui.CancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(this, SIGNAL(finished(int)), this, SLOT(OnFinished())); connect(m_Ui.ProjectTree, SIGNAL(PathSelected(QString)), this, SLOT(OnPathSelected(QString))); connect(m_Ui.ProjectTree, SIGNAL(doubleClicked(QModelIndex)), m_Ui.OkButton, SLOT(click())); connect(m_Ui.FileName, SIGNAL(textChanged(QString)), this, SLOT(OnPathEdited(QString))); OnPathEdited(""); QSettings settings; settings.beginGroup("FilePickerDialog"); restoreGeometry(settings.value("Geometry").toByteArray()); m_Ui.MainSplitter->restoreState(settings.value("MainSplitter").toByteArray()); settings.endGroup(); } ////////////////////////////////////////////////////////////////////////// FilePickerDialog::~FilePickerDialog() { } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnFinished() { QSettings settings; settings.beginGroup("FilePickerDialog"); settings.setValue("Geometry", saveGeometry()); settings.setValue("MainSplitter", m_Ui.MainSplitter->saveState()); settings.endGroup(); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnPathSelected(const QString& path) { if (QtUtil::NormalizeFileName(path) != QtUtil::NormalizeFileName(m_Ui.FileName->text())) m_Ui.FileName->setText(QDir::toNativeSeparators(path)); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnPathEdited(const QString& path) { bool isValid = false; bool isFile = false; bool isAbs = false; if (!path.isEmpty()) { QString absPath = Project::GetInstance()->GetAbsoluteFileName(path.trimmed()); QFileInfo fileInfo(absPath); if (fileInfo.exists()) { m_Ui.ProjectTree->SetCurrentFile(Project::GetInstance()->GetRelativeFileName(absPath)); isValid = true; isFile = fileInfo.isFile() && m_FilterExtensions.contains(fileInfo.suffix().toLower()); isAbs = QDir::isAbsolutePath(path); } } m_Ui.OkButton->setEnabled(isFile); QPalette palette = m_Ui.FileName->palette(); QColor textColor = Qt::black; if (isValid) { if (isAbs) textColor = Qt::red; } else textColor = Qt::darkGray; palette.setColor(QPalette::Active, QPalette::Text, textColor); m_Ui.FileName->setPalette(palette); } ////////////////////////////////////////////////////////////////////////// QString FilePickerDialog::GetCurrentFile() const { return QDir::fromNativeSeparators(m_Ui.FileName->text().trimmed()); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::SetCurrentFile(const QString& fileName) { m_Ui.FileName->setText(QDir::fromNativeSeparators(fileName)); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::SetFilterTypes(const QString& types) { m_FilterTypes = types.split(";", QString::SkipEmptyParts); QtUtil::FileTypeListToExtList(types, m_FilterExtensions); QStringList masks; qforeach (const QString& ext, m_FilterExtensions) { masks << "*." + ext; } m_Ui.ProjectTree->SetFilters(masks); } } // namespace Armed
30.774194
96
0.604036
retrowork
35815d9343ab23878ef8569e186361f1efda9a3b
4,293
cpp
C++
src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
/* * NeutrinoReconstructionByApproximation.cpp * * Created on: Apr 2, 2012 * Author: lkreczko */ #include "../../interface/ReconstructionModules/NeutrinoReconstructionByApproximation.h" namespace BAT { const double initialBigValue = 123456789; boost::array<ParticlePointer, 2> NeutrinoReconstructionByApproximation::getNeutrinos(unsigned int approximation) { ParticlePointer neutrino(new Particle(initialBigValue, initialBigValue, initialBigValue, initialBigValue)); switch (approximation) { case NeutrinoApproximation::ScalingMETApproximation: neutrino = scalingMETApproximation(); break; case NeutrinoApproximation::SameEtaApproximation: neutrino = sameEtaApproximation(); break; case NeutrinoApproximation::ColinearApproximation: neutrino = colinearApproximation(); break; case NeutrinoApproximation::NullDeltaApproximation: neutrino = nullDeltaApproximation(); break; } boost::array<ParticlePointer, 2> neutrinos; neutrinos.at(0) = neutrino; neutrinos.at(1) = neutrino; return neutrinos; } ParticlePointer NeutrinoReconstructionByApproximation::scalingMETApproximation() { const double WMass(BasicNeutrinoReconstruction::W_mass); double MissingPx(met->px()), MissingPy(met->py()); double MissingPt = met->pt(); double SumPt = MissingPt + leptonFromW->pt(); double SumPx = MissingPx + leptonFromW->px(); double SumPy = MissingPy + leptonFromW->py(); double WTransverseMass = sqrt(SumPt * SumPt - SumPx * SumPx - SumPy * SumPy); double factor = WMass / WTransverseMass; double NewMissingPx = MissingPx * (factor * factor); double NewMissingPy = MissingPy * (factor * factor); MissingPt = sqrt(NewMissingPx * NewMissingPx + NewMissingPy * NewMissingPy); SumPx = NewMissingPx + leptonFromW->px(); SumPy = NewMissingPy + leptonFromW->py(); double alpha = WMass * WMass + SumPx * SumPx + SumPy * SumPy - leptonFromW->energy() * leptonFromW->energy(); double beta = 0.5 * (alpha - MissingPt * MissingPt + leptonFromW->pz() * leptonFromW->pz()); double lambda = 2. * beta * leptonFromW->pz() / (leptonFromW->energy() * leptonFromW->energy() - leptonFromW->pz() * leptonFromW->pz()); double Pz = lambda / 2.; double energy = sqrt(MissingPt * MissingPt + Pz * Pz); ParticlePointer neutrino(new Particle(energy, NewMissingPx, NewMissingPy, Pz)); return neutrino; } ParticlePointer NeutrinoReconstructionByApproximation::sameEtaApproximation() { double Theta = leptonFromW->theta(); double MissingPt(met->pt()); double Phi = met->phi(); //calculate the neutrino momentum based on it's transverse momentum and the leptons theta angle(z, xy-plane) double momentum = MissingPt / sin(Theta); TVector3 Vector; Vector.SetMagThetaPhi(momentum, Theta, Phi); ParticlePointer neutrino(new Particle(momentum, Vector.Px(), Vector.Py(), Vector.Pz())); return neutrino; } ParticlePointer NeutrinoReconstructionByApproximation::colinearApproximation() { double MissingPx(met->px()), MissingPy(met->py()); double leptonPz(leptonFromW->pz()); double energy = sqrt(MissingPx * MissingPx + MissingPy * MissingPy + leptonPz * leptonPz); ParticlePointer neutrino(new Particle(energy, MissingPx, MissingPy, leptonPz)); return neutrino; } ParticlePointer NeutrinoReconstructionByApproximation::nullDeltaApproximation() { const double WMass(BasicNeutrinoReconstruction::W_mass); double MissingPx(met->px()), MissingPy(met->py()), MissingPt(met->pt()); double leptonPz(leptonFromW->pz()), leptonEnergy(leptonFromW->energy()); double SumPx = MissingPx + leptonFromW->px(); double SumPy = MissingPy + leptonFromW->py(); double alpha = WMass * WMass + SumPx * SumPx + SumPy * SumPy - leptonEnergy * leptonEnergy; double beta = 0.5 * (alpha - MissingPt * MissingPt + leptonPz * leptonPz); double lambda = 2. * beta * leptonPz / (leptonEnergy * leptonEnergy - leptonPz * leptonPz); double Pz = lambda / 2.; double energy = sqrt(MissingPt * MissingPt + Pz * Pz); ParticlePointer neutrino(new Particle(energy, MissingPx, MissingPy, Pz)); return neutrino; } NeutrinoReconstructionByApproximation::NeutrinoReconstructionByApproximation(const LeptonPointer lepton, const METPointer met) : BasicNeutrinoReconstruction(lepton, met) { } NeutrinoReconstructionByApproximation::~NeutrinoReconstructionByApproximation() { } }
36.07563
115
0.752853
jjacob
3584bcbedc417d2b523b3629db28d225be9ba9bf
3,579
cpp
C++
src/util/runnable_console_listener.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
10
2018-04-28T04:44:56.000Z
2022-02-06T21:12:13.000Z
src/util/runnable_console_listener.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
null
null
null
src/util/runnable_console_listener.cpp
MelbourneSpaceProgram/msp_flight_software_public
de290a2e7181ac43af1232b2ffbca2db8ec4ecd2
[ "MIT" ]
3
2019-02-16T03:22:26.000Z
2022-02-03T14:54:22.000Z
#include <src/payload_processor/runnable_payload_processor.h> #include <src/sensors/runnable_system_health_check.h> #include <src/telecomms/lithium.h> #include <src/util/message_codes.h> #include <src/util/msp_exception.h> #include <src/util/runnable_console_listener.h> #include <src/util/runnable_console_logger.h> #include <ti/sysbios/BIOS.h> #include <ti/sysbios/knl/Mailbox.h> Uart* RunnableConsoleListener::debug_uart = NULL; RunnableConsoleListener::RunnableConsoleListener(Uart* debug_uart) { if (RunnableConsoleListener::debug_uart == NULL) { // WARNING: This task should only ever READ from the debug UART RunnableConsoleListener::debug_uart = debug_uart; } else { throw MspException( "Only one instance of RunnableConsoleListener should ever be " "instantiated", kConsoleListenerMultipleFail, __FILE__, __LINE__); } } fnptr RunnableConsoleListener::GetRunnablePointer() { return &RunnableConsoleListener::Listen; } bool RunnableConsoleListener::ReadUart(byte* read_buffer, uint8_t size) { return size == debug_uart->PerformReadTransaction(read_buffer, size); } void RunnableConsoleListener::Listen() { while (1) { try { byte header_buffer[5]; byte payload_buffer[Lithium::kMaxReceivedUplinkSize - RunnablePayloadProcessor::kUplinkAx25Length]; // Grab sync characters (first two bytes of header/packet) one char // at a time. Not two at a time so we can 'burn off' additional // characters and regain sync if (!ReadUart(header_buffer, 1)) continue; if (header_buffer[0] != RunnableConsoleLogger::kMeasurableLoggerSyncChar1) { continue; } if (!ReadUart(header_buffer + 1, 1)) continue; if (header_buffer[1] != RunnableConsoleLogger::kMeasurableLoggerSyncChar2) { continue; } if (!ReadUart(header_buffer + 2, 1)) continue; // size if (header_buffer[2] == 0) continue; if (!ReadUart(header_buffer + 3, 1)) continue; // id if (!ReadUart(header_buffer + 4, 1)) continue; // TODO(dingbenjamin): Implement checksum if (!ReadUart(payload_buffer, header_buffer[2])) continue; // TODO(dingbenjamin): Do something with the size byte: // header_buffer[2] switch (header_buffer[3]) { case kPayloadProcessorInjection: // Create fake AX.25 bytes for the payload processor to // throw away byte fake_ax25_payload [sizeof(payload_buffer) + RunnablePayloadProcessor::kUplinkAx25Length]; memset(fake_ax25_payload, 0x00, RunnablePayloadProcessor::kUplinkAx25Length); memcpy(fake_ax25_payload + RunnablePayloadProcessor::kUplinkAx25Length, payload_buffer, Lithium::kMaxReceivedUplinkSize - RunnablePayloadProcessor::kUplinkAx25Length); Mailbox_post(Lithium::GetInstance()->GetUplinkMailbox(), fake_ax25_payload, BIOS_WAIT_FOREVER); } } catch (MspException& e) { MspException::LogTopLevelException(e, kRunnableConsoleLoggerCatch); } } }
39.32967
79
0.605197
MelbourneSpaceProgram
3585618ed34f4961ccc77b2e7dd5e0f6ecb06a89
885
cpp
C++
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*FENCE1 - Build a Fence #math There is a wall in your backyard. It is so long that you can’t see its endpoints. You want to build a fence of length L such that the area enclosed between the wall and the fence is maximized. The fence can be of arbitrary shape, but only its two endpoints may touch the wall. Input The input consists of several test cases. For every test case, there is only one integer L (1<=L<=100), indicating the length of the fence. The input ends with L=0. Output For each test case, output one line containing the largest area. Your answer should be rounded to 2 digits after the decimal point. Example Input: 1 0 Output: 0.16 */ #include <cmath> #include <iomanip> #include <iostream> int main() { for (int l; std::cin >> l && l !=0;) { std::cout << std::setprecision(2) << std::fixed << l*l / (std::atan(1) * 8) << std::endl; } }
23.918919
276
0.693785
ravirathee
358565336bad30a16789c0389cdf37d969dfd7d7
478
hpp
C++
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2015 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef HG_PACKDATA #define HG_PACKDATA namespace hg { struct PackData { std::string id, name; float priority; PackData( const std::string& mId, const std::string& mName, float mPriority) : id{mId}, name{mName}, priority{mPriority} { } }; } #endif
20.782609
78
0.60251
mehlon
3586b02ccae01f85d6954123e95c028070b1f195
4,407
cpp
C++
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
null
null
null
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
null
null
null
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
1
2020-12-14T11:52:04.000Z
2020-12-14T11:52:04.000Z
#include <iostream> using namespace std; void variant1(), variant2(), variant3(), variant4(), variant5(), variant6(), variant7(), variant8(), variant9(), variant10(); int main() { int numEx; setlocale(0, ""); while (true) { cout << "\nВведите вариант узора (0 - 10): " << endl; cin >> numEx; switch (numEx) { case 1: variant1(); break; case 2: variant2(); break; case 3: variant3(); break; case 4: variant4(); break; case 5: variant5(); break; case 6: variant6(); break; case 7: variant7(); break; case 8: variant8(); break; case 9: variant9(); break; case 10: variant10(); break; } } } void variant1() { int i = 0, j = 0, k = 0, col = 10; while (0 < col) { i++; col -= 1; j = 0; while (j <= col) { j++; cout << " * "; } cout << endl; k = 0; while (k < i) { cout << " "; k++; } } } void variant2() { int i = 0, j, col = 10; while (i < col) { i++; j = 0; while (j < i) { j++; cout << " * "; } cout << endl; } } void variant3() { int i = 0, j, k, b, col = 10; while (0 <= col ) { i++; col -= 2; j = 0; while (j <= col) { j++; cout << " * "; } cout << endl; k = 0; while (k < i) { cout << " "; k++; } } } void variant4() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((!(i >= n) && !(i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant5() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((!(i >= n) && !(i + n <= col)) || ((i >= n) && (i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant7() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if (i <= n && (i + n ) <= col) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant6() { int n = 0, i = 0, col = 9; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((i <= n && (i + n - 1) <= col) || (i >= n && !(i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant8() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((i >= n && !(i + n - 1 <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant10() { int i = 0, j = 0, k = 0, col = 10; while (0 < col) { i++; col -= 1; k = 0; while (k < i - 1) { k++; cout << " * "; } cout << endl; j = 0; while (j <= col) { cout << " "; j++; } } } void variant9() { int i = 0, j, k, col = 10; while (i < col) { i++; k = i; while (k <= col) { k++; cout << " * "; } cout << endl; } }
17.557769
81
0.256637
pashak14
3587c88b7d11dc508d9a24ec8758b390be867c65
20,157
cc
C++
src/core/rnn/CustomLayers.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
34
2017-03-01T05:49:17.000Z
2022-01-01T15:30:06.000Z
src/core/rnn/CustomLayers.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
1
2018-12-19T17:02:52.000Z
2018-12-19T17:02:52.000Z
src/core/rnn/CustomLayers.cc
junosan/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
24
2017-09-19T01:51:50.000Z
2022-02-04T19:53:16.000Z
/* Copyright 2017 Hosang Yoon 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 "CustomLayers.h" #include <string> namespace fractal { void AddLstmLayer_ForgetOneInit(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ ConnParam initParam(initWeightParam); initParam.dstRangeFrom = 0; initParam.dstRangeTo = size - 1; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); initParam.dstRangeFrom += size; initParam.dstRangeTo += size; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); InitWeightParamUniform oneInitParam; oneInitParam.a = 1.0; oneInitParam.b = 1.0; oneInitParam.isValid = true; ConnParam oneParam(oneInitParam); oneParam.dstRangeFrom = 2 * size; oneParam.dstRangeTo = 3 * size - 1; rnn.AddConnection(biasLayer, prefix + "INPUT", oneParam); initParam.dstRangeFrom += 2 * size; initParam.dstRangeTo += 2 * size; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddResGateLayer(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long size) { // out = in_r * sig(k) + in_1 * (1 - sig(k)) // in_r : residual (output of layer just below) // in_1 : identity (input of layer just below) // assumes in_r.size == in_1.size const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT_R" , ACT_LINEAR , AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_1" , ACT_LINEAR , AGG_MULT, size); rnn.AddLayer(prefix + "SWITCH_R", ACT_SIGMOID , AGG_SUM , size); rnn.AddLayer(prefix + "SWITCH_1", ACT_ONE_MINUS_LINEAR, AGG_SUM , size); rnn.AddLayer(prefix + "OUTPUT" , ACT_LINEAR , AGG_SUM , size); InitWeightParamUniform minusOne; // biased towards identity initially minusOne.a = -1.0; minusOne.b = -1.0; minusOne.isValid = true; rnn.AddConnection(biasLayer , prefix + "SWITCH_R", minusOne); rnn.AddConnection(prefix + "SWITCH_R", prefix + "SWITCH_1", CONN_IDENTITY); rnn.AddConnection(prefix + "SWITCH_R", prefix + "INPUT_R", CONN_IDENTITY); rnn.AddConnection(prefix + "SWITCH_1", prefix + "INPUT_1", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_R", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_1", prefix + "OUTPUT", CONN_IDENTITY); } void AddLstmLayer_LearnInit(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum // switch between init & prev states // reset = 1. (use init states) or 0. (use prev states) { rnn.AddLayer(prefix + "RESET", ACT_LINEAR , AGG_SUM, 1); rnn.AddLayer(prefix + "CARRY", ACT_ONE_MINUS_LINEAR, AGG_SUM, 1); rnn.AddConnection(prefix + "RESET", prefix + "CARRY", CONN_IDENTITY); rnn.AddLayer(prefix + "MEMORY_CELL_INIT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL_PREV", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_INIT" , ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_PREV" , ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(biasLayer, prefix + "MEMORY_CELL_INIT", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_INIT" , initWeightParam); rnn.AddConnection(prefix + "RESET", prefix + "MEMORY_CELL_INIT", CONN_BROADCAST); rnn.AddConnection(prefix + "CARRY", prefix + "MEMORY_CELL_PREV", CONN_BROADCAST); rnn.AddConnection(prefix + "RESET", prefix + "OUTPUT_INIT" , CONN_BROADCAST); rnn.AddConnection(prefix + "CARRY", prefix + "OUTPUT_PREV" , CONN_BROADCAST); rnn.AddConnection(prefix + "MEMORY_CELL_INIT", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL_PREV", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_INIT" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_PREV" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY); } ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); // selfLoop { rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddLstmLayer_DSigmoidOut(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SIGMOID", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_ONE_MINUS_SIGMOID", ACT_ONE_MINUS_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_DSIGMOID", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_ONE_MINUS_SIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_ONE_MINUS_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_DSIGMOID", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddOELstmLayer(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; verify(size % 2 == 0); rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); // 1D weights (input bias & peephole) are added by the internal layers // 2D weights (below-to-input & feedback) are added outside basicLayers::AddFastLstmLayer(rnn, prefix + "OLSTM", biasLayer, 1, size / 2, false, initWeightParam); AddLstmLayer_DSigmoidOut (rnn, prefix + "ELSTM", biasLayer, 1, size / 2, false, initWeightParam); /* Connect "RESET" to * "OLSTM.MEMORY_CELL.DELAYED" and "ELSTM.MEMORY_CELL.DELAYED" directly * * Otherwise, cannot function with "RESET" removed for inference */ rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_SUM, size); ConnParam srcParam(CONN_IDENTITY); srcParam.srcRangeFrom = 0; srcParam.srcRangeTo = 2 * size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "OLSTM.INPUT", srcParam); srcParam.srcRangeFrom += 2 * size; srcParam.srcRangeTo += 2 * size; rnn.AddConnection(prefix + "INPUT", prefix + "ELSTM.INPUT", srcParam); // // relay reset signal // rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size); // // srcParam.srcRangeFrom = 0; // srcParam.srcRangeTo = size / 2 - 1; // rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", // prefix + "OLSTM.MEMORY_CELL.DELAYED", srcParam); // // srcParam.srcRangeFrom += size / 2; // srcParam.srcRangeTo += size / 2; // rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", // prefix + "ELSTM.MEMORY_CELL.DELAYED", srcParam); ConnParam dstParam(CONN_IDENTITY); dstParam.dstRangeFrom = 0; dstParam.dstRangeTo = size / 2 - 1; rnn.AddConnection(prefix + "OLSTM.OUTPUT", prefix + "OUTPUT", dstParam); dstParam.dstRangeFrom += size / 2; dstParam.dstRangeTo += size / 2; rnn.AddConnection(prefix + "ELSTM.OUTPUT", prefix + "OUTPUT", dstParam); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } }
49.283619
126
0.674406
arjun-k-r
358c3223168f206b6db3f4686d2072394f2d571e
648
cpp
C++
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
#include<stdio.h> using namespace std; long long A,B,C; bool check(){ if(A>0 && B>0 && C>0) return A>C-B; if(A<0 && B<0 && C<0) return A>C-B; if(A>0 && B>0 && C<0) return true; if(A<0 && B<0 && C>0) return false; return A+B>C; } int main(void) { // freopen("in.txt","r",stdin); int T; scanf("%d",&T); for(int I=1;I<=T;I++){ printf("Case #%d: ",I); scanf("%lld%lld%lld",&A,&B,&C); if(check()) puts("true"); else puts("false"); } return 0; } /* 4 1 2 3 2 3 4 2147483647 0 2147483646 0 -2147483648 -2147483647 Case #1: false Case #2: true Case #3: true Case #4: false */
16.615385
39
0.512346
iphelf
358d183c0e807d86a5d58dda48fdd53de75f73d3
11,928
cpp
C++
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
#include <common/stdint.h> #include <boot/bootinfo.h> #include <pointers.h> #include <IO/APIC/apic.h> //COMMENT #include <smp/smp.h> //COMMENT #include <gdt/gdt.h> #include <gdt/tss.h> //COMMENT #include <paging/PageTableManager.h> #include <paging/PageFrameAllocator.h> #include <memory/memory.h> #include <memory/heap.h> #include <process/Scheduler/Scheduler.h> //Comment (INCLUDES PROCESSES) #include <interrupts/interrupts.h> #include <exceptions/exceptions.h> #include <interrupts/syscalls.h> //Comment #include <interrupts/timer/pit.h> #include <drivers/Driver.h> #include <drivers/Intel/AHCI/AHCI.h> #include <IO/DeviceManager/DeviceManager.h> //Comment #include <fs/VolumeManager.h> //Comment #include <drivers/Input/PS2KeyboardDriver.h> #include <drivers/Input/PS2MouseDriver.h> #include <common/stdio.h> #include <common/cstring.h> using namespace UnifiedOS; using namespace UnifiedOS::Boot; using namespace UnifiedOS::GlobalDescriptorTable; using namespace UnifiedOS::Paging; using namespace UnifiedOS::Memory; using namespace UnifiedOS::Processes; using namespace UnifiedOS::Interrupts; using namespace UnifiedOS::Exceptions; using namespace UnifiedOS::Interrupts::Syscalls; using namespace UnifiedOS::Interrupts::Timer; using namespace UnifiedOS::Drivers; using namespace UnifiedOS::Devices; using namespace UnifiedOS::FileSystem; //SOMETHING TO HAVE A LOOK INTO FOR MAXIMUM MEMORY EFFICIENCY //Look over code and make sure all needed * are kept but all un needed get removed // (delete pointer) // // // // #include <files/tga.h> #include <interrupts/syscall.h> void InitVolumes(DriverManager* driverM){ //NOTE //TRY TO SETUP WITH LOOKING TO SEE IF THE VOLUME //Locate Driver Driver* driver = driverM->FindDriver("ACPI 1.0 Driver"); //Ensure Driver Found if(driver != nullptr){ //Convert to AHCI if(driver->MainObject != nullptr){ Drivers::AHCI::AHCIDriver* AHCIdriver = (Drivers::AHCI::AHCIDriver*)(driver->MainObject); //Look at ports for(int p = 0; p < AHCIdriver->portCount; p++){ //Find Disks if(AHCIdriver->Ports[p]->portType == AHCI::AHCIPort::PortType::SATA){ //Mount __FS_VOLUME_MANAGER__->MountVolume(AHCIdriver->Ports[p]); } } } } } void DrawBootScreen(){ Clear(0x00); //Read the icon file GeneralFile* File = syscall(6, "B:/UnifiedIcon.tga"); //If the file is found displat the logo if(File->Found){ uint8_t* Buffer = (uint8_t*)Memory::malloc(__BOOT__BootContext__->framebuffer->BufferSize); File->Disk->Read((File->Sectors[0]*512), File->FileSize, Buffer); //Recode this! TGA_Image image = TGA().GetImage(Buffer); Memory::free(Buffer); //Work out system center uint64_t xoff = (__BOOT__BootContext__->framebuffer->Width / 2) - (image.header.width / 2); uint64_t xoffText = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Loading System") * 16) / 4); uint64_t xoffText1 = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Unified OS: Version 0.0.1") * 16) / 4); uint64_t yoff = (__BOOT__BootContext__->framebuffer->Height / 4) - (image.header.width / 2); uint64_t yoffText = ((__BOOT__BootContext__->framebuffer->Height / 2)) - 8; for(int y = image.header.height - 1; y >= 0; y--){ for(int x = image.header.width - 1; x >= 0; x--){ putPix(x + xoff, (image.header.height - 1) - y + yoff, image.Buffer[(y * image.header.width) + x]); } } //Print boot SetPosX(xoffText); SetPosY(yoffText); printf("Loading System\n"); SetPosX(xoffText1); printf("Unified OS: Version 0.0.1"); SetPosX(0); SetPosY(0); //Delete Image Data after delete image.Buffer; } } void KernelStage2(){ //Volumes InitVolumes(Pointers::Drivers::DriverManager); //GP FAULT CAUSED HERE... ^ on real hardware // PS2Init(); //Real hardware is to be imagined right now with how this works //Create Boot Screen DrawBootScreen(); // TestTGA(); //Load System Modules while (true) { /* code */ } } //For locking the memory at the kernel extern uint64_t _KernelStart; extern uint64_t _KernelEnd; void InitialisePaging(){ //Entries (Pages) uint64_t mMapEntries = __BOOT__BootContext__->mMapSize / __BOOT__BootContext__->DescriptorSize; //Load Memory To Page Frame Allocator __PAGING__PFA_GLOBAL = PageFrameAllocator(); __PAGING__PFA_GLOBAL.ReadEFIMemoryMap(__BOOT__BootContext__->mMap, __BOOT__BootContext__->mMapSize, __BOOT__BootContext__->DescriptorSize); uint64_t SizeOfKernel = (uint64_t)&_KernelEnd - (uint64_t)&_KernelStart; uint64_t PageCountOfKernel = (uint64_t)SizeOfKernel / 0x1000 + 1; //Lock memory pages at kernel positions __PAGING__PFA_GLOBAL.LockPages(&_KernelStart, PageCountOfKernel); //Get a Page for the Page Table Manager PageTable* PML4 = (PageTable*)__PAGING__PFA_GLOBAL.RequestPage(); //Fill it with zero to stop any issues with default memset(PML4, 0, 0x1000); //Setup the page table manager __PAGING__PTM_GLOBAL = PageTableManager(PML4); //Map memory addresses to default for(uint64_t t = 0; t < __PAGING__TotalMemorySize__; t+=0x1000){ //We do this in 4KiB Pages __PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t); } //Lock Framebuffer Pages uint64_t FramebufferBase = (uint64_t)__BOOT__BootContext__->framebuffer->BaseAddress; uint64_t FramebufferSize = (uint64_t)__BOOT__BootContext__->framebuffer->BufferSize + 0x1000; //We add this is a padding __PAGING__PFA_GLOBAL.LockPages((void*)FramebufferBase, FramebufferSize / 0x1000 + 1); // +1 just incase not entire fit //Map the framebuffer address for(uint64_t t = FramebufferBase; t < FramebufferBase + FramebufferSize; t+=4096){ //We do this in 4KiB Pages __PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t); } //Load the Page Table asm("mov %0, %%cr3" : : "r" (PML4)); } // inline void WaitSignal() { // IO::Port8Bit CommandPort(0x64); // int timeout = 10000; // while (timeout--) // if ((CommandPort.Read() & 0x2) != 0x2) // return; // } // // template <bool isMouse> inline void WaitData() { // IO::Port8Bit CommandPort(0x64); // int timeout = 10000; // while (timeout--) // if ((CommandPort.Read() & 0x21) == (isMouse ? 0x21 : 0x1)) // return; // } // // void PS2Init(){ // IO::Port8Bit DataPort(0x60); // IO::Port8Bit CommandPort(0x64); // IO::Port8Bit PITMaster(0x20); // // // Start by disabling both ports // WaitSignal(); // CommandPort.Write(0xAD); // WaitSignal(); // CommandPort.Write(0xA7); // // DataPort.Read(); // Discard any data // // WaitSignal(); // CommandPort.Write(0x20); // WaitData<false>(); // uint8_t status = PITMaster.Read(); // // WaitSignal(); // CommandPort.Write(0xAE); // WaitSignal(); // CommandPort.Write(0xA8); // // // Enable interrupts, enable keyboard and mouse clock // status = ((status & ~0x30) | 3); // WaitSignal(); // CommandPort.Write(0x60); // WaitSignal(); // CommandPort.Write(status); // WaitData<false>(); // DataPort.Read(); // } extern "C" void kernelMain(BootInfo* bootInfo) { __BOOT__BootContext__ = bootInfo; //Blank Screen Clear(0x00); //Detect SMP cores test //I Dont know why (I think a delay effect) but whenever I remove the prints //It stops working??? printf("SMP APIC: \n"); IO::APIC::ReadAPIC(); printf("Found "); printf(to_string((int64_t)IO::APIC::CoreCount)); printf(", IOAPIC "); printf(to_hstring(IO::APIC::IOAPIC_PTR)); printf(", LAPIC "); printf(to_hstring(IO::APIC::LAPIC_PTR)); printf(", Processor IDs: "); for(int i = 0; i < IO::APIC::CoreCount; i++){ printf(to_string((int64_t)IO::APIC::LAPIC_IDs[i])); printf(" "); } printf("\n"); //Memory InitialisePaging(); //GDT LoadGDT(&__GDTDesc); //Heap //We use a high address to not interrupt other addresses //Yes this can lead to issues such as what if we reach the heap and overwrite it //Im not sure how I can fix that its just how it is. Well I suppose the pages will be locked //So its not too much of an issue. InitialiseHeap((void*)0x0000100000000000, 0xFF); //Interrupts (Default) Pointers::Interrupts::Interrupts = new InterruptManager(); //Syscalls Pointers::Interrupts::Syscalls::Syscalls = new SyscallHandler(Pointers::Interrupts::Interrupts); //Intialise Exceptions Pointers::Exceptions::Exceptions = new ExceptionManager(Pointers::Interrupts::Interrupts); //Drivers Pointers::Drivers::DriverManager = new DriverManager(); //Devices Pointers::Devices::DeviceManager = new DeviceManager(Pointers::Drivers::DriverManager); // //Keyboard Driver MAKE USING new // PrintfKeyboardEventHandler KeyboardHandler; // PS2KeyboardDriver keyboard(Pointers::Interrupts::Interrupts, &KeyboardHandler); // Pointers::Drivers::DriverManager->AddDriver(&keyboard); // //Mouse Driver MAKE USING new // MouseToScreen MouseHandler; // PS2MouseDriver mouse(Pointers::Interrupts::Interrupts, &MouseHandler); // Pointers::Drivers::DriverManager->AddDriver(&mouse); //Activate Drivers //SETUP NOTE: Make it so when a driver is called to activate it check if already ative and ignores if active //To allow for more drivers to be loaded after this boot Pointers::Drivers::DriverManager->ActivateAll(); //PIT __TIMER__PIT__ = new PIT(Pointers::Interrupts::Interrupts); __TIMER__PIT__->SetFrequency(1000); //INACURRATE //ERRORS WITH PIT MAPPING ON MODERN HARDWARE //Dissable PIC Pointers::Interrupts::Interrupts->DissablePIC(); //APIC NOTE //Sometimes the interrupts do not register which is an issue (With PIT) //As this will cause the smp to fail to initialise //However this only seems to be with qemu not real hardware //APIC Inits //Spurious Interrupt IO::APIC::SpuriousInterrupHandler* SpuriousInterupts = new IO::APIC::SpuriousInterrupHandler(Pointers::Interrupts::Interrupts); IO::APIC::LApicInit(); IO::APIC::IntitateIO(); IO::APIC::MapLegacyIRQ(0x01); //PS2 Keyboard IO::APIC::MapLegacyIRQ(0x0C); //PS2 Mouse //Interrupts activation Pointers::Interrupts::Interrupts->Activate(); //SMP //Will now boot all the cpu's that are not booted. //64-Bit gets toggled with gdt //Interrupts are synced SMP::Intitialise(); printf("All "); printf(to_string((int64_t)SMP::ActiveCPUs)); printf(" Have Been Booted!\n\n"); //Issues here with real hardware: //Either SMP fails to exit (I presume TSS) //Or somthing wrong with the preparation of the SMP Trampoline just not working (well working but breaking everything else) //Scheduling has issues with process swapping and all of that swaps //Processes Scheduling::IntialiseScheduler(Pointers::Interrupts::Interrupts, (uint64_t)KernelStage2); //CAUSES ISSUES (REAL HARDWARE Div by zero Exception) // Process* proctest = Scheduling::__SCHEDULER__->NewProcess("TestProcess", (uint64_t)TaskA, 0); //All issues I thought are actually TSS issues //TYPES //User space (NEED TO IMPLEMENT) (https://wiki.osdev.org/Getting_to_Ring_3) // This will also need to link to system calls for userspace to reach //Kernel space (This) // KernelStage2(); while(true){ // printf("Task Kernel...\n"); // asm("hlt"); //Saves performance } }
31.0625
147
0.662726
Unified-Projects
358d5a54c7d047a78830dec29366b630d8df5df2
3,404
cpp
C++
data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
14
2015-02-28T17:11:23.000Z
2016-09-05T05:00:20.000Z
data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#include <Share.h> #include <bps/event.h> #include <bps/navigator.h> #include <bps/navigator_invoke.h> #include <screen/screen.h> #include <string.h> #include <string> #include <unistd.h> #include <vector> using namespace std; namespace openflShareExtension { void log(const char *msg) { /* FILE *logFile = fopen("logs/log.txt", "a"); fprintf(logFile, "%s\n", msg); fclose(logFile); */ } void doShare(const char *method, const char *text) { navigator_invoke_invocation_t *invoke = NULL; navigator_invoke_invocation_create(&invoke); navigator_invoke_invocation_set_action(invoke, "bb.action.SHARE"); navigator_invoke_invocation_set_data(invoke, text, strlen(text)); navigator_invoke_invocation_set_target(invoke, method); navigator_invoke_invocation_set_type(invoke, "text/plain"); navigator_invoke_invocation_send(invoke); navigator_invoke_invocation_destroy(invoke); } vector<ShareQueryResult> query() { /* FILE *logFile = fopen("logs/log.txt", "w"); fclose(logFile); char msg[64]; */ /* snprintf(msg, 64, "pid %d\n", getpid()); log(msg); */ vector<ShareQueryResult> results; navigator_invoke_query_t *query = NULL; navigator_invoke_query_create(&query); navigator_invoke_query_set_id(query, "12345"); navigator_invoke_query_set_action(query, "bb.action.SHARE"); navigator_invoke_query_set_type(query, "text/plain"); if (navigator_invoke_query_send(query)!=BPS_SUCCESS) { log("navigator_invoke_query_send Failed"); } bps_event_t *event = NULL; do { bps_get_event(&event, -1); /* snprintf(msg, 64, "query result %#04x\n", bps_event_get_code(event)); log(msg); */ } while ( navigator_get_domain()!=bps_event_get_domain(event) || bps_event_get_code(event)!=NAVIGATOR_INVOKE_QUERY_RESULT ); // create integer holding the number of actions returned by the query int action_count = navigator_invoke_event_get_query_result_action_count(event); // loop listing all actions returned by the query for (int i=0; i<action_count; i++) { const navigator_invoke_query_result_action_t *action = navigator_invoke_event_get_query_result_action(event, i); // retrieve action attributes const char *name = navigator_invoke_query_result_action_get_name(action); const char *icon = navigator_invoke_query_result_action_get_icon(action); const char *label = navigator_invoke_query_result_action_get_label(action); // create integer holding the number of targets in the action int target_count = navigator_invoke_query_result_action_get_target_count(action); // loop listing all targets in the action for (int j=0; j < target_count; j++) { const navigator_invoke_query_result_target_t *target = navigator_invoke_query_result_action_get_target(action, j); if (target==NULL) { log("target is null!"); } // retrieve target attributes ShareQueryResult result; const char *key = navigator_invoke_query_result_target_get_key(target); const char *icon = navigator_invoke_query_result_target_get_icon(target); const char *label = navigator_invoke_query_result_target_get_label(target); strcpy(result.key, key); strcpy(result.icon, icon); strcpy(result.label, label); results.push_back(result); } } navigator_invoke_query_destroy(query); return results; } }
24.314286
72
0.730317
harshp8l
358d5cd6ea327f28e023717bcbd1d58fdbaee75e
26,828
cpp
C++
src/plugins/intel_gna/runtime/pwl.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/plugins/intel_gna/runtime/pwl.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/plugins/intel_gna/runtime/pwl.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // // pwl_design.cpp : simple activation function designer // #include <vector> #include <iostream> #include <limits> #include <cstdint> #include <algorithm> #ifdef _NO_MKL_ #include <cmath> #include "backend/make_pwl.hpp" #define SCOPY(num, in, inci, out, inco) for (int i_ = 0; i_ < *(num); i_++) *(out + i_ * *(inco)) = *(in + i_ * *(inci)); #define SSCAL(num, scale, inout, inco) for (int i_ = 0; i_ < *(num); i_++) *(inout + i_ * *(inco)) = *(scale) * *(inout + i_ * *(inco)); #define TANH(num, in, out) for (int i_ = 0; i_ < num; i_++) *(out+i_) = tanh(*(in+i_)) #else #include <mkl.h> #define SCOPY(num, in, incx, out, incy) scopy(num, in, incx, out, incy) #define SSCAL(num, scale, inout, incx) sscal(num, scale, inout, incx) #define TANH(num, in, out) vsTanh(num, in, out) #endif #include "pwl.h" #include "gna_plugin_log.hpp" #include "gna_slope_scale.h" #include "round_float_define.hpp" #include "ops/reference/pwl.hpp" double relu(const double x) { if (x < 0) { return(0.0); } else { return(x); } } double leaky_relu(const double x) { if (x < 0.0) { return(LEAKYRELU_SLOPE*x); } else { return(x); } } double clipping(const double x, const double lbound, const double ubound) { return((x < lbound)?lbound:((x > ubound)?ubound:x)); } inline double power(const double x, const std::tuple<double, double, double>& args) { return (pow(std::get<2>(args) + std::get<1>(args) * x, std::get<0>(args))); } void PwlDesignOpt(const DnnActivation& activation_type, std::vector<gna_pwl_segment_t> &ptr_segment, const float scale_in, const float scale_out, const bool low_precision, const std::shared_ptr<ngraph::Node>& node) { std::vector<pwl_t> pwl; switch (activation_type) { case kActPwl: { make_gna_pwl(node, scale_in, scale_out, low_precision, ptr_segment); break; } case kActRelu: make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment); break; case kActLeakyRelu: make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment); break; case kActIdentity: case kActFakeQuantize: make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment); break; case kActKaldiLstmClipping: make_gna_pwl(activation_type, pwl, activation_type.args.clamp.low, activation_type.args.clamp.high, scale_in, scale_out, low_precision, ptr_segment); break; case kActSign: make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment); break; case kActAbs: make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment); break; default: THROW_GNA_EXCEPTION << "Unknown piecewise linear function type: " << activation_type.type; } } void PwlDesign(const DnnActivation& activation_type, gna_pwl_segment_t *ptr_segment, const uint32_t num_segments, const float scale_in, const float scale_out, const bool low_precision) { switch (activation_type) { case kActSigmoid: { gnalog() << "=========================== Sigmoid Segments===========================\n"; uint32_t num_segment_size = 0; int32_t offset = 0; ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb num_segment_size = static_cast<int32_t>(SIGMOID_DOMAIN * scale_in / ((num_segments-2) / 2) + 0.5); offset = -static_cast<int32_t>(num_segment_size * (num_segments-2) / 2); for (uint32_t i = 1; i < num_segments; i++) { ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb offset += num_segment_size; } for (uint32_t i = 0; i < num_segments; i++) { int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK); int32_t xbasenext = (i < num_segments-1) ? static_cast<int32_t>(ptr_segment[i+1].xBase & XBASEMASK) : INT32_MAX; float floatarg = static_cast<float>(xbase / (2 * scale_in)); float floatargnext = static_cast<float>(xbasenext / (2 * scale_in)); float floatval, floatvalnext, slope; TANH(1, &floatarg, &floatval); floatval = 0.5f * (1.0f + floatval); TANH(1, &floatargnext, &floatvalnext); floatvalnext = 0.5f * (1.0f + floatvalnext); slope = scale_out*(floatvalnext - floatval) / static_cast<float>(xbasenext - xbase); { // find best scale factor uint64_t slope_scale; uint32_t slope_scale_index; for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) { slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0)) break; } slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale); ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index; } ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out); gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK))/scale_out) << " " << (static_cast<float>((ptr_segment[i].yBase))/scale_out) << " " << (slope/scale_out) << "\n"; } } break; case kActTanh: { gnalog() << "=========================== Tanh Segments===========================\n"; uint32_t num_segment_size = 0; int32_t offset = 0; ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb num_segment_size = static_cast<int32_t>(TANH_DOMAIN * scale_in / ((num_segments-2) / 2) + 0.5); offset = -static_cast<int32_t>(num_segment_size * (num_segments-2) / 2); for (uint32_t i = 1; i < num_segments; i++) { ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb offset += num_segment_size; } for (uint32_t i = 0; i < num_segments; i++) { int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK); int32_t xbasenext = (i < num_segments-1) ? static_cast<int32_t>(ptr_segment[i+1].xBase & XBASEMASK) : INT32_MAX; float floatarg = static_cast<float>(xbase / scale_in); float floatargnext = static_cast<float>(xbasenext / scale_in); float floatval, floatvalnext, slope; TANH(1, &floatarg, &floatval); TANH(1, &floatargnext, &floatvalnext); slope = scale_out * (floatvalnext - floatval) / static_cast<float>(xbasenext - xbase); { // find best scale factor uint64_t slope_scale; uint32_t slope_scale_index; for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) { slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0)) break; } slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale); ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index; } ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out); gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK))/scale_out) << " " << (static_cast<float>((ptr_segment[i].yBase))/scale_out) << " " << (slope/scale_out) << "\n"; } } break; case kActSoftSign: { auto softsign = [](const double x) { return(x / (1.0 + fabs(x))); }; gnalog() << "=========================== SoftSign Segments===========================\n"; uint32_t num_segment_size = 0; int32_t offset = 0; ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb num_segment_size = static_cast<int32_t>(SOFTSIGN_DOMAIN * scale_in / ((num_segments - 2) / 2) + 0.5); offset = -static_cast<int32_t>(num_segment_size * (num_segments - 2) / 2); for (uint32_t i = 1; i < num_segments; i++) { ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb offset += num_segment_size; } for (uint32_t i = 0; i < num_segments; i++) { int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK); int32_t xbasenext = (i < num_segments - 1) ? static_cast<int32_t>(ptr_segment[i + 1].xBase & XBASEMASK) : INT32_MAX; float floatarg = static_cast<float>(xbase / (2 * scale_in)); float floatargnext = static_cast<float>(xbasenext / (2 * scale_in)); float floatval, floatvalnext, slope; floatval = softsign(floatarg); floatvalnext = softsign(floatargnext); slope = scale_out * (floatvalnext - floatval) / static_cast<float>(xbasenext - xbase); { // find best scale factor uint64_t slope_scale; uint32_t slope_scale_index; for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) { slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0)) break; } slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale); ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index; } ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out); gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK)) / scale_out) << " " << (static_cast<float>((ptr_segment[i].yBase)) / scale_out) << " " << (slope / scale_out) << "\n"; } } break; case kActRelu: THROW_GNA_EXCEPTION << "Rectilinear activation function design not yet implemented!"; case kActIdentity: case kActKaldiLstmClipping: // clipping of IDENTITY is more aggressive than Kaldi { float slope = 0.0; int64_t x_lower_limit = static_cast<int64_t>((INT16_MIN / scale_out) * scale_in - 0.5); int64_t x_upper_limit = static_cast<int64_t>((INT16_MAX / scale_out) * scale_in + 0.5); int16_t y_lower_limit = INT16_MIN; int16_t y_upper_limit = INT16_MAX; if (activation_type == kActKaldiLstmClipping) gnalog() << "=========================== Clipping Segments ===========================\n"; else gnalog() << "=========================== Identity Segments ===========================\n"; if (x_lower_limit < INT32_MIN) { std::cerr << "Warning: saturation in PwlDesign! " << x_lower_limit << " < INT32_MIN"<< std::endl; x_lower_limit = INT32_MIN; y_lower_limit = static_cast<int16_t>((scale_out / scale_in)*static_cast<float>(INT32_MIN) - 0.5); } if (x_upper_limit > INT32_MAX) { std::cerr << "Warning: saturation in PwlDesign! " << x_upper_limit << " > INT32_MAX"<< std::endl; x_upper_limit = INT32_MAX; y_upper_limit = static_cast<int16_t>((scale_out / scale_in)*static_cast<float>(INT32_MAX) + 0.5); } slope = static_cast<float>(static_cast<uint64_t>(y_upper_limit) - static_cast<uint64_t>(y_lower_limit)) / static_cast<float>(static_cast<uint64_t>(x_upper_limit) - static_cast<uint64_t>(x_lower_limit)); ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb ptr_segment[0].yBase = y_lower_limit; ptr_segment[0].slope = 0; gnalog() << ptr_segment[0].xBase / scale_in << " " << ptr_segment[0].yBase / scale_out << " " << 0 << "\n"; ptr_segment[1].xBase = static_cast<int32_t>(x_lower_limit & XBASEMASK); ptr_segment[1].yBase = y_lower_limit; { // find best scale factor uint64_t slope_scale = 0; uint32_t slope_scale_index = 0; for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) { slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); if (((slope * slope_scale) <= std::numeric_limits<int16_t>::max()) && ((slope * slope_scale) >= std::numeric_limits<int16_t>::min())) break; } slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index)); ptr_segment[1].slope = FLOAT_TO_INT16(slope * slope_scale); ptr_segment[1].xBase = ptr_segment[1].xBase | slope_scale_index; } ptr_segment[2].xBase = static_cast<int32_t>(x_upper_limit & XBASEMASK); ptr_segment[2].yBase = y_upper_limit; ptr_segment[2].slope = 0; } break; case kActPow: { gnalog() << "=========================== Pow Segments===========================\n"; uint32_t num_segment_size = 0; auto fp32eq = [](float p1, float p2) -> bool { return (std::abs(p1 - p2) <= 0.00001f * std::min(std::abs(p1), std::abs(p2))); }; auto args = std::tuple<double, double, double>{ activation_type.args.pow.exponent, activation_type.args.pow.scale, activation_type.args.pow.offset }; auto input_min_value = static_cast<double>(std::numeric_limits<int32_t>::min()); auto input_max_value = static_cast<double>(std::numeric_limits<int32_t>::max()); double x_min = fp32eq(fmod(activation_type.args.pow.exponent, 1.0), 0.0f)? input_min_value / scale_in: 0.0; x_min = std::max(x_min, -POW_DOMAIN); double x_max = input_max_value / scale_in; x_max = std::min(x_max, POW_DOMAIN); double pow_domain = x_max - x_min; ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb num_segment_size = static_cast<int32_t>(pow_domain * scale_in / (num_segments - 2) + 0.5); int32_t x_min_scaled = x_min * scale_in + 0.5; int32_t offset = x_min_scaled; for (uint32_t i = 1; i < num_segments; i++) { ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb offset += num_segment_size; } for (uint32_t i = 0; i < num_segments; i++) { int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK); int32_t xbasenext = (i < num_segments - 1) ? static_cast<int32_t>(ptr_segment[i + 1].xBase & XBASEMASK) : INT32_MAX; double arg = xbase / scale_in; arg = arg < x_min ? x_min : arg; double argnext = xbasenext / scale_in; argnext = argnext < x_min ? x_min : argnext; double val = power(arg, args); double valnext = power(argnext, args); double slope = (valnext - val) / (static_cast<double>(xbasenext - xbase) / scale_in); auto s = gna_slope(slope, scale_in, scale_out); ptr_segment[i].slope = FLOAT_TO_INT16(s.slope * s.slope_scale); ptr_segment[i].xBase = ptr_segment[i].xBase | s.slope_scale_index; ptr_segment[i].yBase = FLOAT_TO_INT16(val * scale_out); gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK)) / scale_out) << " " << (static_cast<float>((ptr_segment[i].yBase)) / scale_out) << " " << (s.slope / scale_out) << "\n"; } } break; default: fprintf(stderr, "Activation function design for %s not yet implemented!\n", intel_dnn_activation_name[activation_type]); throw -1; } } void PwlApply32(intel_dnn_component_t *component, uint32_t num_subset_size) { if (component->orientation_in == kDnnInterleavedOrientation) { // subsets only supported in interleaved orientation PwlApply32(component, 0, num_subset_size - 1, 0, component->num_columns_in - 1); } else { PwlApply32(component, 0, component->num_rows_in - 1, 0, component->num_columns_in - 1); } } void PwlApply32(intel_dnn_component_t *component, uint32_t num_row_start, uint32_t num_row_end, uint32_t num_col_start, uint32_t num_col_end) { intel_piecewiselinear_t *transform = reinterpret_cast<intel_piecewiselinear_t *>(&component->op.pwl); float *ptr_in = reinterpret_cast<float *>(component->ptr_inputs); float *ptr_out = reinterpret_cast<float *>(component->ptr_outputs); uint32_t num_columns = component->num_columns_in; switch (transform->func_id.type) { case kActSigmoid: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = 0.5 * (1.0 + tanh(0.5 * ptr_in[i * num_columns + j])); } } break; case kActTanh: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = tanh(ptr_in[i * num_columns + j]); } } break; case kActSoftSign: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = ptr_in[i * num_columns + j] / (1.0 + fabs(ptr_in[i * num_columns + j])); } } break; case kActRelu: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = (ptr_in[i * num_columns + j] < 0.0f) ? ptr_in[i * num_columns + j] * transform->func_id.args.lrelu.negative_slope : ptr_in[i * num_columns + j]; } } break; case kActIdentity: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = ptr_in[i * num_columns + j]; } } break; case kActKaldiLstmClipping: { float upper_limit = component->op.pwl.func_id.args.clamp.high; float lower_limit = component->op.pwl.func_id.args.clamp.low; for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { float val = ptr_in[i * num_columns + j]; if (val > upper_limit) { ptr_out[i * num_columns + j] = upper_limit; } else if (val < lower_limit) { ptr_out[i * num_columns + j] = lower_limit; } else { ptr_out[i * num_columns + j] = val; } } } break; } case kActExp: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = exp(ptr_in[i * num_columns + j]); } } break; case kActLog: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = log(ptr_in[i * num_columns + j]); } } break; case kActAbs: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = fabs(ptr_in[i * num_columns + j]); } } break; case kActSign: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = (ptr_in[i * num_columns + j] == 0) ? 0.0 : ((ptr_in[i * num_columns + j] > 0) ? 1.0 : -1.0); } } break; case kActNegLog: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = -1.0 * log(ptr_in[i * num_columns + j]); } } break; case kActNegHalfLog: for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = -0.5 * log(ptr_in[i * num_columns + j]); } } break; case kActPow: { float exponent = transform->func_id.args.pow.exponent; float scale = transform->func_id.args.pow.scale; float offset = transform->func_id.args.pow.offset; for (uint32_t i = num_row_start; i <= num_row_end; i++) { for (uint32_t j = num_col_start; j <= num_col_end; j++) { ptr_out[i * num_columns + j] = pow(offset + scale * ptr_in[i * num_columns + j], exponent); } } } break; case kActFakeQuantize: { double levels = transform->func_id.fqParams.levels; for (uint32_t i = num_row_start; i <= num_row_end; i++) { auto inputChannel = transform->func_id.fqParams.inputPerChannel ? i : 0; auto outputChannel = transform->func_id.fqParams.outputPerChannel ? i : 0; double input_low = transform->func_id.fqParams.input_low[inputChannel]; double input_high = transform->func_id.fqParams.input_high[inputChannel]; double output_low = transform->func_id.fqParams.output_low[outputChannel]; double output_high = transform->func_id.fqParams.output_high[outputChannel]; for (uint32_t j = num_col_start; j <= num_col_end; j++) { auto offset = i * num_columns + j; auto x = ptr_in[offset]; if (x <= std::min(input_low, input_high)) { ptr_out[offset] = output_low; } else if (x > std::max(input_low, input_high)) { ptr_out[offset] = output_high; } else { ptr_out[offset] = nearbyint((x - input_low) / (input_high - input_low) * (levels - 1)) / (levels - 1) * (output_high - output_low) + output_low; } } } break; } case kActCustom: default: THROW_GNA_EXCEPTION << component->original_layer_name << ", Unknown piecewise linear function type: " << transform->func_id.type; } }
52.915187
143
0.502684
kurylo
358dd892ae6a47600fdf23472a3f1d53e967a577
2,008
cpp
C++
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include <new> #include <cassert> #include "uiwayblock.h" #include <QListWidget> #include <QLineEdit> #include <QDoubleSpinBox> #include <QCheckBox> #include <QPushButton> gui::uiblocks::UIWayBlock::UIWayBlock() : lstWays(nullptr), txtWayName(nullptr), dsbWayTotalTime(nullptr), cbWayClosed(nullptr), btnWayAdd(nullptr), btnWayRemove(nullptr), lstWayPoints(nullptr), dsbWayPointX(nullptr), dsbWayPointY(nullptr), btnWayPointAdd(nullptr), btnWayPointRemove(nullptr), btnWayPointMoveBack(nullptr), btnWayPointMoveFront(nullptr) { } void gui::uiblocks::UIWayBlock::init(QWidget* w) { assert(w); this->lstWays = w->findChild<QListWidget*>("lstWays"); assert(this->lstWays); this->txtWayName = w->findChild<QLineEdit*>("txtWayName"); assert(this->txtWayName); this->dsbWayTotalTime = w->findChild<QDoubleSpinBox*>("dsbWayTotalTime"); assert(this->dsbWayTotalTime); this->cbWayClosed = w->findChild<QCheckBox*>("cbWayClosed"); assert(this->cbWayClosed); this->btnWayAdd = w->findChild<QPushButton*>("btnWayAdd"); assert(this->btnWayAdd); this->btnWayRemove = w->findChild<QPushButton*>("btnWayRemove"); assert(this->btnWayRemove); this->lstWayPoints = w->findChild<QListWidget*>("lstWayPoints"); assert(this->lstWayPoints); this->dsbWayPointX = w->findChild<QDoubleSpinBox*>("dsbWayPointX"); assert(this->dsbWayPointX); this->dsbWayPointY = w->findChild<QDoubleSpinBox*>("dsbWayPointY"); assert(this->dsbWayPointY); this->btnWayPointAdd = w->findChild<QPushButton*>("btnWayPointAdd"); assert(this->btnWayPointAdd); this->btnWayPointRemove = w->findChild<QPushButton*>("btnWayPointRemove"); assert(this->btnWayPointRemove); this->btnWayPointMoveBack = w->findChild<QPushButton*>("btnWayPointMoveBack"); assert(this->btnWayPointMoveBack); this->btnWayPointMoveFront = w->findChild<QPushButton*>("btnWayPointMoveFront"); assert(this->btnWayPointMoveFront); } gui::uiblocks::UIWayBlock::~UIWayBlock() { }
32.387097
84
0.731076
mamontov-cpp
358f0675afa1d80c560a1dec6fb0401f5642c3dc
3,833
cpp
C++
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
1
2019-02-22T03:11:28.000Z
2019-02-22T03:11:28.000Z
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
null
null
null
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
null
null
null
#include "./headers/shader.h" #include "./headers/opengl_common.h" #define STB_IMAGE_IMPLEMENTATION_2 #include "./headers/stb_image.h" int hello_3d() { GLFWwindow* window = prepareWindow("hello_3d"); if (!window) { return -1; } Shader textureShader("./shaders/3d.shader.vs", "./shaders/3d.shader.fs"); float textureVertices[] = { // positions // colors // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; // Vertex input unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(textureVertices), textureVertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); unsigned int texture1, texture2; texture1 = loadTexture("./pics/container.jpg"); texture2 = loadTexture("./pics/awesomeface.png"); textureShader.use(); textureShader.setInt("texture1", 0); textureShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); textureShader.use(); float timeValue = glfwGetTime(); float sinValue = sin(timeValue); glm::mat4 trans = glm::mat4(1.0f); trans = glm::translate(trans, glm::vec3(sinValue, -0.5f, 0.0f)); trans = glm::rotate(trans, timeValue, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); glm::mat4 projection = glm::mat4(1.0f); //model = glm::translate(model, glm::vec3(sinValue, -0.5f, 0.0f)); model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); //model = glm::rotate(model, timeValue, glm::vec3(0.0f, 0.0f, 1.0f)); // note that we're translating the scene in the reverse direction of where we want to move // Note that in normalized device coordinates OpenGL actually uses a left-handed system view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f)); projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); //textureShader.setMatrix4("sinValue", &sinValue); textureShader.setMat4("model", model); textureShader.setMat4("view", view); textureShader.setMat4("projection", projection); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
32.760684
105
0.651448
xiwan
359290ea28eda47cce73bf4f5b53cc9903f2c87c
5,654
cpp
C++
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
//! [snippet1] // We include what we need for the test #include <gatb/gatb_core.hpp> #include <fstream> #include <queue> #include <stack> #include <map> using namespace std; #define DEBUG(a) //a #define INFO(a) //a /********************************************************************************/ /* Cmd-line: debruijn24 -graph <h5 file> [-out <output file>] */ /* */ /* Sample: debruijn24 -graph gatb-core/gatb-core/test/db/celegans_reads.h5 */ /* */ /* Note: */ /* - '.h5' file contains the HDF5 formatted representation of a de bruijn */ /* graph created from a set of reads. */ /* - a '.h5' file is created using dbgh5 program provided with GATB-Core. */ /* Basic use is as follows: */ /* dbgh5 -in <fasta/q file> -out <h5 file> */ /* You can also control kmer-size and kmer abundance, see dbgh5 help. */ /********************************************************************************/ const char* STR_NODE_TYPE = "-type"; /********************************************************************************/ class DotGeneratorTool : public Tool { public: // Constructor DotGeneratorTool () : Tool ("DotGenerator") { _parser->push_front (new OptionOneParam (STR_URI_GRAPH, "graph file", true )); _parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "dot file", false )); _parser->push_front (new OptionOneParam (STR_NODE_TYPE, "node type (0: all, 1:branching)", false, "1" )); } void processNode(Graph &graph, ofstream &output) { map<Node, u_int64_t> mapping; u_int64_t count = 0; GraphIterator<Node> itMap = graph.iterator (); for (itMap.first(); !itMap.isDone(); itMap.next()) { mapping[itMap.item()] = count++; } ProgressGraphIterator<Node,ProgressTimer> it = graph.iterator (); for (it.first(); !it.isDone(); it.next()) { Node current = it.item(); GraphVector<Node> neighbors = graph.neighbors(current.kmer); for (size_t i=0; i<neighbors.size(); i++) { output << mapping[current.kmer] << " -> " << mapping[neighbors[i].kmer] << " ;\n"; } } output << "}\n"; output.close(); } void processBranchingNode(Graph &graph, ofstream & output) { map<Node, u_int64_t> mapping; u_int64_t count = 0; GraphIterator<BranchingNode> itMap = graph.iteratorBranching(); for (itMap.first(); !itMap.isDone(); itMap.next()) { mapping[itMap.item()] = count++; } ProgressGraphIterator<BranchingNode,ProgressTimer> it = graph.iteratorBranching (); for (it.first(); !it.isDone(); it.next()) { BranchingNode current = it.item(); GraphVector<BranchingNode> neighbors = graph.neighborsBranching (current.kmer); for (size_t i=0; i<neighbors.size(); i++) { output << mapping[current.kmer] << " -> " << mapping[neighbors[i].kmer] << " ;\n"; } } output << "}\n"; output.close(); } // Actual job done by the tool is here void execute () { string outputFile = getInput()->get(STR_URI_OUTPUT) ? getInput()->getStr(STR_URI_OUTPUT) : (System::file().getBaseName(getInput()->getStr(STR_URI_GRAPH)) + ".dot"); ofstream output (outputFile.c_str()); // We load the graph Graph graph = Graph::load (getInput()->getStr(STR_URI_GRAPH)); switch (getInput()->getInt(STR_NODE_TYPE)) { case 0: output << "digraph " << "all" << "{\n"; processNode(graph, output); break; case 1: output << "digraph " << "branching" << "{\n"; processBranchingNode(graph, output); break; default: break; } } }; /********************************************************************************/ /* */ /* Generate dot file from a graph. */ /* */ /* This snippet generates a dot file from a graph file. You can then generate */ /* a pdf file with "dot -Tpdf graph.dot -o graph.pdf" */ /* */ /* NOTE: de Bruijn graphs may be huge and complex, so dot is not the best tool */ /* to display such graphs. You should use it on small graphs with only a few */ /* hundreds of nodes. */ /* */ /********************************************************************************/ int main (int argc, char* argv[]) { try { // We run the tool with the provided command line arguments. DotGeneratorTool().run (argc, argv); } catch (Exception& e) { std::cout << "EXCEPTION: " << e.getMessage() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } //! [snippet1]
36.714286
115
0.44358
cwright7101
359471f04a7f8f0e3fde02afe2e087b4e1c5144b
5,666
cpp
C++
src/Generic/discTagger/DTAltModelSet.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/discTagger/DTAltModelSet.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/discTagger/DTAltModelSet.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" #include "Generic/common/limits.h" #include "Generic/common/UTF8InputStream.h" #include "Generic/common/ParamReader.h" #include "Generic/discTagger/DTTagSet.h" #include "Generic/discTagger/DTFeatureTypeSet.h" #include "Generic/discTagger/P1Decoder.h" #include "Generic/maxent/MaxEntModel.h" #include "Generic/discTagger/DTTagSet.h" #include "Generic/discTagger/DTFeatureTypeSet.h" #include "Generic/discTagger/DTObservation.h" #include "Generic/discTagger/DTAltModelSet.h" #include <boost/scoped_ptr.hpp> DTAltModelSet::DTAltModelSet() : _nDecoders(0), _is_initialized(false) {} void DTAltModelSet::initialize(Symbol modeltype, const char* paramName) { // already been initialized, so just return if (_is_initialized) return; _is_initialized = true; char msg[1000]; boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& uis(*uis_scoped_ptr); UTF8Token tok; /*sub-parameter file looks like #ofAlternativeModels MODEL_NAME-1 model-type-1 tagset-1 featureset-1 modelfile-1 MODEL_NAME-2 model-type-2 tagset-2 featureset-2 modelfile-2 ..... */ std::string stream_name = ParamReader::getParam(paramName); uis.open(stream_name.c_str()); if (uis.fail()) { sprintf(msg, "Error opening %s: %s", paramName, stream_name.c_str()); throw UnrecoverableException("DTAltModelSet:DTAltModelSet()", msg); } uis >> tok; _nDecoders = _wtoi(tok.chars()); //std::cout<<"tok: "<<tok.symValue().to_debug_string()<< " _ndecoders: "<<_nDecoders<<std::endl; if (_nDecoders >= MAX_ALT_DT_DECODERS) { sprintf(msg, "Number of decoders in %s is greater than MAX_ALT_DT_DECODERS: %d", paramName, MAX_ALT_DT_DECODERS); throw UnrecoverableException("DTAltModelSet:DTAltModelSet()", msg); } for (int i = 0; i < _nDecoders; i++) { //std::cout<<"reading decoder: "<<i<<std::endl; uis >> tok; _altDecoders[i]._name = tok.symValue(); uis >> tok; if (tok.symValue() == Symbol(L"MAXENT")) _altDecoders[i]._type = MAXENT; else if (tok.symValue() == Symbol(L"P1")) _altDecoders[i]._type = P1; else { sprintf(msg, "Found unexpected model type in %s, should be 'P1' or 'MAXENT'.", paramName); throw UnexpectedInputException("DTAltModelSet::DTAltModelSet()", msg); } uis >> tok; char buffer[500]; wcstombs(buffer, tok.chars(), 500); _altDecoders[i]._tagSet = _new DTTagSet(buffer, false, false); uis >> tok; wcstombs(buffer, tok.chars(), 500); _altDecoders[i]._features = _new DTFeatureTypeSet(buffer, modeltype); uis >> tok; wcstombs(buffer, tok.chars(), 500); _altDecoders[i]._weights = _new DTFeature::FeatureWeightMap(50000); DTFeature::readWeights(*_altDecoders[i]._weights, buffer, modeltype); if (_altDecoders[i]._type == P1) { _altDecoders[i]._p1Decoder = _new P1Decoder(_altDecoders[i]._tagSet, _altDecoders[i]._features, _altDecoders[i]._weights, 0, 0); _altDecoders[i]._maxentDecoder = 0; } else { // _altDecoders[i]._type == MAXENT _altDecoders[i]._maxentDecoder = _new MaxEntModel(_altDecoders[i]._tagSet, _altDecoders[i]._features, _altDecoders[i]._weights); _altDecoders[i]._p1Decoder = 0; } } } DTAltModelSet::~DTAltModelSet() { for (int i = 0; i < _nDecoders; i++) { delete _altDecoders[i]._tagSet; _altDecoders[i]._tagSet = 0; delete _altDecoders[i]._features; _altDecoders[i]._features = 0; delete _altDecoders[i]._weights; _altDecoders[i]._weights = 0; delete _altDecoders[i]._p1Decoder; _altDecoders[i]._p1Decoder= 0; delete _altDecoders[i]._maxentDecoder; _altDecoders[i]._maxentDecoder= 0; } _nDecoders = 0; } int DTAltModelSet::getNAltDecoders() { return _nDecoders; } Symbol DTAltModelSet::getDecoderName(int i) { char msg[1000]; if( i >= _nDecoders) { sprintf(msg, "getDecoderName i is greater than n_decoders: %d", _nDecoders); throw UnrecoverableException("DTAltModelSet:getDecoderName()", msg); } return _altDecoders[i]._name; } Symbol DTAltModelSet::getDecoderPrediction(int i, DTObservation *obs) { char msg[1000]; if (i >= _nDecoders) { sprintf(msg, "getDecoderPrediction i is greater than n_decoders: %d", _nDecoders); throw UnrecoverableException("DTAltModelSet:getDecoderPrediction()", msg); } Symbol tag; if (_altDecoders[i]._type == P1) tag = _altDecoders[i]._p1Decoder->decodeToSymbol(obs); else // _altDecoders[i]._type == MAXENT tag = _altDecoders[i]._maxentDecoder->decodeToSymbol(obs); return tag; } Symbol DTAltModelSet::getDecoderPrediction(Symbol name, DTObservation *obs) { char msg[1000]; int decnum = -1; for (int i = 0; i <_nDecoders; i++) { if (_altDecoders[i]._name == name) { decnum = i; break; } } if (decnum == -1) { sprintf(msg, "No Decoder defined with name: %s", name.to_debug_string()); throw UnrecoverableException("DTAltModelSet:getDecoderPrediction()", msg); } return getDecoderPrediction(decnum, obs); } int DTAltModelSet::addDecoderPredictionsToObservation(DTObservation *obs) { int i = 0; for (i = 0; i < _nDecoders; i++) { Symbol result; if (_altDecoders[i]._type == P1) result = _altDecoders[i]._p1Decoder->decodeToSymbol(obs); else // _altDecoders[i]._type == MAXENT result = _altDecoders[i]._maxentDecoder->decodeToSymbol(obs); obs->setAltDecoderPrediction(i, result); } return i; }
30.793478
98
0.683022
BBN-E
35969c7d3d5bf587b5c69a49b5535fe6a20368a1
4,970
hpp
C++
libraries/app/include/scorum/app/detail/advertising_api.hpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
libraries/app/include/scorum/app/detail/advertising_api.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
libraries/app/include/scorum/app/detail/advertising_api.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#pragma once #include <scorum/chain/services/advertising_property.hpp> #include <scorum/chain/services/account.hpp> #include <scorum/chain/services/budgets.hpp> #include <scorum/chain/services/dynamic_global_property.hpp> #include <scorum/app/scorum_api_objects.hpp> #include <scorum/app/advertising_api.hpp> #include <boost/range/algorithm/transform.hpp> #include <boost/range/algorithm/sort.hpp> namespace scorum { namespace app { class advertising_api::impl { public: impl(chain::database& db, chain::data_service_factory_i& services) : _db(db) , _services(services) , _adv_service(_services.advertising_property_service()) , _account_service(_services.account_service()) , _banner_budget_service(_services.banner_budget_service()) , _post_budget_service(_services.post_budget_service()) , _dyn_props_service(_services.dynamic_global_property_service()) { } fc::optional<account_api_obj> get_moderator() const { auto& adv_property_object = _adv_service.get(); if (adv_property_object.moderator == SCORUM_MISSING_MODERATOR_ACCOUNT) return {}; auto& moderator_account = _account_service.get_account(adv_property_object.moderator); return account_api_obj(moderator_account, _db); } std::vector<budget_api_obj> get_user_budgets(const std::string& user) const { auto post_budgets = _post_budget_service.get_budgets(user); auto banner_budgets = _banner_budget_service.get_budgets(user); std::vector<budget_api_obj> ret; ret.reserve(post_budgets.size() + banner_budgets.size()); boost::transform(post_budgets, std::back_inserter(ret), [](const post_budget_object& o) { return budget_api_obj(o); }); boost::transform(banner_budgets, std::back_inserter(ret), [](const banner_budget_object& o) { return budget_api_obj(o); }); boost::sort(ret, [](const budget_api_obj& l, const budget_api_obj& r) { return l.created > r.created; }); return ret; } fc::optional<budget_api_obj> get_budget(const uuid_type& uuid, budget_type type) const { switch (type) { case budget_type::post: return get_budget(_post_budget_service, uuid); case budget_type::banner: return get_budget(_banner_budget_service, uuid); } FC_THROW("unreachable"); } std::vector<budget_api_obj> get_current_winners(budget_type type) const { switch (type) { case budget_type::post: return get_current_winners(_post_budget_service); case budget_type::banner: return get_current_winners(_banner_budget_service); } FC_THROW("unreachable"); } std::vector<percent_type> get_auction_coefficients(budget_type type) const { switch (type) { case budget_type::post: return std::vector<percent_type>{ _adv_service.get().auction_post_coefficients.begin(), _adv_service.get().auction_post_coefficients.end() }; case budget_type::banner: return std::vector<percent_type>{ _adv_service.get().auction_banner_coefficients.begin(), _adv_service.get().auction_banner_coefficients.end() }; } FC_THROW("unreachable"); } private: template <budget_type budget_type_v> fc::optional<budget_api_obj> get_budget(const chain::adv_budget_service_i<budget_type_v>& budget_service, const uuid_type& uuid) const { fc::optional<budget_api_obj> ret; if (budget_service.is_exists(uuid)) ret = budget_service.get(uuid); return ret; } template <budget_type budget_type_v> std::vector<budget_api_obj> get_current_winners(const chain::adv_budget_service_i<budget_type_v>& budget_service) const { using object_type = chain::adv_budget_object<budget_type_v>; auto head_block_time = _dyn_props_service.get().time; const auto& auction_coeffs = _adv_service.get().get_auction_coefficients<budget_type_v>(); auto budgets = budget_service.get_top_budgets(head_block_time, auction_coeffs.size()); std::vector<budget_api_obj> ret; ret.reserve(auction_coeffs.size()); boost::transform(budgets, std::back_inserter(ret), [](const object_type& o) { return budget_api_obj(o); }); return ret; } public: chain::database& _db; chain::data_service_factory_i& _services; chain::advertising_property_service_i& _adv_service; chain::account_service_i& _account_service; chain::banner_budget_service_i& _banner_budget_service; chain::post_budget_service_i& _post_budget_service; chain::dynamic_global_property_service_i& _dyn_props_service; }; } }
34.275862
115
0.673441
scorum
35972edb385c1a9e30366229bdfbc43456f337c7
5,286
cpp
C++
WebRtcWrapper/webrtc.PeerConnectionObserver.cpp
eidosmontreal/winrtc
4011f5a9e1924ff16ed6decd7a494a15db27e391
[ "MIT" ]
1
2021-12-30T10:01:15.000Z
2021-12-30T10:01:15.000Z
WebRtcWrapper/webrtc.PeerConnectionObserver.cpp
eidosmontreal/winrtc
4011f5a9e1924ff16ed6decd7a494a15db27e391
[ "MIT" ]
null
null
null
WebRtcWrapper/webrtc.PeerConnectionObserver.cpp
eidosmontreal/winrtc
4011f5a9e1924ff16ed6decd7a494a15db27e391
[ "MIT" ]
1
2022-02-28T02:29:38.000Z
2022-02-28T02:29:38.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // clang-format off #include "pch.h" #include "webrtc.PeerConnectionObserver.h" #include "webrtc.PeerConnectionObserver.g.cpp" // clang-format on #include "webrtc.IceCandidate.h" #include "webrtc.RtpTransceiver.h" namespace winrt::Microsoft::WinRTC::WebRtcWrapper::webrtc::implementation { event_token PeerConnectionObserver::OnSignalingChange( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionObserverOnSignalingChangeDelegate const &handler) { return on_signaling_change_event_.add(handler); } void PeerConnectionObserver::OnSignalingChange(event_token const &token) noexcept { on_signaling_change_event_.remove(token); } event_token PeerConnectionObserver::OnRenegotiationNeeded( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionObserverOnRenegotiationNeededDelegate const &handler) { return on_renegotiation_needed_event_.add(handler); } void PeerConnectionObserver::OnRenegotiationNeeded(winrt::event_token const &token) noexcept { on_renegotiation_needed_event_.remove(token); } event_token PeerConnectionObserver::OnIceGatheringChange( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionObserverOnIceGatheringChangeDelegate const &handler) { return on_ice_gathering_change_event_.add(handler); } void PeerConnectionObserver::OnIceGatheringChange(winrt::event_token const &token) noexcept { on_ice_gathering_change_event_.remove(token); } event_token PeerConnectionObserver::OnIceCandidate( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionObserverOnIceCandidateDelegate const &handler) { return on_ice_candidate_event_.add(handler); } void PeerConnectionObserver::OnIceCandidate(event_token const &token) noexcept { on_ice_candidate_event_.remove(token); } event_token PeerConnectionObserver::OnTrack( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionObserverOnTrackDelegate const &handler) { return on_track_event_.add(handler); } void PeerConnectionObserver::OnTrack(event_token const &token) noexcept { on_track_event_.remove(token); } void PeerConnectionObserver::OnSignalingChange(::webrtc::PeerConnectionInterface::SignalingState webrtc_new_state) { switch (webrtc_new_state) { case ::webrtc::PeerConnectionInterface::SignalingState::kStable: { on_signaling_change_event_(Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::Stable); break; } case ::webrtc::PeerConnectionInterface::SignalingState::kHaveLocalOffer: { on_signaling_change_event_(Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::HaveLocalOffer); break; } case ::webrtc::PeerConnectionInterface::SignalingState::kHaveLocalPrAnswer: { on_signaling_change_event_( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::HaveLocalPrAnswer); break; } case ::webrtc::PeerConnectionInterface::SignalingState::kHaveRemoteOffer: { on_signaling_change_event_(Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::HaveRemoteOffer); break; } case ::webrtc::PeerConnectionInterface::SignalingState::kHaveRemotePrAnswer: { on_signaling_change_event_( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::HaveRemotePrAnswer); break; } case ::webrtc::PeerConnectionInterface::SignalingState::kClosed: { on_signaling_change_event_(Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnectionSignalingState::Closed); break; } default: { throw hresult_illegal_state_change(); } } } void PeerConnectionObserver::OnDataChannel(::rtc::scoped_refptr<::webrtc::DataChannelInterface> /*data_channel*/) { throw hresult_not_implemented(); // FIXME(aurighet) } void PeerConnectionObserver::OnRenegotiationNeeded() { on_renegotiation_needed_event_(); } void PeerConnectionObserver::OnIceGatheringChange(::webrtc::PeerConnectionInterface::IceGatheringState new_state) { switch (new_state) { case ::webrtc::PeerConnectionInterface::kIceGatheringNew: { on_ice_gathering_change_event_(Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnection::IceGatheringState::New); break; } case ::webrtc::PeerConnectionInterface::kIceGatheringGathering: { on_ice_gathering_change_event_( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnection::IceGatheringState::Gathering); break; } case ::webrtc::PeerConnectionInterface::kIceGatheringComplete: { on_ice_gathering_change_event_( Microsoft::WinRTC::WebRtcWrapper::webrtc::PeerConnection::IceGatheringState::Complete); break; } default: { throw hresult_illegal_state_change(); } } } void PeerConnectionObserver::OnIceCandidate(const ::webrtc::IceCandidateInterface *candidate) { if (candidate) { auto winrtc_ice_candidate = make<IceCandidate>(candidate); on_ice_candidate_event_(winrtc_ice_candidate); } else { throw hresult_invalid_argument(); } } void PeerConnectionObserver::OnTrack(::rtc::scoped_refptr<::webrtc::RtpTransceiverInterface> transceiver) { auto winrtc_rtp_transceiver = make<RtpTransceiver>(transceiver); on_track_event_(winrtc_rtp_transceiver); } } // namespace winrt::Microsoft::WinRTC::WebRtcWrapper::webrtc::implementation
30.205714
120
0.79493
eidosmontreal
359b6f223ae30af473858429465ad694eddf411e
6,256
cpp
C++
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <iOS.QuartzCore.CATransform3D.h> #include <Uno.Double.h> namespace g{ namespace iOS{ namespace QuartzCore{ // ../../../../../../../usr/local/share/uno/Packages/Experimental.iOS/0.24.0/struct/$.uno(1471) // -------------------------------------------------------------------------------------------- // public extern struct CATransform3D :1471 // { uStructType* CATransform3D_typeof() { static uSStrong<uStructType*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 16; options.ValueSize = sizeof(CATransform3D); options.TypeSize = sizeof(uStructType); type = uStructType::New("iOS.QuartzCore.CATransform3D", options); type->SetFields(0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M11), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M12), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M13), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M14), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M21), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M22), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M23), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M24), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M31), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M32), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M33), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M34), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M41), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M42), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M43), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M44), 0); type->Reflection.SetFields(16, new uField("M11", 0), new uField("M12", 1), new uField("M13", 2), new uField("M14", 3), new uField("M21", 4), new uField("M22", 5), new uField("M23", 6), new uField("M24", 7), new uField("M31", 8), new uField("M32", 9), new uField("M33", 10), new uField("M34", 11), new uField("M41", 12), new uField("M42", 13), new uField("M43", 14), new uField("M44", 15)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)CATransform3D__New1_fn, 0, true, CATransform3D_typeof(), 16, ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof())); return type; } // public CATransform3D(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) :1473 void CATransform3D__ctor__fn(CATransform3D* __this, double* M111, double* M121, double* M131, double* M141, double* M211, double* M221, double* M231, double* M241, double* M311, double* M321, double* M331, double* M341, double* M411, double* M421, double* M431, double* M441) { __this->ctor_(*M111, *M121, *M131, *M141, *M211, *M221, *M231, *M241, *M311, *M321, *M331, *M341, *M411, *M421, *M431, *M441); } // public CATransform3D New(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) :1473 void CATransform3D__New1_fn(double* M111, double* M121, double* M131, double* M141, double* M211, double* M221, double* M231, double* M241, double* M311, double* M321, double* M331, double* M341, double* M411, double* M421, double* M431, double* M441, CATransform3D* __retval) { *__retval = CATransform3D__New1(*M111, *M121, *M131, *M141, *M211, *M221, *M231, *M241, *M311, *M321, *M331, *M341, *M411, *M421, *M431, *M441); } // public CATransform3D(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) [instance] :1473 void CATransform3D::ctor_(double M111, double M121, double M131, double M141, double M211, double M221, double M231, double M241, double M311, double M321, double M331, double M341, double M411, double M421, double M431, double M441) { uStackFrame __("iOS.QuartzCore.CATransform3D", ".ctor(double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double)"); M11 = M111; M12 = M121; M13 = M131; M14 = M141; M21 = M211; M22 = M221; M23 = M231; M24 = M241; M31 = M311; M32 = M321; M33 = M331; M34 = M341; M41 = M411; M42 = M421; M43 = M431; M44 = M441; } // public CATransform3D New(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) [static] :1473 CATransform3D CATransform3D__New1(double M111, double M121, double M131, double M141, double M211, double M221, double M231, double M241, double M311, double M321, double M331, double M341, double M411, double M421, double M431, double M441) { CATransform3D obj1; obj1.ctor_(M111, M121, M131, M141, M211, M221, M231, M241, M311, M321, M331, M341, M411, M421, M431, M441); return obj1; } // } }}} // ::g::iOS::QuartzCore
57.394495
538
0.646739
sauvikatinnofied
359d83a58dc46b4fa80fded4f093ab723cb9d5a4
1,516
cpp
C++
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
2
2019-06-10T11:50:06.000Z
2019-10-14T08:00:41.000Z
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
null
null
null
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
null
null
null
#include<iostream> int days = 0; int getDayOfWeek(); int getYear(); int getMonth(bool isLeapYear); int main(){ int year = 0, month = 0, dayOfWeek = 0; bool isLeapYear = true; char week[7][10] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; while ((std::cin >> days) && days != -1) { dayOfWeek = getDayOfWeek(); year = getYear(); isLeapYear = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0); month = getMonth(isLeapYear); std::cout << year << "-" << month << "-" << ++days << " " << week[dayOfWeek] << std::endl; } return 0; } int getDayOfWeek(){ int dayOfWeek = 0; dayOfWeek = days % 7; return dayOfWeek; } int getYear(){ int i = 2000; bool isLeapYear = true; while (true) { isLeapYear = (i % 4 == 0 && i % 100 != 0 || i % 400 == 0); if (isLeapYear && days >= 366) { days -= 366; i++; } else if (!isLeapYear && days >= 365) { days -= 365; i++; } else { break; } } return i; } int getMonth(bool isLeapYear){ int pmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int rmonth[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int month = 0; while (true) { if (isLeapYear && days >= rmonth[month]) { days = days - rmonth[month]; month++; } else if (!isLeapYear && days >= pmonth[month]) { days = days - pmonth[month]; month++; } else { break; } } return ++month; }
23.323077
71
0.511214
chtld
359dc15ccb18eb076d57ac1e794a721ab27c673f
215,144
cpp
C++
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
1
2019-06-11T09:00:42.000Z
2019-06-11T09:00:42.000Z
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <list> #include <boost/version.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm_ext/erase.hpp> #include <boost/range/algorithm/unique.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <fc/git_revision.hpp> #include <fc/io/fstream.hpp> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/crypto/aes.hpp> #include <fc/crypto/hex.hpp> #include <fc/thread/mutex.hpp> #include <fc/thread/scoped_lock.hpp> #include <graphene/app/api.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/protocol/fee_schedule.hpp> #include <graphene/utilities/git_revision.hpp> #include <graphene/utilities/key_conversion.hpp> #include <graphene/utilities/string_escape.hpp> #include <graphene/utilities/words.hpp> #include <graphene/wallet/wallet.hpp> #include <graphene/wallet/api_documentation.hpp> #include <graphene/wallet/reflect_util.hpp> #include <graphene/debug_witness/debug_api.hpp> #include <fc/smart_ref_impl.hpp> #ifndef WIN32 # include <sys/types.h> # include <sys/stat.h> #endif #define BRAIN_KEY_WORD_COUNT 16 namespace graphene { namespace wallet { namespace detail { struct operation_result_printer { public: explicit operation_result_printer( const wallet_api_impl& w ) : _wallet(w) {} const wallet_api_impl& _wallet; typedef std::string result_type; std::string operator()(const void_result& x) const; std::string operator()(const object_id_type& oid); std::string operator()(const asset& a); std::string operator()(const advertising_confirm_result& a); }; // BLOCK TRX OP VOP struct operation_printer { private: ostream& out; const wallet_api_impl& wallet; operation_result result; std::string fee(const asset& a) const; public: operation_printer( ostream& out, const wallet_api_impl& wallet, const operation_result& r = operation_result() ) : out(out), wallet(wallet), result(r) {} typedef std::string result_type; template<typename T> std::string operator()(const T& op)const; std::string operator()(const transfer_operation& op)const; std::string operator()(const override_transfer_operation& op)const; std::string operator()(const account_create_operation& op)const; std::string operator()(const asset_create_operation& op)const; }; template<class T> optional<T> maybe_id( const string& name_or_id ) { if( std::isdigit( name_or_id.front() ) ) { try { return fc::variant(name_or_id).as<T>( 1 ); } catch (const fc::exception&) { // not an ID } } return optional<T>(); } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number ) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } struct op_prototype_visitor { typedef void result_type; int t = 0; flat_map< std::string, operation >& name2op; op_prototype_visitor( int _t, flat_map< std::string, operation >& _prototype_ops ):t(_t), name2op(_prototype_ops) {} template<typename Type> result_type operator()( const Type& op )const { string name = fc::get_typename<Type>::name(); size_t p = name.rfind(':'); if( p != string::npos ) name = name.substr( p+1 ); name2op[ name ] = Type(); } }; class wallet_api_impl { public: api_documentation method_documentation; private: void claim_registered_account(const string& name) { auto it = _wallet.pending_account_registrations.find( name ); FC_ASSERT( it != _wallet.pending_account_registrations.end() ); for (const std::string& wif_key : it->second) if( !import_key( name, wif_key ) ) { // somebody else beat our pending registration, there is // nothing we can do except log it and move on elog( "account ${name} registered by someone else first!", ("name", name) ); // might as well remove it from pending regs, // because there is now no way this registration // can become valid (even in the extremely rare // possibility of migrating to a fork where the // name is available, the user can always // manually re-register) } _wallet.pending_account_registrations.erase( it ); } // after a witness registration succeeds, this saves the private key in the wallet permanently // void claim_registered_witness(const std::string& witness_name) { auto iter = _wallet.pending_witness_registrations.find(witness_name); FC_ASSERT(iter != _wallet.pending_witness_registrations.end()); std::string wif_key = iter->second; // get the list key id this key is registered with in the chain fc::optional<fc::ecc::private_key> witness_private_key = wif_to_key(wif_key); FC_ASSERT(witness_private_key); auto pub_key = witness_private_key->get_public_key(); _keys[pub_key] = wif_key; _wallet.pending_witness_registrations.erase(iter); } fc::mutex _resync_mutex; void resync() { fc::scoped_lock<fc::mutex> lock(_resync_mutex); // this method is used to update wallet_data annotations // e.g. wallet has been restarted and was not notified // of events while it was down // // everything that is done "incremental style" when a push // notification is received, should also be done here // "batch style" by querying the blockchain if( !_wallet.pending_account_registrations.empty() ) { // make a vector of the account names pending registration std::vector<string> pending_account_names = boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_account_registrations)); for(string& name : pending_account_names ) { std::map<std::string,account_uid_type> n = _remote_db->lookup_accounts_by_name( name, 1 ); map<std::string, account_uid_type>::iterator it = n.find(name); if( it != n.end() ) { claim_registered_account(name); } } } if (!_wallet.pending_witness_registrations.empty()) { // make a vector of the owner accounts for witnesses pending registration std::vector<string> pending_witness_names = boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_witness_registrations)); for(string& name : pending_witness_names ) { std::map<std::string,account_uid_type> w = _remote_db->lookup_accounts_by_name( name, 1 ); map<std::string, account_uid_type>::iterator it = w.find(name); if( it != w.end() ) { fc::optional<witness_object> witness_obj = _remote_db->get_witness_by_account(it->second); if (witness_obj) claim_registered_witness(name); } } } } void enable_umask_protection() { #ifdef __unix__ _old_umask = umask( S_IRWXG | S_IRWXO ); #endif } void disable_umask_protection() { #ifdef __unix__ umask( _old_umask ); #endif } void init_prototype_ops() { operation op; for( int t=0; t<op.count(); t++ ) { op.set_which( t ); op.visit( op_prototype_visitor(t, _prototype_ops) ); } return; } map<transaction_handle_type, signed_transaction> _builder_transactions; // if the user executes the same command twice in quick succession, // we might generate the same transaction id, and cause the second // transaction to be rejected. This can be avoided by altering the // second transaction slightly (bumping up the expiration time by // a second). Keep track of recent transaction ids we've generated // so we can know if we need to do this struct recently_generated_transaction_record { fc::time_point_sec generation_time; graphene::chain::transaction_id_type transaction_id; }; struct timestamp_index{}; typedef boost::multi_index_container<recently_generated_transaction_record, boost::multi_index::indexed_by<boost::multi_index::hashed_unique<boost::multi_index::member<recently_generated_transaction_record, graphene::chain::transaction_id_type, &recently_generated_transaction_record::transaction_id>, std::hash<graphene::chain::transaction_id_type> >, boost::multi_index::ordered_non_unique<boost::multi_index::tag<timestamp_index>, boost::multi_index::member<recently_generated_transaction_record, fc::time_point_sec, &recently_generated_transaction_record::generation_time> > > > recently_generated_transaction_set_type; recently_generated_transaction_set_type _recently_generated_transactions; public: wallet_api& self; wallet_api_impl( wallet_api& s, const wallet_data& initial_data, fc::api<login_api> rapi ) : self(s), _chain_id(initial_data.chain_id), _remote_api(rapi), _remote_db(rapi->database()), _remote_net_broadcast(rapi->network_broadcast()), _remote_hist(rapi->history()) { chain_id_type remote_chain_id = _remote_db->get_chain_id(); if( remote_chain_id != _chain_id ) { FC_THROW( "Remote server gave us an unexpected chain_id", ("remote_chain_id", remote_chain_id) ("chain_id", _chain_id) ); } init_prototype_ops(); _remote_db->set_block_applied_callback( [this](const variant& block_id ) { on_block_applied( block_id ); } ); _wallet.chain_id = _chain_id; _wallet.ws_server = initial_data.ws_server; _wallet.ws_user = initial_data.ws_user; _wallet.ws_password = initial_data.ws_password; } virtual ~wallet_api_impl() { try { _remote_db->cancel_all_subscriptions(); } catch (const fc::exception& e) { // Right now the wallet_api has no way of knowing if the connection to the // node has already disconnected (via the node exiting first). // If it has exited, cancel_all_subscriptsions() will throw and there's // nothing we can do about it. // dlog("Caught exception ${e} while canceling database subscriptions", ("e", e)); } } void encrypt_keys() { if( !is_locked() ) { plain_keys data; data.keys = _keys; data.checksum = _checksum; auto plain_txt = fc::raw::pack(data); _wallet.cipher_keys = fc::aes_encrypt( data.checksum, plain_txt ); } } void on_block_applied( const variant& block_id ) { fc::async([this]{resync();}, "Resync after block"); } bool copy_wallet_file( string destination_filename ) { fc::path src_path = get_wallet_filename(); if( !fc::exists( src_path ) ) return false; fc::path dest_path = destination_filename + _wallet_filename_extension; int suffix = 0; while( fc::exists(dest_path) ) { ++suffix; dest_path = destination_filename + "-" + to_string( suffix ) + _wallet_filename_extension; } wlog( "backing up wallet ${src} to ${dest}", ("src", src_path) ("dest", dest_path) ); fc::path dest_parent = fc::absolute(dest_path).parent_path(); try { enable_umask_protection(); if( !fc::exists( dest_parent ) ) fc::create_directories( dest_parent ); fc::copy( src_path, dest_path ); disable_umask_protection(); } catch(...) { disable_umask_protection(); throw; } return true; } bool is_locked()const { return _checksum == fc::sha512(); } template<typename T> T get_object(object_id<T::space_id, T::type_id, T> id)const { auto ob = _remote_db->get_objects({id}).front(); return ob.template as<T>( GRAPHENE_MAX_NESTED_OBJECTS ); } void set_operation_fees( signed_transaction& tx, const fee_schedule& s, bool csaf_fee ) { if (csaf_fee) { for (auto& op : tx.operations) s.set_fee_with_csaf(op); } else { for (auto& op : tx.operations) s.set_fee(op); } } variant info() const { auto chain_props = get_chain_properties(); auto global_props = get_global_properties(); auto dynamic_props = get_dynamic_global_properties(); fc::mutable_variant_object result; result["head_block_num"] = dynamic_props.head_block_number; result["head_block_id"] = fc::variant( dynamic_props.head_block_id, 1 ); result["head_block_time"] = dynamic_props.time; result["head_block_age"] = fc::get_approximate_relative_time_string(dynamic_props.time, time_point_sec(time_point::now()), " old"); //result["next_maintenance_time"] = fc::get_approximate_relative_time_string(dynamic_props.next_maintenance_time); result["last_irreversible_block_num"] = dynamic_props.last_irreversible_block_num; result["chain_id"] = chain_props.chain_id; result["participation"] = (100*dynamic_props.recent_slots_filled.popcount()) / 128.0; result["active_witnesses"] = fc::variant( global_props.active_witnesses, GRAPHENE_MAX_NESTED_OBJECTS ); result["active_committee_members"] = fc::variant( global_props.active_committee_members, GRAPHENE_MAX_NESTED_OBJECTS ); return result; } variant_object about() const { string client_version( graphene::utilities::git_revision_description ); const size_t pos = client_version.find( '/' ); if( pos != string::npos && client_version.size() > pos ) client_version = client_version.substr( pos + 1 ); fc::mutable_variant_object result; //result["blockchain_name"] = BLOCKCHAIN_NAME; //result["blockchain_description"] = BTS_BLOCKCHAIN_DESCRIPTION; result["client_version"] = client_version; result["graphene_revision"] = graphene::utilities::git_revision_sha; result["graphene_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec( graphene::utilities::git_revision_unix_timestamp ) ); result["fc_revision"] = fc::git_revision_sha; result["fc_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec( fc::git_revision_unix_timestamp ) ); result["compile_date"] = "compiled on " __DATE__ " at " __TIME__; result["boost_version"] = boost::replace_all_copy(std::string(BOOST_LIB_VERSION), "_", "."); result["openssl_version"] = OPENSSL_VERSION_TEXT; std::string bitness = boost::lexical_cast<std::string>(8 * sizeof(int*)) + "-bit"; #if defined(__APPLE__) std::string os = "osx"; #elif defined(__linux__) std::string os = "linux"; #elif defined(_MSC_VER) std::string os = "win32"; #else std::string os = "other"; #endif result["build"] = os + " " + bitness; return result; } chain_property_object get_chain_properties() const { return _remote_db->get_chain_properties(); } global_property_object get_global_properties() const { return _remote_db->get_global_properties(); } content_parameter_extension_type get_global_properties_extensions() const { return _remote_db->get_global_properties().parameters.get_award_params(); } dynamic_global_property_object get_dynamic_global_properties() const { return _remote_db->get_dynamic_global_properties(); } account_object get_account(account_uid_type uid) const { /* // TODO review. commented out to get around the caching issue const auto& idx = _wallet.my_accounts.get<by_uid>(); auto itr = idx.find(uid); if( itr != idx.end() ) return *itr; */ auto rec = _remote_db->get_accounts_by_uid({uid}).front(); FC_ASSERT( rec, "Can not find account ${uid}.", ("uid",uid) ); return *rec; } account_object get_account(string account_name_or_id) const { FC_ASSERT( account_name_or_id.size() > 0 ); if( graphene::utilities::is_number( account_name_or_id ) ) { // It's a UID return get_account( fc::variant( account_name_or_id ).as<account_uid_type>( 1 ) ); } else { // It's a name /* // TODO review. commented out to get around the caching issue if( _wallet.my_accounts.get<by_name>().count(account_name_or_id) ) { auto local_account = *_wallet.my_accounts.get<by_name>().find(account_name_or_id); auto blockchain_account = _remote_db->lookup_account_names({account_name_or_id}).front(); FC_ASSERT( blockchain_account ); if (local_account.uid != blockchain_account->uid) elog("my account uid ${uid} different from blockchain uid ${uid2}", ("uid", local_account.uid)("uid2", blockchain_account->uid)); if (local_account.name != blockchain_account->name) elog("my account name ${name} different from blockchain name ${name2}", ("name", local_account.name)("name2", blockchain_account->name)); return *_wallet.my_accounts.get<by_name>().find(account_name_or_id); } */ optional<account_object> rec = _remote_db->get_account_by_name( account_name_or_id ); FC_ASSERT( rec && rec->name == account_name_or_id, "Can not find account ${a}.", ("a",account_name_or_id) ); return *rec; } } account_uid_type get_account_uid(string account_name_or_id) const { return get_account(account_name_or_id).get_uid(); } account_id_type get_account_id(string account_name_or_id) const { return get_account(account_name_or_id).get_id(); } optional<asset_object_with_data> find_asset(asset_aid_type aid)const { auto rec = _remote_db->get_assets({aid}).front(); return rec; } optional<asset_object_with_data> find_asset(string asset_symbol_or_id)const { FC_ASSERT( asset_symbol_or_id.size() > 0 ); if(graphene::utilities::is_number(asset_symbol_or_id)) { asset_aid_type id = fc::variant( asset_symbol_or_id ).as_uint64(); return find_asset(id); } else if(auto id = maybe_id<asset_id_type>(asset_symbol_or_id)) { return get_object(*id); } else { auto rec = _remote_db->lookup_asset_symbols({asset_symbol_or_id}).front(); if( rec ) { if( rec->symbol != asset_symbol_or_id ) return optional<asset_object>(); } return rec; } } asset_object_with_data get_asset(asset_aid_type aid)const { auto opt = find_asset(aid); FC_ASSERT( opt, "Can not find asset ${a}", ("a", aid) ); return *opt; } asset_object_with_data get_asset(string asset_symbol_or_id)const { auto opt = find_asset(asset_symbol_or_id); FC_ASSERT( opt, "Can not find asset ${a}", ("a", asset_symbol_or_id) ); return *opt; } asset_aid_type get_asset_aid(string asset_symbol_or_id) const { FC_ASSERT( asset_symbol_or_id.size() > 0 ); auto opt_asset = find_asset( asset_symbol_or_id ); FC_ASSERT( opt_asset.valid(), "Can not find asset ${a}", ("a", asset_symbol_or_id) ); return opt_asset->asset_id; } string get_wallet_filename() const { return _wallet_filename; } fc::ecc::private_key get_private_key(const public_key_type& id)const { FC_ASSERT( !self.is_locked(), "The wallet must be unlocked to get the private key" ); auto it = _keys.find(id); FC_ASSERT( it != _keys.end(), "Can not find private key of ${pub} in the wallet", ("pub",id) ); fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); FC_ASSERT( privkey, "Can not find private key of ${pub} in the wallet", ("pub",id) ); return *privkey; } fc::ecc::private_key get_private_key_for_account(const account_object& account)const { vector<public_key_type> active_keys = account.active.get_keys(); if (active_keys.size() != 1) FC_THROW("Expecting a simple authority with one active key"); return get_private_key(active_keys.front()); } // imports the private key into the wallet, and associate it in some way (?) with the // given account name. // @returns true if the key matches a current active/owner/memo key for the named // account, false otherwise (but it is stored either way) bool import_key(string account_name_or_id, string wif_key) { fc::optional<fc::ecc::private_key> optional_private_key = wif_to_key(wif_key); if (!optional_private_key) FC_THROW("Invalid private key"); graphene::chain::public_key_type wif_pub_key = optional_private_key->get_public_key(); account_object account = get_account( account_name_or_id ); // make a list of all current public keys for the named account flat_set<public_key_type> all_keys_for_account; std::vector<public_key_type> secondary_keys = account.secondary.get_keys(); std::vector<public_key_type> active_keys = account.active.get_keys(); std::vector<public_key_type> owner_keys = account.owner.get_keys(); std::copy(secondary_keys.begin(), secondary_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); std::copy(active_keys.begin(), active_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); std::copy(owner_keys.begin(), owner_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); all_keys_for_account.insert(account.memo_key); _keys[wif_pub_key] = wif_key; _wallet.update_account(account); _wallet.extra_keys[account.uid].insert(wif_pub_key); return all_keys_for_account.find(wif_pub_key) != all_keys_for_account.end(); } bool load_wallet_file(string wallet_filename = "") { if( !self.is_locked() ) self.lock(); // TODO: Merge imported wallet with existing wallet, // instead of replacing it if( wallet_filename == "" ) wallet_filename = _wallet_filename; if( ! fc::exists( wallet_filename ) ) return false; _wallet = fc::json::from_file( wallet_filename ).as< wallet_data >( 2 * GRAPHENE_MAX_NESTED_OBJECTS ); if( _wallet.chain_id != _chain_id ) FC_THROW( "Wallet chain ID does not match", ("wallet.chain_id", _wallet.chain_id) ("chain_id", _chain_id) ); size_t account_pagination = 100; vector< account_uid_type > account_uids_to_send; size_t n = _wallet.my_accounts.size(); account_uids_to_send.reserve( std::min( account_pagination, n ) ); auto it = _wallet.my_accounts.begin(); for( size_t start=0; start<n; start+=account_pagination ) { size_t end = std::min( start+account_pagination, n ); assert( end > start ); account_uids_to_send.clear(); std::vector< account_object > old_accounts; for( size_t i=start; i<end; i++ ) { assert( it != _wallet.my_accounts.end() ); old_accounts.push_back( *it ); account_uids_to_send.push_back( old_accounts.back().uid ); ++it; } std::vector< optional< account_object > > accounts = _remote_db->get_accounts_by_uid(account_uids_to_send); // server response should be same length as request FC_ASSERT( accounts.size() == account_uids_to_send.size(), "remote server error" ); size_t i = 0; for( const optional< account_object >& acct : accounts ) { account_object& old_acct = old_accounts[i]; if( !acct.valid() ) { elog( "Could not find account ${uid} : \"${name}\" does not exist on the chain!", ("uid", old_acct.uid)("name", old_acct.name) ); i++; continue; } // this check makes sure the server didn't send results // in a different order, or accounts we didn't request FC_ASSERT( acct->uid == old_acct.uid, "remote server error" ); if( fc::json::to_string(*acct) != fc::json::to_string(old_acct) ) { wlog( "Account ${uid} : \"${name}\" updated on chain", ("uid", acct->uid)("name", acct->name) ); } _wallet.update_account( *acct ); i++; } } return true; } void save_wallet_file(string wallet_filename = "") { // // Serialize in memory, then save to disk // // This approach lessens the risk of a partially written wallet // if exceptions are thrown in serialization // encrypt_keys(); if( wallet_filename == "" ) wallet_filename = _wallet_filename; wlog( "saving wallet to file ${fn}", ("fn", wallet_filename) ); string data = fc::json::to_pretty_string( _wallet ); try { enable_umask_protection(); // // Parentheses on the following declaration fails to compile, // due to the Most Vexing Parse. Thanks, C++ // // http://en.wikipedia.org/wiki/Most_vexing_parse // fc::ofstream outfile{ fc::path( wallet_filename ) }; outfile.write( data.c_str(), data.length() ); outfile.flush(); outfile.close(); disable_umask_protection(); } catch(...) { disable_umask_protection(); throw; } } transaction_handle_type begin_builder_transaction() { int trx_handle = _builder_transactions.empty()? 0 : (--_builder_transactions.end())->first + 1; _builder_transactions[trx_handle]; return trx_handle; } void add_operation_to_builder_transaction(transaction_handle_type transaction_handle, const operation& op) { FC_ASSERT(_builder_transactions.count(transaction_handle)); _builder_transactions[transaction_handle].operations.emplace_back(op); } void replace_operation_in_builder_transaction(transaction_handle_type handle, uint32_t operation_index, const operation& new_op) { FC_ASSERT(_builder_transactions.count(handle)); signed_transaction& trx = _builder_transactions[handle]; FC_ASSERT( operation_index < trx.operations.size()); trx.operations[operation_index] = new_op; } asset set_fees_on_builder_transaction(transaction_handle_type handle, string fee_asset = GRAPHENE_SYMBOL) { FC_ASSERT(_builder_transactions.count(handle)); auto fee_asset_obj = get_asset(fee_asset); asset total_fee = fee_asset_obj.amount(0); FC_ASSERT(fee_asset_obj.asset_id == GRAPHENE_CORE_ASSET_AID, "Must use core assets as a fee"); auto gprops = _remote_db->get_global_properties().parameters; for( auto& op : _builder_transactions[handle].operations ) total_fee += gprops.current_fees->set_fee( op ); return total_fee; } transaction preview_builder_transaction(transaction_handle_type handle) { FC_ASSERT(_builder_transactions.count(handle)); return _builder_transactions[handle]; } signed_transaction sign_builder_transaction(transaction_handle_type transaction_handle, bool broadcast = true) { FC_ASSERT(_builder_transactions.count(transaction_handle)); return _builder_transactions[transaction_handle] = sign_transaction(_builder_transactions[transaction_handle], broadcast); } signed_transaction propose_builder_transaction( transaction_handle_type handle, string account_name_or_id, time_point_sec expiration = time_point::now() + fc::minutes(1), uint32_t review_period_seconds = 0, bool broadcast = true) { FC_ASSERT(_builder_transactions.count(handle)); proposal_create_operation op; op.fee_paying_account = get_account(account_name_or_id).get_uid(); op.expiration_time = expiration; signed_transaction& trx = _builder_transactions[handle]; std::transform(trx.operations.begin(), trx.operations.end(), std::back_inserter(op.proposed_ops), [](const operation& op) -> op_wrapper { return op; }); if( review_period_seconds ) op.review_period_seconds = review_period_seconds; trx.operations = {op}; _remote_db->get_global_properties().parameters.current_fees->set_fee( trx.operations.front() ); return trx = sign_transaction(trx, broadcast); } void remove_builder_transaction(transaction_handle_type handle) { _builder_transactions.erase(handle); } signed_transaction register_account(string name, public_key_type owner, public_key_type active, string registrar_account, string referrer_account, uint32_t referrer_percent, uint32_t seed, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked() ); account_create_operation account_create_op; // #449 referrer_percent is on 0-100 scale, if user has larger // number it means their script is using GRAPHENE_100_PERCENT scale // instead of 0-100 scale. FC_ASSERT( referrer_percent <= 100 ); // TODO: process when pay_from_account is ID account_object registrar_account_object = this->get_account( registrar_account ); //FC_ASSERT( registrar_account_object.is_lifetime_member() ); account_object referrer_account_object = this->get_account(referrer_account); // TODO review /* account_id_type registrar_account_id = registrar_account_object.id; account_object referrer_account_object = this->get_account( referrer_account ); account_create_op.referrer = referrer_account_object.id; account_create_op.referrer_percent = uint16_t( referrer_percent * GRAPHENE_1_PERCENT ); account_create_op.registrar = registrar_account_id; */ account_create_op.name = name; account_create_op.owner = authority(1, owner, 1); account_create_op.active = authority(1, active, 1); account_create_op.secondary = authority(1, owner, 1); account_create_op.memo_key = active; account_create_op.uid = graphene::chain::calc_account_uid(seed); account_reg_info reg_info; reg_info.registrar = registrar_account_object.uid; reg_info.referrer = referrer_account_object.uid; account_create_op.reg_info = reg_info; signed_transaction tx; tx.operations.push_back( account_create_op ); auto current_fees = _remote_db->get_global_properties().parameters.current_fees; set_operation_fees( tx, current_fees, csaf_fee ); vector<public_key_type> paying_keys = registrar_account_object.active.get_keys(); auto dyn_props = get_dynamic_global_properties(); tx.set_reference_block( dyn_props.head_block_id ); tx.set_expiration( dyn_props.time + fc::seconds(30) ); tx.validate(); for( public_key_type& key : paying_keys ) { auto it = _keys.find(key); if( it != _keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _keys" ); } tx.sign( *privkey, _chain_id ); } } if( broadcast ) _remote_net_broadcast->broadcast_transaction( tx ); return tx; } FC_CAPTURE_AND_RETHROW( (name)(owner)(active)(registrar_account)(referrer_account)(referrer_percent)(csaf_fee)(broadcast) ) } // This function generates derived keys starting with index 0 and keeps incrementing // the index until it finds a key that isn't registered in the block chain. To be // safer, it continues checking for a few more keys to make sure there wasn't a short gap // caused by a failed registration or the like. int find_first_unused_derived_key_index(const fc::ecc::private_key& parent_key) { int first_unused_index = 0; int number_of_consecutive_unused_keys = 0; for (int key_index = 0; ; ++key_index) { fc::ecc::private_key derived_private_key = derive_private_key(key_to_wif(parent_key), key_index); graphene::chain::public_key_type derived_public_key = derived_private_key.get_public_key(); if( _keys.find(derived_public_key) == _keys.end() ) { if (number_of_consecutive_unused_keys) { ++number_of_consecutive_unused_keys; if (number_of_consecutive_unused_keys > 5) return first_unused_index; } else { first_unused_index = key_index; number_of_consecutive_unused_keys = 1; } } else { // key_index is used first_unused_index = 0; number_of_consecutive_unused_keys = 0; } } } signed_transaction create_account_with_private_key(fc::ecc::private_key owner_privkey, string account_name, string registrar_account, string referrer_account, uint32_t seed, bool csaf_fee = true, bool broadcast = false, bool save_wallet = true) { try { int active_key_index = find_first_unused_derived_key_index(owner_privkey); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), active_key_index); int memo_key_index = find_first_unused_derived_key_index(active_privkey); fc::ecc::private_key memo_privkey = derive_private_key( key_to_wif(active_privkey), memo_key_index); graphene::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); graphene::chain::public_key_type active_pubkey = active_privkey.get_public_key(); graphene::chain::public_key_type memo_pubkey = memo_privkey.get_public_key(); account_create_operation account_create_op; // TODO: process when pay_from_account is ID account_object registrar_account_object = get_account( registrar_account ); account_object referrer_account_object = get_account(referrer_account); // TODO: review /* account_id_type registrar_account_id = registrar_account_object.id; account_object referrer_account_object = get_account( referrer_account ); account_create_op.referrer = referrer_account_object.id; account_create_op.referrer_percent = referrer_account_object.referrer_rewards_percentage; account_create_op.registrar = registrar_account_id; */ account_create_op.name = account_name; account_create_op.owner = authority(1, owner_pubkey, 1); account_create_op.active = authority(1, active_pubkey, 1); account_create_op.secondary = authority(1, owner_pubkey, 1); account_create_op.uid = graphene::chain::calc_account_uid(seed); account_reg_info reg_info; reg_info.registrar = registrar_account_object.uid; reg_info.referrer = referrer_account_object.uid; account_create_op.reg_info = reg_info; account_create_op.memo_key = memo_pubkey; // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( account_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); vector<public_key_type> paying_keys = registrar_account_object.active.get_keys(); auto dyn_props = get_dynamic_global_properties(); tx.set_reference_block( dyn_props.head_block_id ); tx.set_expiration( dyn_props.time + fc::seconds(30) ); tx.validate(); for( public_key_type& key : paying_keys ) { auto it = _keys.find(key); if( it != _keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); FC_ASSERT( privkey.valid(), "Malformed private key in _keys" ); tx.sign( *privkey, _chain_id ); } } // we do not insert owner_privkey here because // it is intended to only be used for key recovery _wallet.pending_account_registrations[account_name].push_back(key_to_wif( active_privkey )); _wallet.pending_account_registrations[account_name].push_back(key_to_wif( memo_privkey )); if( save_wallet ) save_wallet_file(); if( broadcast ) _remote_net_broadcast->broadcast_transaction( tx ); return tx; } FC_CAPTURE_AND_RETHROW( (account_name)(registrar_account)(referrer_account)(csaf_fee)(broadcast) ) } signed_transaction create_account_with_brain_key(string brain_key, string account_name, string registrar_account, string referrer_account, uint32_t seed, bool csaf_fee = true, bool broadcast = false, bool save_wallet = true) { try { FC_ASSERT( !self.is_locked() ); string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); return create_account_with_private_key(owner_privkey, account_name, registrar_account, referrer_account, seed, csaf_fee, broadcast, save_wallet); } FC_CAPTURE_AND_RETHROW( (account_name)(registrar_account)(referrer_account) ) } signed_transaction create_asset(string issuer, string symbol, uint8_t precision, asset_options common, share_type initial_supply, bool csaf_fee, bool broadcast = false) { try { account_object issuer_account = get_account( issuer ); FC_ASSERT(!find_asset(symbol).valid(), "Asset with that symbol already exists!"); asset_create_operation create_op; create_op.issuer = issuer_account.uid; create_op.symbol = symbol; create_op.precision = precision; create_op.common_options = common; if( initial_supply != 0 ) { create_op.extensions = extension<asset_create_operation::ext>(); create_op.extensions->value.initial_supply = initial_supply; } signed_transaction tx; tx.operations.push_back( create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (issuer)(symbol)(precision)(common)(csaf_fee)(broadcast) ) } signed_transaction update_asset(string symbol, optional<uint8_t> new_precision, asset_options new_options, bool csaf_fee, bool broadcast /* = false */) { try { optional<asset_object_with_data> asset_to_update = find_asset(symbol); FC_ASSERT( asset_to_update.valid(), "Can not find asset ${a}", ("a", symbol) ); asset_update_operation update_op; update_op.issuer = asset_to_update->issuer; update_op.asset_to_update = asset_to_update->asset_id; update_op.new_precision = new_precision; update_op.new_options = new_options; signed_transaction tx; tx.operations.push_back( update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (symbol)(new_precision)(new_options)(csaf_fee)(broadcast) ) } signed_transaction reserve_asset(string from, string amount, string symbol, bool csaf_fee, bool broadcast /* = false */) { try { account_object from_account = get_account(from); optional<asset_object_with_data> asset_to_reserve = find_asset(symbol); FC_ASSERT( asset_to_reserve.valid(), "Can not find asset ${a}", ("a", symbol) ); asset_reserve_operation reserve_op; reserve_op.payer = from_account.uid; reserve_op.amount_to_reserve = asset_to_reserve->amount_from_string(amount); signed_transaction tx; tx.operations.push_back( reserve_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (from)(amount)(symbol)(csaf_fee)(broadcast) ) } signed_transaction whitelist_account(string authorizing_account, string account_to_list, account_whitelist_operation::account_listing new_listing_status, bool csaf_fee, bool broadcast /* = false */) { try { account_whitelist_operation whitelist_op; whitelist_op.authorizing_account = get_account_uid(authorizing_account); whitelist_op.account_to_list = get_account_uid(account_to_list); whitelist_op.new_listing = new_listing_status; signed_transaction tx; tx.operations.push_back( whitelist_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (authorizing_account)(account_to_list)(new_listing_status)(csaf_fee)(broadcast) ) } signed_transaction create_committee_member(string owner_account, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object committee_member_account = get_account(owner_account); if( _remote_db->get_committee_member_by_account( committee_member_account.uid ) ) FC_THROW( "Account ${owner_account} is already a committee_member", ("owner_account", owner_account) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pledge_asset_symbol) ); committee_member_create_operation committee_member_create_op; committee_member_create_op.account = committee_member_account.uid; committee_member_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); committee_member_create_op.url = url; signed_transaction tx; tx.operations.push_back( committee_member_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } witness_object get_witness(string owner_account) { try { fc::optional<witness_id_type> witness_id = maybe_id<witness_id_type>(owner_account); if (witness_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*witness_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<witness_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No witness is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<witness_object> witness = _remote_db->get_witness_by_account(owner_account_uid); if (witness) return *witness; else FC_THROW("No witness is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or witness named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } platform_object get_platform(string owner_account) { try { fc::optional<platform_id_type> platform_id = maybe_id<platform_id_type>(owner_account); if (platform_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*platform_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<platform_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No platform is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<platform_object> platform = _remote_db->get_platform_by_account(owner_account_uid); if (platform) return *platform; else FC_THROW("No platform is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or platform named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } committee_member_object get_committee_member(string owner_account) { try { fc::optional<committee_member_id_type> committee_member_id = maybe_id<committee_member_id_type>(owner_account); if (committee_member_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*committee_member_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<committee_member_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No committee_member is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<committee_member_object> committee_member = _remote_db->get_committee_member_by_account(owner_account_uid); if (committee_member) return *committee_member; else FC_THROW("No committee_member is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or committee_member named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } signed_transaction create_witness_with_details(string owner_account, public_key_type block_signing_key, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object witness_account = get_account(owner_account); if( _remote_db->get_witness_by_account( witness_account.uid ) ) FC_THROW( "Account ${owner_account} is already a witness", ("owner_account", owner_account) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pledge_asset_symbol) ); witness_create_operation witness_create_op; witness_create_op.account = witness_account.uid; witness_create_op.block_signing_key = block_signing_key; witness_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); witness_create_op.url = url; signed_transaction tx; tx.operations.push_back( witness_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(block_signing_key)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction create_witness(string owner_account, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object witness_account = get_account(owner_account); fc::ecc::private_key active_private_key = get_private_key_for_account(witness_account); int witness_key_index = find_first_unused_derived_key_index(active_private_key); fc::ecc::private_key witness_private_key = derive_private_key(key_to_wif(active_private_key), witness_key_index); graphene::chain::public_key_type witness_public_key = witness_private_key.get_public_key(); witness_create_operation witness_create_op; witness_create_op.account = witness_account.uid; witness_create_op.block_signing_key = witness_public_key; witness_create_op.url = url; if (_remote_db->get_witness_by_account(witness_create_op.account)) FC_THROW("Account ${owner_account} is already a witness", ("owner_account", owner_account)); signed_transaction tx; tx.operations.push_back( witness_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); _wallet.pending_witness_registrations[owner_account] = key_to_wif(witness_private_key); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(csaf_fee)(broadcast) ) } signed_transaction create_platform(string owner_account, string name, string pledge_amount, string pledge_asset_symbol, string url, string extra_data, bool csaf_fee, bool broadcast ) { try { account_object platform_account = get_account( owner_account ); if( _remote_db->get_platform_by_account( platform_account.uid ) ) FC_THROW( "Account ${owner_account} is already a platform", ( "owner_account", owner_account ) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ( "asset", pledge_asset_symbol ) ); platform_create_operation platform_create_op; platform_create_op.account = platform_account.uid; platform_create_op.name = name; platform_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); platform_create_op.extra_data = extra_data; platform_create_op.url = url; signed_transaction tx; tx.operations.push_back( platform_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(name)(pledge_amount)(pledge_asset_symbol)(url)(extra_data)(csaf_fee)(broadcast) ) } signed_transaction update_platform(string platform_account, optional<string> name, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, optional<string> extra_data, bool csaf_fee, bool broadcast ) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ( "asset", *pledge_asset_symbol ) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } platform_object platform = get_platform( platform_account ); account_object platform_owner = get_account( platform.owner ); platform_update_operation platform_update_op; platform_update_op.account = platform_owner.uid; platform_update_op.new_name = name; platform_update_op.new_pledge = pledge; platform_update_op.new_url = url; platform_update_op.new_extra_data = extra_data; signed_transaction tx; tx.operations.push_back( platform_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (platform_account)(name)(pledge_amount)(pledge_asset_symbol)(url)(extra_data)(csaf_fee)(broadcast) ) } signed_transaction account_auth_platform(string account, string platform_owner, string memo, string limit_for_platform = 0, uint32_t permission_flags = account_auth_platform_object::Platform_Permission_Forward | account_auth_platform_object::Platform_Permission_Liked | account_auth_platform_object::Platform_Permission_Buyout | account_auth_platform_object::Platform_Permission_Comment | account_auth_platform_object::Platform_Permission_Reward | account_auth_platform_object::Platform_Permission_Post | account_auth_platform_object::Platform_Permission_Content_Update, bool csaf_fee = true, bool broadcast = false) { try { fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_object user = get_account(account); account_object platform_account = get_account(platform_owner); auto pa = _remote_db->get_platform_by_account(platform_account.uid); FC_ASSERT(pa.valid(), "Account ${platform_owner} is not a platform", ("platform_owner", platform_owner)); account_auth_platform_operation op; op.uid = user.uid; op.platform = pa->owner; account_auth_platform_operation::extension_parameter ext; ext.limit_for_platform = asset_obj->amount_from_string(limit_for_platform).amount; ext.permission_flags = permission_flags; if (memo.size()) { ext.memo = memo_data(); ext.memo->from = user.memo_key; ext.memo->to = platform_account.memo_key; ext.memo->set_message(get_private_key(user.memo_key), platform_account.memo_key, memo); } op.extensions = extension<account_auth_platform_operation::extension_parameter>(); op.extensions->value = ext; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((account)(platform_owner)(limit_for_platform)(permission_flags)(csaf_fee)(broadcast)) } signed_transaction account_cancel_auth_platform(string account, string platform_owner, bool csaf_fee = true, bool broadcast = false) { try { account_object user = get_account( account ); account_object platform_account = get_account( platform_owner ); account_cancel_auth_platform_operation op; op.uid = user.uid; op.platform = platform_account.uid; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(platform_owner)(csaf_fee)(broadcast) ) } signed_transaction update_committee_member( string committee_member_account, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", *pledge_asset_symbol) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } committee_member_object committee_member = get_committee_member( committee_member_account ); account_object committee_member_account = get_account( committee_member.account ); committee_member_update_operation committee_member_update_op; committee_member_update_op.account = committee_member_account.uid; committee_member_update_op.new_pledge = pledge; committee_member_update_op.new_url = url; signed_transaction tx; tx.operations.push_back( committee_member_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction update_witness_with_details( string witness_account, optional<public_key_type> block_signing_key, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", *pledge_asset_symbol) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } witness_object witness = get_witness( witness_account ); account_object witness_account = get_account( witness.account ); witness_update_operation witness_update_op; witness_update_op.account = witness_account.uid; witness_update_op.new_signing_key = block_signing_key; witness_update_op.new_pledge = pledge; witness_update_op.new_url = url; signed_transaction tx; tx.operations.push_back( witness_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_account)(block_signing_key)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction update_witness(string witness_name, string url, string block_signing_key, bool csaf_fee, bool broadcast /* = false */) { try { witness_object witness = get_witness(witness_name); account_object witness_account = get_account( witness.account ); witness_update_operation witness_update_op; //witness_update_op.witness = witness.id; witness_update_op.account = witness_account.uid; if( url != "" ) witness_update_op.new_url = url; if( block_signing_key != "" ) witness_update_op.new_signing_key = public_key_type( block_signing_key ); signed_transaction tx; tx.operations.push_back( witness_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_name)(url)(block_signing_key)(csaf_fee)(broadcast) ) } signed_transaction collect_witness_pay(string witness_account, string pay_amount, string pay_asset_symbol, bool csaf_fee, bool broadcast /* = false */) { try { witness_object witness = get_witness(witness_account); fc::optional<asset_object_with_data> asset_obj = get_asset( pay_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pay_asset_symbol) ); witness_collect_pay_operation witness_collect_pay_op; witness_collect_pay_op.account = witness.account; witness_collect_pay_op.pay = asset_obj->amount_from_string( pay_amount ); signed_transaction tx; tx.operations.push_back( witness_collect_pay_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_account)(pay_amount)(pay_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction collect_csaf(string from, string to, string amount, string asset_symbol, time_point_sec time, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); csaf_collect_operation cc_op; cc_op.from = from_account.uid; cc_op.to = to_account.uid; cc_op.amount = asset_obj->amount_from_string(amount); cc_op.time = time; signed_transaction tx; tx.operations.push_back(cc_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(time)(csaf_fee)(broadcast) ) } signed_transaction update_witness_votes(string voting_account, flat_set<string> witnesses_to_add, flat_set<string> witnesses_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object voting_account_object = get_account(voting_account); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( witnesses_to_add.size() ); uids_to_remove.reserve( witnesses_to_remove.size() ); for( string wit : witnesses_to_add ) uids_to_add.insert( get_witness( wit ).account ); for( string wit : witnesses_to_remove ) uids_to_remove.insert( get_witness( wit ).account ); witness_vote_update_operation witness_vote_update_op; witness_vote_update_op.voter = voting_account_object.uid; witness_vote_update_op.witnesses_to_add = uids_to_add; witness_vote_update_op.witnesses_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( witness_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(witnesses_to_add)(witnesses_to_remove)(csaf_fee)(broadcast) ) } signed_transaction update_platform_votes(string voting_account, flat_set<string> platforms_to_add, flat_set<string> platforms_to_remove, bool csaf_fee, bool broadcast ) { try { account_object voting_account_object = get_account( voting_account ); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( platforms_to_add.size() ); uids_to_remove.reserve( platforms_to_remove.size() ); for( string pla : platforms_to_add ) uids_to_add.insert( get_platform( pla ).owner ); for( string pla : platforms_to_remove ) uids_to_remove.insert( get_platform( pla ).owner ); platform_vote_update_operation platform_vote_update_op; platform_vote_update_op.voter = voting_account_object.uid; platform_vote_update_op.platform_to_add = uids_to_add; platform_vote_update_op.platform_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( platform_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(platforms_to_add)(platforms_to_remove)(csaf_fee)(broadcast) ) } signed_transaction update_committee_member_votes(string voting_account, flat_set<string> committee_members_to_add, flat_set<string> committee_members_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object voting_account_object = get_account(voting_account); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( committee_members_to_add.size() ); uids_to_remove.reserve( committee_members_to_remove.size() ); for( string com : committee_members_to_add ) uids_to_add.insert( get_committee_member( com ).account ); for( string com : committee_members_to_remove ) uids_to_remove.insert( get_committee_member( com ).account ); committee_member_vote_update_operation committee_member_vote_update_op; committee_member_vote_update_op.voter = voting_account_object.uid; committee_member_vote_update_op.committee_members_to_add = uids_to_add; committee_member_vote_update_op.committee_members_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( committee_member_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(committee_members_to_add)(committee_members_to_remove)(csaf_fee)(broadcast) ) } signed_transaction set_voting_proxy(string account_to_modify, optional<string> voting_account, bool csaf_fee, bool broadcast /* = false */) { try { account_update_proxy_operation account_update_op; account_update_op.voter = get_account_uid(account_to_modify); if (voting_account) account_update_op.proxy = get_account_uid(*voting_account); else account_update_op.proxy = GRAPHENE_PROXY_TO_SELF_ACCOUNT_UID; signed_transaction tx; tx.operations.push_back( account_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account_to_modify)(voting_account)(csaf_fee)(broadcast) ) } signed_transaction enable_allowed_assets(string account, bool enable, bool csaf_fee, bool broadcast /* = false */) { try { account_enable_allowed_assets_operation op; op.account = get_account_uid( account ); op.enable = enable; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(enable)(csaf_fee)(broadcast) ) } signed_transaction update_allowed_assets(string account, flat_set<string> assets_to_add, flat_set<string> assets_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object account_obj = get_account( account ); flat_set<asset_aid_type> aids_to_add; flat_set<asset_aid_type> aids_to_remove; aids_to_add.reserve( assets_to_add.size() ); aids_to_remove.reserve( assets_to_remove.size() ); for( string a : assets_to_add ) aids_to_add.insert( get_asset( a ).asset_id ); for( string a : assets_to_remove ) aids_to_remove.insert( get_asset( a ).asset_id ); account_update_allowed_assets_operation op; op.account = get_account_uid( account ); op.assets_to_add = aids_to_add; op.assets_to_remove = aids_to_remove; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(assets_to_add)(assets_to_remove)(csaf_fee)(broadcast) ) } signed_transaction sign_transaction( signed_transaction tx, bool broadcast = false ) { // get required keys to sign the trx const auto& result = _remote_db->get_required_signatures( tx, flat_set<public_key_type>() ); const auto& required_keys = result.first.second; // check whether it's possible to fullfil the authority requirement if( required_keys.find( public_key_type() ) == required_keys.end() ) { // get a subset of available keys flat_set<public_key_type> available_keys; flat_map<public_key_type,fc::ecc::private_key> available_keys_map; for( const auto& pub_key : required_keys ) { auto it = _keys.find( pub_key ); if( it != _keys.end() ) { fc::optional<fc::ecc::private_key> privkey = wif_to_key( it->second ); FC_ASSERT( privkey.valid(), "Malformed private key in _keys" ); available_keys.insert( pub_key ); available_keys_map[ pub_key ] = *privkey; } } // if we have the required key(s), preceed to sign if( !available_keys.empty() ) { // get a subset of required keys const auto& new_result = _remote_db->get_required_signatures( tx, available_keys ); const auto& required_keys_subset = new_result.first.first; //const auto& missed_keys = new_result.first.second; const auto& unused_signatures = new_result.second; // unused signatures can be removed safely for( const auto& sig : unused_signatures ) tx.signatures.erase( std::remove( tx.signatures.begin(), tx.signatures.end(), sig), tx.signatures.end() ); bool no_sig = tx.signatures.empty(); auto dyn_props = get_dynamic_global_properties(); // if no signature is included in the trx, reset the tapos data; otherwise keep the tapos data if( no_sig ) tx.set_reference_block( dyn_props.head_block_id ); // if no signature is included in the trx, reset expiration time; otherwise keep it if( no_sig ) { // first, some bookkeeping, expire old items from _recently_generated_transactions // since transactions include the head block id, we just need the index for keeping transactions unique // when there are multiple transactions in the same block. choose a time period that should be at // least one block long, even in the worst case. 5 minutes ought to be plenty. fc::time_point_sec oldest_transaction_ids_to_track(dyn_props.time - fc::minutes(5)); auto oldest_transaction_record_iter = _recently_generated_transactions.get<timestamp_index>().lower_bound(oldest_transaction_ids_to_track); auto begin_iter = _recently_generated_transactions.get<timestamp_index>().begin(); _recently_generated_transactions.get<timestamp_index>().erase(begin_iter, oldest_transaction_record_iter); } uint32_t expiration_time_offset = 0; for (;;) { if( no_sig ) { tx.set_expiration( dyn_props.time + fc::seconds(120 + expiration_time_offset) ); tx.signatures.clear(); } //idump((required_keys_subset)(available_keys)); // TODO: for better performance, sign after dupe check for( const auto& key : required_keys_subset ) { tx.sign( available_keys_map[key], _chain_id ); /// TODO: if transaction has enough signatures to be "valid" don't add any more, /// there are cases where the wallet may have more keys than strictly necessary and /// the transaction will be rejected if the transaction validates without requiring /// all signatures provided } graphene::chain::transaction_id_type this_transaction_id = tx.id(); auto iter = _recently_generated_transactions.find(this_transaction_id); if (iter == _recently_generated_transactions.end()) { // we haven't generated this transaction before, the usual case recently_generated_transaction_record this_transaction_record; this_transaction_record.generation_time = dyn_props.time; this_transaction_record.transaction_id = this_transaction_id; _recently_generated_transactions.insert(this_transaction_record); break; } // if there was a signature included in the trx, we can not update expiration field if( !no_sig ) break; // if we've generated a dupe, increment expiration time and re-sign it ++expiration_time_offset; } } } //wdump((tx)); if( broadcast ) { try { _remote_net_broadcast->broadcast_transaction( tx ); } catch (const fc::exception& e) { elog("Caught exception while broadcasting tx ${id}: ${e}", ("id", tx.id().str())("e", e.to_detail_string()) ); throw; } } return tx; } transaction_id_type broadcast_transaction( signed_transaction tx ) { try { _remote_net_broadcast->broadcast_transaction( tx ); } catch (const fc::exception& e) { elog("Caught exception while broadcasting tx ${id}: ${e}", ("id", tx.id().str())("e", e.to_detail_string()) ); throw; } return tx.id(); } signed_transaction transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked(), "Should unlock first" ); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); transfer_operation xfer_op; xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if( memo.size() ) { xfer_op.memo = memo_data(); xfer_op.memo->from = from_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(from_account.memo_key), to_account.memo_key, memo); } //xfer_op.fee = fee_type(asset(_remote_db->get_required_fee_data({ xfer_op }).at(0).min_fee)); signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(memo)(csaf_fee)(broadcast) ) } signed_transaction transfer_extension(string from, string to, string amount, string asset_symbol, string memo, optional<string> sign_platform , bool isfrom_balance = true, bool isto_balance = true, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); transfer_operation xfer_op; xfer_op.extensions = extension< transfer_operation::ext >(); if (isfrom_balance) xfer_op.extensions->value.from_balance = asset_obj->amount_from_string(amount); else xfer_op.extensions->value.from_prepaid = asset_obj->amount_from_string(amount); if (isto_balance) xfer_op.extensions->value.to_balance = asset_obj->amount_from_string(amount); else xfer_op.extensions->value.to_prepaid = asset_obj->amount_from_string(amount); if (sign_platform.valid()){ xfer_op.extensions->value.sign_platform = get_account_uid(*sign_platform); } xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if (memo.size()) { xfer_op.memo = memo_data(); xfer_op.memo->from = from_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(from_account.memo_key), to_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from)(to)(amount)(asset_symbol)(memo)(isfrom_balance)(isto_balance)(csaf_fee)(broadcast)) } signed_transaction override_transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked(), "Should unlock first" ); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object issuer_account = get_account(asset_obj->issuer); account_object from_account = get_account(from); account_object to_account = get_account(to); override_transfer_operation xfer_op; xfer_op.issuer = issuer_account.uid; xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if( memo.size() ) { xfer_op.memo = memo_data(); xfer_op.memo->from = issuer_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(issuer_account.memo_key), to_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(memo)(csaf_fee)(broadcast) ) } signed_transaction issue_asset(string to_account, string amount, string symbol, string memo, bool csaf_fee = true, bool broadcast = false) { auto asset_obj = get_asset(symbol); account_object to = get_account(to_account); account_object issuer = get_account(asset_obj.issuer); asset_issue_operation issue_op; issue_op.issuer = asset_obj.issuer; issue_op.asset_to_issue = asset_obj.amount_from_string(amount); issue_op.issue_to_account = to.uid; if( memo.size() ) { issue_op.memo = memo_data(); issue_op.memo->from = issuer.memo_key; issue_op.memo->to = to.memo_key; issue_op.memo->set_message(get_private_key(issuer.memo_key), to.memo_key, memo); } signed_transaction tx; tx.operations.push_back(issue_op); set_operation_fees(tx,_remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } std::map<string,std::function<string(fc::variant,const fc::variants&)>> get_result_formatters() const { std::map<string,std::function<string(fc::variant,const fc::variants&)> > m; m["help"] = [](variant result, const fc::variants& a) { return result.get_string(); }; m["gethelp"] = [](variant result, const fc::variants& a) { return result.get_string(); }; m["get_relative_account_history"] = [this](variant result, const fc::variants& a) { auto r = result.as<vector<operation_detail>>( GRAPHENE_MAX_NESTED_OBJECTS ); std::stringstream ss; ss << "#" << " "; ss << "block_num" << " "; ss << "time " << " "; ss << "description/fee_payer/fee/operation_result" << " "; ss << " \n"; for( operation_detail& d : r ) { operation_history_object& i = d.op; ss << d.sequence << " "; ss << i.block_num << " "; ss << i.block_timestamp.to_iso_string() << " "; i.op.visit(operation_printer(ss, *this, i.result)); ss << " \n"; } return ss.str(); }; m["list_account_balances"] = [this](variant result, const fc::variants& a) { auto r = result.as<vector<asset>>( GRAPHENE_MAX_NESTED_OBJECTS ); vector<asset_object_with_data> asset_recs; std::transform(r.begin(), r.end(), std::back_inserter(asset_recs), [this](const asset& a) { return get_asset(a.asset_id); }); std::stringstream ss; for( unsigned i = 0; i < asset_recs.size(); ++i ) ss << asset_recs[i].amount_to_pretty_string(r[i]) << "\n"; return ss.str(); }; return m; } signed_transaction committee_proposal_create( const string committee_member_account, const vector<committee_proposal_item_type> items, const uint32_t voting_closing_block_num, optional<voting_opinion_type> proposer_opinion, const uint32_t execution_block_num = 0, const uint32_t expiration_block_num = 0, bool csaf_fee = true, bool broadcast = false ) { try { committee_proposal_create_operation op; op.proposer = get_account_uid( committee_member_account ); op.items = items; op.voting_closing_block_num = voting_closing_block_num; op.proposer_opinion = proposer_opinion; op.execution_block_num = execution_block_num; op.expiration_block_num = expiration_block_num; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(items)(voting_closing_block_num)(proposer_opinion)(execution_block_num)(expiration_block_num)(csaf_fee)(broadcast) ) } signed_transaction committee_proposal_vote( const string committee_member_account, const uint64_t proposal_number, const voting_opinion_type opinion, bool csaf_fee = true, bool broadcast = false ) { try { committee_proposal_update_operation update_op; update_op.account = get_account_uid( committee_member_account ); update_op.proposal_number = proposal_number; update_op.opinion = opinion; signed_transaction tx; tx.operations.push_back( update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(proposal_number)(opinion)(csaf_fee)(broadcast) ) } signed_transaction proposal_create(const string fee_paying_account, const vector<op_wrapper> proposed_ops, time_point_sec expiration_time, uint32_t review_period_seconds, bool csaf_fee = true, bool broadcast = false ) { try { proposal_create_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposed_ops = proposed_ops; op.expiration_time = expiration_time; op.review_period_seconds = review_period_seconds; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposed_ops)(expiration_time)(review_period_seconds)(csaf_fee)(broadcast)) } signed_transaction proposal_update(const string fee_paying_account, proposal_id_type proposal, const flat_set<account_uid_type> secondary_approvals_to_add, const flat_set<account_uid_type> secondary_approvals_to_remove, const flat_set<account_uid_type> active_approvals_to_add, const flat_set<account_uid_type> active_approvals_to_remove, const flat_set<account_uid_type> owner_approvals_to_add, const flat_set<account_uid_type> owner_approvals_to_remove, const flat_set<public_key_type> key_approvals_to_add, const flat_set<public_key_type> key_approvals_to_remove, bool csaf_fee = true, bool broadcast = false ) { try { proposal_update_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposal = proposal; op.secondary_approvals_to_add = secondary_approvals_to_add; op.secondary_approvals_to_remove = secondary_approvals_to_remove; op.active_approvals_to_add = active_approvals_to_add; op.active_approvals_to_remove = active_approvals_to_remove; op.owner_approvals_to_add = owner_approvals_to_add; op.owner_approvals_to_remove = owner_approvals_to_remove; op.key_approvals_to_add = key_approvals_to_add; op.key_approvals_to_remove = key_approvals_to_remove; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposal)(secondary_approvals_to_add)(secondary_approvals_to_remove)(active_approvals_to_add)(active_approvals_to_remove) (owner_approvals_to_add)(owner_approvals_to_remove)(key_approvals_to_add)(key_approvals_to_remove)(csaf_fee)(broadcast)) } signed_transaction proposal_delete(const string fee_paying_account, proposal_id_type proposal, bool csaf_fee = true, bool broadcast = false ) { try { proposal_delete_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposal = proposal; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposal)(csaf_fee)(broadcast)) } signed_transaction score_a_post(string from_account, string platform, string poster, post_pid_type post_pid, int8_t score, string csaf, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); score_create_operation create_op; create_op.from_account_uid = get_account_uid(from_account); create_op.platform = get_account_uid(platform); create_op.poster = get_account_uid(poster); create_op.post_pid = post_pid; create_op.score = score; create_op.csaf = asset_obj->amount_from_string(csaf).amount; if (sign_platform.valid()){ create_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(score)(csaf)(csaf_fee)(broadcast)) } signed_transaction reward_post(string from_account, string platform, string poster, post_pid_type post_pid, string amount, string asset_symbol, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); reward_operation reward_op; reward_op.from_account_uid = get_account_uid(from_account); reward_op.platform = get_account_uid(platform); reward_op.poster = get_account_uid(poster); reward_op.post_pid = post_pid; reward_op.amount = asset_obj->amount_from_string(amount); signed_transaction tx; tx.operations.push_back(reward_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(amount)(asset_symbol)(csaf_fee)(broadcast)) } signed_transaction reward_post_proxy_by_platform(string from_account, string platform, string poster, post_pid_type post_pid, string amount, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); reward_proxy_operation reward_op; reward_op.from_account_uid = get_account_uid(from_account); reward_op.platform = get_account_uid(platform); reward_op.poster = get_account_uid(poster); reward_op.post_pid = post_pid; reward_op.amount = asset_obj->amount_from_string(amount).amount; if (sign_platform.valid()){ reward_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(reward_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(amount)(csaf_fee)(broadcast)) } signed_transaction buyout_post(string from_account, string platform, string poster, post_pid_type post_pid, string receiptor_account, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); buyout_operation buyout_op; buyout_op.from_account_uid = get_account_uid(from_account); buyout_op.platform = get_account_uid(platform); buyout_op.poster = get_account_uid(poster); buyout_op.post_pid = post_pid; buyout_op.receiptor_account_uid = get_account_uid(receiptor_account); if (sign_platform.valid()){ buyout_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(buyout_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(receiptor_account)(csaf_fee)(broadcast)) } signed_transaction create_license(string platform, uint8_t license_type, string hash_value, string title, string body, string extra_data, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); fc::optional<platform_object> platform_obj = _remote_db->get_platform_by_account(platform_uid); FC_ASSERT(platform_obj.valid(), "platform doesn`t exsit. "); const account_statistics_object& plat_account_statistics = _remote_db->get_account_statistics_by_uid(platform_uid); license_create_operation create_op; create_op.license_lid = plat_account_statistics.last_license_sequence + 1; create_op.platform = platform_uid; create_op.type = license_type; create_op.hash_value = hash_value; create_op.extra_data = extra_data; create_op.title = title; create_op.body = body; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(license_type)(hash_value)(title)(body)(extra_data)(csaf_fee)(broadcast)) } signed_transaction create_post(string platform, string poster, string hash_value, string title, string body, string extra_data, string origin_platform = "", string origin_poster = "", string origin_post_pid = "", post_create_ext exts = post_create_ext(), bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type poster_uid = get_account_uid(poster); const account_statistics_object& poster_account_statistics = _remote_db->get_account_statistics_by_uid(poster_uid); post_operation create_op; create_op.post_pid = poster_account_statistics.last_post_sequence + 1; create_op.platform = get_account_uid(platform); create_op.poster = poster_uid; if (!origin_platform.empty()) create_op.origin_platform = get_account_uid(origin_platform); if (!origin_poster.empty()) create_op.origin_poster = get_account_uid(origin_poster); if (!origin_post_pid.empty()) create_op.origin_post_pid = fc::to_uint64(fc::string(origin_post_pid)); create_op.hash_value = hash_value; create_op.extra_data = extra_data; create_op.title = title; create_op.body = body; post_operation::ext extension_; if (exts.post_type) extension_.post_type = exts.post_type; if (exts.forward_price.valid()) extension_.forward_price = asset_obj->amount_from_string(*(exts.forward_price)).amount; if (exts.receiptors.valid()) { map<account_uid_type, Receiptor_Parameter> maps_receiptors; for (auto itor = (*exts.receiptors).begin(); itor != (*exts.receiptors).end(); itor++) { Receiptor_Parameter para; para.cur_ratio = uint16_t(itor->second.cur_ratio * GRAPHENE_1_PERCENT); para.to_buyout = itor->second.to_buyout; para.buyout_ratio = uint16_t(itor->second.buyout_ratio * GRAPHENE_1_PERCENT); para.buyout_price = asset_obj->amount_from_string(itor->second.buyout_price).amount; maps_receiptors.insert(std::make_pair(itor->first, para)); } extension_.receiptors = maps_receiptors; } if (exts.license_lid.valid()) extension_.license_lid = exts.license_lid; if (exts.permission_flags) extension_.permission_flags = exts.permission_flags; if (exts.sign_platform.valid()) extension_.sign_platform = get_account_uid(*(exts.sign_platform)); create_op.extensions = graphene::chain::extension<post_operation::ext>(); create_op.extensions->value = extension_; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(poster)(hash_value)(title)(body)(extra_data)(origin_platform)(origin_poster)(origin_post_pid)(exts)(csaf_fee)(broadcast)) } signed_transaction update_post(string platform, string poster, string post_pid, string hash_value, string title, string body, string extra_data, optional<post_update_ext> ext, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); post_update_operation update_op; update_op.post_pid = fc::to_uint64(fc::string(post_pid)); update_op.platform = get_account_uid(platform); update_op.poster = get_account_uid(poster); if (!hash_value.empty()) update_op.hash_value = hash_value; if (!extra_data.empty()) update_op.extra_data = extra_data; if (!title.empty()) update_op.title = title; if (!body.empty()) update_op.body = body; if (ext.valid()) { update_op.extensions = graphene::chain::extension<post_update_operation::ext>(); auto value = *ext; if (value.forward_price.valid()) update_op.extensions->value.forward_price = asset_obj->amount_from_string(*(value.forward_price)).amount; if (value.receiptor.valid()) update_op.extensions->value.receiptor = get_account_uid(*(value.receiptor)); if (value.to_buyout.valid()) update_op.extensions->value.to_buyout = value.to_buyout; if (value.buyout_ratio.valid()) update_op.extensions->value.buyout_ratio = uint16_t((*(value.buyout_ratio))* GRAPHENE_1_PERCENT); if (value.buyout_price.valid()) update_op.extensions->value.buyout_price = asset_obj->amount_from_string(*(value.buyout_price)).amount; if (value.buyout_expiration.valid()) update_op.extensions->value.buyout_expiration = time_point_sec(*(value.buyout_expiration)); if (value.license_lid.valid()) update_op.extensions->value.license_lid = value.license_lid; if (value.permission_flags.valid()) update_op.extensions->value.permission_flags = value.permission_flags; if (value.content_sign_platform.valid()) update_op.extensions->value.content_sign_platform = get_account_uid(*(value.content_sign_platform)); if (value.receiptor_sign_platform.valid()) update_op.extensions->value.receiptor_sign_platform = get_account_uid(*(value.receiptor_sign_platform)); } signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(poster)(post_pid)(hash_value)(title)(body)(extra_data)(ext)(csaf_fee)(broadcast)) } signed_transaction account_manage(string executor, string account, account_manage_operation::opt options, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_manage_operation manage_op; manage_op.account = get_account_uid(account); manage_op.executor = get_account_uid(executor); manage_op.options.value = options; signed_transaction tx; tx.operations.push_back(manage_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((executor)(account)(options)(csaf_fee)(broadcast)) } signed_transaction buy_advertising(string account, string platform, advertising_aid_type advertising_aid, uint32_t start_time, uint32_t buy_number, string extra_data, string memo, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); account_uid_type account_uid = get_account_uid(account); optional<advertising_object> ad_obj = _remote_db->get_advertising(platform_uid, advertising_aid); FC_ASSERT(ad_obj.valid(), "advertising_object doesn`t exsit. "); advertising_buy_operation buy_op; buy_op.from_account = account_uid; buy_op.platform = platform_uid; buy_op.advertising_aid = advertising_aid; buy_op.advertising_order_oid = ad_obj->last_order_sequence + 1; buy_op.start_time = time_point_sec(start_time); buy_op.buy_number = buy_number; buy_op.extra_data = extra_data; account_object user = get_account(account); account_object platform_account = get_account(platform); if (memo.size()) { buy_op.memo = memo_data(); buy_op.memo->from = user.memo_key; buy_op.memo->to = platform_account.memo_key; buy_op.memo->set_message(get_private_key(user.memo_key), platform_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(buy_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((account)(platform)(advertising_aid)(start_time)(buy_number)(extra_data)(memo)(csaf_fee)(broadcast)) } signed_transaction confirm_advertising(string platform, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool confirm, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); advertising_confirm_operation confirm_op; confirm_op.platform = get_account_uid(platform); confirm_op.advertising_aid = advertising_aid; confirm_op.advertising_order_oid = advertising_order_oid; confirm_op.isconfirm = confirm; signed_transaction tx; tx.operations.push_back(confirm_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(advertising_aid)(advertising_order_oid)(confirm)(csaf_fee)(broadcast)) } post_object get_post(string platform_owner, string poster_uid, string post_pid) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform = get_account_uid(platform_owner); account_uid_type poster = get_account_uid(poster_uid); fc::optional<post_object> post = _remote_db->get_post(platform, poster, postid); if (post) return *post; else FC_THROW("poster: ${poster} don't publish post: ${post} in platform: ${platform}", ("poster", poster_uid)("post", post_pid)("platform", platform_owner)); } FC_CAPTURE_AND_RETHROW((platform_owner)(poster_uid)(post_pid)) } vector<post_object> get_posts_by_platform_poster(string platform_owner, optional<string> poster, time_point_sec begin_time_range, time_point_sec end_time_range, object_id_type lower_bound_post, uint32_t limit) { try { account_uid_type platform = get_account_uid(platform_owner); if (poster.valid()){ account_uid_type poster_uid = get_account_uid(*poster); return _remote_db->get_posts_by_platform_poster(platform, poster_uid, std::make_pair(begin_time_range, end_time_range), lower_bound_post, limit); } else{ return _remote_db->get_posts_by_platform_poster(platform, optional<account_uid_type>(), std::make_pair(begin_time_range, end_time_range), lower_bound_post, limit); } } FC_CAPTURE_AND_RETHROW((platform_owner)(poster)(begin_time_range)(end_time_range)(lower_bound_post)(limit)) } uint64_t get_posts_count(optional<string> platform, optional<string> poster) { try { if (platform.valid()) { account_uid_type platform_uid = get_account_uid(*platform); if (poster.valid()) { account_uid_type poster_uid = get_account_uid(*poster); return _remote_db->get_posts_count(platform_uid, poster_uid); } else return _remote_db->get_posts_count(platform_uid, optional<account_uid_type>()); } else { if (poster.valid()) FC_THROW("platform should be valid when poster is valid"); else return _remote_db->get_posts_count(optional<account_uid_type>(), optional<account_uid_type>()); } } FC_CAPTURE_AND_RETHROW((platform)(poster)) } score_object get_score(string platform, string poster_uid, string post_pid, string from_account) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster = get_account_uid(poster_uid); account_uid_type from_uid = get_account_uid(from_account); fc::optional<score_object> score = _remote_db->get_score(platform_uid, poster, postid, from_uid); if (score) return *score; else FC_THROW("score that form account ${from_account} for post ${post} created by poster ${poster} in platform ${platform} not found", ("from_account", from_account)("post", post_pid)("poster", poster_uid)("platform", platform)); } FC_CAPTURE_AND_RETHROW((platform)(poster_uid)(post_pid)(from_account)) } vector<score_object> get_scores_by_uid(string scorer, uint32_t period, object_id_type lower_bound_score, uint32_t limit) { try { account_uid_type scorer_uid = get_account_uid(scorer); return _remote_db->get_scores_by_uid(scorer_uid, period, lower_bound_score, limit); } FC_CAPTURE_AND_RETHROW((scorer)(period)(lower_bound_score)(limit)) } vector<score_object> list_scores(string platform, string poster_uid, string post_pid, object_id_type lower_bound_score, uint32_t limit, bool list_cur_period) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster = get_account_uid(poster_uid); return _remote_db->list_scores(platform_uid, poster, postid, lower_bound_score, limit, list_cur_period); } FC_CAPTURE_AND_RETHROW((platform)(poster_uid)(post_pid)(lower_bound_score)(limit)(list_cur_period)) } license_object get_license(string platform, string license_lid) { try { account_uid_type platform_uid = get_account_uid(platform); license_lid_type lid = fc::to_uint64(fc::string(license_lid)); fc::optional<license_object> license = _remote_db->get_license(platform_uid, lid); if (license) return *license; else FC_THROW("license: ${license} not found in platform: ${platform}", ("license", license_lid)("platform", platform)); } FC_CAPTURE_AND_RETHROW((platform)(license_lid)) } vector<license_object> list_licenses(string platform, object_id_type lower_bound_license, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->list_licenses(platform_uid, lower_bound_license, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_license)(limit)) } vector<advertising_object> list_advertisings(string platform, string lower_bound_advertising, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); advertising_aid_type lower_advertising_aid = fc::to_uint64(fc::string(lower_bound_advertising)); return _remote_db->list_advertisings(platform_uid, lower_advertising_aid, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_advertising)(limit)) } vector<active_post_object> get_post_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, string poster, string post_pid) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster_uid = get_account_uid(poster); post_pid_type postid = fc::to_uint64(fc::string(post_pid)); return _remote_db->get_post_profits_detail(begin_period, end_period, platform_uid, poster_uid, postid); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(platform)(poster)(post_pid)) } vector<Platform_Period_Profit_Detail> get_platform_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, uint32_t lower_bound_index, uint32_t limit) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type platform_uid = get_account_uid(platform); return _remote_db->get_platform_profits_detail(begin_period, end_period, platform_uid, lower_bound_index, limit); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(platform)(lower_bound_index)(limit)) } vector<Poster_Period_Profit_Detail> get_poster_profits_detail(uint32_t begin_period, uint32_t end_period, string poster, uint32_t lower_bound_index, uint32_t limit) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type poster_uid = get_account_uid(poster); return _remote_db->get_poster_profits_detail(begin_period, end_period, poster_uid, lower_bound_index, limit); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(poster)(lower_bound_index)(limit)) } share_type get_score_profit(string account, uint32_t period) { try { account_uid_type account_uid = get_account_uid(account); auto dynamic_props = _remote_db->get_dynamic_global_properties(); FC_ASSERT(period <= dynamic_props.current_active_post_sequence, "period does not exist"); return _remote_db->get_score_profit(account_uid, period); } FC_CAPTURE_AND_RETHROW((account)(period)) } account_statistics_object get_account_statistics(string account) { try { account_uid_type account_uid = get_account_uid(account); account_statistics_object plat_account_statistics = _remote_db->get_account_statistics_by_uid(account_uid); return plat_account_statistics; } FC_CAPTURE_AND_RETHROW((account)) } signed_transaction create_advertising(string platform, string description, string unit_price, uint32_t unit_time, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type platform_uid = get_account_uid(platform); fc::optional<platform_object> platform_obj = _remote_db->get_platform_by_account(platform_uid); FC_ASSERT(platform_obj.valid(), "platform doesn`t exsit. "); const account_statistics_object& plat_account_statistics = _remote_db->get_account_statistics_by_uid(platform_uid); advertising_create_operation create_op; create_op.platform = platform_uid; create_op.advertising_aid = plat_account_statistics.last_advertising_sequence + 1; create_op.description = description; create_op.unit_price = asset_obj->amount_from_string(unit_price).amount; create_op.unit_time = unit_time; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(description)(unit_price)(unit_time)(csaf_fee)(broadcast)) } signed_transaction update_advertising(string platform, advertising_aid_type advertising_aid, optional<string> description, optional<string> unit_price, optional<uint32_t> unit_time, optional<bool> on_sell, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type platform_uid = get_account_uid(platform); advertising_update_operation update_op; update_op.platform = platform_uid; update_op.advertising_aid = advertising_aid; if (description.valid()) update_op.description = *description; if (unit_price.valid()) update_op.unit_price = asset_obj->amount_from_string(*unit_price).amount; if (unit_time.valid()) update_op.unit_time = *unit_time; if (on_sell.valid()) update_op.on_sell = *on_sell; signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(advertising_aid)(description)(unit_price)(unit_time)(on_sell)(csaf_fee)(broadcast)) } signed_transaction ransom_advertising(string platform, string from_account, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); account_uid_type from_account_uid = get_account_uid(from_account); advertising_ransom_operation ransom_op; ransom_op.platform = platform_uid; ransom_op.from_account = from_account_uid; ransom_op.advertising_aid = advertising_aid; ransom_op.advertising_order_oid = advertising_order_oid; signed_transaction tx; tx.operations.push_back(ransom_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(from_account)(advertising_aid)(advertising_order_oid)(csaf_fee)(broadcast)) } signed_transaction create_custom_vote(string create_account, string title, string description, time_point_sec expired_time, asset_aid_type asset_id, share_type required_amount, uint8_t minimum_selected_items, uint8_t maximum_selected_items, vector<string> options, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type creater = get_account_uid(create_account); const account_statistics_object& creater_statistics = _remote_db->get_account_statistics_by_uid(creater); custom_vote_create_operation create_op; create_op.custom_vote_creater = creater; create_op.vote_vid = creater_statistics.last_custom_vote_sequence + 1; create_op.title = title; create_op.description = description; create_op.vote_expired_time = expired_time; create_op.vote_asset_id = asset_id; create_op.required_asset_amount = required_amount; create_op.minimum_selected_items = minimum_selected_items; create_op.maximum_selected_items = maximum_selected_items; create_op.options = options; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((create_account)(title)(description)(expired_time)(asset_id) (required_amount)(minimum_selected_items)(maximum_selected_items)(options)(csaf_fee)(broadcast)) } signed_transaction cast_custom_vote(string voter, string custom_vote_creater, custom_vote_vid_type custom_vote_vid, set<uint8_t> vote_result, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type cast_voter = get_account_uid(voter); account_uid_type creater = get_account_uid(custom_vote_creater); custom_vote_cast_operation vote_op; vote_op.voter = cast_voter; vote_op.custom_vote_creater = creater; vote_op.custom_vote_vid = custom_vote_vid; vote_op.vote_result = vote_result; signed_transaction tx; tx.operations.push_back(vote_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((voter)(custom_vote_creater)(custom_vote_vid)(vote_result)(csaf_fee)(broadcast)) } uint64_t get_account_auth_platform_count(string platform) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->get_account_auth_platform_count(platform_uid); } FC_CAPTURE_AND_RETHROW((platform)) } vector<account_auth_platform_object> list_account_auth_platform_by_platform(string platform, account_uid_type lower_bound_account, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->list_account_auth_platform_by_platform(platform_uid, lower_bound_account, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_account)(limit)) } vector<account_auth_platform_object> list_account_auth_platform_by_account(string account, account_uid_type lower_bound_platform, uint32_t limit) { try { account_uid_type account_uid = get_account_uid(account); return _remote_db->list_account_auth_platform_by_account(account_uid, lower_bound_platform, limit); } FC_CAPTURE_AND_RETHROW((account)(lower_bound_platform)(limit)) } signed_transaction approve_proposal( const string& fee_paying_account, const string& proposal_id, const approval_delta& delta, bool csaf_fee = true, bool broadcast = false) { proposal_update_operation update_op; update_op.fee_paying_account = get_account(fee_paying_account).uid; update_op.proposal = fc::variant(proposal_id).as<proposal_id_type>( 1 ); // make sure the proposal exists get_object( update_op.proposal ); for( const std::string& name : delta.secondary_approvals_to_add ) update_op.secondary_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.secondary_approvals_to_remove ) update_op.secondary_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& name : delta.active_approvals_to_add ) update_op.active_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.active_approvals_to_remove ) update_op.active_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& name : delta.owner_approvals_to_add ) update_op.owner_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.owner_approvals_to_remove ) update_op.owner_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& k : delta.key_approvals_to_add ) update_op.key_approvals_to_add.insert( public_key_type( k ) ); for( const std::string& k : delta.key_approvals_to_remove ) update_op.key_approvals_to_remove.insert( public_key_type( k ) ); signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } void dbg_make_uia(string creator, string symbol) { asset_options opts; opts.flags &= ~(white_list); opts.issuer_permissions = opts.flags; create_asset(get_account(creator).name, symbol, 2, opts, {}, true); } void dbg_push_blocks( const std::string& src_filename, uint32_t count ) { use_debug_api(); (*_remote_debug)->debug_push_blocks( src_filename, count ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_generate_blocks( const std::string& debug_wif_key, uint32_t count ) { use_debug_api(); (*_remote_debug)->debug_generate_blocks( debug_wif_key, count ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_stream_json_objects( const std::string& filename ) { use_debug_api(); (*_remote_debug)->debug_stream_json_objects( filename ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_update_object( const fc::variant_object& update ) { use_debug_api(); (*_remote_debug)->debug_update_object( update ); (*_remote_debug)->debug_stream_json_objects_flush(); } void use_network_node_api() { if( _remote_net_node ) return; try { _remote_net_node = _remote_api->network_node(); } catch( const fc::exception& e ) { std::cerr << "\nCouldn't get network node API. You probably are not configured\n" "to access the network API on the yoyow_node you are\n" "connecting to. Please follow the instructions in README.md to set up an apiaccess file.\n" "\n"; throw(e); } } void use_debug_api() { if( _remote_debug ) return; try { _remote_debug = _remote_api->debug(); } catch( const fc::exception& e ) { std::cerr << "\nCouldn't get debug node API. You probably are not configured\n" "to access the debug API on the node you are connecting to.\n" "\n" "To fix this problem:\n" "- Please ensure you are running debug_node, not witness_node.\n" "- Please follow the instructions in README.md to set up an apiaccess file.\n" "\n"; } } void network_add_nodes( const vector<string>& nodes ) { use_network_node_api(); for( const string& node_address : nodes ) { (*_remote_net_node)->add_node( fc::ip::endpoint::from_string( node_address ) ); } } vector< variant > network_get_connected_peers() { use_network_node_api(); const auto peers = (*_remote_net_node)->get_connected_peers(); vector< variant > result; result.reserve( peers.size() ); for( const auto& peer : peers ) { variant v; fc::to_variant( peer, v, GRAPHENE_MAX_NESTED_OBJECTS ); result.push_back( v ); } return result; } void flood_network(string prefix, uint32_t number_of_transactions) { try { const account_object& master = *_wallet.my_accounts.get<by_name>().lower_bound("import"); int number_of_accounts = number_of_transactions / 3; number_of_transactions -= number_of_accounts; try { dbg_make_uia(master.name, "SHILL"); } catch(...) {/* Ignore; the asset probably already exists.*/} fc::time_point start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { std::ostringstream brain_key; brain_key << "brain key for account " << prefix << i; signed_transaction trx = create_account_with_brain_key(brain_key.str(), prefix + fc::to_string(i), master.name, master.name, /* broadcast = */ true, /* save wallet = */ false); } fc::time_point end = fc::time_point::now(); ilog("Created ${n} accounts in ${time} milliseconds", ("n", number_of_accounts)("time", (end - start).count() / 1000)); start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { signed_transaction trx = transfer(master.name, prefix + fc::to_string(i), "10", "CORE", "", true); trx = transfer(master.name, prefix + fc::to_string(i), "1", "CORE", "", true); } end = fc::time_point::now(); ilog("Transferred to ${n} accounts in ${time} milliseconds", ("n", number_of_accounts*2)("time", (end - start).count() / 1000)); start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { signed_transaction trx = issue_asset(prefix + fc::to_string(i), "1000", "SHILL", "", true); } end = fc::time_point::now(); ilog("Issued to ${n} accounts in ${time} milliseconds", ("n", number_of_accounts)("time", (end - start).count() / 1000)); } catch (...) { throw; } } operation get_prototype_operation( string operation_name ) { auto it = _prototype_ops.find( operation_name ); if( it == _prototype_ops.end() ) FC_THROW("Unsupported operation: \"${operation_name}\"", ("operation_name", operation_name)); return it->second; } string _wallet_filename; wallet_data _wallet; map<public_key_type,string> _keys; fc::sha512 _checksum; chain_id_type _chain_id; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_broadcast_api> _remote_net_broadcast; fc::api<history_api> _remote_hist; optional< fc::api<network_node_api> > _remote_net_node; optional< fc::api<graphene::debug_witness::debug_api> > _remote_debug; flat_map<string, operation> _prototype_ops; static_variant_map _operation_which_map = create_static_variant_map< operation >(); #ifdef __unix__ mode_t _old_umask; #endif const string _wallet_filename_extension = ".wallet"; }; std::string operation_printer::fee(const asset& a)const { out << " (Fee: " << wallet.get_asset(a.asset_id).amount_to_pretty_string(a) << ")"; return ""; } BOOST_TTI_HAS_MEMBER_DATA(fee) template<typename T> const asset get_operation_total_fee(const T& op, std::true_type) { return op.fee; } template<typename T> const asset get_operation_total_fee(const T& op, std::false_type) { return op.fee.total; } template<typename T> const asset get_operation_total_fee(const T& op) { const bool b = has_member_data_fee<T,asset>::value; return get_operation_total_fee( op, std::integral_constant<bool, b>() ); } template<typename T> std::string operation_printer::operator()(const T& op)const { //balance_accumulator acc; //op.get_balance_delta( acc, result ); asset op_fee = get_operation_total_fee(op); auto a = wallet.get_asset( op_fee.asset_id ); // TODO: review //auto payer = wallet.get_account( op.fee_payer() ); auto payer_uid = op.fee_payer_uid(); string op_name = fc::get_typename<T>::name(); if( op_name.find_last_of(':') != string::npos ) op_name.erase(0, op_name.find_last_of(':')+1); out << op_name <<" "; // out << "balance delta: " << fc::json::to_string(acc.balance) <<" "; //out << payer.name << " fee: " << a.amount_to_pretty_string( op.fee ); out << payer_uid << " fee: " << a.amount_to_pretty_string( op_fee ); operation_result_printer rprinter(wallet); std::string str_result = result.visit(rprinter); if( str_result != "" ) { out << " result: " << str_result; } return ""; } string operation_printer::operator()(const transfer_operation& op) const { out << "Transfer " << wallet.get_asset(op.amount.asset_id).amount_to_pretty_string(op.amount) << " from " << op.from << " to " << op.to; std::string memo; if( op.memo ) { if( wallet.is_locked() ) { out << " -- Unlock wallet to see memo."; } else { try { FC_ASSERT(wallet._keys.count(op.memo->to) || wallet._keys.count(op.memo->from), "Memo is encrypted to a key ${to} or ${from} not in this wallet.", ("to", op.memo->to)("from",op.memo->from)); if( wallet._keys.count(op.memo->to) ) { auto my_key = wif_to_key(wallet._keys.at(op.memo->to)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->from); out << " -- Memo: " << memo; } else { auto my_key = wif_to_key(wallet._keys.at(op.memo->from)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->to); out << " -- Memo: " << memo; } } catch (const fc::exception& e) { out << " -- could not decrypt memo"; //elog("Error when decrypting memo: ${e}", ("e", e.to_detail_string())); } } } fee(op.fee.total); return memo; } string operation_printer::operator()(const override_transfer_operation& op) const { out << "Override-transfer " << wallet.get_asset(op.amount.asset_id).amount_to_pretty_string(op.amount) << " from " << op.from << " to " << op.to; std::string memo; if( op.memo ) { if( wallet.is_locked() ) { out << " -- Unlock wallet to see memo."; } else { try { FC_ASSERT(wallet._keys.count(op.memo->to) || wallet._keys.count(op.memo->from), "Memo is encrypted to a key ${to} or ${from} not in this wallet.", ("to", op.memo->to)("from",op.memo->from)); if( wallet._keys.count(op.memo->to) ) { auto my_key = wif_to_key(wallet._keys.at(op.memo->to)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->from); out << " -- Memo: " << memo; } else { auto my_key = wif_to_key(wallet._keys.at(op.memo->from)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->to); out << " -- Memo: " << memo; } } catch (const fc::exception& e) { out << " -- could not decrypt memo"; //elog("Error when decrypting memo: ${e}", ("e", e.to_detail_string())); } } } fee(op.fee.total); return memo; } std::string operation_printer::operator()(const account_create_operation& op) const { out << "Create Account '" << op.name << "'"; return fee(op.fee.total); } std::string operation_printer::operator()(const asset_create_operation& op) const { out << "Create "; out << "Asset "; out << "'" << op.symbol << "' with issuer " << wallet.get_account(op.issuer).name; return fee(op.fee.total); } std::string operation_result_printer::operator()(const void_result& x) const { return ""; } std::string operation_result_printer::operator()(const object_id_type& oid) { return std::string(oid); } std::string operation_result_printer::operator()(const asset& a) { return _wallet.get_asset(a.asset_id).amount_to_pretty_string(a); } std::string operation_result_printer::operator()(const advertising_confirm_result& a) { std::string str = "Return the deposit money: \n"; for (auto iter : a) { str += " account: " + to_string(iter.first) + " : " + to_string(iter.second.value) + "\n"; } return str; } }}} namespace graphene { namespace wallet { vector<brain_key_info> utility::derive_owner_keys_from_brain_key(string brain_key, int number_of_desired_keys) { // Safety-check FC_ASSERT( number_of_desired_keys >= 1 ); // Create as many derived owner keys as requested vector<brain_key_info> results; brain_key = graphene::wallet::detail::normalize_brain_key(brain_key); for (int i = 0; i < number_of_desired_keys; ++i) { fc::ecc::private_key priv_key = graphene::wallet::detail::derive_private_key( brain_key, i ); brain_key_info result; result.brain_priv_key = brain_key; result.wif_priv_key = key_to_wif( priv_key ); result.pub_key = priv_key.get_public_key(); results.push_back(result); } return results; } }} namespace graphene { namespace wallet { wallet_api::wallet_api(const wallet_data& initial_data, fc::api<login_api> rapi) : my(new detail::wallet_api_impl(*this, initial_data, rapi)) { } wallet_api::~wallet_api() { } bool wallet_api::copy_wallet_file(string destination_filename) { return my->copy_wallet_file(destination_filename); } optional<signed_block_with_info> wallet_api::get_block(uint32_t num) { return my->_remote_db->get_block(num); } uint64_t wallet_api::get_account_count() const { return my->_remote_db->get_account_count(); } vector<account_object> wallet_api::list_my_accounts_cached() { // TODO this implementation has caching issue. To get latest data, check the steps in `load_wallet_file()` return vector<account_object>(my->_wallet.my_accounts.begin(), my->_wallet.my_accounts.end()); } map<string,account_uid_type> wallet_api::list_accounts_by_name(const string& lowerbound, uint32_t limit) { return my->_remote_db->lookup_accounts_by_name(lowerbound, limit); } vector<asset> wallet_api::list_account_balances(const string& account) { return my->_remote_db->get_account_balances( get_account( account ).uid, flat_set<asset_aid_type>() ); } vector<asset_object_with_data> wallet_api::list_assets(const string& lowerbound, uint32_t limit)const { return my->_remote_db->list_assets( lowerbound, limit ); } vector<operation_detail> wallet_api::get_relative_account_history(string account, optional<uint16_t> op_type, uint32_t stop, int limit, uint32_t start)const { vector<operation_detail> result; account_uid_type uid = get_account( account ).uid; while( limit > 0 ) { vector <pair<uint32_t,operation_history_object>> current = my->_remote_hist->get_relative_account_history(uid, op_type, stop, std::min<uint32_t>(100, limit), start); for (auto &p : current) { auto &o = p.second; std::stringstream ss; auto memo = o.op.visit(detail::operation_printer(ss, *my, o.result)); result.push_back(operation_detail{memo, ss.str(), p.first, o}); } if (current.size() < std::min<uint32_t>(100, limit)) break; limit -= current.size(); start = result.back().sequence - 1; if( start == 0 || start < stop ) break; } return result; } uint64_t wallet_api::calculate_account_uid(uint64_t n)const { return calc_account_uid( n ); } brain_key_info wallet_api::suggest_brain_key()const { brain_key_info result; // create a private key for secure entropy fc::sha256 sha_entropy1 = fc::ecc::private_key::generate().get_secret(); fc::sha256 sha_entropy2 = fc::ecc::private_key::generate().get_secret(); fc::bigint entropy1( sha_entropy1.data(), sha_entropy1.data_size() ); fc::bigint entropy2( sha_entropy2.data(), sha_entropy2.data_size() ); fc::bigint entropy(entropy1); entropy <<= 8*sha_entropy1.data_size(); entropy += entropy2; string brain_key = ""; for( int i=0; i<BRAIN_KEY_WORD_COUNT; i++ ) { fc::bigint choice = entropy % graphene::words::word_list_size; entropy /= graphene::words::word_list_size; if( i > 0 ) brain_key += " "; brain_key += graphene::words::word_list[ choice.to_int64() ]; } brain_key = normalize_brain_key(brain_key); fc::ecc::private_key priv_key = derive_private_key( brain_key, 0 ); result.brain_priv_key = brain_key; result.wif_priv_key = key_to_wif( priv_key ); result.pub_key = priv_key.get_public_key(); return result; } vector<brain_key_info> wallet_api::derive_owner_keys_from_brain_key(string brain_key, int number_of_desired_keys) const { return graphene::wallet::utility::derive_owner_keys_from_brain_key(brain_key, number_of_desired_keys); } bool wallet_api::is_public_key_registered(string public_key) const { bool is_known = my->_remote_db->is_public_key_registered(public_key); return is_known; } string wallet_api::serialize_transaction( signed_transaction tx )const { return fc::to_hex(fc::raw::pack(tx)); } variant wallet_api::get_object( object_id_type id ) const { return my->_remote_db->get_objects({id}); } string wallet_api::get_wallet_filename() const { return my->get_wallet_filename(); } transaction_handle_type wallet_api::begin_builder_transaction() { return my->begin_builder_transaction(); } void wallet_api::add_operation_to_builder_transaction(transaction_handle_type transaction_handle, const operation& op) { my->add_operation_to_builder_transaction(transaction_handle, op); } void wallet_api::replace_operation_in_builder_transaction(transaction_handle_type handle, unsigned operation_index, const operation& new_op) { my->replace_operation_in_builder_transaction(handle, operation_index, new_op); } asset wallet_api::set_fees_on_builder_transaction(transaction_handle_type handle, string fee_asset) { return my->set_fees_on_builder_transaction(handle, fee_asset); } transaction wallet_api::preview_builder_transaction(transaction_handle_type handle) { return my->preview_builder_transaction(handle); } signed_transaction wallet_api::sign_builder_transaction(transaction_handle_type transaction_handle, bool broadcast) { return my->sign_builder_transaction(transaction_handle, broadcast); } signed_transaction wallet_api::propose_builder_transaction( transaction_handle_type handle, string account_name_or_id, time_point_sec expiration, uint32_t review_period_seconds, bool broadcast) { return my->propose_builder_transaction(handle, account_name_or_id, expiration, review_period_seconds, broadcast); } void wallet_api::remove_builder_transaction(transaction_handle_type handle) { return my->remove_builder_transaction(handle); } account_object wallet_api::get_account(string account_name_or_id) const { return my->get_account(account_name_or_id); } full_account wallet_api::get_full_account(string account_name_or_uid) const { account_uid_type uid = my->get_account_uid( account_name_or_uid ); vector<account_uid_type> uids( 1, uid ); full_account_query_options opt = { true, true, true, true, true, true, true, true, true, true, true, true, true }; const auto& results = my->_remote_db->get_full_accounts_by_uid( uids, opt ); return results.at( uid ); } asset_object_with_data wallet_api::get_asset(string asset_name_or_id) const { auto a = my->find_asset(asset_name_or_id); FC_ASSERT( a, "Can not find asset ${a}", ("a", asset_name_or_id) ); return *a; } asset_aid_type wallet_api::get_asset_aid(string asset_symbol_or_id) const { return my->get_asset_aid(asset_symbol_or_id); } bool wallet_api::import_key(string account_name_or_id, string wif_key) { FC_ASSERT(!is_locked(), "Should unlock first"); // backup wallet fc::optional<fc::ecc::private_key> optional_private_key = wif_to_key(wif_key); if (!optional_private_key) FC_THROW("Invalid private key"); //string shorthash = detail::address_to_shorthash(optional_private_key->get_public_key()); //copy_wallet_file( "before-import-key-" + shorthash ); bool result = my->import_key(account_name_or_id, wif_key); save_wallet_file(); //copy_wallet_file( "after-import-key-" + shorthash ); return result; } map<string, bool> wallet_api::import_accounts( string filename, string password ) { FC_ASSERT( !is_locked() ); FC_ASSERT( fc::exists( filename ) ); const auto imported_keys = fc::json::from_file<exported_keys>( filename ); const auto password_hash = fc::sha512::hash( password ); FC_ASSERT( fc::sha512::hash( password_hash ) == imported_keys.password_checksum ); map<string, bool> result; for( const auto& item : imported_keys.account_keys ) { const auto import_this_account = [ & ]() -> bool { try { const account_object account = get_account( item.account_name ); const auto& owner_keys = account.owner.get_keys(); const auto& active_keys = account.active.get_keys(); for( const auto& public_key : item.public_keys ) { if( std::find( owner_keys.begin(), owner_keys.end(), public_key ) != owner_keys.end() ) return true; if( std::find( active_keys.begin(), active_keys.end(), public_key ) != active_keys.end() ) return true; } } catch( ... ) { } return false; }; const auto should_proceed = import_this_account(); result[ item.account_name ] = should_proceed; if( should_proceed ) { uint32_t import_successes = 0; uint32_t import_failures = 0; // TODO: First check that all private keys match public keys for( const auto& encrypted_key : item.encrypted_private_keys ) { try { const auto plain_text = fc::aes_decrypt( password_hash, encrypted_key ); const auto private_key = fc::raw::unpack<private_key_type>( plain_text ); import_key( item.account_name, string( graphene::utilities::key_to_wif( private_key ) ) ); ++import_successes; } catch( const fc::exception& e ) { elog( "Couldn't import key due to exception ${e}", ("e", e.to_detail_string()) ); ++import_failures; } } ilog( "successfully imported ${n} keys for account ${name}", ("n", import_successes)("name", item.account_name) ); if( import_failures > 0 ) elog( "failed to import ${n} keys for account ${name}", ("n", import_failures)("name", item.account_name) ); } } return result; } bool wallet_api::import_account_keys( string filename, string password, string src_account_name, string dest_account_name ) { FC_ASSERT( !is_locked() ); FC_ASSERT( fc::exists( filename ) ); bool is_my_account = false; const auto accounts = list_my_accounts_cached(); for( const auto& account : accounts ) { if( account.name == dest_account_name ) { is_my_account = true; break; } } FC_ASSERT( is_my_account ); const auto imported_keys = fc::json::from_file<exported_keys>( filename ); const auto password_hash = fc::sha512::hash( password ); FC_ASSERT( fc::sha512::hash( password_hash ) == imported_keys.password_checksum ); bool found_account = false; for( const auto& item : imported_keys.account_keys ) { if( item.account_name != src_account_name ) continue; found_account = true; for( const auto& encrypted_key : item.encrypted_private_keys ) { const auto plain_text = fc::aes_decrypt( password_hash, encrypted_key ); const auto private_key = fc::raw::unpack<private_key_type>( plain_text ); my->import_key( dest_account_name, string( graphene::utilities::key_to_wif( private_key ) ) ); } return true; } save_wallet_file(); FC_ASSERT( found_account ); return false; } string wallet_api::normalize_brain_key(string s) const { return detail::normalize_brain_key( s ); } variant wallet_api::info() { return my->info(); } variant_object wallet_api::about() const { return my->about(); } fc::ecc::private_key wallet_api::derive_private_key(const std::string& prefix_string, int sequence_number) const { return detail::derive_private_key( prefix_string, sequence_number ); } signed_transaction wallet_api::register_account(string name, public_key_type owner_pubkey, public_key_type active_pubkey, string registrar_account, string referrer_account, uint32_t referrer_percent, uint32_t seed, bool csaf_fee, bool broadcast) { return my->register_account(name, owner_pubkey, active_pubkey, registrar_account, referrer_account, referrer_percent, seed, csaf_fee, broadcast); } signed_transaction wallet_api::create_account_with_brain_key(string brain_key, string account_name, string registrar_account, string referrer_account, uint32_t id, bool csaf_fee, bool broadcast /* = false */) { return my->create_account_with_brain_key( brain_key, account_name, registrar_account, referrer_account, id, csaf_fee, broadcast ); } signed_transaction wallet_api::issue_asset(string to_account, string amount, string symbol, string memo, bool csaf_fee, bool broadcast) { return my->issue_asset(to_account, amount, symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::transfer_new(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee, bool broadcast /* = false */) { return my->transfer(from, to, amount, asset_symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::transfer(string from, string to, string amount, string asset_symbol, string memo,bool broadcast /* = false */) { return my->transfer(from, to, amount, asset_symbol, memo, true, broadcast); } signed_transaction wallet_api::transfer_extension(string from, string to, string amount, string asset_symbol, string memo, optional<string> sign_platform, bool isfrom_balance, bool isto_balance, bool csaf_fee, bool broadcast) { return my->transfer_extension(from, to, amount, asset_symbol, memo, sign_platform, isfrom_balance, isto_balance, csaf_fee, broadcast); } signed_transaction wallet_api::override_transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee, bool broadcast /* = false */) { return my->override_transfer(from, to, amount, asset_symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::create_asset(string issuer, string symbol, uint8_t precision, asset_options common, share_type initial_supply, bool csaf_fee, bool broadcast) { return my->create_asset(issuer, symbol, precision, common, initial_supply, csaf_fee, broadcast); } signed_transaction wallet_api::update_asset(string symbol, optional<uint8_t> new_precision, asset_options new_options, bool csaf_fee, bool broadcast /* = false */) { return my->update_asset(symbol, new_precision, new_options, csaf_fee, broadcast); } signed_transaction wallet_api::reserve_asset(string from, string amount, string symbol, bool csaf_fee, bool broadcast /* = false */) { return my->reserve_asset(from, amount, symbol, csaf_fee, broadcast); } signed_transaction wallet_api::whitelist_account(string authorizing_account, string account_to_list, account_whitelist_operation::account_listing new_listing_status, bool csaf_fee, bool broadcast /* = false */) { return my->whitelist_account(authorizing_account, account_to_list, new_listing_status, csaf_fee, broadcast); } signed_transaction wallet_api::create_committee_member(string owner_account, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { return my->create_committee_member(owner_account, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); } vector<witness_object> wallet_api::list_witnesses(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_witnesses(lowerbound, limit, order_by); } vector<committee_member_object> wallet_api::list_committee_members(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_committee_members(lowerbound, limit, order_by); } vector<committee_proposal_object> wallet_api::list_committee_proposals() { return my->_remote_db->list_committee_proposals(); } witness_object wallet_api::get_witness(string owner_account) { return my->get_witness(owner_account); } platform_object wallet_api::get_platform(string owner_account) { return my->get_platform(owner_account); } vector<platform_object> wallet_api::list_platforms(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_platforms(lowerbound, limit, order_by); } uint64_t wallet_api::get_platform_count() { return my->_remote_db->get_platform_count(); } committee_member_object wallet_api::get_committee_member(string owner_account) { return my->get_committee_member(owner_account); } signed_transaction wallet_api::create_witness(string owner_account, public_key_type block_signing_key, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { return my->create_witness_with_details(owner_account, block_signing_key, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); //return my->create_witness(owner_account, url, broadcast); } signed_transaction wallet_api::create_platform(string owner_account, string name, string pledge_amount, string pledge_asset_symbol, string url, string extra_data, bool csaf_fee, bool broadcast ) { return my->create_platform( owner_account, name, pledge_amount, pledge_asset_symbol, url, extra_data, csaf_fee, broadcast ); } signed_transaction wallet_api::update_platform(string platform_account, optional<string> name, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, optional<string> extra_data, bool csaf_fee, bool broadcast ) { return my->update_platform( platform_account, name, pledge_amount, pledge_asset_symbol, url, extra_data, csaf_fee, broadcast ); } signed_transaction wallet_api::update_platform_votes(string voting_account, flat_set<string> platforms_to_add, flat_set<string> platforms_to_remove, bool csaf_fee, bool broadcast ) { return my->update_platform_votes( voting_account, platforms_to_add, platforms_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::account_auth_platform(string account, string platform_owner, string memo, string limit_for_platform, uint32_t permission_flags, bool csaf_fee, bool broadcast) { return my->account_auth_platform(account, platform_owner, memo, limit_for_platform, permission_flags, csaf_fee, broadcast); } signed_transaction wallet_api::account_cancel_auth_platform(string account, string platform_owner, bool csaf_fee, bool broadcast) { return my->account_cancel_auth_platform( account, platform_owner, csaf_fee, broadcast ); } signed_transaction wallet_api::update_committee_member( string committee_member_account, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { return my->update_committee_member(committee_member_account, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); } signed_transaction wallet_api::update_witness( string witness_account, optional<public_key_type> block_signing_key, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { return my->update_witness_with_details(witness_account, block_signing_key, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); //return my->update_witness(witness_name, url, block_signing_key, broadcast); } signed_transaction wallet_api::collect_witness_pay(string witness_account, string pay_amount, string pay_asset_symbol, bool csaf_fee, bool broadcast /* = false */) { return my->collect_witness_pay(witness_account, pay_amount, pay_asset_symbol, csaf_fee, broadcast); } signed_transaction wallet_api::collect_csaf_new(string from, string to, string amount, string asset_symbol, bool csaf_fee, bool broadcast /* = false */) { time_point_sec time( time_point::now().sec_since_epoch() / 60 * 60 ); return my->collect_csaf(from, to, amount, asset_symbol, time, csaf_fee, broadcast); } signed_transaction wallet_api::collect_csaf(string from, string to, string amount, string asset_symbol, bool broadcast /* = false */) { time_point_sec time( time_point::now().sec_since_epoch() / 60 * 60 ); return my->collect_csaf(from, to, amount, asset_symbol, time, true, broadcast); } signed_transaction wallet_api::collect_csaf_with_time(string from, string to, string amount, string asset_symbol, time_point_sec time, bool csaf_fee, bool broadcast /* = false */) { return my->collect_csaf(from, to, amount, asset_symbol, time, csaf_fee, broadcast); } string wallet_api::compute_available_csaf(string account_name_or_uid) { account_uid_type uid = my->get_account_uid( account_name_or_uid ); vector<account_uid_type> uids( 1, uid ); full_account_query_options opt = { true, true, false, false, false, false, false, false, false, false, false, false, false }; const auto& results = my->_remote_db->get_full_accounts_by_uid( uids, opt ); auto& account = results.at( uid ); const auto& global_params = my->get_global_properties().parameters; auto csaf = account.statistics.compute_coin_seconds_earned( global_params.csaf_accumulate_window, time_point_sec(time_point::now()) ).first; auto ao = my->get_asset( GRAPHENE_CORE_ASSET_AID ); auto s1 = global_params.max_csaf_per_account - account.statistics.csaf; auto s2 = (csaf / global_params.csaf_rate).to_uint64(); return ao.amount_to_string(s1 > s2 ? s2 : s1); } signed_transaction wallet_api::update_witness_votes(string voting_account, flat_set<string> witnesses_to_add, flat_set<string> witnesses_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_witness_votes( voting_account, witnesses_to_add, witnesses_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::update_committee_member_votes(string voting_account, flat_set<string> committee_members_to_add, flat_set<string> committee_members_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_committee_member_votes( voting_account, committee_members_to_add, committee_members_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::set_voting_proxy(string account_to_modify, optional<string> voting_account, bool csaf_fee, bool broadcast /* = false */) { return my->set_voting_proxy(account_to_modify, voting_account, csaf_fee, broadcast); } signed_transaction wallet_api::enable_allowed_assets(string account, bool enable, bool csaf_fee, bool broadcast /* = false */) { return my->enable_allowed_assets( account, enable, csaf_fee, broadcast ); } signed_transaction wallet_api::update_allowed_assets(string account, flat_set<string> assets_to_add, flat_set<string> assets_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_allowed_assets( account, assets_to_add, assets_to_remove, csaf_fee, broadcast ); } void wallet_api::set_wallet_filename(string wallet_filename) { my->_wallet_filename = wallet_filename; } signed_transaction wallet_api::sign_transaction(signed_transaction tx, bool broadcast /* = false */) { try { return my->sign_transaction( tx, broadcast); } FC_CAPTURE_AND_RETHROW( (tx) ) } transaction_id_type wallet_api::broadcast_transaction(signed_transaction tx) { try { return my->broadcast_transaction( tx ); } FC_CAPTURE_AND_RETHROW( (tx) ) } operation wallet_api::get_prototype_operation(string operation_name) { return my->get_prototype_operation( operation_name ); } void wallet_api::dbg_make_uia(string creator, string symbol) { FC_ASSERT(!is_locked()); my->dbg_make_uia(creator, symbol); } void wallet_api::dbg_push_blocks( std::string src_filename, uint32_t count ) { my->dbg_push_blocks( src_filename, count ); } void wallet_api::dbg_generate_blocks( std::string debug_wif_key, uint32_t count ) { my->dbg_generate_blocks( debug_wif_key, count ); } void wallet_api::dbg_stream_json_objects( const std::string& filename ) { my->dbg_stream_json_objects( filename ); } void wallet_api::dbg_update_object( fc::variant_object update ) { my->dbg_update_object( update ); } void wallet_api::network_add_nodes( const vector<string>& nodes ) { my->network_add_nodes( nodes ); } vector< variant > wallet_api::network_get_connected_peers() { return my->network_get_connected_peers(); } void wallet_api::flood_network(string prefix, uint32_t number_of_transactions) { FC_ASSERT(!is_locked()); my->flood_network(prefix, number_of_transactions); } signed_transaction wallet_api::committee_proposal_create( const string committee_member_account, const vector<committee_proposal_item_type> items, const uint32_t voting_closing_block_num, optional<voting_opinion_type> proposer_opinion, const uint32_t execution_block_num, const uint32_t expiration_block_num, bool csaf_fee, bool broadcast ) { return my->committee_proposal_create( committee_member_account, items, voting_closing_block_num, proposer_opinion, execution_block_num, expiration_block_num, csaf_fee, broadcast ); } signed_transaction wallet_api::committee_proposal_vote( const string committee_member_account, const uint64_t proposal_number, const voting_opinion_type opinion, bool csaf_fee, bool broadcast /* = false */ ) { return my->committee_proposal_vote( committee_member_account, proposal_number, opinion, csaf_fee, broadcast ); } signed_transaction wallet_api::proposal_create(const string fee_paying_account, const vector<op_wrapper> proposed_ops, time_point_sec expiration_time, uint32_t review_period_seconds, bool csaf_fee, bool broadcast ) { return my->proposal_create(fee_paying_account, proposed_ops, expiration_time, review_period_seconds, csaf_fee, broadcast); } signed_transaction wallet_api::proposal_update(const string fee_paying_account, proposal_id_type proposal, const flat_set<account_uid_type> secondary_approvals_to_add, const flat_set<account_uid_type> secondary_approvals_to_remove, const flat_set<account_uid_type> active_approvals_to_add, const flat_set<account_uid_type> active_approvals_to_remove, const flat_set<account_uid_type> owner_approvals_to_add, const flat_set<account_uid_type> owner_approvals_to_remove, const flat_set<public_key_type> key_approvals_to_add, const flat_set<public_key_type> key_approvals_to_remove, bool csaf_fee, bool broadcast ) { return my->proposal_update(fee_paying_account, proposal, secondary_approvals_to_add, secondary_approvals_to_remove, active_approvals_to_add, active_approvals_to_remove, owner_approvals_to_add, owner_approvals_to_remove, key_approvals_to_add, key_approvals_to_remove, csaf_fee, broadcast); } signed_transaction wallet_api::proposal_delete(const string fee_paying_account, proposal_id_type proposal, bool csaf_fee, bool broadcast ) { return my->proposal_delete(fee_paying_account, proposal, csaf_fee, broadcast); } signed_transaction wallet_api::score_a_post(string from_account, string platform, string poster, post_pid_type post_pid, int8_t score, string csaf, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->score_a_post(from_account, platform, poster, post_pid, score, csaf, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::reward_post(string from_account, string platform, string poster, post_pid_type post_pid, string amount, string asset_symbol, bool csaf_fee, bool broadcast) { return my->reward_post(from_account, platform, poster, post_pid, amount, asset_symbol, csaf_fee, broadcast); } signed_transaction wallet_api::reward_post_proxy_by_platform(string from_account, string platform, string poster, post_pid_type post_pid, string amount, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->reward_post_proxy_by_platform(from_account, platform, poster, post_pid, amount, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::buyout_post(string from_account, string platform, string poster, post_pid_type post_pid, string receiptor_account, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->buyout_post(from_account, platform, poster, post_pid, receiptor_account, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::create_license(string platform, uint8_t license_type, string hash_value, string title, string body, string extra_data, bool csaf_fee, bool broadcast) { return my->create_license(platform, license_type, hash_value, title, body, extra_data, csaf_fee, broadcast); } signed_transaction wallet_api::create_post(string platform, string poster, string hash_value, string title, string body, string extra_data, string origin_platform, string origin_poster, string origin_post_pid, post_create_ext ext, bool csaf_fee, bool broadcast) { return my->create_post(platform, poster, hash_value, title, body, extra_data, origin_platform, origin_poster, origin_post_pid, ext, csaf_fee, broadcast); } signed_transaction wallet_api::update_post(string platform, string poster, string post_pid, string hash_value, string title, string body, string extra_data, optional<post_update_ext> ext, bool csaf_fee, bool broadcast) { return my->update_post(platform, poster, post_pid, hash_value, title, body, extra_data, ext, csaf_fee, broadcast); } signed_transaction wallet_api::account_manage(string executor, string account, account_manage_operation::opt options, bool csaf_fee, bool broadcast ) { return my->account_manage(executor,account, options, csaf_fee, broadcast); } signed_transaction wallet_api::buy_advertising(string account, string platform, advertising_aid_type advertising_aid, uint32_t start_time, uint32_t buy_number, string extra_data, string memo, bool csaf_fee, bool broadcast) { return my->buy_advertising(account, platform, advertising_aid, start_time, buy_number, extra_data, memo, csaf_fee, broadcast); } signed_transaction wallet_api::confirm_advertising(string platform, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool confirm, bool csaf_fee, bool broadcast) { return my->confirm_advertising(platform, advertising_aid, advertising_order_oid, confirm, csaf_fee, broadcast); } post_object wallet_api::get_post(string platform_owner, string poster_uid, string post_pid) { return my->get_post(platform_owner, poster_uid, post_pid); } vector<post_object> wallet_api::get_posts_by_platform_poster(string platform_owner, optional<string> poster, uint32_t begin_time_range, uint32_t end_time_range, object_id_type lower_bound_post, uint32_t limit) { time_point_sec begin_time(begin_time_range); time_point_sec end_time(end_time_range); return my->get_posts_by_platform_poster(platform_owner, poster, begin_time, end_time, lower_bound_post, limit); } uint64_t wallet_api::get_posts_count(optional<string> platform, optional<string> poster) { return my->get_posts_count(platform, poster); } score_object wallet_api::get_score(string platform, string poster_uid, string post_pid, string from_account) { return my->get_score(platform, poster_uid, post_pid, from_account); } vector<score_object> wallet_api::get_scores_by_uid(string scorer, uint32_t period, object_id_type lower_bound_score, uint32_t limit) { return my->get_scores_by_uid(scorer, period, lower_bound_score, limit); } vector<score_object> wallet_api::list_scores(string platform, string poster_uid, string post_pid, object_id_type lower_bound_score, uint32_t limit, bool list_cur_period) { return my->list_scores(platform, poster_uid, post_pid, lower_bound_score, limit, list_cur_period); } license_object wallet_api::get_license(string platform, string license_lid) { return my->get_license(platform, license_lid); } vector<license_object> wallet_api::list_licenses(string platform, object_id_type lower_bound_license, uint32_t limit) { return my->list_licenses(platform, lower_bound_license, limit); } vector<advertising_object> wallet_api::list_advertisings(string platform, string lower_bound_advertising, uint32_t limit) { return my->list_advertisings(platform, lower_bound_advertising, limit); } vector<active_post_object> wallet_api::get_post_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, string poster, string post_pid) { return my->get_post_profits_detail(begin_period, end_period, platform, poster, post_pid); } vector<Platform_Period_Profit_Detail> wallet_api::get_platform_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, uint32_t lower_bound_index, uint32_t limit) { return my->get_platform_profits_detail(begin_period, end_period, platform, lower_bound_index, limit); } vector<Poster_Period_Profit_Detail> wallet_api::get_poster_profits_detail(uint32_t begin_period, uint32_t end_period, string poster, uint32_t lower_bound_index, uint32_t limit) { return my->get_poster_profits_detail(begin_period, end_period, poster, lower_bound_index, limit); } share_type wallet_api::get_score_profit(string account, uint32_t period) { return my->get_score_profit(account, period); } account_statistics_object wallet_api::get_account_statistics(string account) { return my->get_account_statistics(account); } signed_transaction wallet_api::create_advertising(string platform, string description, string unit_price, uint32_t unit_time, bool csaf_fee, bool broadcast) { return my->create_advertising(platform, description, unit_price, unit_time, csaf_fee, broadcast); } signed_transaction wallet_api::update_advertising(string platform, advertising_aid_type advertising_aid, optional<string> description, optional<string> unit_price, optional<uint32_t> unit_time, optional<bool> on_sell, bool csaf_fee, bool broadcast) { return my->update_advertising(platform, advertising_aid, description, unit_price, unit_time, on_sell, csaf_fee, broadcast); } signed_transaction wallet_api::ransom_advertising(string platform, string from_account, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool csaf_fee, bool broadcast) { return my->ransom_advertising(platform, from_account, advertising_aid, advertising_order_oid, csaf_fee, broadcast); } vector<advertising_order_object> wallet_api::list_advertising_orders_by_purchaser(string purchaser, object_id_type lower_bound_advertising_order, uint32_t limit) { account_uid_type account = my->get_account_uid(purchaser); return my->_remote_db->list_advertising_orders_by_purchaser(account, lower_bound_advertising_order, limit); } vector<advertising_order_object> wallet_api::list_advertising_orders_by_ads_aid(string platform, string advertising_aid, string lower_bound_advertising_order, uint32_t limit) { account_uid_type platform_uid = my->get_account_uid(platform); advertising_aid_type ad_aid = fc::to_uint64(fc::string(advertising_aid)); advertising_order_oid_type lower_order_oid = fc::to_uint64(fc::string(lower_bound_advertising_order)); return my->_remote_db->list_advertising_orders_by_ads_aid(platform_uid, ad_aid, lower_order_oid, limit); } signed_transaction wallet_api::create_custom_vote(string create_account, string title, string description, uint32_t expired_time, asset_aid_type asset_id, share_type required_amount, uint8_t minimum_selected_items, uint8_t maximum_selected_items, vector<string> options, bool csaf_fee, bool broadcast) { time_point_sec time = time_point_sec(expired_time); return my->create_custom_vote(create_account, title, description, time, asset_id, required_amount, minimum_selected_items, maximum_selected_items, options, csaf_fee, broadcast); } signed_transaction wallet_api::cast_custom_vote(string voter, string custom_vote_creater, custom_vote_vid_type custom_vote_vid, set<uint8_t> vote_result, bool csaf_fee, bool broadcast) { return my->cast_custom_vote(voter, custom_vote_creater, custom_vote_vid, vote_result, csaf_fee, broadcast); } vector<custom_vote_object> wallet_api::list_custom_votes(const account_uid_type lowerbound, uint32_t limit) { return my->_remote_db->list_custom_votes(lowerbound, limit); } vector<custom_vote_object> wallet_api::lookup_custom_votes(string creater, custom_vote_vid_type lower_bound_custom_vote, uint32_t limit) { account_uid_type account = my->get_account_uid(creater); return my->_remote_db->lookup_custom_votes(account, lower_bound_custom_vote, limit); } vector<cast_custom_vote_object> wallet_api::list_cast_custom_votes_by_id(const string creater, const custom_vote_vid_type vote_vid, const object_id_type lower_bound_cast_custom_vote, uint32_t limit) { account_uid_type creater_account = my->get_account_uid(creater); return my->_remote_db->list_cast_custom_votes_by_id(creater_account, vote_vid, lower_bound_cast_custom_vote, limit); } vector<cast_custom_vote_object> wallet_api::list_cast_custom_votes_by_voter(string voter, object_id_type lower_bound_cast_custom_vote, uint32_t limit) { account_uid_type account = my->get_account_uid(voter); return my->_remote_db->list_cast_custom_votes_by_voter(account, lower_bound_cast_custom_vote, limit); } uint64_t wallet_api::get_account_auth_platform_count(string platform) { return my->get_account_auth_platform_count(platform); } vector<account_auth_platform_object> wallet_api::list_account_auth_platform_by_platform(string platform, account_uid_type lower_bound_account, uint32_t limit) { return my->list_account_auth_platform_by_platform(platform, lower_bound_account, limit); } vector<account_auth_platform_object> wallet_api::list_account_auth_platform_by_account(string account, account_uid_type lower_bound_platform, uint32_t limit) { return my->list_account_auth_platform_by_account(account, lower_bound_platform, limit); } signed_transaction wallet_api::approve_proposal( const string& fee_paying_account, const string& proposal_id, const approval_delta& delta, bool csaf_fee, bool broadcast /* = false */ ) { return my->approve_proposal( fee_paying_account, proposal_id, delta, csaf_fee, broadcast ); } vector<proposal_object> wallet_api::list_proposals( string account_name_or_id ) { auto acc = my->get_account( account_name_or_id ); //return my->_remote_db->get_proposed_transactions( acc.uid ); return {}; } global_property_object wallet_api::get_global_properties() const { return my->get_global_properties(); } content_parameter_extension_type wallet_api::get_global_properties_extensions() const { return my->get_global_properties_extensions(); } dynamic_global_property_object wallet_api::get_dynamic_global_properties() const { return my->get_dynamic_global_properties(); } string wallet_api::help()const { std::vector<std::string> method_names = my->method_documentation.get_method_names(); std::stringstream ss; for (const std::string method_name : method_names) { try { ss << my->method_documentation.get_brief_description(method_name); } catch (const fc::key_not_found_exception&) { ss << method_name << " (no help available)\n"; } } return ss.str(); } string wallet_api::gethelp(const string& method)const { fc::api<wallet_api> tmp; std::stringstream ss; ss << "\n"; // doxygen help string first try { string brief_desc = my->method_documentation.get_brief_description(method); boost::trim( brief_desc ); ss << brief_desc << "\n\n"; std::string doxygenHelpString = my->method_documentation.get_detailed_description(method); if (!doxygenHelpString.empty()) ss << doxygenHelpString << "\n"; else ss << "No doxygen help defined for method " << method << "\n\n"; } catch (const fc::key_not_found_exception&) { ss << "No doxygen help defined for method " << method << "\n\n"; } if( method == "import_key" ) { ss << "usage: import_key ACCOUNT_NAME_OR_ID WIF_PRIVATE_KEY\n\n"; ss << "example: import_key \"1.3.11\" 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3\n"; ss << "example: import_key \"usera\" 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3\n"; } else if( method == "transfer" ) { ss << "usage: transfer FROM TO AMOUNT SYMBOL \"memo\" BROADCAST\n\n"; ss << "example: transfer \"1.3.11\" \"1.3.4\" 1000.03 CORE \"memo\" true\n"; ss << "example: transfer \"usera\" \"userb\" 1000.123 CORE \"memo\" true\n"; } else if( method == "create_account_with_brain_key" ) { ss << "usage: create_account_with_brain_key BRAIN_KEY ACCOUNT_NAME REGISTRAR REFERRER BROADCAST\n\n"; ss << "example: create_account_with_brain_key \"my really long brain key\" \"newaccount\" \"1.3.11\" \"1.3.11\" true\n"; ss << "example: create_account_with_brain_key \"my really long brain key\" \"newaccount\" \"someaccount\" \"otheraccount\" true\n"; ss << "\n"; ss << "This method should be used if you would like the wallet to generate new keys derived from the brain key.\n"; ss << "The BRAIN_KEY will be used as the owner key, and the active key will be derived from the BRAIN_KEY. Use\n"; ss << "register_account if you already know the keys you know the public keys that you would like to register.\n"; } else if( method == "register_account" ) { ss << "usage: register_account ACCOUNT_NAME OWNER_PUBLIC_KEY ACTIVE_PUBLIC_KEY REGISTRAR REFERRER REFERRER_PERCENT BROADCAST\n\n"; ss << "example: register_account \"newaccount\" \"CORE6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV\" \"CORE6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV\" \"1.3.11\" \"1.3.11\" 50 true\n"; ss << "\n"; ss << "Use this method to register an account for which you do not know the private keys."; } else if( method == "create_asset" ) { ss << "usage: ISSUER SYMBOL PRECISION_DIGITS OPTIONS INITIAL_SUPPLY BROADCAST\n\n"; ss << "PRECISION_DIGITS: the number of digits after the decimal point\n\n"; ss << "Example value of OPTIONS: \n"; ss << fc::json::to_pretty_string( graphene::chain::asset_options() ); } else if( method == "committee_proposal_create" ) { ss << "usage: COMMITTEE_MEMBER_UID PROPOSED_ITEMS BLOCK_NUM PROPOSER_OPINION BLOCK_NUM BLOCK_NUM BROADCAST\n\n"; ss << "Example value of PROPOSED_ITEMS: \n"; ss << "item[0].new_priviledges:\n\n"; graphene::chain::committee_update_account_priviledge_item_type::account_priviledge_update_options apuo; apuo.can_vote = true; apuo.is_admin = true; apuo.is_registrar = true; apuo.takeover_registrar = 25638; ss << fc::json::to_pretty_string( apuo ); ss << "\n\nitem[1].parameters:\n\n"; ss << fc::json::to_pretty_string( fee_schedule::get_default().parameters ); ss << "\n\nitem[2]:\n\n"; ss << "see graphene::chain::committee_updatable_parameters or Calling \"get_global_properties\" to see"; ss << "\n\n"; ss << "[[0,{\"account\":28182,\"new_priviledges\": {\"can_vote\":true}}],[1,{\"parameters\": "; ss << "[[16,{\"fee\":10000,\"min_real_fee\":0,\"min_rf_percent\":0}]]}],[2,{\"governance_voting_expiration_blocks\":150000}]]"; ss << "\n\n"; } return ss.str(); } bool wallet_api::load_wallet_file( string wallet_filename ) { return my->load_wallet_file( wallet_filename ); } void wallet_api::save_wallet_file( string wallet_filename ) { my->save_wallet_file( wallet_filename ); } std::map<string,std::function<string(fc::variant,const fc::variants&)> > wallet_api::get_result_formatters() const { return my->get_result_formatters(); } bool wallet_api::is_locked()const { return my->is_locked(); } bool wallet_api::is_new()const { return my->_wallet.cipher_keys.size() == 0; } void wallet_api::encrypt_keys() { my->encrypt_keys(); } void wallet_api::lock() { try { if ( is_locked() ) return; encrypt_keys(); for( auto key : my->_keys ) key.second = key_to_wif(fc::ecc::private_key()); my->_keys.clear(); my->_checksum = fc::sha512(); my->self.lock_changed(true); } FC_CAPTURE_AND_RETHROW() } void wallet_api::unlock(string password) { try { FC_ASSERT( !is_new(), "Please use the set_password method to initialize a new wallet before continuing" ); FC_ASSERT( is_locked(), "The wallet is already unlocked" ); FC_ASSERT(password.size() > 0); auto pw = fc::sha512::hash(password.c_str(), password.size()); vector<char> decrypted = fc::aes_decrypt(pw, my->_wallet.cipher_keys); auto pk = fc::raw::unpack<plain_keys>(decrypted); FC_ASSERT(pk.checksum == pw); my->_keys = std::move(pk.keys); my->_checksum = pk.checksum; my->self.lock_changed(false); } FC_CAPTURE_AND_RETHROW() } void wallet_api::set_password( string password ) { if( !is_new() ) FC_ASSERT( !is_locked(), "The wallet must be unlocked before the password can be set" ); my->_checksum = fc::sha512::hash( password.c_str(), password.size() ); lock(); } map<public_key_type, string> wallet_api::dump_private_keys() { FC_ASSERT( !is_locked(), "Should unlock first" ); return my->_keys; } string wallet_api::get_key_label( public_key_type key )const { auto key_itr = my->_wallet.labeled_keys.get<by_key>().find(key); if( key_itr != my->_wallet.labeled_keys.get<by_key>().end() ) return key_itr->label; return string(); } string wallet_api::get_private_key( public_key_type pubkey )const { return key_to_wif( my->get_private_key( pubkey ) ); } public_key_type wallet_api::get_public_key( string label )const { try { return fc::variant(label).as<public_key_type>( 1 ); } catch ( ... ){} auto key_itr = my->_wallet.labeled_keys.get<by_label>().find(label); if( key_itr != my->_wallet.labeled_keys.get<by_label>().end() ) return key_itr->key; return public_key_type(); } bool wallet_api::set_key_label( public_key_type key, string label ) { auto result = my->_wallet.labeled_keys.insert( key_label{label,key} ); if( result.second ) return true; auto key_itr = my->_wallet.labeled_keys.get<by_key>().find(key); auto label_itr = my->_wallet.labeled_keys.get<by_label>().find(label); if( label_itr == my->_wallet.labeled_keys.get<by_label>().end() ) { if( key_itr != my->_wallet.labeled_keys.get<by_key>().end() ) return my->_wallet.labeled_keys.get<by_key>().modify( key_itr, [&]( key_label& obj ){ obj.label = label; } ); } return false; } } } // graphene::wallet namespace fc { void /*fc::*/to_variant(const account_multi_index_type& accts, fc::variant& vo, uint32_t max_depth) { to_variant( std::vector<account_object>(accts.begin(), accts.end()), vo, max_depth ); } void /*fc::*/from_variant(const fc::variant& var, account_multi_index_type& vo, uint32_t max_depth) { const std::vector<account_object>& v = var.as<std::vector<account_object>>( max_depth ); vo = account_multi_index_type(v.begin(), v.end()); } }
43.577881
299
0.600835
LianshuOne
359fec4dd90b2814e7c0cdaf08cbbe014cf48301
815
cc
C++
net/tools/quic/quic_reliable_client_stream.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
net/tools/quic/quic_reliable_client_stream.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
net/tools/quic/quic_reliable_client_stream.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/tools/quic/quic_reliable_client_stream.h" using std::string; namespace net { namespace tools { // Sends body data to the server and returns the number of bytes sent. ssize_t QuicReliableClientStream::SendBody(const string& data, bool fin) { return WriteData(data, fin).bytes_consumed; } bool QuicReliableClientStream::OnStreamFrame(const QuicStreamFrame& frame) { if (!write_side_closed()) { DLOG(INFO) << "Got a response before the request was complete. " << "Aborting request."; CloseWriteSide(); } return ReliableQuicStream::OnStreamFrame(frame); } } // namespace tools } // namespace net
29.107143
76
0.727607
nagineni
35a0a0730d0aeb6b2ecb3c9d65ff6946c738f578
1,420
cc
C++
chrome/browser/media/webrtc/webrtc_log_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/media/webrtc/webrtc_log_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/media/webrtc/webrtc_log_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/webrtc/webrtc_log_util.h" #include <vector> #include "base/bind.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/webrtc_logging/browser/log_cleanup.h" #include "components/webrtc_logging/browser/text_log_list.h" #include "content/public/browser/browser_thread.h" // static void WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::vector<ProfileAttributesEntry*> entries = g_browser_process->profile_manager()->GetProfileAttributesStorage(). GetAllProfilesAttributes(); for (ProfileAttributesEntry* entry : entries) { base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce( &webrtc_logging::DeleteOldWebRtcLogFiles, webrtc_logging::TextLogList:: GetWebRtcLogDirectoryForBrowserContextPath(entry->GetPath()))); } }
38.378378
79
0.759155
zealoussnow
35a1c9c73db14a968467b53838fd69dd9f31900f
2,721
cpp
C++
Arduino/lib/Machine/Machine.cpp
Kike10hd/ExpendeMax
c0d38a3af2c6df33d9838ac6c9579d110870d1fc
[ "CNRI-Python", "RSA-MD" ]
null
null
null
Arduino/lib/Machine/Machine.cpp
Kike10hd/ExpendeMax
c0d38a3af2c6df33d9838ac6c9579d110870d1fc
[ "CNRI-Python", "RSA-MD" ]
null
null
null
Arduino/lib/Machine/Machine.cpp
Kike10hd/ExpendeMax
c0d38a3af2c6df33d9838ac6c9579d110870d1fc
[ "CNRI-Python", "RSA-MD" ]
null
null
null
#include <Arduino.h> #include "protothreads.h" #include "Machine.h" void Machine::inizialice(Led red, Led green, Servo servo, Joystick joy, Adafruit_SSD1306 oled) { this->_red = red; this->_green = green; this->_servo = servo; this->_joy = joy; this->_oled = oled; this->_servo.write(0); this->_point = 0; this->_actual_balance = 0; this->_message = "I: coin & code"; this->_oled.setTextWrap(false); this->_x = this->_oled.width(); this->_minX = -12 * this->_message.length(); } void Machine::_printMessage() { this->_oled.clearDisplay(); this->_oled.setTextColor(WHITE); this->_oled.setTextSize(2); this->_oled.setCursor(0, 30); this->_oled.print("$:"); this->_oled.print(this -> _actual_balance); this->_oled.setCursor(0, 50); this->_oled.print("$:"); this->_oled.print(this->_balance); this->_oled.setCursor(this->_x, 3); this->_oled.print(this->_message); this->_oled.display(); this->_x = this->_x-1; if(this->_x < this->_minX)this->_x = this->_oled.width(); } void Machine::_changeMessage(String new_message) { this->_message = new_message; this->_x = this->_oled.width(); this->_minX = -12 * this->_message.length(); } int Machine::changeBalance(struct pt* pt) { int values[] = {0,1,2,5,10,20,50,100,200}; unsigned int timeout = 300; PT_BEGIN(pt); for(;;) { if(this->_joy.getX() >= 0 && this->_joy.getX() < 480) { this->_point = (this->_point > 0) ? this->_point-1 : 0; PT_SLEEP(pt, timeout); } if (this->_joy.getX() > 540 && this->_joy.getX() < 1023 ) { this->_point = (this->_point < 8) ? this->_point+1 : 8; PT_SLEEP(pt, timeout); } if(this->_joy.getS() == LOW) { this->_actual_balance += this->_balance; Serial.println(this->_actual_balance); this->_balance = 0; this->_point = 0; PT_SLEEP(pt,timeout); } this->_balance = values[this->_point]; PT_YIELD(pt); } PT_END(pt); } int Machine::reciveData(struct pt *pt) { String data; String key; String info; int index; unsigned int timeout = 10000; PT_BEGIN(pt); for(;;) { if(Serial.available()) { data = Serial.readString(); index = data.indexOf(":"); key = data.substring(0,index); info = data.substring(index+1); _changeMessage(info); if(key == "accepted") { this->_green.turnOn(); this->_actual_balance = 0; this->_servo.write(180); PT_SLEEP(pt, 300); this->_servo.write(0); } if(key == "rejected") { this->_red.turnOn(); } PT_SLEEP(pt, timeout); _changeMessage("I: coin & code"); this->_green.turnOff(); this->_red.turnOff(); } PT_YIELD(pt); } PT_END(pt); } int Machine::printOnOled(struct pt *pt) { PT_BEGIN(pt); for(;;) { _printMessage(); PT_YIELD(pt); } PT_END(pt); }
21.425197
96
0.629915
Kike10hd
35a7a08561f25f446421101cf82034e46321f4f9
503
cpp
C++
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
#include "logpicker_t.hpp" #include "types.hpp" #include "logpicker_t.hpp" #include "log.hpp" #include "cert.hpp" #include "utils.hpp" int main() { cert_t cert = read_cert_from_disk("/home/leen/Projects/TU_BS/misc/LogPicker/lpp/data/github/DER/github.com"); hash_t hash = hash_certificate(cert); std::cout << "Hash: " << hash << "\n"; std::vector<Log> logs = make_logs(1); log_pool_t pool; for(const auto& log : logs) { //pool.emplace_back(make_instance(log)); } }
26.473684
113
0.658052
logpicker
35a8f8a2e57d67bf9ee9fd02b644b79bf7480f8d
2,006
cpp
C++
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
1
2021-12-22T07:52:39.000Z
2021-12-22T07:52:39.000Z
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
null
null
null
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
null
null
null
// // // #include <gtest/gtest.h> #include "AutoVersion.h" TEST(AutoVersionTest, ParsesUpstreamOnly) { AutoVersion v("1"); EXPECT_EQ(0, v.Epoch()); EXPECT_STREQ("1", v.Upstream()); EXPECT_STREQ("0", v.Revision()); } TEST(AutoVersionTest, ParsesEpochs) { AutoVersion v("1:2.0.1"); EXPECT_EQ(1, v.Epoch()); EXPECT_STREQ("2.0.1", v.Upstream()); EXPECT_STREQ("0", v.Revision()); } TEST(AutoVersionTest, ParsesRevisions) { AutoVersion v("10:4.0.1~alpha-4-5"); EXPECT_EQ(10, v.Epoch()); EXPECT_STREQ("4.0.1~alpha-4", v.Upstream()); EXPECT_STREQ("5", v.Revision()); } TEST(AutoVersionTest, ComparesNumbers) { EXPECT_LT(AutoVersion("1"), AutoVersion("2")); EXPECT_EQ(AutoVersion("10"), AutoVersion("10")); EXPECT_LT(AutoVersion("9"), AutoVersion("10")); EXPECT_GT(AutoVersion("10"), AutoVersion("9")); } TEST(AutoVersionTest, ComparesEpochs) { EXPECT_GT(AutoVersion("2:1"), AutoVersion("1:2")); EXPECT_LT(AutoVersion("10"), AutoVersion("1:2")); } TEST(AutoVersionTest, ComparesAlphas) { EXPECT_LT(AutoVersion("alpha"), AutoVersion("beta")); EXPECT_LT(AutoVersion("alpha1"), AutoVersion("alpha2")); EXPECT_GT(AutoVersion("alpha10"), AutoVersion("alpha2")); } TEST(AutoVersionTest, ComparesTildes) { EXPECT_LT(AutoVersion("3.0~beta1"), AutoVersion("3.0")); EXPECT_GT(AutoVersion("3.0~beta"), AutoVersion("3.0~~prebeta")); EXPECT_LT(AutoVersion("3.0~beta4"), AutoVersion("3.0~rc1")); } TEST(AutoVersionTest, ComparesRevisions) { EXPECT_LT(AutoVersion("3.0-2"), AutoVersion("3.0-10")); } assert mycmp('1', '2') == -1 assert mycmp('2', '1') == 1 assert mycmp('1', '1') == 0 assert mycmp('1.0', '1') == 0 assert mycmp('1', '1.000') == 0 assert mycmp('12.01', '12.1') == 0 assert mycmp('13.0.1', '13.00.02') == -1 assert mycmp('1.1.1.1', '1.1.1.1') == 0 assert mycmp('1.1.1.2', '1.1.1.1') == 1 assert mycmp('1.1.3', '1.1.3.000') == 0 assert mycmp('3.1.1.0', '3.1.2.10') == -1 assert mycmp('1.1', '1.10') == -1
25.717949
68
0.631107
adamyg
35b0d73ad5bd33b850e20510997f61490a994c66
1,508
cpp
C++
src/provider/widgets/auditlogbrowserdialog.cpp
KDE/kuserfeedback
7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c
[ "MIT", "BSD-3-Clause" ]
7
2017-04-26T07:00:24.000Z
2020-07-30T10:19:36.000Z
src/provider/widgets/auditlogbrowserdialog.cpp
KDE/kuserfeedback
7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/provider/widgets/auditlogbrowserdialog.cpp
KDE/kuserfeedback
7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c
[ "MIT", "BSD-3-Clause" ]
3
2017-06-17T19:16:07.000Z
2021-12-13T20:40:51.000Z
/* SPDX-FileCopyrightText: 2017 Volker Krause <vkrause@kde.org> SPDX-License-Identifier: MIT */ #include "auditlogbrowserdialog.h" #include "ui_auditlogbrowserdialog.h" #include <auditloguicontroller.h> #include <QDateTime> #include <QPushButton> using namespace KUserFeedback; AuditLogBrowserDialog::AuditLogBrowserDialog(QWidget *parent) : QDialog(parent) , ui(new Ui::AuditLogBrowserDialog) , m_controller(nullptr) { ui->setupUi(this); connect(ui->logEntryBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &AuditLogBrowserDialog::logEntrySelected); auto clearButton = ui->buttonBox->button(QDialogButtonBox::Discard); Q_ASSERT(clearButton); clearButton->setText(tr("Delete Log")); connect(clearButton, &QPushButton::clicked, this, &AuditLogBrowserDialog::close); setEnabled(false); } AuditLogBrowserDialog::~AuditLogBrowserDialog() { } void AuditLogBrowserDialog::setUiController(AuditLogUiController *controller) { Q_ASSERT(controller); m_controller = controller; ui->logEntryBox->setModel(controller->logEntryModel()); logEntrySelected(); auto clearButton = ui->buttonBox->button(QDialogButtonBox::Discard); connect(clearButton, &QPushButton::clicked, controller, &AuditLogUiController::clear); setEnabled(true); } void AuditLogBrowserDialog::logEntrySelected() { const auto dt = ui->logEntryBox->currentData().toDateTime(); ui->logEntryView->setText(m_controller->logEntry(dt)); }
26.928571
139
0.744695
KDE
35b4271fe40b17a31882ef7de3665b6288a65975
782
hpp
C++
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
1
2022-02-15T01:03:05.000Z
2022-02-15T01:03:05.000Z
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
null
null
null
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
null
null
null
//-------------------Joysticks---------------- #define DRIVE_STICK 0 #define STEER_STICK 1 //-------------------Drivetrain--------------- #define SWERVE_DISTANCE_FRONT 10 //distance between swerve drives from front to back (inches) #define SWERVE_DISTANCE_SIDE 10 //distance between swerve drives from side to side (inches) //Swerve CAN bus defines for steering motors #define FLS 4 #define FRS 1 #define BLS 2 #define BRS 3 //Swerve CAN bus defines for drive motors #define FLD 15 #define FRD 12 #define BLD 13 #define BRD 14 //Swerve Can bus defines for non drivetrain motors #define SHOOTER 11 #define Intake 8 #define Magazine 7 #define Trigger 5 #define Hood 6 //value multiplyers #define VELOCITY_MULTIPLIER 30 //add actual speed later #define pi 3.14 //aproximate fore pi
26.965517
93
0.713555
Apophis5006
35b4e0dce88084df4ceabb3d7fdedcaacce3fa5f
8,498
cpp
C++
Boost/Boost/errorHandling/boost_system.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
1
2021-03-12T19:29:33.000Z
2021-03-12T19:29:33.000Z
Boost/Boost/errorHandling/boost_system.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
1
2019-03-13T01:36:12.000Z
2019-03-13T01:36:12.000Z
Boost/Boost/errorHandling/boost_system.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
null
null
null
/* Boost.System is a small library defining four classes to identify errors. boost::system::error_code is the most basic class and represents operating system specific errors. Since operating systems typically enumerate errors, boost::system::error_code saves an error code in a variable of type int. The following example illustrates how to use this class by accessing the Boost.Asio library. */ //#include <boost/system/error_code.hpp> //#include <boost/asio.hpp> //#include <iostream> //#include <string> // //int main() //{ // boost::system::error_code ec; // std::string hostname = boost::asio::ip::host_name(ec); // std::cout << ec.value() << std::endl; //} /* Boost.Asio offers the free-standing boost::asio::ip::host_name() function that returns the name of the computer the application is executed on. An object of type boost::system::error_code can be passed as the sole argument to boost::asio::ip::host_name(). If the underlying operating system function fails, this argument contains the corresponding error code. It is also possible to call boost::asio::ip::host_name() without any argument in case the error code is irrelevant. boost::asio::ip::host_name() was actually broken in Boost 1.36.0 and therefore serves as a perfect example. The function possibly returned an error code even though the underlying operating system function did actually return the name of the computer successfully. Since the issue was resolved in Boost 1.37.0, boost::asio::ip::host_name() can now be used without concerns. Since an error code is nothing but a numeric value, it can be displayed with the help of the value() method. Since the error code 0 usually means that no error has occurred, the meaning of other values depends on the operating system and should be looked up in the manual accordingly. Compiled on Windows XP using Visual Studio 2008, the above application repeatedly generated error code 14 (not enough storage available to complete the operation) while using Boost 1.36.0. Even though boost::asio::ip::host_name() successfully determined the name of the computer, error code 14 was reported. This behavior is actually due to a broken implementation of boost::asio::ip::host_name(). */ /* Besides value(), boost::system::error_code offers the category() method. This method returns an object of the second class defined in Boost.System: boost::system::category. Error codes are simply numeric values. While operating system manufacturers such as Microsoft are able to guarantee the uniqueness of system error codes, keeping error codes unique throughout all existing applications is virtually impossible for any application developer. It would require a centralized database filled with error codes by all software developers to avoid reusing the same codes for different scenarios which certainly is impractical. For this reason, error categories exist. */ /* Error codes of type boost::system::error_code always belong to a category that can be retrieved using the category() method. Operating system errors are represented by the predefined object boost::system::system_category. By calling category(), a reference to the predefined boost::system::system_category is returned. It allows to retrieve specific information about the category such as the name using the name() method which is system in case of the system category. */ //#include <boost/system/error_code.hpp> //#include <boost/asio.hpp> //#include <iostream> //#include <string> // //int main() //{ // boost::system::error_code ec; // std::string hostname = boost::asio::ip::host_name(ec); // std::cout << ec.value() << std::endl; // std::cout << ec.category().name() << std::endl; //} /* Errors are uniquely identified by the error code and the error category. Since error codes are only required to be unique within a category, developers should create a new category whenever they want to define error codes specific to an application. This allows for arbitrary error codes that do not interfere with error codes of other developers. */ //#include <boost/system/error_code.hpp> //#include <iostream> //#include <string> // //class application_category : // public boost::system::error_category //{ //public: // const char *name() const { return "application"; } // std::string message(int ev) const { return "error message"; } //}; // //application_category cat; // //int main() //{ // boost::system::error_code ec(14, cat); // std::cout << ec.value() << std::endl; // std::cout << ec.category().name() << std::endl; //} /* A new error category is defined by creating a class derived from boost::system::error_category and implementing different methods as required by the interface of the new category. At minimum, the methods name() and message() must be supplied since they are defined as pure virtual in boost::system::error_category. For additional methods, the default behavior can be overridden accordingly if required. */ /* While name() returns the name of the error category, message() is used to retrieve the error description for a particular error code. Unlike the above example, the ev parameter is usually evaluated to return a description based on the error code. Objects of type of the newly created error category can be used to initialize an error code accordingly. The example defines the error code ec using the new application_category category. Therefore, error code 14 is no longer a system error; its meaning is specified by the developer of the new error category instead. boost::system::error_code contains a method named default_error_condition() which returns an object of type boost::system::error_condition. The interface of boost::system::error_condition is almost identical to the one of boost::system::error_code. The only difference is the default_error_condition() method which is only provided by boost::system::error_code. */ #include <boost/system/error_code.hpp> #include <boost/asio.hpp> #include <iostream> #include <string> int main() { boost::system::error_code ec; std::string hostname = boost::asio::ip::host_name(ec); boost::system::error_condition ecnd = ec.default_error_condition(); std::cout << ecnd.value() << std::endl; std::cout << ecnd.category().name() << std::endl; } /* boost::system::error_condition is used just like boost::system::error_code. Both the value() and category() method can be called for the boost::system::error_condition object as shown in the above example. The reason for having two more or less identical classes is fairly simple: While boost::system::error_code is used for platform dependent error codes, boost::system::error_condition is used to access platform independent error codes instead. By calling the default_error_condition() method, a platform dependent error code is translated into a platform independent error code of type boost::system::error_condition. If the above application is executed, it displays the number 12 and the error category GENERIC. The platform dependent error code 14 has been translated into the platform independent error code 12. Thanks to boost::system::error_condition, the error is always represented by the same number - disregarding of the underlying platform. While Windows reports the error as 14, the same error may be reported as 25 with a different operating system. Using boost::system::error_condition, the error will always be reported as 12. The last class offered by Boost.System is boost::system::system_error which is derived from std::runtime_error. It can be used to transport an error code of type boost::system::error_code within an exception. */ //#include <boost/asio.hpp> //#include <boost/system/system_error.hpp> //#include <iostream> // //int main() //{ // try // { // std::cout << boost::asio::ip::host_name() << std::endl; // } // catch (boost::system::system_error &e) // { // boost::system::error_code ec = e.code(); // std::cerr << ec.value() << std::endl; // std::cerr << ec.category().name() << std::endl; // } //} /* The free-standing boost::asio::ip::host_name() function is provided in two versions: One expecting an argument of type boost::system::error_code and one expecting no arguments. The second version will throw an exception of type boost::system::system_error in case of an error. The exception transports the error code of type boost::system::error_code accordingly. */
40.084906
94
0.751589
goodspeed24e
35b549edc2bb88298d2a8d909de8118dade9ba15
3,156
hpp
C++
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
1
2022-02-19T21:34:42.000Z
2022-02-19T21:34:42.000Z
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
null
null
null
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
1
2021-12-07T09:33:42.000Z
2021-12-07T09:33:42.000Z
#pragma once #include "forwarddecl/Tex.hpp" #include "forwarddecl/Ren.hpp" #include "Base.hpp" #include "PixelFmt.hpp" #include "Geom.hpp" namespace rolmodl { enum class TextureType { Static, Lock, Ren }; namespace textureType::unsafe { constexpr TextureType fromSDLEnum(const int a) noexcept { if (a == SDL_TEXTUREACCESS_STATIC) return TextureType::Static; if (a == SDL_TEXTUREACCESS_STREAMING) return TextureType::Lock; // if (a == SDL_TEXTUREACCESS_TARGET) return TextureType::Ren; } constexpr int toSDLEnum(const TextureType a) noexcept { if (a == TextureType::Static) return SDL_TEXTUREACCESS_STATIC; if (a == TextureType::Lock) return SDL_TEXTUREACCESS_STREAMING; // if (a == TextureType::Ren) return SDL_TEXTUREACCESS_TARGET; } } struct TextureInfo { public: pixelfmt::Id fmt; TextureType type; geom::Size size; }; class Tex { public: ~Tex() noexcept; Tex(const Tex& that) = delete; Tex(Tex&& that) noexcept; Tex& operator=(const Tex& that) = delete; Tex& operator=(Tex&& that) noexcept; friend void swap(Tex& a, Tex& b) noexcept; BlendMode getBlendMode(); void setBlendMode(const BlendMode m); uint8_t getAlphaMod(); void setAlphaMod(const uint8_t i); RGB getRGBMod(); void setRGBMod(const RGB i); TextureInfo query(); SDL_Texture* unsafeRaw() noexcept; const SDL_Texture* unsafeRaw() const noexcept; protected: Tex() noexcept; Tex(Ren& r, const pixelfmt::Id fmt, const int access, const geom::Size s); SDL_Texture* h_; }; class StaticTex : public Tex { public: StaticTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); }; class LockTex : public Tex { public: LockTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); pixelfmt::Id format() const noexcept; private: LockTex() noexcept; pixelfmt::Id format_; }; class RenTex : public Tex { public: RenTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); }; class TexLock { public: explicit TexLock(LockTex& tex); TexLock(LockTex& tex, const geom::RectWH r); TexLock(LockTex& tex, const geom::RectXY r); ~TexLock() noexcept; TexLock(const TexLock& that) = delete; TexLock(TexLock&& that) noexcept; TexLock& operator=(const TexLock& that) = delete; TexLock& operator=(TexLock&& that) noexcept; friend void swap(TexLock& a, TexLock& b) noexcept; TexLock& drawPoint(const RGBA c, const geom::Pos p) noexcept; RGBA getPoint(const geom::Pos p) const noexcept; uint32_t& unsafePoint(const geom::Pos p) noexcept; const uint32_t& unsafePoint(const geom::Pos p) const noexcept; void* unsafeRaw() noexcept; const void* unsafeRaw() const noexcept; private: TexLock() noexcept; TexLock(LockTex& tex, const SDL_Rect* r); TexLock(LockTex& tex, const SDL_Rect r); LockTex* t_; void* h_; unsigned int pitch_; }; }
24.276923
80
0.631179
maximsmol