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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
50f527b18788b52c38ea6e11fa240c91a476f68d
2,346
cpp
C++
iOS/Game/GameWindows.cpp
Amazong/Nebula
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
null
null
null
iOS/Game/GameWindows.cpp
Amazong/Nebula
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
11
2016-07-14T11:55:17.000Z
2016-07-14T12:14:01.000Z
iOS/Game/GameWindows.cpp
Amazong/iOS---Instrument-Outlet-Simulator
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
null
null
null
#include "headers\GameWindows.h" #include "headers\Errors.h" int render_splash() { sf::RenderWindow *splash_screen = new sf::RenderWindow(sf::VideoMode(887, 407), "", sf::Style::None); sf::Clock splash_clk; sf::Texture splash_png; if (!(splash_png.loadFromFile("res/png/Splash.png"))) { splash_screen->setVisible(0); return 42; } sf::Sprite splash_sprite; splash_sprite.setTexture(splash_png); while (splash_clk.getElapsedTime().asSeconds() < 4.0f) { splash_screen->clear(sf::Color::Black); splash_screen->draw(splash_sprite); splash_screen->display(); } delete splash_screen; return 0; } int n_words(const std::string & str) { if (str.empty()) return(0); int counter = 0; int size = str.length(); int num = str.find_first_of(' '); if (num == std::string::npos) return(1); while (num != std::string::npos) { counter++; num = str.find_first_of(' ', num + 1); } return(counter + 1); } std::string * get_string_tab(std::string & str, int & size, unsigned int line_size) { if (str.empty()) { size = 1; return(new std::string("")); } if (str.length() <= line_size) { size = 1; return(new std::string(str)); } int words = n_words(str), pos = 0, counter = 0, i = 0; size = str.length(); if (words == 1) { size = 1; return(new std::string(str)); } // edge cases std::string * tab_ptr = new std::string[words]; for (int i = 0, j = 0; i < size; i++) { if (str[i] == ' ') { tab_ptr[j] = str.substr(pos, (i - pos)) + ' '; pos = ++i; counter++; j++; } if (words - counter == 1) tab_ptr[j] = str.substr(pos); } // now tab_ptr[j] has all words of phrase. std::vector<std::string *> fitted_strings; std::string temp = ""; for (int i = 0; i < words; i++) { if (temp.size() + tab_ptr[i].size() > line_size) { fitted_strings.push_back(new std::string(temp)); temp.clear(); temp += tab_ptr[i]; continue; } temp += tab_ptr[i]; } fitted_strings.push_back(new std::string(temp)); delete[] tab_ptr; size = fitted_strings.size(); std::string * str_ptr = new std::string[size]; for (int i = 0; i < size; i++) { str_ptr[i] = *(fitted_strings[i]); delete fitted_strings[i]; } return(str_ptr); } void show_textbox(std::string & str, unsigned int line_size, unsigned int char_size) //NO DOUBLE FUCKING SPACES { }
18.046154
113
0.617221
50f529c402184d29c166aededf54b2345c95266c
429
cpp
C++
testing/park_test.cpp
Chukwuemeka-Ike/deepRacerControllers
c1c2901d87a45538aa0e38970c780ade3457c604
[ "MIT" ]
4
2019-12-30T08:54:36.000Z
2020-11-16T11:01:06.000Z
testing/park_test.cpp
Chukwuemeka-Ike/deepRacerControllers
c1c2901d87a45538aa0e38970c780ade3457c604
[ "MIT" ]
null
null
null
testing/park_test.cpp
Chukwuemeka-Ike/deepRacerControllers
c1c2901d87a45538aa0e38970c780ade3457c604
[ "MIT" ]
null
null
null
// To test the parallel parking controller before implementing it in a ROS pkg #include <cmath.h> #include <stdio.h> using namespace std; #define steeringGain 2 #define throttleGain 2 float computeDistance(float first, float second); int main() { x = -2; xd = -5; while(x != xd){ steeringCtrl = -steeringGain*(xd-x); } } float computeDistance(float first, float second) { return first - second; }
15.321429
78
0.675991
50f5eac597a7a48fdf25f1af7c48233c64a486e6
260
cpp
C++
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
37
2020-12-09T20:24:36.000Z
2022-02-18T17:19:23.000Z
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
25
2020-11-25T20:37:33.000Z
2022-02-25T15:53:11.000Z
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
8
2020-11-30T15:34:06.000Z
2022-01-09T21:06:00.000Z
#ifndef __PREPROCESSING #define __PREPROCESSING #include "../preprocessing/errormsg.cpp" #include "../preprocessing/ioutilities.cpp" #include "../preprocessing/readbinaryfiles.cpp" #ifdef HAVE_CUDA #include "../preprocessing/gpuDeviceInfo.cpp" #endif #endif
21.666667
47
0.788462
50f7589a35ef392e993cef7dfd97e16115d1e4be
508
cpp
C++
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/utility_make_from_tuple.exe ./cpp/utility_make_from_tuple.cpp && (cd ../_build/cpp/;./utility_make_from_tuple.exe) https://en.cppreference.com/w/cpp/utility/make_from_tuple */ #include <iostream> #include <tuple> struct Foo { Foo(int first, float second, int third) { std::cout << first << ", " << second << ", " << third << "\n"; } }; int main() { auto tuple = std::make_tuple(42, 3.14f, 0); std::make_from_tuple<Foo>(std::move(tuple)); }
28.222222
156
0.635827
50f96c187b9ce94499cc1b4e6b8e24405bfdfa12
4,365
cxx
C++
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Author: Panos Christakoglou. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------- // AliDetectorTagCuts class // This is the class to deal with the Detector tag level cuts // Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch //----------------------------------------------------------------- class AliLog; #include "AliDetectorTag.h" #include "AliDetectorTagCuts.h" #include "TObjString.h" #include "TString.h" ClassImp(AliDetectorTagCuts) //___________________________________________________________________________ AliDetectorTagCuts::AliDetectorTagCuts() : TObject(), fDetectorsReco(0), fDetectorsDAQ(0), fDetectorsFlag(kFALSE), fDetectorValidityMatch(), fDetectorValidityFlag() { //Default constructor which calls the Reset method. for (int iter = 0; iter<AliDAQ::kHLTId; iter++) { fDetectorValidityMatch[iter] = 0; fDetectorValidityFlag[iter] = 0; } } //___________________________________________________________________________ AliDetectorTagCuts::~AliDetectorTagCuts() { //Defaut destructor. } //___________________________________________________________________________ Bool_t AliDetectorTagCuts::IsAccepted(AliDetectorTag *detTag) const { //Returns true if the event is accepted otherwise false. if (fDetectorsFlag) { Bool_t daqsel = (detTag->GetIntDetectorMaskDAQ() & fDetectorsDAQ) > 0; Bool_t recsel = (detTag->GetIntDetectorMaskReco() & fDetectorsReco) > 0; Bool_t valsel = kTRUE; for (int iter=0; iter<AliDAQ::kHLTId; iter++) { if (fDetectorValidityFlag[iter]) if (!(fDetectorValidityMatch[iter] == detTag->GetDetectorValidityRange(iter))) valsel = kFALSE; } return (daqsel && recsel && valsel); } return true; // if(fDetectorsFlag){ // TString detStr = fDetectors; // TObjArray *activeDetectors = detTag->GetDetectorMask(); // for (Int_t iDet = 0; iDet < activeDetectors->GetEntries(); iDet++) { // TObjString *detectorString = (TObjString *)activeDetectors->At(iDet); // if (!IsSelected(detectorString->GetString(), detStr))return kFALSE; // } // } // return kTRUE; } void AliDetectorTagCuts::SetDetectorValidityValue(TString det, UShort_t val) { // Set Validity requiement for detector Short_t detid = AliDAQ::DetectorID(det.Data()); if (detid >= 0) { fDetectorValidityMatch[detid] = val; fDetectorsFlag = kTRUE; } } //___________________________________________________________________________ // Bool_t AliDetectorTagCuts::IsSelected(TString detName, TString& detectors) const { // //Returns true if the detector is included // if ((detectors.CompareTo("ALL") == 0) || // detectors.BeginsWith("ALL ") || // detectors.EndsWith(" ALL") || // detectors.Contains(" ALL ")) { // detectors = "ALL"; // return kTRUE; // } // // search for the given detector // Bool_t result = kFALSE; // if ((detectors.CompareTo(detName) == 0) || // detectors.BeginsWith(detName+" ") || // detectors.EndsWith(" "+detName) || // detectors.Contains(" "+detName+" ")) { // detectors.ReplaceAll(detName, ""); // result = kTRUE; // } // // clean up the detectors string // while (detectors.Contains(" ")) detectors.ReplaceAll(" ", " "); // while (detectors.BeginsWith(" ")) detectors.Remove(0, 1); // while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1); // return result; // }
36.680672
85
0.6252
50ff1bc5ed5b30251e2a0c6b4e0289112d84e0e2
6,165
hpp
C++
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../widget.hpp" #include "../container.hpp" #include "../base/oriented_widget.hpp" namespace morda{ /** * @brief Scrollable list widget. * This is a base class for vertical and horizontal lists. */ class list_widget : // NOTE: order of virtual public and private declarations here matters for clang due to some bug, // see http://stackoverflow.com/questions/42427145/clang-cannot-cast-to-private-base-while-there-is-a-public-virtual-inheritance virtual public widget, public container, protected oriented_widget { // index of the first item added to container as child size_t added_index = size_t(-1); size_t pos_index = 0; // index of the first visible item // offset in pixels of the first visible item. // the value is positive, tough the item is biased towards negative coordinate values. real pos_offset = real(0); size_t num_tail_items = 0; // zero means that number of tail items has to be recomputed size_t first_tail_item_index = 0; real first_tail_item_offset = real(0); real first_tail_item_dim = real(0); protected: list_widget(std::shared_ptr<morda::context> c, const treeml::forest& desc, bool vertical); public: list_widget(const list_widget&) = delete; list_widget& operator=(const list_widget&) = delete; /** * @brief list items provider. * User should subclass this class to provide items to the list. */ class provider : virtual public utki::shared{ friend class list_widget; list_widget* parent_list = nullptr; protected: provider(){} public: /** * @brief Get parent list widget. * @return list widget which owns the provider, in case the provider is set to some list widget. * @return nullptr in case the provider is not set to any list widget. */ list_widget* get_list()noexcept{ return this->parent_list; } /** * @brief Get total number of items in the list. * @return Number of items in the list. */ virtual size_t count()const noexcept = 0; /** * @brief Get widget for item. * @param index - index of item to get widget for. * @return widget for the requested item. */ virtual std::shared_ptr<widget> get_widget(size_t index) = 0; /** * @brief Recycle widget of item. * @param index - index of item to recycle widget of. * @param w - widget to recycle. */ virtual void recycle(size_t index, std::shared_ptr<widget> w){} void notify_data_set_change(); }; void set_provider(std::shared_ptr<provider> item_provider = nullptr); void lay_out()override; morda::vector2 measure(const morda::vector2& quotum) const override; /** * @brief Set scroll position as factor from [0:1]. * @param factor - factor of the scroll position to set. */ void set_scroll_factor(real factor); /** * @brief Get scroll factor. * @return Current scroll position as factor from [0:1]. */ real get_scroll_factor()const noexcept; /** * @brief Get scroll band. * Returns scroll band as a fraction of 1. This is basically the number of visible elements divided by total number of elements in the list. * @return scroll band. */ real get_scroll_band()const noexcept; /** * @brief Get index of the first visible item. * @return index of the first visible item. */ size_t get_pos_index()const noexcept{ return this->pos_index; } /** * @brief Get offset of the first visible item. * The value is positive, though the item coordinate is <= 0. * @return offset in pixels of the first visible item. */ real get_pos_offset()const noexcept{ return this->pos_offset; } /** * @brief Scroll the list by given number of pixels. * @param delta - number of pixels to scroll, can be positive or negative. */ void scroll_by(real delta); /** * @brief Data set changed signal. * Emitted when list widget contents have actually been updated due to change in provider's model data set. */ std::function<void(list_widget&)> data_set_change_handler; /** * @brief Scroll position changed signal. * Emitted when list's scroll position has changed. */ std::function<void(list_widget&)> scroll_change_handler; private: std::shared_ptr<provider> item_provider; void update_children_list(); // returns true if it was the last visible widget bool arrange_widget( std::shared_ptr<widget>& w, real& pos, bool add, size_t index, widget_list::const_iterator& insertBefore ); void update_tail_items_info(); void handle_data_set_changed(); void notify_scroll_pos_changed(); void notify_scroll_pos_changed(size_t old_index, real old_offset); real calc_num_visible_items()const noexcept; }; /** * @brief Horizontal list widget. * Panorama list widget. * From GUI script it can be instantiated as "pan_list". */ class pan_list : public list_widget{ public: pan_list(std::shared_ptr<morda::context> c, const treeml::forest& desc) : widget(std::move(c), desc), list_widget(this->context, desc, false) {} pan_list(const pan_list&) = delete; pan_list& operator=(const pan_list&) = delete; }; /** * @brief Vertical list widget. * From GUI script it can be instantiated as "list". */ class list : public list_widget{ public: list(std::shared_ptr<morda::context> c, const treeml::forest& desc) : widget(std::move(c), desc), list_widget(this->context, desc, true) {} list(const list&) = delete; list& operator=(const list&) = delete; }; }
28.022727
144
0.710949
dd00c037105c4c257d0293e8d5c4d7cc9b5180d3
1,415
cpp
C++
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
96
2018-08-23T16:49:05.000Z
2021-11-25T00:47:16.000Z
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
1,011
2018-08-17T12:25:21.000Z
2021-11-18T09:30:19.000Z
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
65
2018-08-20T20:05:40.000Z
2022-02-26T23:54:35.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "settings/help.hpp" #include "settings/setting_collection.hpp" namespace { constexpr char const *NAME = "help"; constexpr char const *DESCRIPTION = "Print this help and exit"; } // namespace namespace fetch { namespace settings { Help::Help(SettingCollection &reg) : SettingBase(reg, NAME, DESCRIPTION) , reg_(reg) {} void Help::FromStream(std::istream & /*stream*/) {} void Help::ToStream(std::ostream & /*stream*/) const {} bool Help::TerminateNow() const { reg_.DisplayHelp(); return true; } std::string Help::envname() const { return {}; } } // namespace settings } // namespace fetch
25.267857
80
0.619081
dd011de4d4974377abef93788e2e99b1a3e3afcd
137
cpp
C++
src/tests/noCanon.cpp
atonks2/Serial
555f6d233ee27b0d4c04d01e63876be3755e69bd
[ "MIT" ]
null
null
null
src/tests/noCanon.cpp
atonks2/Serial
555f6d233ee27b0d4c04d01e63876be3755e69bd
[ "MIT" ]
null
null
null
src/tests/noCanon.cpp
atonks2/Serial
555f6d233ee27b0d4c04d01e63876be3755e69bd
[ "MIT" ]
null
null
null
#include "serial.h" int main() { Serial gps(4800,"/dev/ttyUSB0",false); std::cout << gps.serialRead(41) << std::endl; return 0; }
15.222222
46
0.620438
dd033758b6c3f0807ce81c62ef206680f2338422
1,930
hpp
C++
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog.Experimental/Gameplay/detail/ComponentTypeIndex.hpp" #include "Pomdog.Experimental/Gameplay/Component.hpp" #include "Pomdog/Basic/Export.hpp" #include "Pomdog/Math/Quaternion.hpp" #include "Pomdog/Math/Radian.hpp" #include "Pomdog/Math/Vector2.hpp" #include "Pomdog/Math/Vector3.hpp" namespace Pomdog { class POMDOG_EXPORT Transform final : public Component { public: Transform() noexcept; Vector2 GetPosition2D() const noexcept; void SetPosition2D(const Vector2& positionIn) noexcept; const Vector3& GetPosition() const noexcept; void SetPosition(const Vector3& positionIn) noexcept; void SetPositionX(float x) noexcept; void SetPositionY(float y) noexcept; void SetPositionZ(float z) noexcept; const Vector3& GetScale() const noexcept; void SetScale(const Vector3& scaleIn) noexcept; void SetScale(float scaleIn) noexcept; Vector2 GetScale2D() const noexcept; Radian<float> GetRotation2D() const noexcept; Quaternion GetRotation() const noexcept; void SetRotation(const Quaternion& rotationIn) noexcept; void SetRotationX(const Radian<float>& angle) noexcept; void SetRotationY(const Radian<float>& angle) noexcept; void SetRotationZ(const Radian<float>& angle) noexcept; void Rotate(const Vector3& eulerAngles); void Rotate2D(const Radian<float>& rotationZ); Matrix4x4 GetTransformMatrix() const noexcept; private: Vector3 position; Vector3 scale; Quaternion rotation; }; template <> struct ComponentTypeDeclaration<Transform> final { static std::uint8_t GetTypeIndex(); }; template <> class ComponentCreator<Transform> final : public ComponentCreatorBase { public: std::shared_ptr<Component> CreateComponent() override; std::uint8_t GetComponentType() override; }; } // namespace Pomdog
24.43038
71
0.74715
dd03afbf58d3d03eb05365cd7623fa1cef1ac089
1,766
cpp
C++
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
// CG1_EdgeTableRow.cpp: implementation of the CG1_EdgeTableRow class. // ////////////////////////////////////////////////////////////////////// #include "CG1_EdgeTableRow.h" #include <stdio.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------- CG1_EdgeTableRow::CG1_EdgeTableRow() { } //-------------------------------------------------------------------- CG1_EdgeTableRow::~CG1_EdgeTableRow() { CG1_Edge *CurrentEdge = 0; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end(); EdgeIterator++) { CurrentEdge = *EdgeIterator; delete CurrentEdge; } Edges.erase(Edges.begin(), Edges.end()); } //-------------------------------------------------------------------- void CG1_EdgeTableRow::AddEdge(CG1_Edge* Newedge) { bool inserted = false; CG1_Edge* CurrentEdge; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end() && !inserted; EdgeIterator++) { CurrentEdge = *EdgeIterator; if(CurrentEdge->x_down > Newedge->x_down) { Edges.insert(EdgeIterator, Newedge); inserted = true; } } if(!inserted) { Edges.push_back(Newedge); } } //-------------------------------------------------------------------- void CG1_EdgeTableRow::WriteData(int index) { if(Edges.size() > 0) { printf("%d: ", index); CG1_Edge* CurrentEdge; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end(); EdgeIterator++) { CurrentEdge = *EdgeIterator; printf(" x = %d ", CurrentEdge->x_down); } printf("\n"); } else { printf("%d: empty\n", index); } }
24.527778
93
0.460362
dd04525b5224e62126bbb901f63b44d59724b3a2
12,579
cpp
C++
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Lars Maier //////////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "Cluster/Maintenance.h" #include "Replication2/ReplicatedLog/LogStatus.h" #include "Replication2/ReplicatedState/StateStatus.h" #include "Basics/StringUtils.h" using namespace arangodb; using namespace arangodb::maintenance; using namespace arangodb::replication2; struct ReplicatedStateMaintenanceTest : ::testing::Test { MaintenanceFeature::errors_t errors; containers::FlatHashSet<DatabaseID> dirtyset; bool callNotify = false; std::vector<std::shared_ptr<ActionDescription>> actions; DatabaseID const database{"mydb"}; ParticipantId const serverId{"MyServerId"}; LogId const logId{12}; }; namespace { template<typename T> auto decodeFromString(std::string_view src) -> std::optional<T> { auto buffer = arangodb::basics::StringUtils::decodeBase64(src); auto slice = VPackSlice(reinterpret_cast<uint8_t const*>(buffer.c_str())); if (!slice.isNone()) { return T::fromVelocyPack(slice); } return std::nullopt; } } // namespace TEST_F(ReplicatedStateMaintenanceTest, create_state_test_without_local_log) { /* * Test that the maintenance waits for the replicated log to be present first * before creating a replicated state. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{}; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {}}, {"otherServer", {}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 0); } TEST_F(ReplicatedStateMaintenanceTest, create_state_test_with_local_log) { /* * Test that the maintenance create an action to create the replicated state. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, std::nullopt); } TEST_F(ReplicatedStateMaintenanceTest, create_state_test_with_local_log_and_current_entry) { /* * Test that the maintenance creates a replicated state and forwards the * current entry into the action. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, currentStates.at(logId)); } TEST_F(ReplicatedStateMaintenanceTest, do_nothing_if_stable) { /* * Check that if the configuration is stable, nothing happens. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{ {logId, {{replicated_state::UnconfiguredStatus{ .generation = replicated_state::StateGeneration{1}, .snapshot = {}}}}}, }; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 0); } TEST_F(ReplicatedStateMaintenanceTest, check_resync_if_generation_changes) { /* * Check that the maintenance triggers a resync if the generation changes. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{ {logId, {{replicated_state::UnconfiguredStatus{ .generation = replicated_state::StateGeneration{0}, .snapshot = {}}}}}, }; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, std::nullopt); // Current not needed. }
40.317308
80
0.581922
dd04eeadcb3d3eec69af42fe91c490728494de2b
3,977
cpp
C++
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
51
2017-03-24T06:08:11.000Z
2022-03-18T00:28:14.000Z
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
1
2019-06-23T07:33:42.000Z
2019-12-12T13:14:04.000Z
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
25
2017-04-07T13:22:45.000Z
2022-03-18T00:28:15.000Z
// 8.exercise.05.cpp // // Write two functions that reverse the order of element in a vector<int>. // For example, 1, 3, 5, 6, 9 becomes 9, 7, 5, 3, 1. The first reverse // function should produce a new vector with the reverse sequence, leaving the // original vector unchanged. The other reverse function should reverse the // elements of its vector without using any other vectors (hint: swap). // // COMMENTS // // The fibonacci() and print() functions comes in handy to test the proposed // functions on this exercise. // // The first function will be named reverse_cr() as parameter will be passed // by const-reference. The other one will be reverse_r() as parameter will be // passed by reference. For this one we use swap(), as the hint says, but we // will no implement it since its available on the standard library, as // pointed out in §8.5.5. // // We must check for odd and even size sequences. #include "std_lib_facilities.h" void print(const string& label, const vector<int>& data) // Only read arguments, so it safe to pass them by const-reference { cout << label << ": { "; for (int i : data) cout << i << ' '; cout << "}\n"; } int check_add(int a, int b) // Adds two integers performing overflow control to avoid undefined behavior. // (Search for INT32-C on https://www.securecoding.cert.org) { if (((b > 0) && (a > (numeric_limits<int>::max() - b))) || ((b < 0) && (a < (numeric_limits<int>::min() - b)))) error("check_add(): integer add overflows."); else return a+b; } void fibonacci(int x, int y, vector<int>& v, int n) // Generates a Fibonacci sequence of n values into v, starting with values x // and y (integers passed by value, and we are modifying v, so it is passed by // reference). // Preconditions: // Vector must be empty // To simplify, n must be equal or greater than two. { if (v.size() != 0) error("fibonacci(): Non empty vector passed as argument."); if (n < 2) error("fibonacci(): n must be al least 2."); v.push_back(x); v.push_back(y); // Add a try-catch block to catch overflow and let the program continue try { for (int i = 2; i < n; ++i) v.push_back(check_add(v[i-2],v[i-1])); } catch(exception& e){ cerr << e.what() << '\n'; } } vector<int> reverse_cr(const vector<int>& v) // Returns a new vector with vector v elements in reverse order { vector<int> r; for (size_t i = v.size(); i > 0; --i) r.push_back(v[i-1]); return r; } void reverse_r(vector<int>& v) // Reverses order of elements of vector v { size_t limit{v.size()/2}; // Only traverse half of the elements. // This way, if we have an odd number of elements // the division ignores the middle one. size_t last_idx{v.size()-1}; // Last element index. To avoid recalc. for (size_t i = 0; i < limit; ++i) swap(v[i], v[last_idx-i]); } int main() try { // Test a vector with even element number vector<int> e1; fibonacci(1, 2, e1, 8); // Generate a vector with even element number print("Original even ", e1); vector<int> e2{reverse_cr(e1)}; // New vector reversed print("Reverse even by const-ref", e2); reverse_r(e1); // Reverse original vector print("Reverse even by ref ", e1); // Test a vector with odd element number vector<int> o1; fibonacci(1, 2, o1, 7); // Generate a vector with odd element number print("Original odd ", o1); vector<int> o2{reverse_cr(o1)}; // New vector reversed print("Reverse odd by const-ref ", o2); reverse_r(o1); // Reverse original vector print("Reverse odd by ref ", o1); return 0; } catch(exception& e) { cerr << e.what() << '\n'; return 1; } catch(...) { cerr << "Unknwon exception!!\n"; return 2; }
31.816
81
0.608499
dd050b40b3689ecaa72f8691d1d6f53df4276d02
274
cpp
C++
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
#include "shared_traits.h" #include<cassert> using namespace logs2::SharedTraits; AssertCheck::AssertCheck() : _threadId{ std::this_thread::get_id() } { } void AssertCheck::isSameThread() const { assert(std::this_thread::get_id() == _threadId); }
17.125
53
0.671533
dd08360f1d9633daaf49c3bce9979d7835eca5e8
6,324
cpp
C++
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
null
null
null
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
1
2021-09-27T13:16:08.000Z
2021-09-27T13:16:08.000Z
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
null
null
null
/* * BitMatrixParser.cpp * zxing * * Created by Christian Brunschen on 20/05/2008. * Copyright 2008 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <zxing/qrcode/decoder/BitMatrixParser.h> #include <zxing/qrcode/decoder/DataMask.h> namespace zxing { namespace qrcode { int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) { return bitMatrix_.get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1; } BitMatrixParser::BitMatrixParser (sampled_grid_t& bitMatrix) : bitMatrix_(bitMatrix), found_error(false), parsedVersion_(0), parsedFormatInfo_() { size_t dimension = bitMatrix.getHeight(); if ((dimension < 21) || (dimension & 0x03) != 1) { found_error = true; } } std::optional<FormatInformation> BitMatrixParser::readFormatInformation() { if (parsedFormatInfo_) { return parsedFormatInfo_; } // Read top-left format info bits int formatInfoBits1 = 0; for (int i = 0; i < 6; i++) { formatInfoBits1 = copyBit(i, 8, formatInfoBits1); } // .. and skip a bit in the timing pattern ... formatInfoBits1 = copyBit(7, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 7, formatInfoBits1); // .. and skip a bit in the timing pattern ... for (int j = 5; j >= 0; j--) { formatInfoBits1 = copyBit(8, j, formatInfoBits1); } // Read the top-right/bottom-left pattern int dimension = bitMatrix_.getHeight(); int formatInfoBits2 = 0; int jMin = dimension - 7; for (int j = dimension - 1; j >= jMin; j--) { formatInfoBits2 = copyBit(8, j, formatInfoBits2); } for (int i = dimension - 8; i < dimension; i++) { formatInfoBits2 = copyBit(i, 8, formatInfoBits2); } return FormatInformation::decodeFormatInformation(formatInfoBits1,formatInfoBits2); } const Version* BitMatrixParser::readVersion() { if (parsedVersion_ != nullptr) { return parsedVersion_; } int dimension = bitMatrix_.getHeight(); int provisionalVersion = (dimension - 17) >> 2; if (provisionalVersion <= 6) { return Version::getVersionForNumber(provisionalVersion); } // Read top-right version info: 3 wide by 6 tall int versionBits = 0; for (int y = 5; y >= 0; y--) { int xMin = dimension - 11; for (int x = dimension - 9; x >= xMin; x--) { versionBits = copyBit(x, y, versionBits); } } parsedVersion_ = Version::decodeVersionInformation(versionBits); if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension) { return parsedVersion_; } // Hmm, failed. Try bottom left: 6 wide by 3 tall versionBits = 0; for (int x = 5; x >= 0; x--) { int yMin = dimension - 11; for (int y = dimension - 9; y >= yMin; y--) { versionBits = copyBit(x, y, versionBits); } } parsedVersion_ = Version::decodeVersionInformation(versionBits); if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension) { return parsedVersion_; } return nullptr; } codewords_t BitMatrixParser::readCodewords() { codewords_t result = {0}; auto formatInfo = readFormatInformation(); const Version* version = readVersion(); if (version == nullptr || !formatInfo) { return result; } // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. auto dataMask = DataMask::select((int) formatInfo.value().getDataMask()); if (!dataMask) { return result; } int dimension = bitMatrix_.getHeight(); dataMask.value().unmaskBitMatrix(bitMatrix_, dimension); bitmatrix_t<config::MaxGridSize, config::MaxGridSize> functionPattern(dimension); version->buildFunctionPattern(functionPattern); bool readingUp = true; int resultOffset = 0; int currentByte = 0; int bitsRead = 0; // Read columns in pairs, from right to left for (int x = dimension - 1; x > 0; x -= 2) { if (x == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly x--; } // Read alternatingly from bottom to top then top to bottom for (int counter = 0; counter < dimension; counter++) { int y = readingUp ? dimension - 1 - counter : counter; for (int col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern.get(x - col, y)) { // Read a bit bitsRead++; currentByte <<= 1; if (bitMatrix_.get(x - col, y)) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = (char)currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp = !readingUp; // switch directions } if (resultOffset != version->getTotalCodewords()) { for (auto n = 0; n < result.size(); ++n) { result[n] = 0; } } return result; } } // ns qrcode } // ns zxing
28.232143
92
0.576534
dd085a10754d853dfa6fc05db45c3c43bdb39bf4
155
hpp
C++
src/utils/assert.hpp
JacobDomagala/Shady
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
2
2020-10-27T00:16:18.000Z
2021-03-29T12:59:48.000Z
src/utils/assert.hpp
JacobDomagala/DEngine
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
58
2020-08-23T21:38:21.000Z
2021-08-05T16:12:31.000Z
src/utils/assert.hpp
JacobDomagala/Shady
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
null
null
null
#pragma once #include <string_view> namespace shady::utils { void Assert(bool assertion, std::string_view logMsg); } // namespace shady::utils
15.5
49
0.703226
dd085d6124666640274f9c20f98790de6a10b19f
2,554
cpp
C++
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
7
2018-01-19T00:19:19.000Z
2021-06-22T00:53:00.000Z
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
66
2021-06-22T22:44:21.000Z
2022-03-16T15:18:00.000Z
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
6
2017-04-13T19:42:27.000Z
2022-03-26T18:46:24.000Z
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #include "ads/simulation.hpp" #include "tumor.hpp" #include "vasculature.hpp" // clang-tidy 12 complains about deleted default constructor not // initializing some members // // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init) struct sim_params { int p; // 2 int elems; // 80 ads::timesteps_config steps; // 10000, 0.1 int plot_every; tumor::params tumor_params; tumor::vasc::config vasc_config; }; sim_params parse_params(char* args[], int idx) { using std::atof; using std::atoi; auto next = [&]() { return args[idx++]; }; auto next_int = [&]() { return atoi(next()); }; auto next_float = [&]() { return atof(next()); }; int p = next_int(); int elems = next_int(); int nsteps = next_int(); double dt = next_float(); int plot_every = next_int(); // tumor parameters tumor::params tumor; tumor.tau_b = next_float(); tumor.o_prol_TC = next_float(); tumor.o_death_TC = next_float(); tumor.t_prol_TC = next_float(); tumor.t_death_TC = next_float(); tumor.P_b = next_float(); tumor.r_b = next_float(); tumor.beta_m = next_float(); tumor.gamma_a = next_float(); tumor.chi_aA = next_float(); tumor.gamma_oA = next_float(); tumor.diff_c = next_float(); tumor.cons_c = next_float(); // 3D only tumor.alpha_0 = next_float(); tumor.gamma_T = next_float(); tumor.alpha_1 = next_float(); // Vasculature parameters tumor::vasc::config vasc; vasc.init_stability = next_float(); vasc.degeneration = next_float(); vasc.t_ec_sprout = next_float(); vasc.segment_length = next_float(); vasc.t_ec_collapse = next_float(); vasc.c_min = next_float(); // 2D only vasc.t_ec_migr = next_float(); // 3D only vasc.r_sprout = next_float(); vasc.r_max = next_float(); vasc.t_ec_switch = next_float(); vasc.c_switch = next_float(); vasc.dilatation = next_float(); return {p, elems, {nsteps, dt}, plot_every, tumor, vasc}; } int main(int /*argc*/, char* argv[]) { sim_params sp = parse_params(argv, 1); ads::dim_config dim{sp.p, sp.elems, 0, 3000.0}; int ders = 1; ads::config_2d c{dim, dim, sp.steps, ders}; tumor::vasc::random_vasculature rand_vasc{sp.vasc_config, 0}; tumor::tumor_2d sim{c, sp.tumor_params, sp.plot_every, rand_vasc()}; sim.run(); }
26.884211
76
0.632733
dd0b152d97aca70163eb9763adb4b0c8a2a44997
3,748
cpp
C++
src/cpp/ws-server/ws-server.cpp
jimba81/qt-virtualkeyboard-server
8b2093cda28779fc8bc898d5ac9135b8b1cf3003
[ "Apache-2.0" ]
null
null
null
src/cpp/ws-server/ws-server.cpp
jimba81/qt-virtualkeyboard-server
8b2093cda28779fc8bc898d5ac9135b8b1cf3003
[ "Apache-2.0" ]
null
null
null
src/cpp/ws-server/ws-server.cpp
jimba81/qt-virtualkeyboard-server
8b2093cda28779fc8bc898d5ac9135b8b1cf3003
[ "Apache-2.0" ]
null
null
null
#include "ws-server.h" #include "cpp/common/common.h" #include "cpp/common/util.h" WsServer::WsServer(QObject *parent) : QObject(parent) { server = new QWebSocketServer("IMR WebSocket Server", QWebSocketServer::NonSecureMode, this); connect(server, &QWebSocketServer::newConnection, this, &WsServer::slotClientConnected); connect(server, &QWebSocketServer::closed, this, &WsServer::slotClosed); start(); // TESTING /*connect(&tmrTest, &QTimer::timeout, this, [=] { this->tx("hey I'm Qt"); }); tmrTest.start(2000);*/ } WsServer::~WsServer() { stop(); qDeleteAll(clients.begin(), clients.end()); } void WsServer::start() { stop(); if (server->listen(QHostAddress::Any, WS_SERVER_PORT)) { qDebug("Server listening on port %d...\n", WS_SERVER_PORT); } else { qErrnoWarning("Server listening on port %d failed: %s\n", WS_SERVER_PORT, server->errorString().CSTR()); } } void WsServer::stop() { if (server->isListening()) { // Close connection first. When closed, start() will be called server->close(); } } void WsServer::slotClosed() { /*if (env->state == EnvGlobal::STATE_EXITING) { return; } LOG_INFO("Server Closed.\n"); if (env->ds.capabilities->getGeneral_WebApplicationEnabled().value.toBool()) { LOG_INFO("Server closed unexpectedly. Starting server again..\n"); start(); }*/ } void WsServer::slotClientConnected() { QWebSocket *pSocket = server->nextPendingConnection(); // check if client already connected foreach (QWebSocket *pClient, clients) { if (pClient != NULL) { if ( (pClient->peerAddress() == pSocket->peerAddress()) && (pClient->peerPort() == pSocket->peerPort()) ) { // client already connected, ignore return; } } } connect(pSocket, &QWebSocket::textMessageReceived, this, &WsServer::slotRxMessage); connect(pSocket, &QWebSocket::binaryMessageReceived, this, &WsServer::slotRxBinMessage); connect(pSocket, &QWebSocket::disconnected, this, &WsServer::socketDisconnected); clients << pSocket; qDebug("New Connection[%d]: %s%s:%u\n", clients.length() - 1, pSocket->peerName().CSTR(), pSocket->peerAddress().toString().CSTR(), pSocket->peerPort()); } void WsServer::tx(QString msg) { QVariantMap messageMap; messageMap.insert("from", "KeyboardServer"); messageMap.insert("data", msg); QString payload = Util::qVarientToJsonData(messageMap); foreach (QWebSocket *pClient, clients) { if (pClient != NULL) { pClient->sendTextMessage(payload); } } } void WsServer::slotRxMessage(QString message) { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); qDebug("Message received: %s\n", message.CSTR()); if (pClient) { pClient->sendTextMessage(message); } } void WsServer::slotRxBinMessage(QByteArray message) { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); qDebug("Binary Message received: %s\n", message.toHex().CSTR()); if (pClient) { pClient->sendBinaryMessage(message); } } void WsServer::socketDisconnected() { QWebSocket *pClient = qobject_cast<QWebSocket *>(sender()); if (pClient) { clients.removeAll(pClient); pClient->deleteLater(); qDebug("Socket Disconnected[%d]: %s%s:%u\n", clients.length(), pClient->peerName().CSTR(), pClient->peerAddress().toString().CSTR(), pClient->peerPort()); } }
24.986667
112
0.605656
dd0b9b7c456ca5ce3c9b526dde6e385123c9401a
1,012
cpp
C++
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
1
2017-11-16T02:13:15.000Z
2017-11-16T02:13:15.000Z
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
null
null
null
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
null
null
null
// BEGIN_COPYRIGHT // // Copyright 2009-2014 CRS4. // // 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. // // END_COPYRIGHT #include "hdfs_common.hpp" void hdfs_exception_translator(hdfs_exception const& x) { PyErr_SetString(PyExc_IOError, x.what()); } //++++++++++++++++++++++++++++++// // Exporting class definitions. // //++++++++++++++++++++++++++++++// using namespace boost::python; void export_hdfs_common() { register_exception_translator<hdfs_exception>(hdfs_exception_translator); }
28.111111
78
0.699605
dd0eb99be4447e58a8bfd4d6efe3a0f03c41d8ff
26,469
cpp
C++
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
1
2021-12-09T14:24:04.000Z
2021-12-09T14:24:04.000Z
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
null
null
null
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
null
null
null
#include <set> #define GLFW_INCLUDE_VULKAN #include "Context.h" #include "imgui/imgui_impl_vulkan.h" #include "imgui/imgui_impl_glfw.h" #include "spdlog/sinks/stdout_color_sinks.h" namespace help { VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback) { auto func = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT")); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator) { auto func = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT")); if (func != nullptr) { func(instance, callback, pAllocator); } } } //todo remove this when the SDK update happened VkResult vkCreateAccelerationStructureNV(VkDevice device, const VkAccelerationStructureCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureNV* pAccelerationStructure) { auto func = reinterpret_cast<PFN_vkCreateAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkCreateAccelerationStructureNV")); if (func != nullptr) { return func(device, pCreateInfo, pAllocator, pAccelerationStructure); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void vkDestroyAccelerationStructureNV(VkDevice device, VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks* pAllocator) { auto func = reinterpret_cast<PFN_vkDestroyAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkDestroyAccelerationStructureNV")); if (func != nullptr) { return func(device, accelerationStructure, pAllocator); } } void vkGetAccelerationStructureMemoryRequirementsNV(VkDevice device, const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) { auto func = reinterpret_cast<PFN_vkGetAccelerationStructureMemoryRequirementsNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureMemoryRequirementsNV")); if (func != nullptr) { return func(device, pInfo, pMemoryRequirements); } } VkResult vkBindAccelerationStructureMemoryNV(VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) { auto func = reinterpret_cast<PFN_vkBindAccelerationStructureMemoryNV>(vkGetDeviceProcAddr(device, "vkBindAccelerationStructureMemoryNV")); if (func != nullptr) { return func(device, bindInfoCount, pBindInfos); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkGetAccelerationStructureHandleNV( VkDevice device, VkAccelerationStructureNV accelerationStructure, size_t dataSize, void* pData) { auto func = reinterpret_cast<PFN_vkGetAccelerationStructureHandleNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureHandleNV")); if (func != nullptr) { return func(device, accelerationStructure, dataSize, pData); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkRayTracingPipelineCreateInfoNV* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) { auto func = reinterpret_cast<PFN_vkCreateRayTracingPipelinesNV>(vkGetDeviceProcAddr(device, "vkCreateRayTracingPipelinesNV")); if (func != nullptr) { return func(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkGetRayTracingShaderGroupHandlesNV(VkDevice device, VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData) { auto func = reinterpret_cast<PFN_vkGetRayTracingShaderGroupHandlesNV>(vkGetDeviceProcAddr(device, "vkGetRayTracingShaderGroupHandlesNV")); if (func != nullptr) { return func(device, pipeline, firstGroup, groupCount, dataSize, pData); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } namespace vg { Context::Context(const std::vector<const char*>& requiredDeviceExtensions) : m_requiredDeviceExtensions(requiredDeviceExtensions) { // init logger m_logger = spdlog::stdout_color_mt("standard"); m_logger->info("Logger initialized."); // init rest initWindow(); initVulkan(); initImgui(); } Context::~Context() { cleanupImgui(); vmaDestroyAllocator(m_allocator); for (const auto& imageView : m_swapChainImageViews) { m_device.destroyImageView(imageView); } m_device.destroySwapchainKHR(m_swapchain); m_instance.destroySurfaceKHR(m_surface); m_device.destroy(); help::DestroyDebugUtilsMessengerEXT(m_instance, m_callback, nullptr); m_instance.destroy(); glfwDestroyWindow(m_window); glfwTerminate(); } void Context::initWindow() { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); m_window = glfwCreateWindow(m_width, m_height, "Vulkan", nullptr, nullptr); glfwSetWindowUserPointer(m_window, this); glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback); } void Context::framebufferResizeCallback(GLFWwindow* window, int width, int height) { auto context = reinterpret_cast<Context*>(glfwGetWindowUserPointer(window)); context->m_frameBufferResized = true; } void Context::initVulkan() { createInstance(); setupDebugCallback(); createSurface(); pickPhysicalDevice(); createLogicalDevice(); createAllocator(); createSwapChain(); createImageViews(); } void Context::createAllocator() { VmaAllocatorCreateInfo createInfo = {}; createInfo.device = m_device; createInfo.physicalDevice = m_phsyicalDevice; //createInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; auto result = vmaCreateAllocator(&createInfo, &m_allocator); if (result != VK_SUCCESS) throw std::runtime_error("Failed to create Allocator"); } void Context::createInstance() { if (g_enableValidationLayers && !checkValidationLayerSupport()) { throw std::runtime_error("Validation layers requested, but not available!"); } vk::ApplicationInfo appInfo("Vulkan Test New", 1, "No Engine", 1, VK_API_VERSION_1_1); // glfw + (cond.) debug layer auto requiredExtensions = getRequiredExtensions(); std::vector<const char*> layerNames; if constexpr (g_enableValidationLayers) layerNames = g_validationLayers; vk::InstanceCreateInfo createInfo({}, &appInfo, static_cast<uint32_t>(layerNames.size()), layerNames.data(), static_cast<uint32_t>(requiredExtensions.size()), requiredExtensions.data()); if (vk::createInstance(&createInfo, nullptr, &m_instance) != vk::Result::eSuccess) throw std::runtime_error("Instance could not be created"); // print instance extensions // getAllSupportedExtensions(true); } std::vector<const char*> Context::getRequiredExtensions() { uint32_t glfwExtensionCount = 0; const auto exts = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(exts, exts + glfwExtensionCount); if constexpr (g_enableValidationLayers) extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); return extensions; } std::vector<vk::ExtensionProperties> Context::getAllSupportedExtensions() { return vk::enumerateInstanceExtensionProperties(); } bool Context::checkValidationLayerSupport() const { auto availableLayers = vk::enumerateInstanceLayerProperties(); for (const char* layerName : g_validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } VKAPI_ATTR VkBool32 VKAPI_CALL Context::debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { auto logger = spdlog::get("standard"); // todo log this properly depending on severity & type switch (messageSeverity) { case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: logger->warn("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: logger->critical("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT: break; default: break ; } return VK_FALSE; } void Context::setupDebugCallback() { if constexpr (!g_enableValidationLayers) return; using sevFlags = vk::DebugUtilsMessageSeverityFlagBitsEXT; using typeFlags = vk::DebugUtilsMessageTypeFlagBitsEXT; vk::DebugUtilsMessengerCreateInfoEXT createInfo( {}, sevFlags::eError | sevFlags::eWarning | sevFlags::eVerbose,// | sevFlags::eInfo, typeFlags::eGeneral | typeFlags::ePerformance | typeFlags::eValidation, reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(debugCallback) ); if (help::CreateDebugUtilsMessengerEXT(m_instance, reinterpret_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&createInfo), nullptr, reinterpret_cast<VkDebugUtilsMessengerEXT *>(&m_callback)) != VK_SUCCESS) { throw std::runtime_error("failed to set up debug callback!"); } } void Context::pickPhysicalDevice() { // TODO scoring system preferring discrete GPUs auto physDevices = m_instance.enumeratePhysicalDevices(); if (physDevices.empty()) throw std::runtime_error("No physical devices found"); for (const auto& device : physDevices) { if (isDeviceSuitable(device)) { m_phsyicalDevice = device; break; } } if (!m_phsyicalDevice) throw std::runtime_error("No suitable physical device found"); } bool Context::isDeviceSuitable(vk::PhysicalDevice physDevice) { // TODO use actual stuff here auto properties = physDevice.getProperties(); auto features = physDevice.getFeatures(); vk::PhysicalDeviceSubgroupProperties subProps; vk::PhysicalDeviceProperties2 props; props.pNext = &subProps; if(std::find_if(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end(), [](const char* input){ return (strcmp(input, "VK_NV_ray_tracing") == 0); }) != m_requiredDeviceExtensions.end()) { m_raytracingProperties.emplace(); props.pNext = &m_raytracingProperties.value(); m_raytracingProperties.value().pNext = &subProps; } physDevice.getProperties2(&props); //NVIDIA only? const bool testSubgroups = static_cast<uint32_t>(subProps.supportedStages) & static_cast<uint32_t>(vk::ShaderStageFlagBits::eRaygenNV); // look for a GPU with geometry shader const bool suitable = (properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu || properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) && features.geometryShader; // look for a graphics queue QueueFamilyIndices indices = findQueueFamilies(physDevice); // look if the wanted extensions are supported const bool extensionSupport = checkDeviceExtensionSupport(physDevice); // look for swapchain support bool swapChainAdequate = false; if (extensionSupport) { SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physDevice); swapChainAdequate = !swapChainSupport.m_formats.empty() && !swapChainSupport.m_presentModes.empty(); } return suitable && indices.isComplete() && extensionSupport && swapChainAdequate && features.samplerAnisotropy; } bool Context::checkDeviceExtensionSupport(vk::PhysicalDevice physDevice) { auto availableExtensions = physDevice.enumerateDeviceExtensionProperties(); std::set<std::string> requiredExtensions(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end()); for (const auto& extension : availableExtensions) requiredExtensions.erase(extension.extensionName); return requiredExtensions.empty(); } QueueFamilyIndices Context::findQueueFamilies(vk::PhysicalDevice physDevice) const { QueueFamilyIndices indices; auto qfprops = physDevice.getQueueFamilyProperties(); uint32_t i = 0; for (const auto& queueFamily : qfprops) { if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) indices.graphicsFamily = i; bool presentSupport = physDevice.getSurfaceSupportKHR(i, m_surface); if (queueFamily.queueCount > 0 && presentSupport && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) indices.presentFamily = i; if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eTransfer && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)) indices.transferFamily = i; if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eCompute && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)) indices.computeFamily = i; if (indices.isComplete()) break; i++; } //indices.computeFamily = 0; return indices; } void Context::createLogicalDevice() { QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice); std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value(), indices.transferFamily.value(), indices.computeFamily.value() }; const float queuePriority = 1.0f; for (uint32_t queueFamily : uniqueQueueFamilies) { vk::DeviceQueueCreateInfo queueCreateInfo({}, queueFamily, 1, &queuePriority); queueCreateInfos.push_back(queueCreateInfo); } vk::PhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = VK_TRUE; deviceFeatures.vertexPipelineStoresAndAtomics = VK_TRUE; deviceFeatures.fragmentStoresAndAtomics = VK_TRUE; deviceFeatures.multiDrawIndirect = VK_TRUE; deviceFeatures.shaderStorageImageExtendedFormats = VK_TRUE; vk::DeviceCreateInfo createInfo({}, static_cast<uint32_t>(queueCreateInfos.size()), queueCreateInfos.data(), 0, nullptr, static_cast<uint32_t>(m_requiredDeviceExtensions.size()), m_requiredDeviceExtensions.data(), &deviceFeatures); if constexpr (g_enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size()); createInfo.ppEnabledLayerNames = g_validationLayers.data(); } m_device = m_phsyicalDevice.createDevice(createInfo); // get all the queues! m_presentQueue = m_device.getQueue(indices.presentFamily.value(), 0); m_graphicsQueue = m_device.getQueue(indices.graphicsFamily.value(), 0); m_transferQueue = m_device.getQueue(indices.transferFamily.value(), 0); m_computeQueue = m_device.getQueue(indices.computeFamily.value(), 0); } void Context::createSurface() { if (glfwCreateWindowSurface(m_instance, m_window, nullptr, reinterpret_cast<VkSurfaceKHR*>(&m_surface)) != VK_SUCCESS) throw std::runtime_error("Surface creation failed"); } SwapChainSupportDetails Context::querySwapChainSupport(vk::PhysicalDevice physDevice) const { SwapChainSupportDetails details; details.m_capabilities = physDevice.getSurfaceCapabilitiesKHR(m_surface); details.m_formats = physDevice.getSurfaceFormatsKHR(m_surface); details.m_presentModes = physDevice.getSurfacePresentModesKHR(m_surface); return details; } vk::SurfaceFormatKHR Context::chooseSwapChainSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats) { if (availableFormats.size() == 1 && availableFormats.at(0).format == vk::Format::eUndefined) return { vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear }; for (const auto& availableFormat : availableFormats) { if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) return availableFormat; } return availableFormats.at(0); } vk::PresentModeKHR Context::chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes) { auto bestMode = vk::PresentModeKHR::eFifo; for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == vk::PresentModeKHR::eMailbox) return availablePresentMode; if (availablePresentMode == vk::PresentModeKHR::eImmediate) bestMode = availablePresentMode; } return bestMode; } vk::Extent2D Context::chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities) { if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) { return capabilities.currentExtent; } else { glfwGetFramebufferSize(m_window, &m_width, &m_height); VkExtent2D actualExtent = { static_cast<uint32_t>(m_width), static_cast<uint32_t>(m_height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } void Context::createSwapChain() { auto swapChainSupport = querySwapChainSupport(m_phsyicalDevice); auto surfaceFormat = chooseSwapChainSurfaceFormat(swapChainSupport.m_formats); auto presentMode = chooseSwapPresentMode(swapChainSupport.m_presentModes); auto extent = chooseSwapExtent(swapChainSupport.m_capabilities); // determine the number of images in the swapchain (queue length) uint32_t imageCount = swapChainSupport.m_capabilities.minImageCount + 1; if (swapChainSupport.m_capabilities.maxImageCount > 0 && imageCount > swapChainSupport.m_capabilities.maxImageCount) imageCount = swapChainSupport.m_capabilities.maxImageCount; vk::SwapchainCreateInfoKHR createInfo({}, m_surface, imageCount, surfaceFormat.format, surfaceFormat.colorSpace, extent, 1, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eStorage); QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = vk::SharingMode::eConcurrent; // exclusive is standard value createInfo.queueFamilyIndexCount = 2; // 0 is standard value } else { createInfo.imageSharingMode = vk::SharingMode::eExclusive; createInfo.queueFamilyIndexCount = 1; } createInfo.pQueueFamilyIndices = queueFamilyIndices; createInfo.preTransform = swapChainSupport.m_capabilities.currentTransform; createInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque; createInfo.presentMode = presentMode; createInfo.clipped = true; createInfo.oldSwapchain = nullptr; m_swapchain = m_device.createSwapchainKHR(createInfo); m_swapChainImages = m_device.getSwapchainImagesKHR(m_swapchain); m_swapChainImageFormat = surfaceFormat.format; m_swapChainExtent = extent; } void Context::createImageViews() { m_swapChainImageViews.resize(m_swapChainImages.size()); for (size_t i = 0; i < m_swapChainImages.size(); i++) { vk::ImageViewCreateInfo createInfo({}, m_swapChainImages.at(i), vk::ImageViewType::e2D, m_swapChainImageFormat, {}, { vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 }); m_swapChainImageViews.at(i) = m_device.createImageView(createInfo); } } vk::ShaderModule Context::createShaderModule(const std::vector<char>& code) const { vk::ShaderModuleCreateInfo createInfo({}, code.size(), reinterpret_cast<const uint32_t*>(code.data())); return m_device.createShaderModule(createInfo); } void Context::initImgui() { ImGui::CreateContext(); ImGui_ImplGlfw_InitForVulkan(m_window, true); // create imgui descriptor pool vk::DescriptorPoolSize poolSizeCombinedImageSampler(vk::DescriptorType::eCombinedImageSampler, 1); std::array<vk::DescriptorPoolSize, 1> poolSizes = { poolSizeCombinedImageSampler }; vk::DescriptorPoolCreateInfo poolInfo({}, 1, static_cast<uint32_t>(poolSizes.size()), poolSizes.data()); m_imguiDescriptorPool = m_device.createDescriptorPool(poolInfo); // create imgui renderpass vk::AttachmentDescription colorAttachment({}, m_swapChainImageFormat, vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eStore, // load store op vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, // stencil op vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR ); vk::AttachmentReference colorAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentDescription depthAttachment({}, vk::Format::eD32SfloatS8Uint, vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eDontCare, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageLayout::eDepthStencilAttachmentOptimal ); vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDependency dependency(VK_SUBPASS_EXTERNAL, 0, vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput, {}, vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite, vk::DependencyFlagBits::eByRegion); vk::SubpassDescription subpass({}, vk::PipelineBindPoint::eGraphics, 0, nullptr, // input attachments (standard values) 1, &colorAttachmentRef, // color attachments: layout (location = 0) out -> colorAttachmentRef is at index 0 nullptr, // no resolve attachment &depthAttachmentRef); // depth stencil attachment // other attachment at standard values: Preserved std::array<vk::AttachmentDescription, 2> attachments = { colorAttachment, depthAttachment }; vk::RenderPassCreateInfo renderpassInfo({}, static_cast<uint32_t>(attachments.size()), attachments.data(), 1, &subpass, 1, &dependency); m_imguiRenderpass = m_device.createRenderPass(renderpassInfo); // init imgui ImGui_ImplVulkan_InitInfo initInfo = {}; initInfo.Instance = static_cast<VkInstance>(m_instance); initInfo.PhysicalDevice = static_cast<VkPhysicalDevice>(m_phsyicalDevice); initInfo.Device = static_cast<VkDevice>(m_device); initInfo.QueueFamily = findQueueFamilies(m_phsyicalDevice).graphicsFamily.value(); initInfo.Queue = m_graphicsQueue; initInfo.PipelineCache = nullptr; initInfo.DescriptorPool = m_imguiDescriptorPool; ImGui_ImplVulkan_Init(&initInfo, static_cast<VkRenderPass>(m_imguiRenderpass)); } void Context::cleanupImgui() { ImGui_ImplVulkan_InvalidateFontUploadObjects(); ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); m_device.destroyDescriptorPool(m_imguiDescriptorPool); m_device.destroyRenderPass(m_imguiRenderpass); } }
41.55259
231
0.689297
dd1068e1623204396bc4ae2d3b64b14cb7c2f6e8
1,381
cpp
C++
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
#include "main.hpp" #include <iostream> #include <stack> using namespace std; ListNode* Solution::reverseKGroup(ListNode* head, int k){ stack<ListNode*> storage; ListNode* curPtr = head; if (k == 1){ return head; } for (int i = 0; i < k; i++){ if (curPtr == nullptr){ return head; } storage.push(curPtr); curPtr = curPtr->next; } ListNode* reverseHead = storage.top(); ListNode* nextRec = reverseHead->next; storage.pop(); reverseHead->next = storage.top(); for (int i = 0; i < k - 1; i++){ ListNode* reverseCur = storage.top(); storage.pop(); if (storage.empty()){ reverseCur->next = reverseKGroup(nextRec, k); } else{ reverseCur->next = storage.top(); } } return reverseHead; } int main(int argc, char* argv[]){ ListNode *empty = new ListNode(); ListNode *a1 = new ListNode(1); ListNode *a2 = new ListNode(2); ListNode *a3 = new ListNode(3); ListNode *a4 = new ListNode(4); ListNode *a5 = new ListNode(5); a1->next = a2; a2->next = a3; a3->next = a4; a4->next = a5; Solution sol; auto result = sol.reverseKGroup(a1, 1); while (result){ cout << result->val << " "; result = result->next; } cout << endl; return 0; }
23.40678
57
0.539464
dd113b5535d1ff6a1a61ff598beeb5c329880ad4
871
cpp
C++
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
null
null
null
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
7
2021-12-25T11:54:10.000Z
2021-12-27T17:24:30.000Z
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
null
null
null
#include "leddriver/ledimage.hpp" namespace LEDDriver { LEDImage::LEDImage() : red(std::make_unique<Channel>()), green(std::make_unique<Channel>()), blue(std::make_unique<Channel>()) { this->Clear(); } void LEDImage::Clear() { this->red->fill(0); this->green->fill(0); this->blue->fill(0); } void LEDImage::SetPixel(const unsigned int ix, const unsigned int iy, const uint8_t r, const uint8_t g, const uint8_t b) { const size_t idx = ix + (LEDArray::nCols * iy); this->red->at(idx) = r; this->green->at(idx) = g; this->blue->at(idx) = b; } void LEDImage::SendToLEDArray(LEDArray &target) const { target.UpdateBuffer(*(this->red), *(this->green), *(this->blue)); } }
27.21875
78
0.523536
dd13f8ef1f5dc809a9358cb3a5be8178d5e380e8
726
cpp
C++
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
4
2019-12-12T19:59:50.000Z
2020-01-20T15:44:44.000Z
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
// Question Link ---> https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ class Solution { public: static bool cmp(vector<int> &a, vector<int> &b) { if (a[1] == b[1]) { return a[0] < b[0]; } return a[1] < b[1]; } int maxEvents(vector<vector<int>>& events) { unordered_set<int> attended; sort(events.begin(), events.end(), cmp); for (auto event : events) { for (int i = event[0]; i <= event[1]; i++) { if (!attended.count(i)) { attended.insert(i); break; } } } return attended.size(); } };
30.25
100
0.453168
dd166f8404be9351b29d0b3ec652e9c95cd2dce7
6,584
cpp
C++
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
1
2021-02-23T20:47:29.000Z
2021-02-23T20:47:29.000Z
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
null
null
null
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
2
2020-01-03T17:14:39.000Z
2020-03-04T14:21:27.000Z
/* This file is part of PEST++. PEST++ is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PEST++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PEST++. If not, see<http://www.gnu.org/licenses/>. */ #include "TerminationController.h" #include <vector> #include <algorithm> #include "utilities.h" #include "ObjectiveFunc.h" using namespace pest_utils; using namespace std; TerminationController::TerminationController(int _noptmax, double _phiredstp, int _nphistp, int _nphinored, double _relparstp, int _nrelpar, bool _use_dynaimc_regul, double _phim_accept) : phiredstp(_phiredstp), relparstp(_relparstp), phim_accept(_phim_accept), current_phi(99e99), nphistp(_nphistp), noptmax(_noptmax), nphinored(_nphinored), nopt_count(0), nphinored_count(0), nrelpar(_nrelpar), nrelpar_count(0), terminate_code(false), use_dynaimc_regul(_use_dynaimc_regul), phi_accept_achieved(false) { termimate_reason = "unknown"; } void TerminationController::reset() { nopt_count = 0; nphinored_count = 0; lowest_phi.clear(); terminate_code = false; } bool TerminationController::process_iteration(const PhiComponets &phi_comp, double relpar) { ++nopt_count; double phi_m = phi_comp.meas; double phi_r = phi_comp.regul; double phi = 9e99; bool regul_reject = false; if (use_dynaimc_regul == false) { phi = phi_m + phi_r; } else if (!phi_accept_achieved && phi_m > phim_accept) { phi = phi_m; regul_reject = false; } else if (use_dynaimc_regul && !phi_accept_achieved && phi_m <= phim_accept) { lowest_phi.clear(); phi_accept_achieved = true; phi = phi_r; regul_reject = false; } else if (use_dynaimc_regul && phi_m < phim_accept) { phi = phi_r; regul_reject = false; } else { regul_reject = true; } current_phi = phi; if (!regul_reject) { // keep track of number of iterations since lowest phi if (lowest_phi.size() == 0 || phi <= lowest_phi.front()) { nphinored_count = 0; } else { ++nphinored_count; } // keep track of NPHISTP lowest phi's if (lowest_phi.size() < nphistp) { lowest_phi.push_back(phi); } else if (phi < lowest_phi.back()) { lowest_phi.back() = phi; } sort(lowest_phi.begin(), lowest_phi.end()); } // Check maximum relative parameter change if (abs(relpar) < relparstp) { ++nrelpar_count; } else { nrelpar_count = 0; } return check_last_iteration(); } bool TerminationController::check_last_iteration() { if (nopt_count >= noptmax) { terminate_code = true; termimate_reason = "NOPTMAX criterion met"; return terminate_code; } double min_phi_diff = lowest_phi.back() - lowest_phi.front(); if (current_phi <= std::numeric_limits<double>::denorm_min()) { terminate_code = true; termimate_reason = "PHI is zero"; } // Impose Termination Criteria else if (nphinored_count > nphinored) { terminate_code = true; termimate_reason = "NPHINORED criterion met"; } else if (lowest_phi.size() >= nphistp && min_phi_diff <= phiredstp*current_phi) { terminate_code = true; termimate_reason = "PHIREDSTP / NPHISTP criterion met"; } else if (nrelpar_count > nrelpar) { terminate_code = true; termimate_reason = "RELPARSTP / NRELPAR criterion met"; } else { terminate_code = false; termimate_reason = "Unexpected Termination"; } return terminate_code; } void TerminationController::termination_summary(std::ostream &fout) { fout << "-----------------------------------------" << endl; fout << " --- OPTIMIZATION COMPLETE --- " << endl; fout << " Reason for terminating PEST++ simulation: " << termimate_reason << endl; fout << " Summary of termination criteria:" << endl; fout << " NOPTMAX = " << noptmax << " ; NOPT at termination = " << nopt_count << endl; fout << " NPHINORED = " << nphinored << " ; NPHINORED at termination = " << nphinored_count << endl; fout << " NRELPAR = " << nrelpar << "; RELPARSTP = " << relparstp << " ; NRELPAR at termination = " << nrelpar_count << endl; fout << " PHIREDSTP = " << phiredstp << "; NPHISTP = " << nphistp << endl; if (!use_dynaimc_regul || !phi_accept_achieved) { fout << " NPHISTP lowest PHI's:" << endl; } else { fout << " NPHISTP lowest regularization PHI componets:" << endl; } for (const auto &it : lowest_phi) { fout << " " << it << endl; } } const TerminationController& TerminationController::operator=(const TerminationController &rhs) { noptmax = rhs.noptmax; nphinored = rhs.nphinored; nphinored_count = rhs.nphinored_count; nrelpar = rhs.nrelpar; nrelpar_count = rhs.nrelpar_count; nphistp = rhs.nphistp; phiredstp = rhs.phiredstp; relparstp = rhs.relparstp; lowest_phi = rhs.lowest_phi; return *this; } void TerminationController::save_state(std::ostream &fout) { fout << "termination_info_1 " << noptmax << " " << nopt_count << " " << nphinored << " " << nphinored_count << " " << nrelpar << endl; fout << "termination_info_2 " << nrelpar_count << " " << nphistp << " " << phiredstp << " " << relparstp << endl; fout << "termination_info_3 "; for (double &a : lowest_phi) { fout << " " << a; } fout << endl; } void TerminationController::read_state(const std::string &line) { vector<string> tokens; tokenize(line, tokens); try { string line_type = upper_cp(tokens[0]); if (line_type == "TERMINATION_INFO_1") { convert_ip(tokens[1], noptmax); convert_ip(tokens[2], nopt_count); convert_ip(tokens[3], nphinored); convert_ip(tokens[4], nphinored_count); convert_ip(tokens[5], nrelpar); } else if (line_type == "TERMINATION_INFO_2") { convert_ip(tokens[1], nrelpar_count); convert_ip(tokens[2],nphistp); convert_ip(tokens[3],phiredstp); convert_ip(tokens[4],relparstp ); } else if (line_type == "TERMINATION_INFO_3") { lowest_phi.clear(); for (int i=1; i<tokens.size(); ++i) { double val = convert_cp<double>(tokens[1]); lowest_phi.push_back(val); } } } catch(std::runtime_error &e) { cerr << "Error processing restart file on line:" << endl; cerr << line << endl << endl; cerr << e.what() << endl << endl; throw(e); } } TerminationController::~TerminationController(void) { }
25.71875
128
0.68226
dd1d6b6636cd1bd56bda65e303c3c37afcb999cc
9,568
cpp
C++
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
// SysMonDlg.cpp : implementation file // #include "stdafx.h" #include "SysMon.h" #include "SysMonDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define VK_ESCAPE 0x1B ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange *pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSysMonDlg dialog CSysMonDlg::CSysMonDlg(CWnd *pParent /*=NULL*/) : CDialog(CSysMonDlg::IDD, pParent) { //{{AFX_DATA_INIT(CSysMonDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CSysMonDlg::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSysMonDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSysMonDlg, CDialog) //{{AFX_MSG_MAP(CSysMonDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_COMMAND(IDR_SYS_ABOUT, OnSysAbout) ON_COMMAND(IDM_SYS_HELP, OnSysHelp) ON_COMMAND(IDM_PROC_REFRESH, OnProcRefresh) ON_COMMAND(IDM_PROC_TERMINATE, OnProcTerminate) ON_COMMAND(IDM_PROC_SENDMSG, OnProcSendmsg) ON_WM_CHAR() ON_COMMAND(IDM_SYS_EXIT, OnSysExit) ON_WM_CLOSE() ON_WM_SIZE() ON_COMMAND(IDM_SHELLICON_SHOWWINDOW, OnShelliconShowwindow) ON_COMMAND(IDM_SHELLICON_EXIT, OnShelliconExit) ON_COMMAND(IDM_SVR_LOAD, OnSvrLoad) ON_COMMAND(IDM_SVR_PAUSE, OnSvrPause) ON_COMMAND(IDM_SVR_REFRESH, OnSvrRefresh) ON_COMMAND(IDM_SVR_RESUME, OnSvrResume) ON_COMMAND(IDM_SVR_STOP, OnSvrStop) ON_UPDATE_COMMAND_UI(IDM_SVR_LOAD, OnUpdateSvrLoad) //}}AFX_MSG_MAP ON_MESSAGE(WM_SYSMONNOTIFY, OnSysMonNotify) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSysMonDlg message handlers BOOL CSysMonDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu *pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here nIsHide = SW_SHOW; // 初始化属性单 m_sheet.AddPage(&m_propSysinfo); m_sheet.AddPage(&m_propProcess); m_sheet.AddPage(&m_propService); m_sheet.AddPage(&m_propRule); m_sheet.AddPage(&m_propTask); m_sheet.AddPage(&m_propSetting); m_sheet.Create(this, WS_CHILD | WS_VISIBLE, 0); m_sheet.ModifyStyleEx(0, WS_EX_CONTROLPARENT); m_sheet.ModifyStyle(0, WS_TABSTOP); return TRUE; // return TRUE unless you set the focus to a control } void CSysMonDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CSysMonDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM)dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CSysMonDlg::OnQueryDragIcon() { return (HCURSOR)m_hIcon; } void CSysMonDlg::OnSysAbout() { // TODO: Add your command handler code here CAboutDlg dlgAbout; dlgAbout.DoModal(); } void CSysMonDlg::OnSysHelp() { // TODO: Add your command handler code here AfxMessageBox("Sorry, Help is not available for now!"); } void CSysMonDlg::OnProcRefresh() { // TODO: Add your command handler code here m_propProcess.OnProcRefresh(); } void CSysMonDlg::OnProcTerminate() { // TODO: Add your command handler code here m_propProcess.OnProcTerminate(); } void CSysMonDlg::OnProcSendmsg() { // TODO: Add your command handler code here m_propProcess.OnProcSendmsg(); } void CSysMonDlg::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default AfxMessageBox(nChar); // 添加任务栏图标 if (nChar == VK_ESCAPE) { NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.uCallbackMessage = WM_SYSMONNOTIFY; nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); strcpy(nid.szTip, _T("系统监控器")); Shell_NotifyIcon(NIM_ADD, &nid); } // 隐藏窗体 ShowWindow(SW_HIDE); CDialog::OnChar(nChar, nRepCnt, nFlags); } void CSysMonDlg::OnSysMonNotify(WPARAM wParam, LPARAM lParam) { UINT uID; //发出该消息的图标的ID UINT uMouseMsg; //鼠标动作 POINT point; uID = (UINT)wParam; uMouseMsg = (UINT)lParam; if (uMouseMsg == WM_RBUTTONUP) // 如果是双击左键 { if (uID == IDR_MAINFRAME) // 如果是我们的图标 { GetCursorPos(&point); //取得鼠标位置 // 取菜单资源 CMenu mnuTop; mnuTop.LoadMenu(IDR_MENU_SHELLICON); // 取子菜单 CMenu *pPopup = mnuTop.GetSubMenu(0); ASSERT_VALID(pPopup); // 设置默认菜单 SetMenuDefaultItem(pPopup->m_hMenu, 0, TRUE); // 显示菜单 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON, point.x, point.y, AfxGetMainWnd(), NULL); // 弹出式菜单的命令会被 MFC 的消息路由机制自动处理 } } if (uMouseMsg == WM_LBUTTONDBLCLK) //如果是双击左键 { if (uID == IDR_MAINFRAME) //如果是我们的图标 OnShelliconShowwindow(); // 显示窗体 } return; } void CSysMonDlg::OnSysExit() { // TODO: Add your command handler code here // 退出程序 SendMessage(WM_CLOSE); } void CSysMonDlg::OnClose() { // TODO: Add your message handler code here and/or call default if (IDOK == AfxMessageBox(_T("确定要退出系统监控程序吗?"), MB_OKCANCEL)) { CDialog::OnClose(); // CDialog::OnOK(); } } void CSysMonDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here // 添加任务栏图标 if (nType == SIZE_MINIMIZED) { NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.uCallbackMessage = WM_SYSMONNOTIFY; nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); strcpy(nid.szTip, _T("系统监控器")); Shell_NotifyIcon(NIM_ADD, &nid); } // 隐藏窗体 if (nIsHide == SW_SHOW) { ShowWindow(SW_SHOWMINIMIZED); ShowWindow(SW_HIDE); UpdateWindow(); nIsHide = SW_HIDE; } } void CSysMonDlg::OnShelliconShowwindow() { // TODO: Add your command handler code here // 显示窗体 if (nIsHide == SW_HIDE) { ShowWindow(SW_RESTORE); SetForegroundWindow(); nIsHide = SW_SHOW; } // 删除任务栏图标 NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; // 保证删除的是我们的图标 Shell_NotifyIcon(NIM_DELETE, &nid); } void CSysMonDlg::OnShelliconExit() { // TODO: Add your command handler code here OnShelliconShowwindow(); SendMessage(WM_CLOSE); } void CSysMonDlg::OnSvrLoad() { // TODO: Add your command handler code here m_propService.OnSvrLoad(); } void CSysMonDlg::OnSvrPause() { // TODO: Add your command handler code here m_propService.OnSvrPause(); } void CSysMonDlg::OnSvrResume() { // TODO: Add your command handler code here m_propService.OnSvrResume(); } void CSysMonDlg::OnSvrStop() { // TODO: Add your command handler code here m_propService.OnSvrStop(); } void CSysMonDlg::OnSvrRefresh() { // TODO: Add your command handler code here m_propService.OnSvrRefresh(); } void CSysMonDlg::OnUpdateSvrLoad(CCmdUI *pCmdUI) { // TODO: Add your command update UI handler code here AfxMessageBox("!"); }
23.055422
80
0.676526
dd1d9c969864541580624569ad00c7b04983d2c8
2,471
cpp
C++
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
#include <iostream> #include <tachyon/component.hpp> #include <itestcontract.hpp> using namespace tachyon; int main() { MasterFactory &mf = MasterFactory::Instance(); mf.Manage("component1"); mf.Manage("component2"); // test 1 is implemented in a shared dll sp<ITestContract> sp1 = mf.Create<ITestContract>("ITestContract.TestComponent1"); // test 2 is implemented in a shared dll sp<ITestContract> sp2 = mf.Create<ITestContract>("ITestContract.TestComponent2"); sp<ITestContract> sp3 = sp1; sp<ITestContract> sp4 = sp2; sp<ITestContract> sp5 = mf.Create<ITestContract>("ITestContract.TestComponent1"); if (!sp1.isValid() || !sp3.isValid() || !sp5.isValid()) { std::cerr << "Invalid TestComponent1, program abort" << std::endl; exit(0); } if (!sp2.isValid() || !sp4.isValid()) { std::cerr << "Invalid TestComponent2, program abort" << std::endl; exit(0); } if (!sp1->PostInit() || !sp3->PostInit() || !sp5->PostInit()) { std::cerr << "TestComponent1, PostInit failure, program abort" << std::endl; exit(0); } if (!sp2->PostInit() || !sp4->PostInit()) { std::cerr << "TestComponent2, PostInit failure, program abort" << std::endl; exit(0); } std::cout << std::endl; std::cout << "BEGIN TESTS" << std::endl; std::cout << std::endl; std::cout << "TEST sp1->TestMethod() shows Implementation TestComponent1" << std::endl; sp1->TestMethod(); std::cout << std::endl; std::cout << "TEST sp2->TestMethod() shows Implementation TestComponent2" << std::endl; sp2->TestMethod(); std::cout << std::endl; std::cout << "TEST sp1 and sp3 have same name" << std::endl; std::cout << "sp1 name :" << sp1->GetName() << std::endl; std::cout << "sp3 name :" << sp3->GetName() << std::endl; std::cout << std::endl; std::cout << "TEST sp5 has unique name" << std::endl; std::cout << "sp5 name :" << sp5->GetName() << std::endl; std::cout << std::endl; std::cout << "TEST sp2 and sp4 have same name" << std::endl; std::cout << "sp2 name :" << sp2->GetName() << std::endl; std::cout << "sp4 name :" << sp4->GetName() << std::endl; std::cout << std::endl; std::string pattern = "ITestContract\\.(.*)"; std::cout << "TEST find contracts using Regex pattern: " << pattern << std::endl; auto spList = mf.CreateAll<ITestContract>(pattern); for (auto itr = spList.begin(); itr != spList.end(); itr++) { if (itr->isValid()) { std::cout << "PATTERN TEST FOUND : " << (*itr)->GetName() << std::endl; } } }
27.455556
88
0.630109
dd1dfe71d762e7da81b590cad1e11600554650b8
8,063
cpp
C++
WallpapersFrame.cpp
YoshiLeLama/wp_manager
90a49621c698b3dd3097dce306c276f96e0af639
[ "MIT" ]
null
null
null
WallpapersFrame.cpp
YoshiLeLama/wp_manager
90a49621c698b3dd3097dce306c276f96e0af639
[ "MIT" ]
null
null
null
WallpapersFrame.cpp
YoshiLeLama/wp_manager
90a49621c698b3dd3097dce306c276f96e0af639
[ "MIT" ]
null
null
null
// // Created by Antoine Roumilhac on 24/12/2021. // #include "WallpapersFrame.h" BEGIN_EVENT_TABLE(WallpapersFrame, wxFrame) EVT_MENU(ADD_FILES, WallpapersFrame::OnAddFiles) EVT_MENU(DELETE_SELECTED, WallpapersFrame::DeleteSelectedFiles) EVT_MENU(wxID_EXIT, WallpapersFrame::OnExit) EVT_MENU(wxID_ABOUT, WallpapersFrame::OnAbout) END_EVENT_TABLE() wxIcon GetAppIcon() { wxIcon iconImg("MAIN_ICON"); if (!iconImg.IsOk()) return nullptr; return iconImg; } inline std::string WallpapersFrame::GetCategoryChoiceLabel(const std::string &cat_name, int count) { return (cat_name.empty() ? "Not categorized" : cat_name) + " (" + std::to_string(count) + " elements)"; } void WallpapersFrame::OnAddFiles(wxCommandEvent &event) { //auto files(GetFilePaths()); wxFileDialog openFileDialog(this, "Open wallpapers images...", "", "", "Images (*.png,*.jpg,*.jpeg)|*.png;*.jpg;*.jpeg", wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE); if (openFileDialog.ShowModal() == wxID_CANCEL) return; wxArrayString files; openFileDialog.GetPaths(files); auto newFiles = MoveFiles(files, imagesList->GetCategoryName(categoryChoice->GetSelection()), imagesList->GetDataDir()); int count = imagesList->AddImages(newFiles); SetStatusText("Added " + std::to_string(count) + (count > 1 ? " files." : " file.")); categoryChoice->SetString(categoryChoice->GetSelection(), GetCategoryChoiceLabel( imagesList->GetCurrentCategoryName(), imagesList->GetCurrentCategoryCount())); } void WallpapersFrame::OnExit(wxCommandEvent &event) { if (wxMessageBox("Do you want to exit the app ?", "Exit confirmation", wxYES | wxYES_DEFAULT | wxNO | wxICON_WARNING) == wxYES) Close(true); } void WallpapersFrame::OnAbout(wxCommandEvent &event) { wxMessageBox("Little app to manage wallpapers", "About", wxOK | wxICON_INFORMATION); } WallpapersFrame::WallpapersFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame(parent, id, title, pos, size), imagesList(new ImagesList(this)), pMenuBar(new wxMenuBar(3)) { SetIcon(GetAppIcon()); this->SetBackgroundColour(*ColorSettings::Accent2()); auto *sizer = new wxBoxSizer(wxVERTICAL); auto *topBarSizer = new wxBoxSizer(wxHORIZONTAL); WallpapersFrame::SetMinSize(imagesList->GetMinSize()); categoryChoice = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize); categoryChoice->SetBackgroundColour(*ColorSettings::Accent1()); Connect(categoryChoice->GetId(), wxEVT_CHOICE, wxCommandEventHandler(WallpapersFrame::OnChoice)); categoryChoice->Disable(); addCatButton = new wxButton(this, id, "Add category", wxDefaultPosition, wxDefaultSize); addCatButton->Bind(wxEVT_BUTTON, wxCommandEventHandler(WallpapersFrame::OnAddCategory), this); removeCatButton = new wxButton(this, id, "Remove category", wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); removeCatButton->Bind(wxEVT_BUTTON, wxCommandEventHandler(WallpapersFrame::OnRemoveCategory), this); SetupMenuBar(); this->SetMenuBar(pMenuBar); this->CreateStatusBar(); this->GetStatusBar()->SetBackgroundColour(*ColorSettings::Accent0()); this->GetStatusBar()->SetForegroundColour(*wxWHITE); pStatusBarText = new wxStaticText( this->GetStatusBar(), wxID_ANY,wxT("Validation failed"), wxPoint(10, 5), wxDefaultSize, 0 ); topBarSizer->Add(categoryChoice, 2, wxEXPAND, 20); topBarSizer->AddSpacer(10); topBarSizer->Add(addCatButton); topBarSizer->AddSpacer(5); topBarSizer->Add(removeCatButton); sizer->Add(topBarSizer, 0, wxALL, 10); sizer->Add(imagesList, 15, wxEXPAND, 0); SetSizer(sizer); imagesList->SetParentSBText(pStatusBarText); Bind(wxEVT_KEY_DOWN, wxKeyEventHandler(WallpapersFrame::OnKeyDown), this); imagesList->Bind(wxEVT_KEY_DOWN, wxKeyEventHandler(WallpapersFrame::OnKeyDown), this); } void WallpapersFrame::SetupMenuBar() { pFileMenu = new wxMenu(); pFileMenu->Append(ADD_FILES, _T("&Add Files\tCtrl+O")); pFileMenu->AppendSeparator(); pFileMenu->Append(wxID_EXIT, _T("&Quit\tCtrl+Q")); pMenuBar->Insert(0, pFileMenu, "&File"); pSelectionMenu = new wxMenu(); pSelectionMenu->Append(DELETE_SELECTED, _T("&Delete selected files\tDel")); pMenuBar->Insert(1, pSelectionMenu, "&Select"); pHelpMenu = new wxMenu(); pHelpMenu->Append(wxID_ABOUT, _T("&About")); pMenuBar->Insert(2, pHelpMenu, "&Help"); } void WallpapersFrame::LoadWallpapers() { auto oldTitle(wxTopLevelWindowMSW::GetTitle()); SetCursor(*wxHOURGLASS_CURSOR); SetTitle("Loading wallpapers..."); auto countByCat = imagesList->LoadImages(); SetTitle(oldTitle); int sum(0); for (const auto &cnt: imagesList->GetCountByCat()) { categoryChoice->Append(GetCategoryChoiceLabel(imagesList->GetCategoryName(cnt.first), cnt.second)); sum += cnt.second; } categoryChoice->SetSelection(0); categoryChoice->Enable(true); SetCursor(*wxSTANDARD_CURSOR); pStatusBarText->SetLabelText("Loaded " + std::to_string(sum) + (sum > 1 ? " images" : " image.")); } void WallpapersFrame::DeleteSelectedFiles(wxCommandEvent &event) { auto deletedImagesCount(imagesList->DeleteSelectedFiles()); if (deletedImagesCount > 0) { SetStatusText("Deleted " + (deletedImagesCount == 1 ? "1 image." : (std::to_string(deletedImagesCount) + " images."))); } auto choice = categoryChoice->GetSelection(); categoryChoice->SetString(choice, GetCategoryChoiceLabel(imagesList->GetCategoryName(choice), imagesList->GetCurrentCategoryCount())); } void WallpapersFrame::OnChoice(wxCommandEvent &event) { imagesList->SetCurrentCategory(categoryChoice->GetSelection()); imagesList->SetFocus(); } void WallpapersFrame::OnAddCategory(wxCommandEvent &event) { wxTextEntryDialog textEntry(this, "Enter the new category name"); if (textEntry.ShowModal() == wxID_CANCEL) return; auto name = textEntry.GetValue(); if (name.empty()) { wxMessageBox("Category name can't be empty"); } auto nameString = name.ToStdString(); if (imagesList->DoesCategoryExists(nameString)) { wxMessageBox("Category already exists"); return; } imagesList->AddEmptyCategory(nameString); categoryChoice->Append(GetCategoryChoiceLabel(nameString, 0)); categoryChoice->SetSelection(imagesList->GetCurrentCategoryIndex()); } void WallpapersFrame::OnRemoveCategory(wxCommandEvent &event) { int res = wxMessageBox("Are you sure you want to delete this category ?", "Deletion confirmation", wxYES | wxNO | wxNO_DEFAULT); if (res == wxNO) return; imagesList->DeleteCategory(categoryChoice->GetSelection()); RefreshCategoryChoice(); } void WallpapersFrame::OnKeyDown(wxKeyEvent &event) { if (wxGetKeyState(WXK_CONTROL)) { if (event.GetUnicodeKey() == L'A') { imagesList->SelectAllCurrent(); } if (event.GetUnicodeKey() == L'D') { imagesList->UnselectAll(); } } event.Skip(); } void WallpapersFrame::RefreshCategoryChoice() { categoryChoice->Clear(); auto countByCat = imagesList->GetCountByCat(); for (const auto& count : countByCat) categoryChoice->Append(GetCategoryChoiceLabel( imagesList->GetCategoryName(count.first), count.second)); categoryChoice->SetSelection(0); }
35.519824
131
0.658812
dd1ebe2c18a8823b5181e05b83c5dbcf972340c5
14,728
cpp
C++
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
7
2016-12-10T15:44:00.000Z
2020-08-27T17:40:11.000Z
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2020-04-14T15:19:53.000Z
2021-01-26T21:26:47.000Z
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2017-01-29T03:01:06.000Z
2021-12-15T14:59:10.000Z
/* * <one line to give the library's name and an idea of what it does.> * Copyright (C) 2015 Guillaume L. <guillaume.lozenguez@mines-douai.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "global.h" #include "moinag.h" #include "tools.h" #include <iostream> #include <array> using namespace :: mia; using namespace :: std; Moinag::Moinag(float eps, float robot_radius, float pcpt_radius):Agent(pcpt_number, act_number), a_stateMachine(this, state_number, &Moinag::stateDefault), a_body( 0.f, 0.f, robot_radius), //Global::config["robot"]["radius"].as<float>() ), a_epsilon( eps ), //Global::config["robot"]["epsilon"].as<float>() ),// 0.06f a_topo(eps, pcpt_radius), a_controlTarget( 100.f, 0.f ), a_traceDistance2( 0.8*0.8 ), a_wait(1), a_waitCount(0), a_perceptionRadius( pcpt_radius ) //Global::config["robot"]["perception"].as<float>() ) { a_stateMachine.setStateProcess( state_wait, &Moinag::stateWait ); a_stateMachine.setStateProcess( state_new_target, &Moinag::stateNewTarget ); a_stateMachine.setState(state_wait); // a_stateMachine.setStateProcess( state_2, &Moinag::state2 ); } Moinag::~Moinag() { } // Static Factory : //------------------ Moinag * Moinag :: factory( int agentType ) { switch( agentType ) { case agent_moinag : return new Moinag( Global::config["robot"]["epsilon"].as<float>(), Global::config["robot"]["radius"].as<float>(), Global::config["robot"]["perception"].as<float>() ); default : return new Moinag( Global::config["robot"]["epsilon"].as<float>(), Global::config["robot"]["radius"].as<float>(), Global::config["robot"]["perception"].as<float>() ); } } // state machine : //------------------ void Moinag :: act( const InteractStr &sensor, InteractStr &actuator ){ for( int iact(0); iact < actuator_size() ; ++iact ) actuator[iact].clear(); cout << "Moinag process...\n"; a_stateMachine.process(sensor, actuator); cout << "\t visibility map with " << a_topo.a_visibility.edge_size() << " edges\n"; cout << "Moinag process end" << endl; } // State Tools : //-------------- int Moinag :: processSensor(const InteractStr& sensor) { list<Particle> obstacle; Particle move; Particle lastBody= a_body; int count(0); // for( list<Data>::const_iterator it= a_sensor[pcpt_communication].begin(); it != a_sensor[pcpt_communication].end(); ++it ) // ; for( list<Data>::const_iterator it= sensor[pcpt_position].begin(); it != sensor[pcpt_position].end(); ++it ) { a_body= Particle(*it); } for( list<Data>::const_iterator it= sensor[pcpt_movement].begin(); it != sensor[pcpt_movement].end(); ++it ) { move= Particle( *it ); a_body.position+= move.position; a_body.theta= reduceRadian( a_body.theta + move.theta); a_body.radius= a_body.radius + move.radius; } for( list<Data>::const_iterator it= sensor[pcpt_map].begin(); it != sensor[pcpt_map].end(); ++it ) { //Get meta-data : int width( it->flag(0) ), height( it->flag(1) ); float resolution( it->value(0) ); cout << "\t" << it->mesage() << " " << width << "x" << height << endl; //Clear map : a_topo.clear(); a_topo.setEpsilon(resolution*0.999f); int ** node = new int*[width]; int obs_dist= 1; //Copy map: for( int i(0); i < width ; ++i ) { node[i]= new int[height]; for( int j(0); j < height ; ++j ) { node[i][j]= it->flag(2+i+j*width); } } //threshold: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { if( node[i][j] > 0 ) node[i][j]= 100; } } //filtering too little free area; for(bool map_ok(false) ; !map_ok ; map_ok= true ) { for( int i(0); i < width ; ++i ) for( int j(0); j < height ; ++j ) { int nbFreeNeiborg(0); int i1(max(0, i-1)), i2(min(i+1, width-1)); int j1(max(0, j-1)), j2(min(j+1, height-1)); nbFreeNeiborg+= ( node[i1][j] == 0 )?1:0; nbFreeNeiborg+= ( node[i2][j] == 0 )?1:0; nbFreeNeiborg+= ( node[i][j1] == 0 )?1:0; nbFreeNeiborg+= ( node[i][j2] == 0 )?1:0; if( node[i][j] == 0 && ( nbFreeNeiborg == 0 || nbFreeNeiborg == 1 && ( node[i1][j] == -1 || node[i2][j] == -1 || node[i][j1] == -1 || node[i][j2] == -1 ) ) ) { node[i][j]= -1; map_ok= false; } } } //filtering thick obstatcle definition: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { int i1(max(0, i-1)), i2(min(i+1, width-1)); int j1(max(0, j-1)), j2(min(j+1, height-1)); if( node[i][j] == 100 && node[i1][j] != 0 && node[i2][j] != 0 && node[i][j1] != 0 && node[i][j2] != 0 ) node[i][j]= -1; } } //From grid to vector: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { if( node[i][j] == 100 ) { Float2 p(i*resolution, j*resolution); node[i][j]= a_topo.add_corner(p); for( int iiend(i), ii= max(0, i-obs_dist); ii < iiend ; ++ii ) for( int jjend( min(height, j+1+obs_dist) ), jj= max(0, j-obs_dist); jj < jjend ; ++jj ) { if( node[ii][jj] != -1 ) { a_topo.add_edge( node[i][j], node[ii][jj], Visibility::edge_obstacle ); } } for( int jjend(j), jj= max(0, j-obs_dist); jj < jjend ; ++jj ) { if( node[i][jj] != -1 ) { a_topo.add_edge( node[i][j], node[i][jj], Visibility::edge_obstacle ); } } } else node[i][j]= -1; } } // topo clean : a_topo.clean(); } for( list<Data>::const_iterator it= sensor[pcpt_wall].begin(); it != sensor[pcpt_wall].end(); ++it ) { obstacle.push_back( Particle( *it ) ); } if( a_trace.empty() || distance2( *(a_trace.rbegin()), a_body.position ) > a_traceDistance2 ) a_trace.push_back( a_body.position ); a_obstacle.resize( obstacle.size() ); std::copy( obstacle.begin(), obstacle.end(), a_obstacle.begin() ); return count; } int Moinag :: processLocal() { //a_obstacle : float epsilon2( a_epsilon*a_epsilon ), doubleEpsilon2(epsilon2*4); float safeDist( ( a_epsilon+a_body.radius*1.1f ) ), _2safeDist2( safeDist*safeDist*4 ); Particle::sortAngle( a_obstacle ); if( a_obstacle.size() > 1 ){ a_filterObs= Particle::polarFiltering( a_obstacle, a_epsilon); vector<Particle> filterOdst( a_filterObs.size() ); int size(0); for( list<Float2>::iterator it= a_filterObs.begin(); it != a_filterObs.end() ; ++it ){ filterOdst[size].position= *it; filterOdst[size].radius= a_epsilon; ++size; } // Initialize local entrance/exit : list< int > section; for(int i= 1; i < filterOdst.size(); ++i){ if( distance2(filterOdst[i].position, filterOdst[i-1].position) > _2safeDist2 ) { section.push_back(i-1); section.push_back(i); } } if( distance2( filterOdst[0].position, filterOdst[size-1].position ) > _2safeDist2 ) { section.push_front(0); section.push_back( filterOdst.size()-1 ); } else{ section.push_back( *section.begin() ); section.pop_front(); } if( section.size() == 0 ){ // The farest obstacle from the agent : int iMax1(0), iMax2(0); float max2= 0.f; for(int i= 1; i < filterOdst.size(); ++i){ float dist2= filterOdst[i].position.length2(); if( dist2 > max2 ) { iMax1= i; max2= dist2; } } max2= 0.f; // The farest obstacle from the first farest obstacle : for(int i= 1; i < filterOdst.size(); ++i){ float dist2= distance2Between( filterOdst[iMax1].position, filterOdst[i].position ); if( dist2 > max2 ) { iMax2= i; max2= dist2; } } section.push_back( iMax1 ); section.push_back( iMax2 ); section.push_back( iMax2 ); section.push_back( iMax1 ); } // Rafine section (target multiple linear regression) : list<int>::iterator it2, it1= section.begin(); while( it1 != section.end() ){ it2= it1; ++it2; int select(-1); float maxDist= 0.0; float angle= ( filterOdst[*it2].position - filterOdst[*it1].position ).angle(); for(int i= *it1 ; i != *it2 ; i= (i+1)%filterOdst.size() ) { Float2 p= filterOdst[i].position.toBasis( angle, filterOdst[*it1].position ); p.y= fabsf( p.y ); if( p.y > maxDist ){ maxDist= p.y; select= i; } } if( maxDist > a_epsilon ){ section.insert( it2, select ); section.insert( it2, select ); } else{ ++it1; ++it1; } } // TODO linear Regression section per section ? : // Build local topology : a_localMap.initialize( a_body, filterOdst, section, a_epsilon, safeDist ); // TODO initializeObstacles with list<Float2> wall, float epsilon, foat safeDistance : using particle fusion. a_localMap.actualize(); } return boost::num_vertices( a_localMap.a_local ); } int Moinag :: processControl(InteractStr& actuator) { float angle( a_controlTarget.angle() ); float dist( a_controlTarget.length() ); float rotation= 1.f; float speed= 2.0f; if( angle < 0.f ){ rotation= -1; angle*= -1.f; } if( angle < 0.01f ) rotation= 0.f; else if( angle < 0.1f ) rotation*= 0.2f; else if( angle < 0.5f ) rotation*= 0.8f; else if( angle < 1.2f ) rotation*= 1.4f; if( dist < a_epsilon ){ speed= 0.f; rotation= 0.f; } else if( dist < a_body.radius ) speed*= 0.4f; Data control( "control", 0, 4 ); control.a_value[0]= speed; // speed; control.a_value[1]= rotation; // rotation; control.a_value[2]= 0.f; // scale; control.a_value[3]= 0.f; // brake; actuator[ act_move ].push_back( control ); return 1; } // State Machine : //---------------- int Moinag :: stateWait(const InteractStr & sensor, InteractStr &actuator){ cout << "\tMoinag State Wait" << "\n"; if( a_waitCount < 0 || a_waitCount > a_wait ) a_waitCount= 0; int nbMsg= processSensor(sensor); processLocal(); ++a_waitCount; if( a_waitCount == a_wait ){ a_waitCount= 0; return state_new_target; } return state_wait; } int Moinag :: stateNewTarget(const InteractStr & sensor, InteractStr &actuator) { cout << "\tMoinag State New Target" << "\n"; stateDefault(sensor, actuator); // a_targetVertex= a_topo.a_visibility.random_vertex_index(); // assert( a_topo.a_visibility.is_vertex_index( a_targetVertex ) ); // cout << "target vertex :" << a_targetVertex << "\n"; return state_default; } int Moinag :: stateDefault(const InteractStr & sensor, InteractStr &actuator) { cout << "\tMoinag State Default" << "\n"; int nbMsg= processSensor(sensor); processLocal(); // cout << ""\n"\t- Position: " << a_body.position << " angle: " << a_body.theta << "\n"; // cout << "\t- Actualize visibility graph:" << "\n"; a_topo.actualize( &a_localMap, a_body.position ); // cout << "\t- " << a_topo.a_visibility.vertex_size() << " vertices and " << a_topo.a_visibility.edge_size() << " edges" << "\n"; // a_topo.print(cout); // cout << "\t- Define control:" << "\n"; a_controlTarget= a_localMap.getDirection( Float2( 100.f, 0.f ), LocalModel::particle_exit ).first.position; processControl(actuator); // a_targetVertex= a_topo.a_visibility.random_vertex_index(); // assert( a_topo.a_visibility.is_vertex_index( a_targetVertex ) ); return state_default; } void Moinag :: log( const InteractStr& sensor, std::ostream & os ) const { /// log perceived data os << sensor.size() << "\n"; for(unsigned int i(0) ; i < sensor.size() ; ++i ) { os << sensor[i].size() << "\n"; for( list<Data>::const_iterator itEnd( sensor[i].end() ), it( sensor[i].begin() ); it != itEnd ; ++it ) { it->log(os); } } }
32.227571
174
0.502444
dd1f67c1ddda587b369e6747e25dc400b32df9f1
2,336
hh
C++
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
71
2018-04-15T13:02:43.000Z
2022-03-26T11:19:18.000Z
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
309
2018-04-15T12:10:59.000Z
2022-01-22T20:13:04.000Z
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
17
2018-04-17T16:09:31.000Z
2022-03-04T08:49:03.000Z
#ifndef RA_UI_WIN32_MULTILINEGRIDBINDING_H #define RA_UI_WIN32_MULTILINEGRIDBINDING_H #pragma once #include "GridBinding.hh" namespace ra { namespace ui { namespace win32 { namespace bindings { class MultiLineGridBinding : public GridBinding { public: explicit MultiLineGridBinding(ViewModelBase& vmViewModel) noexcept : GridBinding(vmViewModel) {} GSL_SUPPRESS_F6 ~MultiLineGridBinding() noexcept = default; MultiLineGridBinding(const MultiLineGridBinding&) noexcept = delete; MultiLineGridBinding& operator=(const MultiLineGridBinding&) noexcept = delete; MultiLineGridBinding(MultiLineGridBinding&&) noexcept = delete; MultiLineGridBinding& operator=(MultiLineGridBinding&&) noexcept = delete; GSL_SUPPRESS_CON3 LRESULT OnLvnItemChanging(const LPNMLISTVIEW pnmListView) override; GSL_SUPPRESS_CON3 void OnLvnItemChanged(const LPNMLISTVIEW pnmListView) override; LRESULT OnCustomDraw(NMLVCUSTOMDRAW* pCustomDraw) override; void OnNmClick(const NMITEMACTIVATE* pnmItemActivate) override; void OnNmDblClick(const NMITEMACTIVATE* pnmItemActivate) override; void EnsureVisible(gsl::index nIndex) override; protected: void UpdateAllItems() override; void UpdateItems(gsl::index nColumn) override; void OnViewModelStringValueChanged(gsl::index nIndex, const StringModelProperty::ChangeArgs& args) override; void OnViewModelAdded(gsl::index nIndex) override; void OnViewModelRemoved(gsl::index nIndex) override; void OnEndViewModelCollectionUpdate() override; private: gsl::index GetIndexForLine(gsl::index nLine) const; void UpdateLineBreaks(gsl::index nIndex, gsl::index nColumn, const ra::ui::win32::bindings::GridColumnBinding* pColumn, size_t nChars); static void GetLineBreaks(const std::wstring& sText, size_t nChars, std::vector<unsigned int>& vLineBreaks); void UpdateLineOffsets(); int GetMaxCharsForColumn(gsl::index nColumn) const; struct ItemMetrics { unsigned int nFirstLine = 0; unsigned int nNumLines = 1; std::map<int, std::vector<unsigned int>> mColumnLineOffsets; }; std::vector<ItemMetrics> m_vItemMetrics; gsl::index m_nLastClickedItem = 0; }; } // namespace bindings } // namespace win32 } // namespace ui } // namespace ra #endif // !RA_UI_WIN32_MULTILINEGRIDBINDING_H
36.5
139
0.769692
dd200071bfce5c6e220d3a598d1c6775aad5419a
1,070
cpp
C++
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
//Uva- 10616 - Divisible Group Sums #include <iostream> #include <cstring> using namespace std; using ll = long long; int N, Q, D, M; int arr[200]; ll memo[200][20][10]; //Index,Sum % 20,#Items picked ll knapsack( int idx, int sum, int m ) { if( idx + M - m > N ) //Impossible to collect M items return 0; if( m == M ) //Collected all M items return sum == 0; ll &comb{ memo[idx][sum][m] }; //Memoization if( comb != -1 ) return comb; comb = 0; //To guarantee that modulo is always +ve int rem{ ( ( (sum + arr[idx]) % D ) + D ) % D }; //Taking item arr[idx] comb += knapsack( idx + 1, rem, m + 1 ); //Not taking item arr[idx] comb += knapsack( idx + 1, sum, m ); return comb; } int main() { int setNo{ 0 }; while( scanf("%d %d", &N, &Q ), N ) { printf( "SET %d:\n", ++setNo ); for( int i{0}; i < N; ++i ) scanf( "%d", &arr[i] ); int Qno{ 0 }; while( Q-- ) { memset(memo, -1, sizeof(memo)); scanf( "%d %d", &D, &M ); printf("QUERY %d: %lld\n",++Qno,knapsack(0, 0, 0)); } } return 0; }
18.448276
59
0.530841
dd237c93e24ce9fe0246c6a0e207899a455714f3
2,610
cpp
C++
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
#include "CApp.h" #undef main CApp::CApp() { // SDL resources window = NULL; renderer = NULL; // User Resources resourceManager = NULL; running = true; score = 0; beginTime = 0; numb_lives_to_gen = PLAYER_MAX_HEALTH - 2; generateLives = true; } CApp::CApp(SDL_Renderer* renderer, ResourceManager* resourceManager) { // SDL resources window = NULL; this->renderer = renderer; // User Resources this->resourceManager = resourceManager; running = true; score = 0; beginTime = 0; numb_lives_to_gen = PLAYER_MAX_HEALTH - 2; generateLives = true; } int CApp::OnExecute() { if(OnInit() == false) { printf("Initialization failed!\n"); OnCleanup(); return -1; } SDL_Event event; while (running) { while (SDL_PollEvent(&event)) { OnEvent(&event); } OnLoop(); OnRender(); } if(score != -1) { // load the music file gameover_music = Mix_LoadMUS(GAMEOVER_MUSIC_FILE); if (gameover_music != NULL) { Mix_PlayMusic(gameover_music, -1); } // START display GameLost SDL_RenderClear(renderer); SDL_Color whiteColor = { 0xff, 0xff, 0xff }; FontTexture endMsgTexture; FontTexture endTexture; std::stringstream endMsg; endMsg << GAME_END_1 << score << GAME_END_2 << timeText.str() << GAME_END_3; resourceManager->loadFontTexture(endMsgTexture, endMsg.str(), &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9)); endMsgTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.3)); resourceManager->loadFontTexture(endTexture, GAME_END, &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9)); endTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.9)); SDL_RenderPresent(renderer); SDL_Event e; // remove events during delay SDL_Delay(1000); SDL_PumpEvents(); SDL_FlushEvent(SDL_KEYDOWN | SDL_QUIT); while(SDL_WaitEvent(&e)) { if (e.type == SDL_KEYDOWN || e.type == SDL_QUIT) { break; } } // set elaped time in milliseconds beginTime = SDL_GetTicks() - beginTime; // END display GameLost } OnCleanup(); return 0; } int main2(int argc, char* argv[]) { CApp theApp; return theApp.OnExecute(); } int CApp::GetFinalScore() { return score; } Uint32 CApp::GetFinalTime() { return beginTime; }
21.570248
122
0.586207
dd248d32555237459b88abf3d9a3703abb16eac6
174
hpp
C++
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
null
null
null
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
null
null
null
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
1
2019-05-23T11:09:42.000Z
2019-05-23T11:09:42.000Z
#pragma once #include "SDK.hpp" #include "RecvProxyHook.hpp" extern VMTHook* g_client_hook; extern VMTHook* g_game_event_manager_hook; extern RecvPropHook* g_sequence_hook;
21.75
42
0.821839
dd25f6c5d6c0376cd11b5e8d0bba88ddfba6a7d8
421
cpp
C++
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
5
2019-04-08T15:25:32.000Z
2019-12-07T16:31:55.000Z
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
null
null
null
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
null
null
null
#include "agg.hpp" extern "C" { PG_FUNCTION_INFO_V1(internal_to_array); Datum internal_to_array(PG_FUNCTION_ARGS); } Datum internal_to_array(PG_FUNCTION_ARGS) { //TODO trigger destructor Assert(AggCheckCallContext(fcinfo, NULL)); if (PG_ARGISNULL(0)) { PG_RETURN_NULL(); } else { AggInternal* state = (AggInternal*)(PG_GETARG_POINTER(0)); PG_RETURN_ARRAYTYPE_P( state->fnc(state) ); } }
21.05
63
0.712589
dd269092067c738ec28eaa4435a0ab0069323c62
77,457
cpp
C++
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #include "Compiler/CISACodeGen/LinkTessControlShaderMCFPass.h" #include "Compiler/IGCPassSupport.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/IR/Constants.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Function.h> #include <llvm/IR/InstVisitor.h> #include <llvm/IR/IRBuilder.h> #include "llvm/IR/Dominators.h" #include "llvm/IR/InstIterator.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <llvmWrapper/IR/Function.h> #include <llvmWrapper/IR/InstrTypes.h> #include "llvm/Analysis/PostDominators.h" #include "llvm/Analysis/LoopInfo.h" #include "common/LLVMWarningsPop.hpp" #include "common/IGCIRBuilder.h" #include "Compiler/MetaDataUtilsWrapper.h" #include "Compiler/CodeGenPublic.h" using namespace llvm; using namespace IGC; using namespace IGC::IGCMD; // Summary: The role of this pass is to link the TCS generated by OGL FE // by adding a loop to loop through the number of output control points and // replace all occurrences of HSControlPointID with the loopCounter // When barriers are present in TCS this pass elimates them by splitting // a shader into multiple continuation functions (code between barriers, // see http ://compilers.cs.uni-saarland.de/papers/karrenberg_opencl.pdf ) // running every continuation function in a control point loop before // moving to the next phase. // Values that need to be passed between phases are converted into // global allocas and sized (arrays) by the number of control points. // Continuation functions receive pointers to proper global alloca entries // (i.e. indexed by control point ID) for data passing. namespace IGC { class LinkTessControlShaderMCF : public llvm::ModulePass { public: // Pass identification, replacement for typeid static char ID; static const uint32_t LARGE_INSTRUCTIONS_COUNT = 1000; /// @brief Constructor LinkTessControlShaderMCF(); ~LinkTessControlShaderMCF() { delete mpBuilder; }; /// @brief Provides name of pass virtual llvm::StringRef getPassName() const override { return "LinkTessControlShaderMCF"; } virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override { AU.addRequired<MetaDataUtilsWrapper>(); AU.addRequired<CodeGenContextWrapper>(); AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTreeWrapperPass>(); } /// @brief Main entry point. /// @param F The current function. virtual bool runOnModule(llvm::Module& M) override; private: llvm::IGCIRBuilder<>* mpBuilder{ nullptr }; Module* mpModule{ nullptr }; DominatorTree* mpDT{ nullptr }; Function* mpMainFunction{ nullptr }; uint32_t mNumBarriers; uint32_t mOutputControlPointCount; uint32_t mNumInstructions; bool m_useMultipleHardwareThread; // SIMD size for tessellation workloads is SIMD8 static const uint32_t SIMDSize = 8; // Special state that indicates that program has exited. static const uint32_t ExitState = 0xFFFFFFFF; ////////////////////////////////////////////////////////////////////////// /// BarrierInfo ////////////////////////////////////////////////////////////////////////// struct BarrierInfo { uint32_t id{ 0 }; // Unique identifier }; std::vector<CallInst*> mBarriers; std::map<CallInst*, BarrierInfo> mBarrierInfo; std::vector<CallInst*> mBarriersPHIInLoop; std::vector<CallInst*> mMemoryFence; ////////////////////////////////////////////////////////////////////////// /// GlobalAllocas /// @brief Used to keep track of all alloca values that are live across /// barrier. ////////////////////////////////////////////////////////////////////////// typedef llvm::Value* global_alloca_key_t; class GlobalAllocas { std::map<global_alloca_key_t, Value*> mGlobalAllocas; bool mGlobalAllocasUpdated = { false }; public: /// @brief Returns LLVM type for the alloca specified by key. Type* GetType(global_alloca_key_t key) { assert(!mGlobalAllocasUpdated && "map updated - type no longer available"); Value* pVal = mGlobalAllocas[key]; assert(pVal && "global alloca not found!"); return pVal->getType(); } /// @brief Inserts alloca into a global map. void AddAllocaRef(Value* pAlloca) { assert(!mGlobalAllocasUpdated && "map updated - cannot add new allocas"); mGlobalAllocas[pAlloca] = pAlloca; } /// @brief Returns pointer to local alloca specified by key. Value* GetAllocaRef(global_alloca_key_t allocaKey) { assert(!mGlobalAllocasUpdated && "map updated - cannot reference local allocas"); return mGlobalAllocas[allocaKey]; } /// @brief Returns pointer to global alloca specified by key. Value* GetGlobalAlloca(global_alloca_key_t allocaKey) { assert(mGlobalAllocasUpdated && "map not yet updated - alloca not available"); return mGlobalAllocas[allocaKey]; } void MoveAllocas(Instruction* pInsert); void CreateGlobalAllocas(llvm::IGCIRBuilder<>& builder, uint32_t count); }; GlobalAllocas mGlobalAllocas; ////////////////////////////////////////////////////////////////////////// /// ContinuationFunction /// @brief Represents a sequence of basic blocks for a single shader phase /// (up to a barrier) and pointers to allocas that are used for /// accross barrier value passing. /// @todo Can change lists to vector. ////////////////////////////////////////////////////////////////////////// struct ContinuationFunction { uint32_t id{ 0 }; ///< This id is used for switch case. Function* pFunc{ nullptr }; BasicBlock* pEntry{ nullptr }; std::vector<BasicBlock*> exits; ///< terminator blocks std::vector<BasicBlock*> blocks; ///< blocks in a continuation function std::set<global_alloca_key_t> inputs; ///< global allocas for ins/outs }; std::set<global_alloca_key_t> fullInputsList; ////////////////////////////////////////////////////////////////////////// /// EdgeLives - Tracks all lives between edges in CFG. ////////////////////////////////////////////////////////////////////////// struct EdgeLives { BasicBlock* pFrom{ nullptr }; BasicBlock* pTo{ nullptr }; std::set<Value*> lives; }; std::map<BasicBlock*, EdgeLives> mEdgeLives; // Maps an entry block to each continuation function. std::map<BasicBlock*, ContinuationFunction> mEntryMap; std::vector<ContinuationFunction*> mContinuationFunctions; std::map<BasicBlock*, bool> mVisited; ////////////////////////////////////////////////////////////////////////// /// BasicBlockMeta ////////////////////////////////////////////////////////////////////////// struct BasicBlockMeta { bool isPreBarrierBlock{ false }; BarrierInfo* pBarrierInfo{ nullptr }; BarrierInfo* pPreBarrierInfo{ nullptr }; BasicBlock* pPostBarrierBlock{ nullptr }; }; // Maps metadata to basic blocks. std::map<BasicBlock*, BasicBlockMeta> mBlockMeta; // Each post barrier basic block will become an entry block for a continuation function. // The FunctionEntryBlock list contains all post-barrier blocks and the main entry block. std::vector<BasicBlock*> mFunctionEntryBlocks; // For 'switch' instructions each CF needs to receive full function arguments list. bool mIsPhiWith3OrMoreIncomingValues; ////////////////////////////////////////////////////////////////////////// /// Internal methods. ////////////////////////////////////////////////////////////////////////// /// Helper getters. llvm::IGCIRBuilder<>& Builder(void) { assert(mpBuilder); return *mpBuilder; } Module* GetModule(void) { assert(mpModule); return mpModule; } Function* GetMainFunction(void) { assert(mpMainFunction); return mpMainFunction; } DominatorTree* GetDT(void) { assert(mpDT); return mpDT; } ////////////////////////////////////////////////////////////////////////// /// @brief Returns true if basic block is a pre-barrier block. bool IsPreBarrierBlock(BasicBlock* pBlock) { BasicBlockMeta& meta = mBlockMeta[pBlock]; return (meta.isPreBarrierBlock); } ////////////////////////////////////////////////////////////////////////// /// @brief Returns true if basic block is a post barrier block. bool IsPostBarrierBlock(BasicBlock* pBlock) { BasicBlockMeta& meta = mBlockMeta[pBlock]; return (meta.pBarrierInfo != nullptr); } ////////////////////////////////////////////////////////////////////////// /// @brief Returns the immediate dominator for the current basic block. /// This is used by live-ness analysis to help walk up the CFG. BasicBlock* GetImmediateDominator(BasicBlock* pBlock) { assert(GetDT()->getNode(pBlock) != nullptr); DomTreeNode* pNode = GetDT()->getNode(pBlock)->getIDom(); return pNode ? pNode->getBlock() : nullptr; } // Forward declarations. HullShaderDispatchModes DetermineDispatchMode(void); void FindBarriers(Function& f); void ReplaceReturn(Function& f, uint32_t retValue); void SplitBasicBlocksAtBarriers(Function& f); void UnlinkPreBarrierBlocks(Function& f); void GetContinuationBlocks(BasicBlock* pCurBlock, ContinuationFunction& cf); bool IsBlockOutside(ContinuationFunction& cf, BasicBlock* pBlock); void AddLive(BasicBlock* pCurBlock, BasicBlock* pEndBlock, Instruction* pLive); void FindBarrierLives(Function& f); void ReplaceValueWithinBB(BasicBlock* pBlock, Value* pOld, Value* pNew); AllocaInst* ReplaceWithIntermittentAlloca(Instruction* pDef); void ReplaceLive(Value* pOld, Value* pNew); void ConvertBarrierLivesToAllocas(Function& f); void CollectArguments(ContinuationFunction& cf); void FixUpControlPointID(ContinuationFunction& cf); void DetectBarrierPHIInLoop(Function& cf); void FixUpHSControlPointIDVsGlobalVar(Function& f); void RemovePhiInstructions(Function& cf); void PurgeFunction(Function& f); void BuildContinuationFunction(ContinuationFunction& cf); void BuildContinuationFunctions(Function& f); void RebuildMainFunction(void); void TCSwHWBarriersSupport(MetaDataUtils* pMdUtils); bool SelectTCSwHWBarrierSupport(void); llvm::Function* CreateNewTCSFunction(llvm::Function* pCurrentFunc); }; char LinkTessControlShaderMCF::ID = 0; // Register pass to igc-opt #define PASS_FLAG "igc-LinkTessControlShaderMCF" #define PASS_DESCRIPTION "Perform looping of tessellation function based on control point count" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false IGC_INITIALIZE_PASS_BEGIN(LinkTessControlShaderMCF, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_END(LinkTessControlShaderMCF, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) LinkTessControlShaderMCF::LinkTessControlShaderMCF() : llvm::ModulePass(ID), mNumBarriers(0), mOutputControlPointCount(0), mNumInstructions(0), m_useMultipleHardwareThread(false), mIsPhiWith3OrMoreIncomingValues(false) { initializeLinkTessControlShaderMCFPass(*llvm::PassRegistry::getPassRegistry()); } HullShaderDispatchModes LinkTessControlShaderMCF::DetermineDispatchMode(void) { llvm::NamedMDNode* metaData = GetModule()->getOrInsertNamedMetadata("HullShaderDispatchMode"); IGC::CodeGenContext* pCodeGenContext = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); /* Instance Count ** This field determines the number of threads(minus one) spawned per input patch. ** If the HS kernel uses a barrier function, software must restrict the Instance Count ** to the number of threads that can be simultaneously active within a subslice. ** Factors which must be considered includes scratch memory availability. ** Value Description ** [0, 15] representing[1, 16] instances */ // Use HS single patch if WA exists and input control points >= 29 as there are not enough registers for push constants bool useSinglePatch = false; if (pCodeGenContext->platform.WaDispatchGRFHWIssueInGSAndHSUnit()) { llvm::GlobalVariable* pGlobal = GetModule()->getGlobalVariable("TessInputControlPointCount"); if (pGlobal && pGlobal->hasInitializer()) { unsigned int inputControlPointCount = int_cast<unsigned int>(llvm::cast<llvm::ConstantInt>(pGlobal->getInitializer())->getZExtValue()); if (inputControlPointCount >= 29) { useSinglePatch = true; } } } if (pCodeGenContext->platform.useOnlyEightPatchDispatchHS() || (pCodeGenContext->platform.supportHSEightPatchDispatch() && !(m_useMultipleHardwareThread && mOutputControlPointCount >= 16) && !useSinglePatch && IGC_IS_FLAG_DISABLED(EnableHSSinglePatchDispatch))) { Constant* cval = llvm::ConstantInt::get( Builder().getInt32Ty(), HullShaderDispatchModes::EIGHT_PATCH_DISPATCH_MODE); llvm::MDNode* mdNode = llvm::MDNode::get( Builder().getContext(), llvm::ConstantAsMetadata::get(cval)); metaData->addOperand(mdNode); return HullShaderDispatchModes::EIGHT_PATCH_DISPATCH_MODE; } else { Constant* cval = llvm::ConstantInt::get( Builder().getInt32Ty(), HullShaderDispatchModes::SINGLE_PATCH_DISPATCH_MODE); llvm::MDNode* mdNode = llvm::MDNode::get( Builder().getContext(), llvm::ConstantAsMetadata::get(cval)); metaData->addOperand(mdNode); return HullShaderDispatchModes::SINGLE_PATCH_DISPATCH_MODE; } } ////////////////////////////////////////////////////////////////////////// /// @brief Finds all barriers in program and populates barrier info. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::FindBarriers(Function& f) { mNumBarriers = 0; for (auto i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction& inst = cast<Instruction>(*i); mNumInstructions++; if (GenIntrinsicInst * pInst = dyn_cast<GenIntrinsicInst>(&inst)) { GenISAIntrinsic::ID IID = pInst->getIntrinsicID(); if (IID == GenISAIntrinsic::GenISA_threadgroupbarrier) { BarrierInfo& info = mBarrierInfo[pInst]; if (info.id > 0) continue; mNumBarriers++; info.id = mNumBarriers; // id starts at 1. mBarriers.push_back(pInst); } if (IID == GenISAIntrinsic::GenISA_memoryfence) { // MemoryFence inst is going to be removed for MCF solution. mMemoryFence.push_back(pInst); } } else if (PHINode * pPhi = dyn_cast<PHINode>(&inst)) { // Set this member only when 'barrier' instr is before PHI. mIsPhiWith3OrMoreIncomingValues = ((pPhi->getNumIncomingValues() >= 3) && (mNumBarriers > 0)); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace original returns (void) with our exit marker ret(0xFFFFFFFF). /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::ReplaceReturn(Function& f, uint32_t retValue) { SmallVector<Instruction*, 8> retInstructions; for (inst_iterator i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction* pInst = &(*i); if (isa<ReturnInst>(pInst)) { retInstructions.push_back(pInst); } } for (Instruction* pRet : retInstructions) { Builder().SetInsertPoint(pRet); Builder().CreateRet(Builder().getInt32(retValue)); pRet->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Splits all basic blocks with barriers and setup meta info. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::SplitBasicBlocksAtBarriers(Function& f) { mFunctionEntryBlocks.push_back(&f.getEntryBlock()); for (auto pBarrier : mBarriers) { BasicBlock* pBarrierBlock = pBarrier->getParent(); assert(pBarrierBlock != nullptr); Builder().SetInsertPoint(pBarrier); BarrierInfo& info = mBarrierInfo[pBarrier]; llvm::StringRef name = pBarrierBlock->getName(); std::string postfix = std::string(".postbarrier.") + std::to_string(info.id); BasicBlock* pPostBarrierBlock = pBarrierBlock->splitBasicBlock(pBarrier->getNextNode(), name + postfix.c_str()); // Check whether the current barrier instruction is on the mBarriersPHIInLoop list. // This solution handles only barriers within loop in one BB i.e. without any control flow. for (auto pLocBarrier : mBarriersPHIInLoop) { if (pLocBarrier->getParent() == pBarrierBlock) { for (BasicBlock::iterator i = pPostBarrierBlock->begin(), e = pPostBarrierBlock->end(); i != e; ++i) { Instruction* pInst = &(*i); if (llvm::BranchInst * pBrInst = dyn_cast<BranchInst>(pInst)) { // Replace : br COND, BB_IF_TRUE, BB_IF_FALSE // with : br COND, BB_IF_TRUE.postbarrier, BB_IF_FALSE Builder().SetInsertPoint(pInst); BranchInst::Create(pPostBarrierBlock, pBrInst->getSuccessor(1), pBrInst->getCondition(), pPostBarrierBlock); pInst->eraseFromParent(); break; } } break; } } // Each post barrier basic block is an entry block for a continuation function. mFunctionEntryBlocks.push_back(pPostBarrierBlock); // The pBarrierBlock is now the pre-barrier block after the split. BasicBlockMeta& preBarrierMeta = mBlockMeta[pBarrierBlock]; preBarrierMeta.isPreBarrierBlock = true; preBarrierMeta.pPreBarrierInfo = &info; preBarrierMeta.pPostBarrierBlock = pPostBarrierBlock; BasicBlockMeta& postBarrierMeta = mBlockMeta[pPostBarrierBlock]; postBarrierMeta.pBarrierInfo = &info; EdgeLives& edge = mEdgeLives[pPostBarrierBlock]; edge.pFrom = pBarrierBlock; edge.pTo = pPostBarrierBlock; } // Remove barrier instructions. for (auto pBarrier : mBarriers) { pBarrier->eraseFromParent(); } mBarriers.clear(); // Remove barrier instructions from 'in loop' sections of code. mBarriersPHIInLoop.clear(); // Remove 'memory fence' instructions. for (auto pMemoryFence : mMemoryFence) { pMemoryFence->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief For each pre-barrier block insert new return instruction /// and remove original terminator. These new returns will be used /// by continuation functions. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::UnlinkPreBarrierBlocks(Function& f) { for (BasicBlock& basicBlock : f.getBasicBlockList()) { BasicBlock* pBasicBlock = &basicBlock; if (IsPreBarrierBlock(pBasicBlock)) { BasicBlockMeta& meta = mBlockMeta[pBasicBlock]; // Insert return(n) that will be used by continuation function. Builder().SetInsertPoint(pBasicBlock->getTerminator()); Builder().CreateRet(Builder().getInt32(meta.pPreBarrierInfo->id)); // Unlink the pre-barrier block from the post-barrier block by removing // original terminator. pBasicBlock->getTerminator()->eraseFromParent(); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Finds all blocks that belong to a continuation function. /// @param pCurBlock - Current block in depth-first traversal. /// @param cf - Continuation function we're adding to. void LinkTessControlShaderMCF::GetContinuationBlocks(BasicBlock* pCurBlock, ContinuationFunction& cf) { // If we have already visited this node then can end traversal. if (mVisited[pCurBlock] == true) { return; } mVisited[pCurBlock] = true; BasicBlockMeta& meta = mBlockMeta[pCurBlock]; cf.blocks.push_back(pCurBlock); // If the current block is pre-barrier block then end traversal. if (meta.isPreBarrierBlock) { cf.exits.push_back(pCurBlock); return; } uint32_t numSuccessors = 0; for (auto i = succ_begin(pCurBlock), e = succ_end(pCurBlock); i != e; ++i) { BasicBlock* pSuccessor = *i; GetContinuationBlocks(pSuccessor, cf); numSuccessors++; } if (numSuccessors == 0) { cf.exits.push_back(pCurBlock); } } ////////////////////////////////////////////////////////////////////////// /// @brief Return true if basic block does not belong to CF. /// @param cf - current continuation function /// @param pBlock - Block we're testing bool LinkTessControlShaderMCF::IsBlockOutside(ContinuationFunction& cf, BasicBlock* pBlock) { for (auto pCfBlock : cf.blocks) { if (pCfBlock == pBlock) { return false; } } return true; } ////////////////////////////////////////////////////////////////////////// /// @brief This walks the CFG from the current block to the end block /// and if it finds a post-barrier block along the way then it /// adds the "live" to the edge between pre and post barrier blocks. /// These lives are later used to generate spill/fills. void LinkTessControlShaderMCF::AddLive(BasicBlock* pCurBlock, BasicBlock* pEndBlock, Instruction* pLive) { if (mVisited[pCurBlock] == true) { return; } mVisited[pCurBlock] = true; if (pCurBlock != pEndBlock) { for (auto i = pred_begin(pCurBlock), end = pred_end(pCurBlock); i != end; ++i) { BasicBlock* pPredBlock = *i; if (pPredBlock != pEndBlock) { AddLive(pPredBlock, pEndBlock, pLive); } } } if (IsPostBarrierBlock(pCurBlock)) { EdgeLives& edge = mEdgeLives[pCurBlock]; edge.lives.insert(pLive); } } ////////////////////////////////////////////////////////////////////////// /// @brief Analyzes all instructions in the function and for each use /// determines the live range. If any barrier falls within this live /// range then we need to generate a spill/fill. /// @note Post-barrier blocks should never contain a phi. Algorithm assumes that. void LinkTessControlShaderMCF::FindBarrierLives(Function& f) { // Update dominator tree. mpDT = &getAnalysis<DominatorTreeWrapperPass>(*GetMainFunction()).getDomTree(); for (auto i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction* pDef = &*i; BasicBlock* pDefBlock = pDef->getParent(); for (User* pUser : pDef->users()) { Instruction* pUserInst = cast<Instruction>(pUser); BasicBlock* pUseBlock = pUserInst->getParent(); if (PHINode * pPhi = dyn_cast<PHINode>(pUser)) { for (uint32_t incoming = 0; incoming < pPhi->getNumIncomingValues(); ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } while (pDefBlock != pUseBlock) { BasicBlock* pIDom = GetImmediateDominator(pUseBlock); if (pIDom) { mVisited.clear(); // Reset visited for next traversal. AddLive(pUseBlock, pIDom, pDef); } pUseBlock = pIDom; } } } mVisited.clear(); // Reset visited for future use. } ////////////////////////////////////////////////////////////////////////// /// @brief Replace all uses of old value with a new value within BB only. void LinkTessControlShaderMCF::ReplaceValueWithinBB(BasicBlock* pBlock, Value* pOld, Value* pNew) { std::set<llvm::Use*> useList; for (auto ui = pOld->use_begin(), ue = pOld->use_end(); ui != ue; ++ui) { Use& use = *ui; Instruction* pUser = dyn_cast<Instruction>(use.getUser()); if (pUser && pUser->getParent() == pBlock) { useList.insert(&use); } } for (auto pUse : useList) { pUse->set(pNew); } } ////////////////////////////////////////////////////////////////////////// /// @brief Create intermittent alloca for a value and add loads for uses. /// @param def - value to be processed through alloca. AllocaInst* LinkTessControlShaderMCF::ReplaceWithIntermittentAlloca(Instruction* pDef) { assert(pDef); Type* pType = pDef->getType(); BasicBlock* pDefBlock = pDef->getParent(); std::string defName = pDef->getName(); std::string newName = "l_" + defName; // Start with inserting new alloca after defining instruction. BasicBlock::iterator ii(pDef); Builder().SetInsertPoint(&(*(++ii))); AllocaInst* pAlloca = Builder().CreateAlloca(pType, nullptr, VALUE_NAME(defName)); // Add load new value. // We replace def value even within defining BB just to be sure // alghorithm is consistent. Compiler will optimize this later. Value* pNewValue = Builder().CreateLoad(pAlloca, VALUE_NAME(newName)); // Step 1. // Insert load instruction in all post-barrier basic blocks, // where this value is used. std::map<BasicBlock*, Value*> loadedValueMap; mVisited.clear(); loadedValueMap[pDefBlock] = pNewValue; mVisited[pDefBlock] = true; for (auto ui = pDef->user_begin(), ue = pDef->user_end(); ui != ue; ++ui) { Instruction* pUser = cast<Instruction>(*ui); BasicBlock* pUseBlock = pUser->getParent(); PHINode* pPhi = dyn_cast<PHINode>(pDef); // For phi instructions actual use block is incoming one. if (pPhi != nullptr) { uint32_t numIncoming = pPhi->getNumIncomingValues(); for (uint32_t incoming = 0; incoming < numIncoming; ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } if (!mVisited[pUseBlock]) { mVisited[pUseBlock] = true; Builder().SetInsertPoint(pUseBlock->getFirstNonPHI()); Value* pNewValue = Builder().CreateLoad(pAlloca, VALUE_NAME(newName)); loadedValueMap[pUseBlock] = pNewValue; } } mVisited.clear(); // Step 2. // Replace all uses. // while (pDef->use_begin() != pDef->use_end()) { Instruction* pUser = cast<Instruction>(pDef->use_begin()->getUser()); BasicBlock* pUseBlock = pUser->getParent(); PHINode* pPhi = dyn_cast<PHINode>(pDef); // For phi instructions actual use block is incoming one. if (pPhi != nullptr) { uint32_t numIncoming = pPhi->getNumIncomingValues(); for (uint32_t incoming = 0; incoming < numIncoming; ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } // If we have new value fetched for the block already, then use it as replacement, // if not, then walk up dominance tree to find the correct one. auto mi = loadedValueMap.find(pUseBlock); pNewValue = (*mi).second; assert(pNewValue && "loaded value not found for added alloca!!!"); if (pNewValue != pDef) { ReplaceValueWithinBB(pUseBlock, pDef, pNewValue); } } // Add 'store' inst for storing an old value. BasicBlock::iterator bbi(pAlloca); Builder().SetInsertPoint(&(*++bbi)); Builder().CreateStore(pDef, pAlloca); return pAlloca; } ////////////////////////////////////////////////////////////////////////// /// @brief Replace live value marked in our tables with a new one. void LinkTessControlShaderMCF::ReplaceLive(Value* pOld, Value* pNew) { for (auto& edgeMapEntry : mEdgeLives) { EdgeLives& edge = edgeMapEntry.second; auto pos = edge.lives.find(pOld); if (pos != edge.lives.end()) { edge.lives.erase(pos); edge.lives.insert(pNew); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Make any values crossing barriers to use intermittent allocas. /// Alghoritm depends on only allocas being live at barriers; // these are then moved to main function and converted into // continuation function arguments. void LinkTessControlShaderMCF::ConvertBarrierLivesToAllocas(Function& f) { for (auto edgeMapEntry : mEdgeLives) { EdgeLives& edge = edgeMapEntry.second; for (Value* pLive : edge.lives) { Instruction* pInst = cast<Instruction>(pLive); // If it's not alloca, create an intermittent alloca // and make all uses go through it. if (!isa<AllocaInst>(pInst)) { Instruction* pNewDef = ReplaceWithIntermittentAlloca(pInst); ReplaceLive(pLive, pNewDef); } } } } ////////////////////////////////////////////////////////////////////////// /// @brief Collects information about lives across barrier boundaries. void LinkTessControlShaderMCF::CollectArguments(ContinuationFunction& cf) { // First continuation function should not have live-ins. assert(cf.id != 0 || mEdgeLives[cf.pEntry].lives.size() == 0); // Generate inputs first. EdgeLives& edge = mEdgeLives[cf.pEntry]; for (auto& pLive : edge.lives) { Instruction* pInst = dyn_cast<Instruction>(pLive); assert(isa<AllocaInst>(pInst)); cf.inputs.insert(pLive); mGlobalAllocas.AddAllocaRef(pLive); } if (mIsPhiWith3OrMoreIncomingValues) { // For 'switch' inst scenarios, each CF needs to get a complete list of arguments. for (auto inputArg : fullInputsList) { cf.inputs.insert(inputArg); } } // Generate outputs. for (auto& pExit : cf.exits) { BasicBlockMeta& meta = mBlockMeta[pExit]; if (meta.isPreBarrierBlock) { BasicBlock* pPostBarrier = meta.pPostBarrierBlock; assert(pPostBarrier != nullptr); EdgeLives& edge = mEdgeLives[pPostBarrier]; assert((edge.pFrom != nullptr) && (pExit == edge.pFrom)); for (auto pLive : edge.lives) { Instruction* pInst = dyn_cast<Instruction>(pLive); assert(isa<AllocaInst>(pInst)); cf.inputs.insert(pLive); mGlobalAllocas.AddAllocaRef(pLive); if (mIsPhiWith3OrMoreIncomingValues) { // Collect input arguments from each CF. fullInputsList.insert(pLive); } } } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace all uses of @genISA.DCL.HSControlPointID() with /// first argument of continuation function. /// @param cf - current continuation function void LinkTessControlShaderMCF::FixUpControlPointID(ContinuationFunction& cf) { SmallVector<Instruction*, 10> instructionToRemove; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration( cf.pFunc->getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); Argument* arg0 = &(*cf.pFunc->arg_begin()); for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); if (useInst->getParent()->getParent() == cf.pFunc) { instructionToRemove.push_back(useInst); useInst->replaceAllUsesWith(arg0); } } for (auto& inst : instructionToRemove) { inst->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Detect whether barrier inst is within 'inloop' section. /// For such scenarios each relevant PHI instruction must be /// replaced with set of alloca/store/load/store. /// See RemovePhiInstructions description. /// @param f - main function void LinkTessControlShaderMCF::DetectBarrierPHIInLoop(Function& f) { // Examine only BB which contains Barrier instruction. for (auto pBarrier : mBarriers) { BasicBlock* pBarrierBlock = pBarrier->getParent(); assert(pBarrierBlock != nullptr); bool isPHIInBB = false; bool isBarrierInLoop = false; for (BasicBlock::iterator i = pBarrierBlock->begin(), e = pBarrierBlock->end(); i != e; ++i) { Instruction* pInst = &(*i); if (dyn_cast<PHINode>(pInst)) { isPHIInBB = true; } else if (llvm::BranchInst * pBrInst = dyn_cast<BranchInst>(pInst)) { // Check whether any of successors(i.e. BB) matches pBarrierBlock. for (unsigned int successorId = 0; successorId < pBrInst->getNumSuccessors(); ++successorId) { isBarrierInLoop = (pBrInst->getSuccessor(successorId) == pBarrierBlock) ? true : isBarrierInLoop; } } } if (isPHIInBB && isBarrierInLoop) { // Barrier and PHI instructions are in the loop. // Store Barrier instruction , this data is needed in the RemovePhiInstructions. // This solution handles only barriers within loop in one BB i.e. without any control flow. mBarriersPHIInLoop.push_back(pBarrier); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace each relevant PHI instruction with /// set of alloca/store/load/store. /// E.g. /// %Temp-91.i.i = phi float [ %Temp-87.i.i, %MainCode ], [ %Temp-92.i.i, %Label-88.i.i ] /// --> /// %Temp-91.i.i28 = alloca float /// store float %Temp-87.i.i, float* %Temp-91.i.i28 /// ( Label.postbarrier: ) <-- added by SplitBasicBlocksAtBarriers() /// %Temp-91.i.i29 = load float* %Temp-91.i.i28 /// store float %Temp-92.i.i, float* %Temp-91.i.i28 /// @param f - main function void LinkTessControlShaderMCF::RemovePhiInstructions(Function& f) { SmallVector<Instruction*, 4> phiToRemove; // Do removal of PHI instructions only in BB which contains Barrier and PHI in the loop. // This solution handles only barriers within loop in one BB i.e. without any control flow. for (auto pBarrier : mBarriersPHIInLoop) { BasicBlock* pBarrierBlock = pBarrier->getParent(); Instruction* pBarrierInst = cast<Instruction>(pBarrier); for (BasicBlock::iterator i = pBarrierBlock->begin(), e = pBarrierBlock->end(); i != e; ++i) { Instruction* pDef = &*i; if (PHINode * pPhi = dyn_cast<PHINode>(pDef)) { phiToRemove.push_back(pPhi); std::string defName = pPhi->getName(); std::string newName = pDef->getName(); Type* pType = pPhi->getType(); BasicBlock::iterator ii(pDef); Builder().SetInsertPoint(&(*ii)); // 1. Create 'alloca' inst to store incoming values to PHI instruction. AllocaInst* pAllocaPHI = Builder().CreateAlloca(pType, nullptr, VALUE_NAME(defName)); // 2. Create 'store' inst to store the 1st out of the PHI incoming values. Instruction* pIncoming1stDef = cast<Instruction>(pPhi->getIncomingValue(0)); Builder().CreateStore(pIncoming1stDef, pAllocaPHI); // 3. Create 'load' inst after barrier inst to load one of the PHI incoming values. // This instruction loads firstly the value from the 1st PHI incoming values // and secondly,later the 2nd PHI incoming value. BasicBlock::iterator iAfterThreadBarrier(pBarrierInst); Builder().SetInsertPoint(&(*++iAfterThreadBarrier)); Value* pNewValue = Builder().CreateLoad(pAllocaPHI, VALUE_NAME(newName)); // 4. Create 'store' inst to store the 2nd out of the PHI incoming values. Instruction* pIncoming2ndDef = cast<Instruction>(pPhi->getIncomingValue(1)); BasicBlock::iterator iAfterIncoming2ndDef(pIncoming2ndDef); Builder().SetInsertPoint(&(*++iAfterIncoming2ndDef)); Builder().CreateStore(pIncoming2ndDef, pAllocaPHI); pPhi->replaceAllUsesWith(pNewValue); } } } for (auto& phiInst : phiToRemove) { phiInst->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Makes a "shell" function removing all basic blocks. /// @param f - The function we're working on. void LinkTessControlShaderMCF::PurgeFunction(Function& f) { std::vector<BasicBlock*> blocksToRemove; // Find blocks to be removed. for (Function::iterator bb = f.begin(), be = f.end(); bb != be; ++bb) { BasicBlock* pBlock = &*bb; if (pBlock->getParent() == &f) { blocksToRemove.push_back(pBlock); pBlock->dropAllReferences(); } } for (BasicBlock* pBlock : blocksToRemove) { pBlock->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Builds LLVM function for continuation. /// @param cf - The continuation function we're working on. void LinkTessControlShaderMCF::BuildContinuationFunction(ContinuationFunction& cf) { Function* pMainFunc = GetMainFunction(); // We don't expect main function to have any arguments. assert(pMainFunc->arg_begin() == pMainFunc->arg_end()); // Prepare argument list for a function. std::vector<Type*> argTypes; argTypes.push_back(Builder().getInt32Ty()); // CPId for (auto alloca_key : cf.inputs) { argTypes.push_back(mGlobalAllocas.GetType(alloca_key)); } std::string funcName = std::string("tcs.phase.") + std::to_string(cf.id); cf.pFunc = Function::Create( FunctionType::get(Builder().getInt32Ty(), argTypes, false), llvm::GlobalValue::PrivateLinkage, funcName, mpModule); cf.pFunc->addFnAttr(llvm::Attribute::AlwaysInline); // Map ValueToValueMapTy vmap; SmallVector<ReturnInst*, 8> returns; // Loop over the arguments, copying the names of the mapped arguments over... Function::arg_iterator ai = cf.pFunc->arg_begin(); ai->setName("CPId"); ++ai; for (auto ii : cf.inputs) { const Value* pVal = mGlobalAllocas.GetAllocaRef(ii); if (vmap.count(pVal) == 0) { // Copy the name over... ai->setName("arg" + pVal->getName()); // Add mapping to ValueMap vmap[pVal] = static_cast<Argument*>(&*ai); ++ai; } } // Fix up starting block, by moving it to the function beginning. cf.pEntry->moveBefore(&*(pMainFunc->begin())); CloneAndPruneFunctionInto(cf.pFunc, pMainFunc, vmap, false, returns); FixUpControlPointID(cf); } ////////////////////////////////////////////////////////////////////////// /// @brief Replace each usage of global loaded from HSControlPointID by /// a call directly to it. As a result, instead of having one load /// of CPID and multiple usages of the global variable initialized /// by that value, there are calls to HSControlPointID before each /// usage. /// E.g. /// See method replacing the 'load' instructions that reference to /// global variable which stores the CPId value with /// HSControlPointID() calls. /// /// FROM --> /// % 3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// store i32 % 3, i32* @0 /// . . . /// % 4 = load i32, i32* @0 /// . . . /// % 10 = insertelement <4 x i32> <i32 0, i32 0, i32 undef, i32 1>, i32 % 4, i32 2 /// /// TO --> /// % 3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// store i32 % 3, i32* @0 /// . . . /// % 4 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// . . . /// % 10 = insertelement <4 x i32> <i32 0, i32 0, i32 undef, i32 1>, i32 % 4, i32 2 /// /// /// @param f - The function we're working on. void LinkTessControlShaderMCF::FixUpHSControlPointIDVsGlobalVar(Function& f) { SmallVector<Instruction*, 10> instructionToUpdate; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration( f.getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); // Pass through usages of the call to HSControlPointID. // e.g.: %3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() // %16 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); // Pass through the usages of the each HSControlPointID's call result. // e.g.: call void @llvm.genx.GenISA.OutputTessControlPoint(float %19, float %20, float %21, float %22, i32 %11, i32 %16, i32 %17) // store i32 %3, i32* @0 for (Value::user_iterator _i = useInst->user_begin(), _e = useInst->user_end(); _i != _e; ++_i) { // Find the 'store' instr and check if it is storing local val(i.e.the result of HSControlPointID's call) into a global variable. // e.g.: store i32 %3, i32* @0 if (llvm::StoreInst * storeInst = llvm::dyn_cast<llvm::StoreInst>(*_i)) { llvm::Value* op1 = storeInst->getOperand(1); if (isa<GlobalVariable>(op1)) { // Pass through usages of that global to find load instructions to replace. // e.g.: %5 = load i32, i32* @0 // % 4 = load i32, i32* @0 for (auto ui = op1->user_begin(), ue = op1->user_end(); ui != ue; ++ui) { if (llvm::LoadInst * ldInst = llvm::dyn_cast<llvm::LoadInst>(*ui)) { instructionToUpdate.push_back(ldInst); } } } } } } // Do the actual replacement of global variable to variable resulting // from call to HSControlPointID. for (auto& ldInst : instructionToUpdate) { Builder().SetInsertPoint(ldInst); llvm::Value* pCPId = Builder().CreateCall(pHSControlPointID); ldInst->replaceAllUsesWith(pCPId); ldInst->eraseFromParent(); // e.g.: %4 = load i32, i32* @0 <--replaced with --> %4 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() } } ////////////////////////////////////////////////////////////////////////// /// @brief Constructs a set of barrier-free functions from a main function /// that contains barriers. Each new function is called a continuation /// function that contains all of the basic blocks up to a barrier. /// @param f - Main function we're breaking up into multiple functions. void LinkTessControlShaderMCF::BuildContinuationFunctions(Function& f) { FixUpHSControlPointIDVsGlobalVar(f); DetectBarrierPHIInLoop(f); RemovePhiInstructions(f); SplitBasicBlocksAtBarriers(f); FindBarrierLives(f); ConvertBarrierLivesToAllocas(f); // Perform a depth-first traversal from each continuation entry // basic block to find all blocks that belong to each continuation // function. Traversal for each continuation function ends when a // pre-barrier block is hit or the final return block. for (auto pEntry : mFunctionEntryBlocks) { // Effectively we're allocating the Continuation Function with the entry map. ContinuationFunction& cf = mEntryMap[pEntry]; cf.pEntry = pEntry; BasicBlockMeta& meta = mBlockMeta[pEntry]; if (meta.pBarrierInfo != nullptr) { cf.id = meta.pBarrierInfo->id; } GetContinuationBlocks(pEntry, cf); // We'll traverse this list and build continuation functions from this. mContinuationFunctions.push_back(&cf); // Reset the visited list for generating next continuation function. mVisited.clear(); } // Collect arguments for continuation functions. for (auto pCF : mContinuationFunctions) { CollectArguments(*pCF); } // Here we are done with analysis. // Now we create actual continuation functions through transforming // and cloning the main function. // Replace existing returns with ret(-1) which marks end of program. ReplaceReturn(f, ExitState); // Remove BR instructions linking pre- and post-barrier blocks and replace // them with ret(N) instructions (where N is barrier id). UnlinkPreBarrierBlocks(f); // Create new basic block to temporary hold all global allocas, // and move allocas into it. This way alloca instructions won't be cloned // into continuation functions. BasicBlock* pEntry = &(f.getEntryBlock()); BasicBlock* pAllocaBlock = BasicBlock::Create( GetModule()->getContext(), VALUE_NAME("alloca_block"), &f, pEntry); Instruction* pTerminator = BranchInst::Create(pEntry, pAllocaBlock); mGlobalAllocas.MoveAllocas(pTerminator); for (auto pCF : mContinuationFunctions) { BuildContinuationFunction(*pCF); } } ////////////////////////////////////////////////////////////////////////// /// @brief Moves global allocas to the BB specified by insertion point. /// @param pIsert - Insertion point. void LinkTessControlShaderMCF::GlobalAllocas::MoveAllocas(Instruction* pInsert) { assert(pInsert); for (auto& ai : mGlobalAllocas) { Instruction* pAllocaInst = cast<Instruction>(ai.second); pAllocaInst->moveBefore(pInsert); } } ////////////////////////////////////////////////////////////////////////// /// @brief Creates global allocas for values shared between phases. /// @param arraySize - number of elements in allocas. /// @note Caller should set IRBuilder insert point. void LinkTessControlShaderMCF::GlobalAllocas::CreateGlobalAllocas( llvm::IGCIRBuilder<>& builder, uint32_t arraySize) { std::string suffix = "[" + std::to_string(arraySize) + "]"; for (auto& ai : mGlobalAllocas) { Value* pOldAlloca = ai.second; std::string name = pOldAlloca->getName().str() + suffix; Type* oldType = pOldAlloca->getType()->getPointerElementType(); Type* allocaType = ArrayType::get(oldType, arraySize); Value* pAlloca = builder.CreateAlloca(allocaType, nullptr, name); ai.second = pAlloca; } mGlobalAllocasUpdated = true; } ////////////////////////////////////////////////////////////////////////// /// @brief Builds the wrapper function that calls the continuation /// functions. Each continuation function returns a state. The /// wrapper implements a state machine using while loop and a switch. /// @param f- The original function. void LinkTessControlShaderMCF::RebuildMainFunction() { LLVMContext& ctx = GetModule()->getContext(); std::string oldEntryFuncName = GetMainFunction()->getName().str(); // Need to create unconnected entry block for the new function first, // Because we need info from old main function to create global allocas. BasicBlock* pEntry = BasicBlock::Create(ctx, oldEntryFuncName); Builder().SetInsertPoint(pEntry); mGlobalAllocas.CreateGlobalAllocas(Builder(), mOutputControlPointCount); // Now we can delete old function. PurgeFunction(*GetMainFunction()); Function* pNewFunc = GetMainFunction(); // Determine the dispatch mode HullShaderDispatchModes dispatchMode = DetermineDispatchMode(); // Create new basic blocks for main function. pEntry->insertInto(pNewFunc); BasicBlock* pStateLoopHeader = BasicBlock::Create(ctx, "state_loop_header", pNewFunc); BasicBlock* pStateDone = BasicBlock::Create(ctx, "state_done", pNewFunc); BasicBlock* pExit = BasicBlock::Create(ctx, "exit", pNewFunc); Value* pConstant0 = llvm::ConstantInt::get(Builder().getInt32Ty(), 0); Value* pLoopLimit = llvm::ConstantInt::get(Builder().getInt32Ty(), mOutputControlPointCount); Value* pBaseCPID = nullptr; Value* pCpidIncrement = nullptr; // Map to keep pointers to global alloca variables. std::map<size_t, Value*> allocas; // Create rest of the entry block, setting starting CPID value and adding block terminator branch. // Starting CPID is zero for EIGHT_PATCH dispatch and lane ID for SINGLE_PATCH. Builder().SetInsertPoint(pEntry); switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: // In single patch mode we will need SIMD lane ID to calculate CPID. { Value* pSimdLane = Builder().CreateCall( GenISAIntrinsic::getDeclaration(pNewFunc->getParent(), GenISAIntrinsic::GenISA_simdLaneId), None, VALUE_NAME("simd_lane_id")); pBaseCPID = Builder().CreateZExt(pSimdLane, Builder().getInt32Ty()); pCpidIncrement = llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize); } break; case EIGHT_PATCH_DISPATCH_MODE: pBaseCPID = pConstant0; pCpidIncrement = llvm::ConstantInt::get(Builder().getInt32Ty(), 1); break; default: assert(0 && "should not reach here"); break; } Builder().CreateBr(pStateLoopHeader); // The barrier state machine part. It consists of the loop enclosing switch // over the next state == barrier ID. Loop is finished when the next state is (-1). Builder().SetInsertPoint(pStateDone); PHINode* pNextStatePhi = Builder().CreatePHI(Builder().getInt32Ty(), mContinuationFunctions.size(), VALUE_NAME("next_state_phi")); Builder().SetInsertPoint(pStateLoopHeader); PHINode* pStatePhi = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("state_phi")); pStatePhi->addIncoming(pConstant0, pEntry); pStatePhi->addIncoming(pNextStatePhi, pNextStatePhi->getParent()); BasicBlock* pPrevStateCheckBlock = nullptr; std::vector<Instruction*> nextState; for (auto pCF : mContinuationFunctions) { //switch(state) std::string strId = std::to_string(pCF->id); BasicBlock* pStateCheckBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("state_check_cf") + strId), pNewFunc, pStateDone); BasicBlock* pStateExecBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("state_exec_cf") + strId), pNewFunc, pStateDone); BasicBlock* pCpidExecBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("cpid_exec_cf") + strId), pNewFunc, pStateDone); if (pPrevStateCheckBlock != nullptr) { IGCLLVM::TerminatorInst* pTerminator = pPrevStateCheckBlock->getTerminator(); BranchInst* pCondBranch = cast<BranchInst>(pTerminator); assert(pCondBranch->isConditional()); pCondBranch->setOperand(1, pStateCheckBlock); } else { Builder().SetInsertPoint(pStateLoopHeader); Builder().CreateBr(pStateCheckBlock); } Builder().SetInsertPoint(pStateCheckBlock); Value* pCond = Builder().CreateICmpEQ(pStatePhi, llvm::ConstantInt::get(Builder().getInt32Ty(), pCF->id)); Builder().CreateCondBr(pCond, pStateExecBlock, pExit); // Create a loop over CPID. Builder().SetInsertPoint(pStateExecBlock); PHINode* pCurrentCPID = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("CPID")); // Create counter incrementation. Builder().SetInsertPoint(pCpidExecBlock); Value* pIncrementedCPID = Builder().CreateAdd(pCurrentCPID, pCpidIncrement, VALUE_NAME("cpid_inc")); // Continue with loop creation. Builder().SetInsertPoint(pStateExecBlock); pCurrentCPID->addIncoming(pBaseCPID, pStateCheckBlock); pCurrentCPID->addIncoming(pIncrementedCPID, pCpidExecBlock); PHINode* pStateVal = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("next_state")); pStateVal->addIncoming(pStatePhi, pStateCheckBlock); nextState.push_back(pStateVal); // Create CPID loop header with checking of the loop condition: "CPID < NumOutputControlPoints" Value* pCounterConditionalRes = Builder().CreateICmpULT( pCurrentCPID, pLoopLimit, VALUE_NAME("tcs_if_ult_cond2")); Builder().CreateCondBr(pCounterConditionalRes, pCpidExecBlock, pStateDone); // Build cpid exec block by inserting GEPs and call to continuation function. Builder().SetInsertPoint(pCpidExecBlock); // Just forward arguments to continuation functions. std::vector<Value*> args; // First argument is control point ID. args.push_back(pCurrentCPID); for (auto input : pCF->inputs) { Value* pAlloca = mGlobalAllocas.GetGlobalAlloca(input); Value* indexList[2] = { pConstant0, pCurrentCPID }; // Create GEP for curent instance. Value* pGEP = Builder().CreateGEP(pAlloca, ArrayRef<Value*>(indexList, 2), VALUE_NAME(std::string("p_") + pAlloca->getName())); args.push_back(pGEP); } // CFn(uint arg0, type1* arg1, type2* arg2, ...); Instruction* pCfResult = Builder().CreateCall( pCF->pFunc, args, VALUE_NAME(std::string("cf_result") + strId)); pStateVal->addIncoming(pCfResult, pCpidExecBlock); // Add CPID loop termination. Builder().CreateBr(pStateExecBlock); pPrevStateCheckBlock = pStateCheckBlock; } // Now complete the phi instruction for the "state done" block. Builder().SetInsertPoint(pStateDone); for (auto pNextStateCall : nextState) { // pNextStateCall should always be in immediate predecessor. pNextStatePhi->addIncoming(pNextStateCall, pNextStateCall->getParent()); } // Add state loop condition check. Value* pCond = Builder().CreateICmpEQ(pNextStatePhi, llvm::ConstantInt::get(Builder().getInt32Ty(), ExitState)); Builder().CreateCondBr(pCond, pExit, pStateLoopHeader); // Add function terminator. Builder().SetInsertPoint(pExit); Builder().CreateRetVoid(); } llvm::Function* LinkTessControlShaderMCF::CreateNewTCSFunction(llvm::Function* pCurrentFunc) { llvm::IRBuilder<> irBuilder(pCurrentFunc->getContext()); CodeGenContext* ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); std::vector<llvm::Type*> callArgTypes; for (auto& argIter : range(pCurrentFunc->arg_begin(), pCurrentFunc->arg_end())) { callArgTypes.push_back(argIter.getType()); } callArgTypes.push_back(irBuilder.getInt32Ty()); std::string funcName = "tessControlShaderEntry"; llvm::Function* pNewFunction = llvm::Function::Create( llvm::FunctionType::get( irBuilder.getVoidTy(), callArgTypes, false), llvm::GlobalValue::PrivateLinkage, funcName, ctx->getModule()); pNewFunction->addFnAttr(llvm::Attribute::AlwaysInline); // Move over the contents of the original function pNewFunction->getBasicBlockList().splice(pNewFunction->begin(), pCurrentFunc->getBasicBlockList()); llvm::Function* pToBeDeletedFunc = pCurrentFunc; for (auto oldArg = pToBeDeletedFunc->arg_begin(), oldArgEnd = pToBeDeletedFunc->arg_end(), newArg = pNewFunction->arg_begin(); oldArg != oldArgEnd; ++oldArg, ++newArg) { oldArg->replaceAllUsesWith(&(*newArg)); newArg->takeName(&(*oldArg)); } // delete the old function signature pToBeDeletedFunc->eraseFromParent(); // now replace all occurrences of HSControlPointID with the current // loop iteration CPID - pCurrentCPID SmallVector<Instruction*, 10> instructionToRemove; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration(pNewFunction->getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); unsigned int argIndexInFunc = IGCLLVM::GetFuncArgSize(pNewFunction) - 1; Function::arg_iterator arg = pNewFunction->arg_begin(); for (unsigned int i = 0; i < argIndexInFunc; ++i, ++arg); for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); if (useInst->getParent()->getParent() == pNewFunction) { instructionToRemove.push_back(useInst); useInst->replaceAllUsesWith(&(*arg)); } } for (auto& inst : instructionToRemove) { inst->eraseFromParent(); } return pNewFunction; } void LinkTessControlShaderMCF::TCSwHWBarriersSupport(MetaDataUtils* pMdUtils) { CodeGenContext* ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); std::string oldEntryFuncName = GetMainFunction()->getName().str(); llvm::Function* pNewTCSFunction = CreateNewTCSFunction(mpMainFunction); m_useMultipleHardwareThread = (mNumBarriers != 0) ? true : false; // Determine the dispatch mode HullShaderDispatchModes dispatchMode = DetermineDispatchMode(); // This function is the new entry function llvm::Function* pNewLoopFunc = llvm::Function::Create(llvm::FunctionType::get(Builder().getVoidTy(), false), llvm::GlobalValue::ExternalLinkage, oldEntryFuncName, ctx->getModule()); llvm::BasicBlock* pEntryBlock = llvm::BasicBlock::Create( pNewLoopFunc->getContext(), oldEntryFuncName, pNewLoopFunc); Builder().SetInsertPoint(pEntryBlock); // first create a call to simdLaneId() intrinsic llvm::Value* pCPId = nullptr; llvm::Function* pFuncPatchInstanceIdOrSIMDLaneId = nullptr; switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_simdLaneId); pCPId = Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId); if (m_useMultipleHardwareThread) { // CPID = patchInstanceID * 8 + SimdLaneId; pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_patchInstanceId); pCPId = Builder().CreateAdd( Builder().CreateZExt( pCPId, Builder().getInt32Ty()), Builder().CreateMul( Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId), llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize))); } break; case EIGHT_PATCH_DISPATCH_MODE: pCPId = Builder().getInt32(0); if (m_useMultipleHardwareThread) { pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_patchInstanceId); pCPId = Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId); } break; default: assert(0 && "should not reach here"); break; } // We don't need to deal with any loops when we are using multiple hardware threads if (!m_useMultipleHardwareThread) { // initialize instanceCount to output control point count llvm::Value* pInstanceCount = Builder().getInt32(mOutputControlPointCount); // initialize loopCounter llvm::Value* pLoopCounter = Builder().CreateAlloca(Builder().getInt32Ty(), 0, "loopCounter"); llvm::Value* pConstInt = Builder().getInt32(0); Builder().CreateStore(pConstInt, pLoopCounter, false); // create loop-entry basic block and setInsertPoint to loop-entry llvm::BasicBlock* pLoopEntryBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_entry"), pNewLoopFunc); llvm::BasicBlock* pLoopConditionTrue = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_condition_true"), pNewLoopFunc); // Create loop-continue basic block llvm::BasicBlock* pLoopContinueBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_continue"), pNewLoopFunc); // create loop exit basic block llvm::BasicBlock* pAfterLoopBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_after_loop"), pNewLoopFunc); // setInsertPoint to loopEntryBB Builder().CreateBr(pLoopEntryBB); Builder().SetInsertPoint(pLoopEntryBB); // Load the loop counter llvm::LoadInst* pLoadLoopCounter = Builder().CreateLoad(pLoopCounter); llvm::Value* pMulLoopCounterRes = nullptr; llvm::Value* pCurrentCPID = nullptr; llvm::Value* pConditionalRes1 = nullptr; uint32_t loopIterationCount = 0; switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: // currentCPID = pCPId + loopCounter x simdsize ( in this case its always simd 8 ) pMulLoopCounterRes = Builder().CreateMul( pLoadLoopCounter, llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize)); pCurrentCPID = Builder().CreateAdd( Builder().CreateZExt( pCPId, Builder().getInt32Ty()), pMulLoopCounterRes); // cmp currentCPID to instanceCount so we enable only the required lanes pConditionalRes1 = Builder().CreateICmpULT( pCurrentCPID, pInstanceCount, VALUE_NAME("tcs_if_ult_cond1")); // if true go to startBB else jump to pAfterLoopBB Builder().CreateCondBr(pConditionalRes1, pLoopConditionTrue, pAfterLoopBB); loopIterationCount = ((mOutputControlPointCount - 1) / 8) + 1; break; case EIGHT_PATCH_DISPATCH_MODE: pCurrentCPID = pLoadLoopCounter; loopIterationCount = mOutputControlPointCount; // jump to startBB Builder().CreateBr(pLoopConditionTrue); break; default: assert(false && "should not reach here"); break; } // branch to pLoopContinueBB from endBB Builder().SetInsertPoint(pLoopConditionTrue); // Create a call to the TCS function when condition is true to loop the function as many times as the number of control points Builder().CreateCall(pNewTCSFunction, pCurrentCPID); Builder().CreateBr(pLoopContinueBB); // setInsertPoint to pLoopContinueBB Builder().SetInsertPoint(pLoopContinueBB); // increment loop counter loopCounter = loopCounter + 1 llvm::Value* pIncrementedLoopCounter = Builder().CreateAdd( pLoadLoopCounter, llvm::ConstantInt::get(Builder().getInt32Ty(), 1)); Builder().CreateStore(pIncrementedLoopCounter, pLoopCounter, false); // now evaluate loop, if( ( incrementedLoopCounter ) < ( ( maxControlPointCount - 1 )/8) + 1 ) // then continue loop else go to after loop llvm::Value* pNumberOfLoopIterationsRequired = llvm::ConstantInt::get(Builder().getInt32Ty(), loopIterationCount); llvm::Value* pConditionalRes2 = Builder().CreateICmpULT( pIncrementedLoopCounter, pNumberOfLoopIterationsRequired, VALUE_NAME("tcs_if_ult_cond2")); // create branch to LoopEntryBB or AfterLoopBB based on result of conditional branch Builder().CreateCondBr(pConditionalRes2, pLoopEntryBB, pAfterLoopBB); // set insert point to afterloop basic block Builder().SetInsertPoint(pAfterLoopBB); } else if (dispatchMode == SINGLE_PATCH_DISPATCH_MODE) { // In single patch dispatch mode the execution mask is 0xFF. Make // that only valid CPIDs execute. // Create the main basic block for the shader llvm::BasicBlock* pTcsBody = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_body"), pNewLoopFunc); // and the end block. llvm::BasicBlock* pAfterTcsBody = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_end"), pNewLoopFunc); // Compare current CPID to the number of CPIDs to enable only the required lanes. llvm::Value* pIsLaneEnabled = Builder().CreateICmpULT( pCPId, Builder().getInt32(mOutputControlPointCount), VALUE_NAME("tcs_if_ult_cond1")); Builder().CreateCondBr(pIsLaneEnabled, pTcsBody, pAfterTcsBody); Builder().SetInsertPoint(pTcsBody); // Call TCS function. Builder().CreateCall(pNewTCSFunction, pCPId); Builder().CreateBr(pAfterTcsBody); Builder().SetInsertPoint(pAfterTcsBody); } else { // when using multiple hardware threads just call the Control Point function once with the appropriate CPID Builder().CreateCall(pNewTCSFunction, pCPId); } // add terminator to the afterloop basic block Builder().CreateRetVoid(); pMdUtils->clearFunctionsInfo(); IGCMetaDataHelper::addFunction(*pMdUtils, pNewLoopFunc); } ////////////////////////////////////////////////////////////////////////// /// @brief - Checks whether the TCS with HW barrier support is a better /// option in comparison to TCS with SW barriers. bool LinkTessControlShaderMCF::SelectTCSwHWBarrierSupport(void) { if ((mNumBarriers == 0) || (mNumInstructions > LARGE_INSTRUCTIONS_COUNT)) { // Comment for mNumInstructions > LARGE_INSTRUCTIONS_COUNT: // TCSs with SW barrier enabled and having large instructions count consume much more scratch space per // thread than TCSs with HW barriers enabled. For a very large instructions count TCSs with SW barriers enabled // can run in pull vertex mode what negatively impacts performance. return true; } else { return false; } } ////////////////////////////////////////////////////////////////////////// /// @brief Perform pass operations. /// @param M- The original module. bool LinkTessControlShaderMCF::runOnModule(llvm::Module& M) { mpModule = &M; MetaDataUtils* pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils(); if (pMdUtils->size_FunctionsInfo() != 1) { return false; } mpMainFunction = pMdUtils->begin_FunctionsInfo()->first; assert(mpMainFunction); mpBuilder = new llvm::IGCIRBuilder<>(M.getContext()); // Get the output control point count. llvm::GlobalVariable* pOCPCount = GetMainFunction()->getParent()->getGlobalVariable("HSOutputControlPointCount"); mOutputControlPointCount = int_cast<uint32_t>(llvm::cast<llvm::ConstantInt>(pOCPCount->getInitializer())->getZExtValue()); // Get the barriers count. FindBarriers(*mpMainFunction); if (SelectTCSwHWBarrierSupport()) { TCSwHWBarriersSupport(pMdUtils); } else { // SW barriers support. BuildContinuationFunctions(*mpMainFunction); RebuildMainFunction(); } return true; } ////////////////////////////////////////////////////////////////////////// /// @brief Create this pass. llvm::Pass* createLinkTessControlShaderMCF() { return new LinkTessControlShaderMCF(); } }
41.069459
151
0.56279
dd27326be8d22edbd4a9ba089e777615d84611af
4,217
tpp
C++
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
TITLE("NTLvsSTL") TOPIC_TEXT( "[ $$0,0#00000000000000000000000000000000:Default][l288;i704;a17;O9;~~~.992; $$1," "0#10431211400427159095818037425705:param][a83;*R6 $$2,5#3131016247420302412518841" "7583966:caption][b83;* $$3,5#07864147445237544204411237157677:title][b167;a42;C $" "$4,6#40027414424643823182269349404212:item][b42;a42; $$5,5#4541300047534217475409" "1244180557:text][l288;a17; $$6,6#27521748481378242620020725143825:desc][l321;t246" ";C@5;1 $$7,7#20902679421464641399138805415013:code][b2503; $$8,0#6514237545610002" "3862071332075487:separator][*@(0.0.255) $$9,0#83433469410354161042741608181528:ba" "se][t4167;C+117 $$10,0#37138531426314131251341829483380:class][l288;a17;*1 $$11,1" "1#70004532496200323422659154056402:requirement][i416;b42;a42;O9;~~~.416; $$12,12#" "10566046415157235020018451313112:tparam][b167;C $$13,13#9243045944346046191110808" "0531343:item1][a42;C $$14,14#77422149456609303542238260500223:item2][*@2$(0.128.1" "28) $$15,15#34511555403152284025741354420178:NewsDate][l321;*C$7 $$16,16#03451589" "433145915344929335295360:result][l321;b83;a83;*C$7 $$17,17#0753155046352950537122" "8428965313:result`-line][l160;t4167;*C+117 $$18,5#8860394944220582595880005322242" "5:package`-title][{_}%EN-US [s2; NTL - STL Comparison&][s5; NTL was created to so" "lve following problems we used to encounter when using STL: &][s3; Copy-construct" "ible requirements&][s5; STL requires the elements stored in containers to meet th" "e requirements of copy-constructible and assignable types. This causes two proble" "ms:&][s5;i150;O2; Elements that do not satisfy these requirements cannot be direc" "tly stored in STL containers.&][s5;i150;O2; For many types of elements, including" " STL containers themselves, copy-constructor and assign operator is a very expens" "ive operation, that is why often they cannot be stored in STL containers effectiv" "ely.&][s5; NTL addresses this problem by introducing [^dpp`:`/`/SourceDoc`/Contai" "ners`/Overview^ Vector] and [^dpp`:`/`/SourceDoc`/Containers`/Overview^ Array] fl" "avors of containers.&][s3; Value transfer&][s5; Content o") TOPIC_TEXT( "f STL containers can be transfered only using expensive deep-copy constructor/as" "sigment operator. This causes performance problems especially when using STL cont" "ainers as function return values, but lack of better functionality is missing els" "ewhere too. NTL provides [^dpp`:`/`/SourceDoc`/Containers`/pick`_^ transfer seman" "tics] concepts to deal with this problem.&][s3; Random access and random access n" "otation&][s5; STL uses iterators as the preferred way how to access and identify " "elements in containers. While this is generally the most generic way, real-life p" "roblems often require or at least benefit from random access using indices. NTL p" "rovides fast random access to all kinds of containers and NTL interfaces prefer n" "otation using indices. As a side effect, NTL user can completely avoid using iter" "ators in favor of indices, which in current C`++ results in much simpler and less" " verbose syntax (using modern optimizing compilers there is no difference in perf" "ormance).&][s3; Index&][s5; A completely new type of associative container, [^dpp" "`:`/`/`:`:`/Index`<class T`, class HashFn `= StdHash`<T`> `>`/template `<class T`" ", class HashFn `= StdHash`<T`> `> class Index^ Index], is introduced, as an ideal" " building block for all kinds of associative operations.&][s3; Algorithm requirem" "ents&][s5; Requirements of STL algorithms are very loosely defined. NTL tries to " "provide more specific requirements and also minimal ones. This allows e.g. [^dpp`" ":`/`/www`/pages`/polyarray^ direct sorting of Array of polymorphic elements].&][s" "3; Minor improvements&][s5; There are also some minor improvements:&][s5;i150;O2;" " Besides [* reserve] present in STL, NTL provides also [* Shrink] method to minim" "ize a container's memory consumption.&][s5;i150;O2; Iterators can be assigned a N" "ULL value.&][s5;i150;O2; Associative containers are based on hashing to provide b" "etter performance. Utility classes and functions are provided to support building" " correct hashing functions.")
78.092593
84
0.751008
dd2c81e44b3caf19cc2cbec4b4667358fca2c594
3,917
cpp
C++
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2012 Motorola Mobility, Inc. All rights reserved. * Copyright (C) 2014-2020 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY MOTOROLA MOBILITY, INC. AND ITS CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MOTOROLA MOBILITY, INC. OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "RadioNodeList.h" #include "HTMLFormElement.h" #include "HTMLInputElement.h" #include "HTMLObjectElement.h" #include "NodeRareData.h" #include <wtf/IsoMallocInlines.h> namespace WebCore { using namespace HTMLNames; WTF_MAKE_ISO_ALLOCATED_IMPL(RadioNodeList); RadioNodeList::RadioNodeList(ContainerNode& rootNode, const AtomString& name) : CachedLiveNodeList(rootNode, InvalidateForFormControls) , m_name(name) , m_isRootedAtDocument(is<HTMLFormElement>(rootNode)) { } Ref<RadioNodeList> RadioNodeList::create(ContainerNode& rootNode, const AtomString& name) { return adoptRef(*new RadioNodeList(rootNode, name)); } RadioNodeList::~RadioNodeList() { ownerNode().nodeLists()->removeCacheWithAtomName(*this, m_name); } static RefPtr<HTMLInputElement> nonEmptyRadioButton(Element& element) { if (!is<HTMLInputElement>(element)) return nullptr; auto& inputElement = downcast<HTMLInputElement>(element); if (!inputElement.isRadioButton() || inputElement.value().isEmpty()) return nullptr; return &inputElement; } String RadioNodeList::value() const { auto length = this->length(); for (unsigned i = 0; i < length; ++i) { if (auto button = nonEmptyRadioButton(*item(i))) { if (button->checked()) return button->value(); } } return String(); } void RadioNodeList::setValue(const String& value) { auto length = this->length(); for (unsigned i = 0; i < length; ++i) { if (auto button = nonEmptyRadioButton(*item(i))) { if (button->value() == value) { button->setChecked(true); return; } } } } bool RadioNodeList::elementMatches(Element& element) const { if (!is<HTMLObjectElement>(element) && !is<HTMLFormControlElement>(element)) return false; if (is<HTMLInputElement>(element) && downcast<HTMLInputElement>(element).isImageButton()) return false; if (is<HTMLFormElement>(ownerNode())) { RefPtr<HTMLFormElement> form; if (is<HTMLObjectElement>(element)) form = downcast<HTMLObjectElement>(element).form(); else form = downcast<HTMLFormControlElement>(element).form(); if (!form || form != &ownerNode()) return false; } return element.getIdAttribute() == m_name || element.getNameAttribute() == m_name; } } // namespace WebCore
33.478632
93
0.697728
dd2f39398626d6035f8b8ec8dcb0379927b7c5cc
1,555
cpp
C++
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
2
2019-10-24T12:43:18.000Z
2019-12-22T20:59:18.000Z
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
9
2019-07-18T19:39:14.000Z
2021-06-13T18:29:55.000Z
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
5
2019-10-24T12:49:15.000Z
2021-05-17T10:47:42.000Z
#include "utils.h" #include <notification.h> #include <iostream> void Utils::simpleNotification(QString header, QString body, QString function, QVariantList parameters) { Notification notification; notification.setCategory("powietrze.update"); notification.setSummary(header); notification.setBody(body); notification.setPreviewSummary(header); notification.setPreviewBody(body); notification.setRemoteAction(Notification::remoteAction("default", "", "harbour.powietrze.service", "/harbour/powietrze/service", "harbour.powietrze.service", function, parameters)); notification.publish(); } float Utils::calculateWHONorms(const Pollution& sensorData) { if (!sensorData.isInitialized()) { return -1; } std::list<WHONorm> pollutions = { {"pm25", 25.f, 24}, {"pm10", 50.f, 24}, {"no2", 200.f, 1}, {"o3", 100.f, 8}, {"so2", 350.f, 1}, {"co", 30000.f, 1} }; for (auto pollution: pollutions) { if (pollution.name == sensorData.code) { float avg = sensorData.avg(pollution.hours); return avg / pollution.value * 100; } } return -1; }
31.1
103
0.48746
dd33a90e8cc809ea9c75c6242e9d70d25c283785
3,655
cxx
C++
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Trident // Copyright (C) Microsoft Corporation, 1997 - 1998. // // File: misc.cxx // // Contents: misc helpers for scriptoid handlers // //---------------------------------------------------------------------------- #include <headers.hxx> #ifndef X_DISPEX_H_ #define X_DISPEX_H_ #include <dispex.h> #endif #ifndef X_MISC_HXX_ #define X_MISC_HXX_ #include "misc.hxx" #endif //+------------------------------------------------------------------------ // // Function: GetProperty_Dispatch // //------------------------------------------------------------------------- HRESULT GetProperty_Dispatch(IDispatch * pDisp, LPTSTR pchName, IDispatch ** ppDispRes) { HRESULT hr; DISPID dispid; DISPPARAMS dispparams = {NULL, NULL, 0, 0}; VARIANT varRes; EXCEPINFO excepinfo; UINT nArgErr; *ppDispRes = NULL; hr = pDisp->GetIDsOfNames(IID_NULL, &pchName, 1, LOCALE_SYSTEM_DEFAULT, &dispid); if (hr) goto Cleanup; hr = pDisp->Invoke( dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispparams, &varRes, &excepinfo, &nArgErr); if (hr) goto Cleanup; if (VT_DISPATCH != V_VT(&varRes)) { hr = E_UNEXPECTED; goto Cleanup; } (*ppDispRes) = V_DISPATCH(&varRes); Cleanup: return hr; } //+------------------------------------------------------------------------ // // Function: PutProperty_Dispatch // //------------------------------------------------------------------------- HRESULT PutProperty_Dispatch(IDispatch * pDisp, LPTSTR pchName, IDispatch * pDispArg) { HRESULT hr; DISPID dispid; VARIANT varArg; VARIANT varRes; EXCEPINFO excepinfo; UINT nArgErr; DISPPARAMS dispparams = {&varArg, NULL, 1, 0}; VariantInit(&varArg); V_VT(&varArg) = VT_DISPATCH; V_DISPATCH(&varArg) = pDispArg; hr = pDisp->GetIDsOfNames(IID_NULL, &pchName, 1, LOCALE_SYSTEM_DEFAULT, &dispid); if (hr) goto Cleanup; hr = pDisp->Invoke( dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, &dispparams, &varRes, &excepinfo, &nArgErr); Cleanup: return hr; } //+------------------------------------------------------------------------ // // Function: GetDocument // //------------------------------------------------------------------------- HRESULT GetDocument(IDispatch * pElement, IDispatch ** ppDispDocument) { return GetProperty_Dispatch(pElement, _T("document"), ppDispDocument); } //+------------------------------------------------------------------------ // // Function: GetWindow // //------------------------------------------------------------------------- HRESULT GetWindow(IDispatch * pElement, IDispatchEx ** ppDispWindow) { HRESULT hr; IDispatch * pDispDocument = NULL; IDispatch * pDispWindow = NULL; *ppDispWindow = NULL; hr = GetDocument(pElement, &pDispDocument); if (hr) goto Cleanup; hr = GetProperty_Dispatch (pDispDocument, _T("parentWindow"), &pDispWindow); if (hr) goto Cleanup; hr = pDispWindow->QueryInterface (IID_IDispatchEx, (void**) ppDispWindow); Cleanup: ReleaseInterface(pDispDocument); ReleaseInterface(pDispWindow); return S_OK; }
24.046053
86
0.468947
dd35531bf699f1b942f91eee1b38b6f15f2bdb4b
69
hpp
C++
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
6
2018-08-05T21:45:23.000Z
2021-10-30T19:48:34.000Z
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
null
null
null
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
1
2021-11-01T20:15:38.000Z
2021-11-01T20:15:38.000Z
#ifndef FAINTED_HPP #define FAINTED_HPP struct Fainted { }; #endif
9.857143
19
0.753623
dd37a9ec1f567d6efebbf27b6a8daabc460e3d5a
4,472
cpp
C++
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given the running logs of n functions that are executed in a nonpreemptive // single threaded CPU, find the exclusive time of these functions. // Each function has a unique id, start from 0 to n-1. A function may be called // recursively or by another function. // A log is a string has this format : function_id:start_or_end:timestamp. For // example, "0:start:0" means function 0 starts from the very beginning of time // 0. "0:end:0" means function 0 ends to the very end of time 0. // Exclusive time of a function is defined as the time spent within this // function, the time spent by calling other functions should not be considered // as this function's exclusive time. You should return the exclusive time of // each function sorted by their function id. // Example 1: // Input: // n = 2 // logs = // ["0:start:0", // "1:start:2", // "1:end:5", // "0:end:6"] // Output:[3, 4] // Explanation: // Function 0 starts at time 0, then it executes 2 units of time and reaches the // end of time 1. Now function 0 calls function 1, function 1 starts at time 2, // executes 4 units of time and end at time 5. Function 0 is running again at // time 6, and also end at the time 6, thus executes 1 unit of time. So function // 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 // units of time. // Note: // Input logs will be sorted by timestamp, NOT log id. // Your output should be sorted by function id, which means the 0th element // of your output corresponds to the exclusive time of function 0. Two // functions won't start or end at the same time. Functions could be called // recursively, and will always end. 1 <= n <= 100 // WTF the problem description is class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); vector<vector<int>> ilogs(logs.size(), vector<int>(3)); // ilogs[i] == {id, start or end, time}, with unified timestamp for (int i = 0; i < logs.size(); ++i) { auto c = logs[i].find(':'); ilogs[i][0] = stoi(logs[i].substr(0, c)); ilogs[i][1] = logs[i][c + 1]; ilogs[i][2] = stoi(logs[i].substr(logs[i].rfind(':') + 1)) + (ilogs[i][1] == 'e'); } stack<vector<int>> s; for (int i = 0; i < ilogs.size(); ++i) { if (s.empty()) { s.push(ilogs[i]); continue; } ret[s.top()[0]] += ilogs[i][2] - s.top()[2]; if (ilogs[i][0] == s.top()[0] && ilogs[i][1] == 'e') { int t = ilogs[i][2]; s.pop(); if (!s.empty()) s.top()[2] = t; } else s.push(ilogs[i]); // cout << ret[0] << ' ' << ret[1] << endl; } return ret; } }; // simplified class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); stack<array<int, 3>> s; int id, status, t; // {id, status, unified timestamp} for (auto &&lg : logs) { auto c = lg.find(':'); id = stoi(lg.substr(0, c)); status = lg[c + 1]; t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e'); if (s.empty()) { s.push({id, status, t}); continue; } ret[s.top()[0]] += t - s.top()[2]; if (id == s.top()[0] && status == 'e') { s.pop(); if (!s.empty()) s.top()[2] = t; } else s.push({id, status, t}); } return ret; } }; // further simplified class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); stack<int> s; int id, t, prevt; char status; for (auto &&lg : logs) { auto c = lg.find(':'); id = stoi(lg.substr(0, c)); status = lg[c + 1]; t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e'); if (s.empty()) s.push(id); else { ret[s.top()] += t - prevt; if (id == s.top() && status == 'e') s.pop(); else s.push(id); } prevt = t; } return ret; } };
30.421769
80
0.503801
dd38657946b816e7b1dfe0382561956675f3d3bd
376
cpp
C++
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int dp(int arr[],int n) { int res=0,ans=0; for(int i=0;i<n;i++) { res = max(arr[i],res+arr[i]); ans = max(ans,res); } return ans; } int main() { int n,arr[1000]; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("%d\n",dp(arr,n)); return 0; } /* Input: 6 3 -4 9 -8 8 7 Output: 16 * */
10.444444
31
0.518617
dd3b3c9771b3885e6a182e1137e291c6d2a4d353
541
hpp
C++
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
120
2015-12-31T22:30:14.000Z
2022-03-29T15:08:01.000Z
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
6
2016-08-22T02:14:56.000Z
2021-11-06T22:39:52.000Z
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
23
2016-02-03T01:56:26.000Z
2021-09-28T16:36:27.000Z
#ifndef color_gray_akin_lab #define color_gray_akin_lab #include "../../generic/akin/gray.hpp" #include "../category.hpp" #include "../../lab/category.hpp" namespace color { namespace akin { template < typename tag_name ,::color::constant::lab::reference_enum lab_reference_number > struct gray< ::color::category::lab< tag_name, lab_reference_number > > { public: typedef ::color::category::gray< tag_name > akin_type; }; } } #endif
19.321429
77
0.593346
dd3db5d0b991ef5bb0432c8f80547d9095427916
1,279
hpp
C++
pgm.hpp
aravindev/PGM-improc
a38ae612fa093f24875c46ba824321721c4ab917
[ "Apache-2.0" ]
1
2015-04-02T05:26:11.000Z
2015-04-02T05:26:11.000Z
pgm.hpp
aravindev/PGM-improc
a38ae612fa093f24875c46ba824321721c4ab917
[ "Apache-2.0" ]
null
null
null
pgm.hpp
aravindev/PGM-improc
a38ae612fa093f24875c46ba824321721c4ab917
[ "Apache-2.0" ]
null
null
null
/* This header file has been created by Name : Aravind E Vijayan B110487EC National Institute of Technology Calicut */ #ifndef PGM_HPP #define PGM_HPP struct table //image structure { int **data; int cols; int rows; }; /* function to read pgm image Usage : parameter must be the path of image passed from terminal the function returns the image as a 2-D matrix along with size informations */ table pgm_imread(char *); /* function to calculate the histogram usage : parameter is the image structure it returns a 256 element structure containing the histogram information */ double *pgm_hist_calc(table); /* function to find the maximum value in the histogram usage : The maximum value of the histogram is returned. This can be used to resize the histogram image the histogram array must be passed along with the image structure */ double pgm_hist_maxval(double*, table); /* function to save the histogram as an image usage : This function can be used to save the histogram file as a PGM image. The second image name passed through the terminal, histogram array and the maximum value of histogram must be passed The last parameter is the size of the histogram image. Default value if 1024 */ void pgm_hist_save(char *,double *, double, int); #endif
27.804348
117
0.763878
dd3dfe96c626cba5ef08dd7a1d50a578b5654795
1,383
cpp
C++
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
#include "EdgarRequests.h" #include "../../../Private/source/markets/edgar/Edgar.h" #include "../../../Private/source/markets/edgar/Form13F.h" namespace Jde::Markets::TwsWebSocket { void EdgarRequests::Filings( Cik cik, ProcessArg&& inputArg )noexcept { std::thread( [cik, arg=move(inputArg)]() { try { auto p = Edgar::LoadFilings(cik); p->set_request_id( arg.ClientId ); MessageType msg; msg.set_allocated_filings( p.release() ); arg.Push( move(msg) ); } catch( IException& e ) { arg.Push( "could not retreive filings", e ); } }).detach(); } void Investors2( function<up<Edgar::Proto::Investors>()> f, ProcessArg&& inputArg )noexcept { std::thread( [f, arg=move(inputArg)]() { try { auto p = f(); p->set_request_id( arg.ClientId ); MessageType msg; msg.set_allocated_investors( p.release() ); arg.Push( move(msg) ); } catch( IException& e ) { arg.Push( "Could not load investors", e ); } }).detach(); } void EdgarRequests::Investors( ContractPK contractId, ProcessArg&& arg )noexcept { return Investors2( [contractId]() { auto pDetails = SFuture<::ContractDetails>( Tws::ContractDetail(contractId) ).get(); //TwsClientSync::ReqContractDetails( contractId ).get(); CHECK( (pDetails->size()==1) ); return Edgar::Form13F::LoadInvestors( pDetails->longName ); }, move(arg) ); } }
27.66
92
0.647144
dd3f5a22d08de4ccd846d871c43757f0f2945b2c
8,007
cpp
C++
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
#include "Export_Lua_Scene.h" #include "Export_Lua_Const.h" #include "../Header/SceneConst.h" #include "../Classes/LoadingScene.h" #include "../Classes/TitleScene.h" #include "../Classes/HelpScene.h" #include "../Classes/StageSelectScene.h" #include "../Classes/MissionSelectScene.h" #include "../Classes/StoryScene.h" #include "../Classes/PlayScene.h" #define LUASCENE_SCENE_IO "Scene_IO" #define LUASCENE_SCENE_CB "Scene_CB" #define LUASCENE_INPUTLAYER_CB "InputLayer_CB" #define LUASCENE_TOUCHLAYER_CB "TouchLayer_CB" LuaFunction<bool> * Export_Lua_Scene::ioScene; LuaFunction<bool> * Export_Lua_Scene::cbScene; LuaFunction<bool> * Export_Lua_Scene::cbInputLayer; LuaFunction<bool> * Export_Lua_Scene::cbTouchLayer; bool Export_Lua_Scene::_LuaRegistConst(LuaObject * obj) { obj->SetInteger("SceneIOFlag_OnInit", LUASCENE_IOFLAG_ONINIT); obj->SetInteger("SceneIOFlag_OnEnter", LUASCENE_IOFLAG_ONENTER); obj->SetInteger("SceneIOFlag_OnEnterA", LUASCENE_IOFLAG_ONENTERA); obj->SetInteger("SceneIOFlag_OnEnterTDF", LUASCENE_IOFLAG_ONENTERTDF); obj->SetInteger("SceneIOFlag_OnEnterTDFA", LUASCENE_IOFLAG_ONENTERTDFA); obj->SetInteger("SceneIOFlag_OnUpdate", LUASCENE_IOFLAG_ONUPDATE); obj->SetInteger("SceneIOFlag_OnExit", LUASCENE_IOFLAG_ONEXIT); obj->SetInteger("SceneIOFlag_OnTouchBegin", LUASCENE_IOFLAG_ONTOUCHBEGIN); obj->SetInteger("SceneIOFlag_OnTouchEnd", LUASCENE_IOFLAG_ONTOUCHEND); obj->SetInteger("ktag_BaseSceneLayer", KTAG_BASESCENELAYER); obj->SetInteger("ktag_LoadingSceneLayer", KTAG_LOADINGSCENELAYER); obj->SetInteger("ktag_TitleSceneLayer", KTAG_TITLESCENELAYER); obj->SetInteger("ktag_HelpSceneLayer", KTAG_HELPSCENELAYER); obj->SetInteger("ktag_StageSelectSceneLayer", KTAG_STAGESELECTSCENELAYER); obj->SetInteger("ktag_MissionSelectSceneLayer", KTAG_MISSIONSELECTSCENELAYER); obj->SetInteger("ktag_StorySceneLayer", KTAG_STORYSCENELAYER); obj->SetInteger("ktag_PlaySceneLayer", KTAG_PLAYSCENELAYER); obj->SetInteger("ktag_OverlayLayer", KTAG_OVERLAYLAYER); return true; } bool Export_Lua_Scene::_LuaRegistFunction(LuaObject * obj) { return true; } bool Export_Lua_Scene::InitCallbacks() { LuaState * ls = state; LuaObject _obj = ls->GetGlobal(LUASCENE_SCENE_IO); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_IO); return false; } static LuaFunction<bool> _fsceneio = _obj; _fsceneio = _obj; ioScene = &_fsceneio; _obj = ls->GetGlobal(LUASCENE_SCENE_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_CB); return false; } static LuaFunction<bool> _fscenecb = _obj; _fscenecb = _obj; cbScene = &_fscenecb; _obj = ls->GetGlobal(LUASCENE_INPUTLAYER_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_INPUTLAYER_CB); return false; } static LuaFunction<bool> _finputlayercb = _obj; _finputlayercb = _obj; cbInputLayer = &_finputlayercb; _obj = ls->GetGlobal(LUASCENE_TOUCHLAYER_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_TOUCHLAYER_CB); return false; } static LuaFunction<bool> _ftouchlayercb = _obj; _ftouchlayercb = _obj; cbTouchLayer = &_ftouchlayercb; return true; } /************************************************************************/ /* SceneGet */ /************************************************************************/ void Export_Lua_Scene::_GetSceneMenuCallback(int scenetag, SEL_MenuHandler * cbfunc, SEL_CallFuncND * cbndfunc) { scenetag = scenetag & KTAG_SCENELAYERMASK; switch (scenetag) { case KTAG_LOADINGSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(LoadingScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(LoadingScene::NodeCallbackFunc); } break; case KTAG_TITLESCENELAYER: if (cbfunc) { *cbfunc = menu_selector(TitleScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(TitleScene::NodeCallbackFunc); } break; case KTAG_HELPSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(HelpScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(HelpScene::NodeCallbackFunc); } break; case KTAG_STAGESELECTSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(StageSelectScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(StageSelectScene::NodeCallbackFunc); } break; case KTAG_MISSIONSELECTSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(MissionSelectScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(MissionSelectScene::NodeCallbackFunc); } break; case KTAG_STORYSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(StoryScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(StoryScene::NodeCallbackFunc); } break; case KTAG_PLAYSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(PlayScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(PlayScene::NodeCallbackFunc); } break; } } int Export_Lua_Scene::_GetTopTag(int itemtag) { return itemtag & KTAG_SCENELAYERMASK; } int Export_Lua_Scene::_GetSubLayerTag(int itemtag) { return itemtag & KTAG_SUBLAYERMASK; } int Export_Lua_Scene::_GetMenuGroupTag(int itemtag) { return itemtag & KTAG_MENUGROUPMASK; } int Export_Lua_Scene::_GetMenuItemTag(int itemtag) { return itemtag & KTAG_MENUITEMMASK; } CCScene * Export_Lua_Scene::_GetNewScene(int scenetag) { scenetag = scenetag & KTAG_SCENELAYERMASK; switch (scenetag) { case KTAG_LOADINGSCENELAYER: return LoadingScene::scene(); break; case KTAG_TITLESCENELAYER: return TitleScene::scene(); break; case KTAG_HELPSCENELAYER: return HelpScene::scene(); break; case KTAG_STAGESELECTSCENELAYER: return StageSelectScene::scene(); break; case KTAG_MISSIONSELECTSCENELAYER: return MissionSelectScene::scene(); break; case KTAG_STORYSCENELAYER: return StoryScene::scene(); break; case KTAG_PLAYSCENELAYER: return PlayScene::scene(); break; } return NULL; } /************************************************************************/ /* Callback */ /************************************************************************/ bool Export_Lua_Scene::ExecuteIOScene(BYTE flag, CCLayer *toplayer, int toptag) { LuaState * ls = state; bool bret = (*ioScene)(flag, CDOUBLEN(toplayer), toptag); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBScene(int tag, CCLayer * toplayer, int dataindex /* = -1 */) { LuaState * ls = state; bool bret = (*cbScene)(tag, CDOUBLEN(toplayer), _GetTopTag(tag), _GetSubLayerTag(tag), _GetMenuGroupTag(tag), _GetMenuItemTag(tag), dataindex); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBInputLayer(int tag, CCLayer * toplayer, int eventtag, const char * text) { LuaState * ls = state; bool bret = (*cbInputLayer)(tag, CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), _GetSubLayerTag(tag), text); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBTouchLayer(int tag, CCLayer * toplayer, int eventtag, CCLayer * thislayer, int index, BYTE gesture) { LuaState * ls = state; bool bret = (*cbTouchLayer)(CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), tag&KTAG_SUBLAYERMASK, CDOUBLEN(thislayer), index, gesture); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; }
28.393617
145
0.690396
dd436f744aa5f2ac3f40b87939557997b4564269
605
cpp
C++
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
class Solution { public: TreeNode* constructBST(vector<int> preorder,int low,int high){ if(low>=preorder.size() || low>high) return NULL; TreeNode* root=new TreeNode(preorder[low]); if(high==low) return root; int i; for(i=low;i<=high;i++) if(preorder[i]>root->val) break; root->left=constructBST(preorder,low+1,i-1); root->right=constructBST(preorder,i,high); return root; } TreeNode* bstFromPreorder(vector<int>& preorder) { return constructBST(preorder,0,preorder.size()-1); } };
25.208333
66
0.585124
dd4991383ae5a7f0cb1828b5206684bafedca6f5
5,205
cpp
C++
src/essentials.cpp
lockpicker1/NumMethods
e4a3beef4e584e69bd84d072645f7f18895730c6
[ "MIT" ]
null
null
null
src/essentials.cpp
lockpicker1/NumMethods
e4a3beef4e584e69bd84d072645f7f18895730c6
[ "MIT" ]
null
null
null
src/essentials.cpp
lockpicker1/NumMethods
e4a3beef4e584e69bd84d072645f7f18895730c6
[ "MIT" ]
null
null
null
/* Essential functions that will be used throughout the whole project */ #include "essentials.hpp" using namespace std; using namespace ess; ess::variableTable::variableTable () {//Constructor of variableTable classs ess::variableTable::numberOfVariables=0; ess::variableTable::nameOfVariable.clear(); ess::variableTable::valueOfVariable.clear(); } int ess::variableTable::addVariable(std::string name, double value){//Inserts a variable at the variable table if (numberOfVariables==UINT_MAX){ cout << "VariableTable at full size, can't add more\n"; return 1; } numberOfVariables+=1; nameOfVariable.push_back(*(new string(name))); valueOfVariable.push_back(value); return 0; } int ess::variableTable::removeVariable(std::string name){//Removes a variable from the variable table if (numberOfVariables==0){ cout << "No variables in this table\n"; return 1; } unsigned int iterator; for (iterator=0;iterator<numberOfVariables;iterator++){ if (!(std::strcmp(&(nameOfVariable[iterator][0]),&name[0]))){ nameOfVariable.erase(nameOfVariable.begin()+iterator); valueOfVariable.erase(valueOfVariable.begin()+iterator); numberOfVariables-=1; return 0; } } cout << "No variable with such name\n"; return 1; } int ess::variableTable::changeValueOfVariable(std::string name, double value){//Change the value of a variable in the variable table if (numberOfVariables==0){ cout << "No variables in this table\n"; return 1; } unsigned int iterator; for (iterator=0;iterator<numberOfVariables;iterator++){ if (!(std::strcmp(&name[0],&(nameOfVariable[iterator][0])))){ valueOfVariable[iterator] = value; return 0; } } cout << "No variable with such name\n"; return 1; } double ess::variableTable::getValueOfVariable(std::string name){//Get the value of the variable in the variable table if (numberOfVariables==0){ cout << "No variables in this table\n"; return 0; } unsigned int iterator; for (iterator=0;iterator<numberOfVariables;iterator++){ if (!(std::strcmp(&name[0],&(nameOfVariable[iterator][0])))){ return valueOfVariable[iterator]; } } cout << "No variable with such name\n"; return 0; } int ess::variableTable::printVariableTable(){//Display the entire variable table if (numberOfVariables==0){ cout << "No variables in this table\n"; return 1; } unsigned int iterator; for (iterator=0;iterator<numberOfVariables;iterator++){ cout << "Variable " << nameOfVariable[iterator] << " = " << valueOfVariable[iterator] << "\n"; } return 0; } //------------------------------------------------------------------- //Action node code //------------------------------------------------------------------- ess::actionnode::actionnode(){ ess::actionnode::act=act_null; ess::actionnode::value=0; ess::actionnode::actFuncPara.empty(); ess::actionnode::oper=oper_add; ess::actionnode::left=NULL; ess::actionnode::right=NULL; } ess::actionnode::actionnode(double number){ ess::actionnode::act=act_num; ess::actionnode::value=number; ess::actionnode::actFuncPara.empty(); ess::actionnode::oper=oper_add; ess::actionnode::left=NULL; ess::actionnode::right=NULL; } ess::actionnode::actionnode(ess::oper oper){ ess::actionnode::act=act_oper; ess::actionnode::value=0; ess::actionnode::actFuncPara.empty(); ess::actionnode::oper=oper; ess::actionnode::left=NULL; ess::actionnode::right=NULL; } double ess::actionnode::calculate(){ switch (act) { case act_null: return std::nan(""); case act_num: return value; break; case act_oper: if (left == NULL || right == NULL) { return 0; break; } switch (oper) { case oper_add: return left->calculate()+right->calculate(); break; case oper_min: return left->calculate()-right->calculate(); break; case oper_mul: return left->calculate()*right->calculate(); break; case oper_div: return left->calculate()/right->calculate(); break; } } } int ess::actionnode::printnode(){ switch (act) { case act_null: std::cout << "***NULLNODE***"; break; case act_oper: left->printnode(); switch (oper){ case oper_add: std::cout << '+'; break; case oper_min: std::cout << '-'; break; case oper_mul: std::cout << '*'; break; case oper_div: std::cout << '/'; break; } right->printnode(); break; case act_num: std::cout << value; } return 0; } int ess::actionnode::setleft(actionnode *left1){ left=left1; return 0; } int ess::actionnode::setright(actionnode *right1){ right = right1; return 0; } ess::actiontree::actiontree(ess::actionnode *topin){ top=topin; } double ess::actiontree::calculate(){ return top->calculate(); } int ess::actiontree::printtree(){ top->printnode(); std::cout << std::endl; return 0; } ess::mathfun::parsefunc(){ std::string a; cin >> &a; a. }
25.26699
132
0.620365
dd50ebbb858c8453eb9a4bd8aabf945f87c3bd67
1,716
hpp
C++
HugeCTR/include/pybind/data_source_wrapper.hpp
mikemckiernan/HugeCTR
1a0a618f9848eb908e9d1265c555fba9924d2861
[ "Apache-2.0" ]
130
2021-10-11T11:55:28.000Z
2022-03-31T21:53:07.000Z
HugeCTR/include/pybind/data_source_wrapper.hpp
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
72
2021-10-09T04:59:09.000Z
2022-03-31T11:27:54.000Z
HugeCTR/include/pybind/data_source_wrapper.hpp
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
29
2021-11-03T22:35:01.000Z
2022-03-30T13:11:59.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #pragma once #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <hdfs_backend.hpp> namespace HugeCTR { namespace python_lib { void DataSourcePybind(pybind11::module &m) { pybind11::module data = m.def_submodule("data", "data submodule of hugectr"); pybind11::class_<HugeCTR::DataSourceParams, std::shared_ptr<HugeCTR::DataSourceParams>>( data, "DataSourceParams") .def(pybind11::init<const bool, const std::string &, const int>(), pybind11::arg("use_hdfs") = false, pybind11::arg("namenode") = "localhost", pybind11::arg("port") = 9000) .def_readwrite("use_hdfs", &HugeCTR::DataSourceParams::use_hdfs) .def_readwrite("namenode", &HugeCTR::DataSourceParams::namenode) .def_readwrite("port", &HugeCTR::DataSourceParams::port); pybind11::class_<HugeCTR::DataSource, std::shared_ptr<HugeCTR::DataSource>>(data, "DataSource") .def(pybind11::init<const DataSourceParams &>(), pybind11::arg("data_source_params")) .def("move_to_local", &HugeCTR::DataSource::move_to_local); } } // namespace python_lib } // namespace HugeCTR
41.853659
97
0.7162
dd53adb8829fe1a6c7df45a709fbe0d46c630245
2,221
cc
C++
base/base_paths_android.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
base/base_paths_android.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
base/base_paths_android.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Defines base::PathProviderAndroid which replaces base::PathProviderPosix for // Android in base/path_service.cc. #include <limits.h> #include <unistd.h> #include "base/android/jni_android.h" #include "base/android/path_utils.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/notreached.h" #include "base/process/process_metrics.h" namespace base { bool PathProviderAndroid(int key, FilePath* result) { switch (key) { case base::FILE_EXE: { FilePath bin_dir; if (!ReadSymbolicLink(FilePath(kProcSelfExe), &bin_dir)) { NOTREACHED() << "Unable to resolve " << kProcSelfExe << "."; return false; } *result = bin_dir; return true; } case base::FILE_MODULE: // dladdr didn't work in Android as only the file name was returned. NOTIMPLEMENTED(); return false; case base::DIR_MODULE: return base::android::GetNativeLibraryDirectory(result); case base::DIR_SRC_TEST_DATA_ROOT: case base::DIR_GEN_TEST_DATA_ROOT: // These are only used by tests. In that context, they are overridden by // PathProviders in //base/test/test_support_android.cc. NOTREACHED(); return false; case base::DIR_USER_DESKTOP: // Android doesn't support GetUserDesktop. NOTIMPLEMENTED(); return false; case base::DIR_CACHE: return base::android::GetCacheDirectory(result); case base::DIR_ASSETS: // On Android assets are normally loaded from the APK using // base::android::OpenApkAsset(). In tests, since the assets are no // packaged, DIR_ASSETS is overridden to point to the build directory. return false; case base::DIR_ANDROID_APP_DATA: return base::android::GetDataDirectory(result); case base::DIR_ANDROID_EXTERNAL_STORAGE: return base::android::GetExternalStorageDirectory(result); } // For all other keys, let the PathService fall back to a default, if defined. return false; } } // namespace base
33.651515
80
0.697434
dd542d215fe0fe0fb9d485c8e756b68b4c9ebd9e
2,151
cpp
C++
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
//1 #include <CGAL/Exact_predicates_exact_constructions_kernel.h> typedef CGAL::Exact_predicates_exact_constructions_kernel K; typedef K::Point_2 P; typedef K::Segment_2 S; typedef K::Ray_2 R; using namespace std; double floor_to_double(const K::FT& x) { double a = std::floor(CGAL::to_double(x)); while (a > x) a -= 1; while (a+1 <= x) a += 1; return a; } int main() { ios_base::sync_with_stdio(false); int n; std::cin >> n; while(n > 0) { long x, y, a, b; cin >> x; cin >> y; cin >> a; cin >> b; P source = P(x,y); P closest_hit; R ray(source, P(a,b)); S hit_seg; bool hits = false; vector<S> segments(n); for(int i = 0; i < n; i++) { long r, s, t, u; cin >> r; cin >> s; cin >> t; cin >> u; P seg_p1 = P(r,s); P seg_p2 = P(t,u); S seg(seg_p1, seg_p2); segments[i] = seg; } random_shuffle(segments.begin(), segments.end()); for(int i = 0; i < n; i++) { S seg = segments[i]; P seg_p1 = seg.source(); P seg_p2 = seg.target(); if(!hits && CGAL::do_intersect(ray,seg)) { // no hit yet, i.e. only have ray auto o = CGAL::intersection(ray,seg); if (const P* op = boost::get<P>(&*o)) { // point intersec closest_hit = *op; } else { // segment intersec closest_hit = CGAL::has_larger_distance_to_point(source, seg_p1, seg_p2) ? seg_p2 : seg_p1; } hit_seg = S(source, closest_hit); hits = true; } else if(CGAL::do_intersect(hit_seg,seg)) { // hit once, so we have a segment auto o = CGAL::intersection(hit_seg,seg); if (const P* op = boost::get<P>(&*o)) { // point intersec closest_hit = *op; hit_seg = S(source, closest_hit); } else { // segment intersec closest_hit = CGAL::has_larger_distance_to_point(source, seg_p1, seg_p2) ? seg_p2 : seg_p1; hit_seg = S(source, closest_hit); } } } if(!hits) cout << "no" << endl; else cout << long(floor_to_double(closest_hit.x())) << " " << long(floor_to_double(closest_hit.y())) << endl; cin >> n; } }
29.875
111
0.55881
dd552ff3fb052cc6a64cc3f993fc688091cbefe2
862
cpp
C++
Notebook/src-bkp/Highly Decomposite Number.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Notebook/src-bkp/Highly Decomposite Number.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Notebook/src-bkp/Highly Decomposite Number.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
bool p[MAXN]; vector<int> primes; void build(void) { memset(p, true, sizeof(p)); for (int i = 2; i <= MAXN; i++) { if (p[i]) { primes.push_back(i); for (int j = i * i; j <= MAXN; j += i) { p[j] = false; } } } } int func(Int x) { int ans = 1; for (int i = 0; i < (int) primes.size() && x > 1; i++) { if (x % primes[i] == 0) { int curr = 0; while (x % primes[i] == 0) { x /= primes[i]; curr += 1; } ans *= (curr + 1); } } return ans; } set<Int> st; void go(int id, Int v, int last) { Int base = primes[id]; if (v > MAXV) return; st.insert(v); for (int i = 0; i <= last; i++) { v *= (Int) base; if (v > MAXV) break; go(id + 1, v, i); } } vector<Int> ans; for (set<Int>::iterator it = st.begin(); it != st.end(); it++) { int s = func(*it); if (s > curr) { ans.push_back(*it); curr = s; } }
15.392857
64
0.474478
dd55c9a76e5fab0d929abdd83067aeef115e8bf4
64
cc
C++
MCDataProducts/src/CrvDigiMC.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
MCDataProducts/src/CrvDigiMC.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
MCDataProducts/src/CrvDigiMC.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#include "MCDataProducts/inc/CrvDigiMC.hh" namespace mu2e { }
10.666667
42
0.75
dd577fbba4ad66aad44dc64db78a2025c5131ea1
478
cpp
C++
main.cpp
duongnb09/Davim_TAC
9be613a7ab68e2ba13e9a0b67a0279d403fe1ecb
[ "MIT" ]
1
2021-04-11T14:17:32.000Z
2021-04-11T14:17:32.000Z
main.cpp
duongnb09/Davim_TAC
9be613a7ab68e2ba13e9a0b67a0279d403fe1ecb
[ "MIT" ]
1
2021-11-03T12:49:50.000Z
2021-11-03T12:49:50.000Z
main.cpp
duongnb09/Davim_TAC
9be613a7ab68e2ba13e9a0b67a0279d403fe1ecb
[ "MIT" ]
2
2020-09-29T07:12:18.000Z
2021-07-05T15:41:56.000Z
/*========================================================================= Program: Flow Visualization Module: main.cpp Copyright (c) 2018 Duong B. Nguyen All rights reserved. See LICENSE for details =========================================================================*/ #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
20.782609
75
0.433054
dd5bd5d2272934b306850d72505e29339fcaf099
2,006
cc
C++
cpp/functions/run/run_benchmark_santos.cc
michieluithetbroek/A-MDVRP
fe7739f3961ddb25db8f64ec20472915d3c95168
[ "MIT" ]
23
2020-04-09T16:33:23.000Z
2022-03-21T16:41:11.000Z
cpp/functions/run/run_benchmark_santos.cc
michieluithetbroek/A-MDVRP
fe7739f3961ddb25db8f64ec20472915d3c95168
[ "MIT" ]
2
2020-04-10T11:55:28.000Z
2020-04-10T12:11:51.000Z
cpp/functions/run/run_benchmark_santos.cc
michieluithetbroek/A-MDVRP
fe7739f3961ddb25db8f64ec20472915d3c95168
[ "MIT" ]
10
2020-05-28T18:59:52.000Z
2022-03-10T13:32:44.000Z
#include "./../../main.ih" /* * This functions runs all the instances from Santos * * TODO remove bool deterministic */ void run_benchmark_santos(int idx_instance, bool deterministic, int rep) { bool const withoutGurobi = false; if (not deterministic) throw string("Opportunistic run is not allowed! (run_benchmark_santos)"); g_cutPasses = 500; g_userSettingA = 200; //200; g_userSettingB = 200; g_cplexFocusLB = true; // CPLEX focussed on LB g_onlyRoot = false; // Solve the whole branch-and-bound g_cplexCuts = true; // 0 = with cplex cuts, -1 = without g_useGurobi = true; if (withoutGurobi) { g_cplexFocusLB = false; // CPLEX focussed on LB g_onlyRoot = false; // Solve the whole branch-and-bound g_cplexCuts = true; // 0 = with cplex cuts, -1 = without g_useGurobi = false; } int const cutProfile = 1; /* * The following sets the global enums INSTANCE and DATA_ASYMMETRY * This is used in the Data struct to set the costs and to activate * the proper constraints in the ModelA class. * */ hash_and_set_globals(12, 0); Data data (idx_instance); if (deterministic and not withoutGurobi) { string folder("results/santos/" + to_string(idx_instance) + "_nThreads-" + to_string(g_nThreads) + "_rep-" + to_string(rep)); run_single_instance(data, folder, cutProfile); } else if (deterministic and withoutGurobi) { cout << "without Gurobi!" << endl; string folder("results/santos/" + to_string(idx_instance) + "_nThreads-" + to_string(g_nThreads) + "_withoutGurobi" + "_rep-" + to_string(rep)); run_single_instance(data, folder, cutProfile); } else { string folder("results/santos/" + to_string(idx_instance) + "_par_" + to_string(rep)); run_single_instance(data, folder, cutProfile); } }
24.168675
77
0.621137
dd5f44f135378685091c3e4105c9a09dec58f000
2,639
cpp
C++
src/main.cpp
finnff/IPASS-19
b65ad79282a63c1f0db3addfaf865e99677ecd2c
[ "MIT" ]
null
null
null
src/main.cpp
finnff/IPASS-19
b65ad79282a63c1f0db3addfaf865e99677ecd2c
[ "MIT" ]
null
null
null
src/main.cpp
finnff/IPASS-19
b65ad79282a63c1f0db3addfaf865e99677ecd2c
[ "MIT" ]
null
null
null
#include "mpu6050.hpp" #include "pongresources.hpp" int main(int argc, char **argv) { namespace target = hwlib::target; // Intialize OLED display auto scl = target::pin_oc(target::pins::d10); auto sda = target::pin_oc(target::pins::d11); auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda); auto w = hwlib::glcd_oled(i2c_bus, 0x3c); // Intialize i2c bus for use with 2x gy-521 Breakout boards auto scl1 = target::pin_oc(target::pins::d21); auto sda1 = target::pin_oc(target::pins::d20); auto iic = hwlib::i2c_bus_bit_banged_scl_sda(scl1, sda1); auto chipL = mpu6050(iic, 0x68); // AD0 LOW auto chipR = mpu6050(iic, 0x69); // AD0 HI chipL.init(); chipR.init(); int rwidth = 128; // Set screen width resolution , OLED is 128*64, used for scaling int rheight = 64; int Lscore = 0; // init score int Rscore = 0; RandomBall b(w, 128, 64); // Construct random ball object bat r(w, hwlib::xy((rwidth - (rwidth / 10)) - 2, rheight / 2), hwlib::xy((rwidth - (rwidth / 10)), ((rheight / 2) + (rheight / 5)))); bat l(w, hwlib::xy(rwidth / 10, rheight / 2), hwlib::xy((rwidth / 10 + 2), ((rheight / 2) + (rheight / 5)))); for (;;) { int lroll = chipL.readRollAngle(); // read roll angle of MPU6050, this is // the input of the game. int rroll = chipR.readRollAngle(); w.clear(); if (lroll < -30 && l.start.y > 0) { l.moveup(); } if (lroll > 30 && l.end.y < rheight) { l.movedown(); } if (rroll < -30 && r.start.y > 0) { r.moveup(); } if (rroll > 30 && r.end.y < rheight) { r.movedown(); } r.draw(); l.draw(); b.move(); if (b.end.x == (rwidth - (rwidth / 10) - 2) || b.end.x == (rwidth - (rwidth / 10) - 3)) { // Right Collision if (b.start.y <= r.end.y && b.start.y >= r.start.y) { b.change_speed_factor(-1, 1); } else { Lscore++; // Lose condition hwlib::cout << Lscore << " - " << Rscore << hwlib::endl; hwlib::wait_ms(500); b.reset(); } } if (b.start.x == (rwidth / 10) + 1 || b.start.x == (rwidth / 10)) { // Left Collision if (b.start.y <= l.end.y && b.start.y >= l.start.y) { b.change_speed_factor(-1, 1); } else { Rscore++; // Lose condition hwlib::cout << Lscore << " - " << Rscore << hwlib::endl; hwlib::wait_ms(500); b.reset(); } } if (b.start.y >= rheight - 1 || b.start.y <= 0) { // Bounce top/bottom of screen b.change_speed_factor(1, -1); } w.flush(); } }
29.322222
78
0.535809
e578239b4948fa914b39f0e674029a09d13b6d54
7,285
cpp
C++
src/engine/drawSys.cpp
karwler/BKGraph
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
[ "WTFPL" ]
null
null
null
src/engine/drawSys.cpp
karwler/BKGraph
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
[ "WTFPL" ]
null
null
null
src/engine/drawSys.cpp
karwler/BKGraph
1b65f82d4c44e3982cf6cef775e88a16c857d6e3
[ "WTFPL" ]
2
2017-11-09T16:14:39.000Z
2018-02-08T19:09:40.000Z
#include "world.h" // FONT SET FontSet::FontSet(const string& path) : file(path) { // check if font can be loaded TTF_Font* tmp = TTF_OpenFont(file.c_str(), Default::fontTestHeight); if (!tmp) throw "Couldn't open font " + file + '\n' + TTF_GetError(); // get approximate height scale factor int size; TTF_SizeUTF8(tmp, Default::fontTestString, nullptr, &size); heightScale = float(Default::fontTestHeight) / float(size); TTF_CloseFont(tmp); } FontSet::~FontSet() { for (const pair<const int, TTF_Font*>& it : fonts) TTF_CloseFont(it.second); } void FontSet::clear() { for (const pair<const int, TTF_Font*>& it : fonts) TTF_CloseFont(it.second); fonts.clear(); } TTF_Font* FontSet::addSize(int size) { TTF_Font* font = TTF_OpenFont(file.c_str(), size); if (font) fonts.insert(make_pair(size, font)); return font; } TTF_Font* FontSet::getFont(int height) { height = int(float(height) * heightScale); return fonts.count(height) ? fonts.at(height) : addSize(height); // load font if it hasn't been loaded yet } int FontSet::length(const string& text, int height) { int len = 0; TTF_Font* font = getFont(height); if (font) TTF_SizeUTF8(font, text.c_str(), &len, nullptr); return len; } // DRAW SYS DrawSys::DrawSys(SDL_Window* window, int driverIndex) : fontSet(Filer::findFont(World::winSys()->getSettings().font)) { renderer = SDL_CreateRenderer(window, driverIndex, Default::rendererFlags); if (!renderer) throw "Couldn't create renderer:\n" + string(SDL_GetError()); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); } DrawSys::~DrawSys() { SDL_DestroyRenderer(renderer); } SDL_Rect DrawSys::viewport() const { SDL_Rect view; SDL_RenderGetViewport(renderer, &view); return view; } SDL_Texture* DrawSys::renderText(const string& text, int height, vec2i& size) { if (text.empty()) { // not possible to draw empty text size = 0; return nullptr; } SDL_Surface* surf = TTF_RenderUTF8_Blended(fontSet.getFont(height), text.c_str(), Default::colorText); SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf); size = vec2i(surf->w, surf->h); SDL_FreeSurface(surf); return tex; } void DrawSys::drawWidgets() { SDL_SetRenderDrawColor(renderer, Default::colorBackground.r, Default::colorBackground.g, Default::colorBackground.b, Default::colorBackground.a); SDL_RenderClear(renderer); World::scene()->getLayout()->drawSelf(); // draw main widgets if (World::scene()->getPopup()) { // draw popup if exists and dim main widgets SDL_Rect view = viewport(); SDL_SetRenderDrawColor(renderer, Default::colorPopupDim.r, Default::colorPopupDim.g, Default::colorPopupDim.b, Default::colorPopupDim.a); SDL_RenderFillRect(renderer, &view); World::scene()->getPopup()->drawSelf(); } if (World::scene()->getContext()) // draw context if exists drawContext(World::scene()->getContext()); if (LineEdit* let = dynamic_cast<LineEdit*>(World::scene()->capture)) // draw caret if capturing LineEdit drawRect(let->caretRect(), Default::colorLight); SDL_RenderPresent(renderer); } void DrawSys::drawButton(Button* wgt) { drawRect(overlapRect(wgt->rect(), wgt->parentFrame()), Default::colorNormal); } void DrawSys::drawCheckBox(CheckBox* wgt) { SDL_Rect frame = wgt->parentFrame(); drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background drawRect(overlapRect(wgt->boxRect(), frame), wgt->on ? Default::colorLight : Default::colorDark); // draw checkbox } void DrawSys::drawColorBox(ColorBox* wgt) { SDL_Rect frame = wgt->parentFrame(); drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background drawRect(overlapRect(wgt->boxRect(), frame), wgt->color); // draw colorbox } void DrawSys::drawSlider(Slider* wgt) { SDL_Rect frame = wgt->parentFrame(); drawRect(overlapRect(wgt->rect(), frame), Default::colorNormal); // draw background drawRect(overlapRect(wgt->barRect(), frame), Default::colorDark); // draw bar drawRect(overlapRect(wgt->sliderRect(), frame), Default::colorLight); // draw slider } void DrawSys::drawLabel(Label* wgt) { SDL_Rect rect = overlapRect(wgt->rect(), wgt->parentFrame()); drawRect(rect, Default::colorNormal); // draw background if (wgt->tex) { // modify frame and draw text if exists rect.x += Default::textOffset; rect.w -= Default::textOffset * 2; drawText(wgt->tex, wgt->textRect(), rect); } } void DrawSys::drawGraphView(GraphView* wgt) { vec2i pos = wgt->position(); vec2i siz = wgt->size(); int endy = pos.y + siz.y; // draw lines vec2i lstt = vec2i(dotToPix(vec2f(World::winSys()->getSettings().viewPos.x, 0.f), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos; drawLine(lstt, vec2i(lstt.x + siz.x - 1, lstt.y), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y}); lstt = vec2i(dotToPix(vec2f(0.f, World::winSys()->getSettings().viewPos.y), World::winSys()->getSettings().viewPos, World::winSys()->getSettings().viewSize, vec2f(siz))) + pos; drawLine(lstt, vec2i(lstt.x, lstt.y + siz.y - 1), Default::colorGraph, {pos.x, pos.y, siz.x, siz.y}); // draw graphs for (const Graph& it : wgt->getGraphs()) { SDL_Color color = World::program()->getFunction(it.fid).color; SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); sizt start = 0; bool lastIn = false; for (sizt x=0; x<it.pixs.size(); x++) { bool curIn = inRange(it.pixs[x].y, pos.y, endy); if (curIn) { if (!lastIn) start = x; } else if (lastIn) SDL_RenderDrawLines(renderer, &it.pixs[start], int(x-start)); lastIn = curIn; } if (lastIn) SDL_RenderDrawLines(renderer, &it.pixs[start], int(it.pixs.size()-start)); } } void DrawSys::drawScrollArea(ScrollArea* box) { vec2t vis = box->visibleWidgets(); // get index interval of items on screen and draw children for (sizt i=vis.l; i<vis.u; i++) box->getWidget(i)->drawSelf(); drawRect(box->barRect(), Default::colorDark); // draw scroll bar drawRect(box->sliderRect(), Default::colorLight); // draw scroll slider } void DrawSys::drawPopup(Popup* pop) { drawRect(pop->rect(), Default::colorNormal); // draw background for (Widget* it : pop->getWidgets()) // draw children it->drawSelf(); } void DrawSys::drawContext(Context* con) { SDL_Rect rect = con->rect(); drawRect(rect, Default::colorLight); // draw background const vector<ContextItem>& items = con->getItems(); for (sizt i=0; i<items.size(); i++) // draw items aka. text drawText(items[i].tex, con->itemRect(i), rect); } void DrawSys::drawRect(const SDL_Rect& rect, SDL_Color color) { SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); SDL_RenderFillRect(renderer, &rect); } void DrawSys::drawLine(vec2i pos, vec2i end, SDL_Color color, const SDL_Rect& frame) { if (cropLine(pos, end, frame)) { SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); SDL_RenderDrawLine(renderer, pos.x, pos.y, end.x, end.y); } } void DrawSys::drawText(SDL_Texture* tex, const SDL_Rect& rect, const SDL_Rect& frame) { // crop destination rect and original texture rect if (SDL_Rect dst; SDL_IntersectRect(&rect, &frame, &dst)) { SDL_Rect src = {dst.x - rect.x, dst.y - rect.y, dst.w, dst.h}; SDL_RenderCopy(renderer, tex, &src, &dst); } }
33.883721
183
0.700069
e57c906c68ba77d31d2b02e65cc1fbd6aa245ee8
4,123
cpp
C++
solution/solutionthread.cpp
vitkorob/studentprojects
3b071eabec33f9e27eec81eaf5df339276c039be
[ "MIT" ]
null
null
null
solution/solutionthread.cpp
vitkorob/studentprojects
3b071eabec33f9e27eec81eaf5df339276c039be
[ "MIT" ]
null
null
null
solution/solutionthread.cpp
vitkorob/studentprojects
3b071eabec33f9e27eec81eaf5df339276c039be
[ "MIT" ]
null
null
null
#include "solutionthread.h" solutionThread::solutionThread() { metRKu = 1; gam = 0.2; g = 9.81; L = 2; del = 0.9; p2 = 4; eps = 0.0005; x0 = 2; v0 = 3; t = 30; step = 0.01; } double solutionThread::p(double y2) { return y2; } double solutionThread::q(double x2, double y2, double t2) { return ((-1) * gam * y2) - g * x2 / (L * (1 + del * cos(p2 * t2))); } void solutionThread::nextValueEuler(double *x, double *y, double t, double h) { *x += h * p(*y); *y += h * q(*x, *y, t); } void solutionThread::nextValueRKutt(double *x, double *y, double t, double h) { double x1 = h * p(*y); double y1 = h * q(*x, *y, t); double x2 = h * p(*y + y1 * 0.5); double y2 = h * q(*x + x1 * 0.5, *y + y1 * 0.5, t + h * 0.5); double x3 = h * p(*y + y2 * 0.5); double y3 = h * q(*x + x2 * 0.5, *y + y2 * 0.5, t + h * 0.5); double x4 = h * p(*y + y3); double y4 = h * q(*x + x3, *y + y3, t + h); *x += (x1 + 2 * x2 + 2 * x3 + x4) / 6; *y += (y1 + 2 * y2 + 2 * y3 + y4) / 6; } void solutionThread::run() { pnt_t.clear(); pnt_x.clear(); pnt_y.clear(); pnt_t.append(0); pnt_x.append(x0); pnt_y.append(v0); double next_t0 = 0; FILE *data = fopen("ivan-data.txt", "w"); fprintf(data, "%f\t%f\t%f\n", 0.0, x0, v0); FILE *fileMetod = fopen("ivan-step.txt", "a"); double next_x0; double next_y0; double next_x1; double next_y1; double next_x2; double next_y2; double next_x3; double next_y3; double next_x_tmp = x0; double next_y_tmp = v0; if(metRKu) { while(next_t0 < t) { next_x0 = next_x1 = next_x2 = next_x_tmp; next_y0 = next_y1 = next_y2 = next_y_tmp; nextValueRKutt(&next_x0, &next_y0, next_t0, step); nextValueRKutt(&next_x1, &next_y1, next_t0, 2 * step); next_x3 = next_x0; next_y3 = next_y0; nextValueRKutt(&next_x3, &next_y3, next_t0 + step, step); nextValueRKutt(&next_x2, &next_y2, next_t0, 0.5 * step); nextValueRKutt(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step); if((fabs(next_x0 - next_x2) / 15 <= eps && fabs(next_x3 - next_x1) / 15 > eps) || next_y_tmp == 0) { pnt_t.append(next_t0 += step); pnt_x.append(next_x_tmp = next_x0); pnt_y.append(next_y_tmp = next_y0); fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0); } else if(fabs(next_x3 - next_x1) / 15 < eps) { step *= 2; } else { step *= 0.5; } } fprintf(fileMetod, "rkutt\t%.18lf\t%.18lf\n", eps, t / pnt_t.size()); fclose(fileMetod); } else { while(next_t0 < t) { next_x0 = next_x1 = next_x2 = next_x_tmp; next_y0 = next_y1 = next_y2 = next_y_tmp; nextValueEuler(&next_x0, &next_y0, next_t0, step); nextValueEuler(&next_x1, &next_y1, next_t0, 2 * step); next_x3 = next_x0; next_y3 = next_y0; nextValueEuler(&next_x3, &next_y3, next_t0 + step, step); nextValueEuler(&next_x2, &next_y2, next_t0, 0.5 * step); nextValueEuler(&next_x2, &next_y2, next_t0 + 0.5 * step, 0.5 * step); if((fabs(next_x0 - next_x2) <= eps && fabs(next_x3 - next_x1) > eps) || next_y_tmp == 0) { pnt_t.append(next_t0 += step); pnt_x.append(next_x_tmp = next_x0); pnt_y.append(next_y_tmp = next_y0); fprintf(data, "%f\t%f\t%f\n", next_t0, next_x0, next_y0); } else if(fabs(next_x3 - next_x1) < eps) { step *= 2; } else { step *= 0.5; } } fprintf(fileMetod, "euler\t%.18lf\t%.18lf\n", eps, t / pnt_t.size()); fclose(fileMetod); } fclose(data); }
25.140244
110
0.489207
e57c9863ca18340b608f0fa9bc4715893eb932b2
1,303
cxx
C++
Qt/Components/pqColorOverlay.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
815
2015-01-03T02:14:04.000Z
2022-03-26T07:48:07.000Z
Qt/Components/pqColorOverlay.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
9
2015-04-28T20:10:37.000Z
2021-08-20T18:19:01.000Z
Qt/Components/pqColorOverlay.cxx
xj361685640/ParaView
0a27eef5abc5a0c0472ab0bc806c4db881156e64
[ "Apache-2.0", "BSD-3-Clause" ]
328
2015-01-22T23:11:46.000Z
2022-03-14T06:07:52.000Z
#include "pqColorOverlay.h" #include <QPainter> //----------------------------------------------------------------------------- pqColorOverlay::pqColorOverlay(QWidget* parent) : QWidget(parent) { setAttribute(Qt::WA_NoSystemBackground); setAttribute(Qt::WA_TransparentForMouseEvents); } //----------------------------------------------------------------------------- QColor pqColorOverlay::rgb() const { return Rgba; } //----------------------------------------------------------------------------- void pqColorOverlay::setRgb(int r, int g, int b) { Rgba.setRgb(r, g, b); this->repaint(); } //----------------------------------------------------------------------------- void pqColorOverlay::setRgb(QColor rgb) { Rgba.setRgb(rgb.red(), rgb.green(), rgb.blue()); this->repaint(); } //----------------------------------------------------------------------------- int pqColorOverlay::opacity() const { return Rgba.alpha(); } //----------------------------------------------------------------------------- void pqColorOverlay::setOpacity(int opacity) { Rgba.setAlpha(opacity); this->repaint(); } //----------------------------------------------------------------------------- void pqColorOverlay::paintEvent(QPaintEvent*) { QPainter(this).fillRect(rect(), QBrush{ Rgba }); }
25.54902
79
0.403684
e57eee5672315a1c7762eba6e21dd57c0a8e7435
128
hpp
C++
Vendor/GLM/glm/ext/vector_uint1.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Vendor/GLM/glm/ext/vector_uint1.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Vendor/GLM/glm/ext/vector_uint1.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:936046e1e48adf16a2daa297a69e3318537c55f39572a05efbae9aca1479cf89 size 711
32
75
0.882813
e57f1c150401e191e72e2d45d0f8c099ca968370
1,190
cpp
C++
bin-inorder-preorder.cpp
ananyas2501/CS202
5cbfa83f1f93dec7b2fb8c84afd4142ff0f29fe1
[ "MIT" ]
null
null
null
bin-inorder-preorder.cpp
ananyas2501/CS202
5cbfa83f1f93dec7b2fb8c84afd4142ff0f29fe1
[ "MIT" ]
null
null
null
bin-inorder-preorder.cpp
ananyas2501/CS202
5cbfa83f1f93dec7b2fb8c84afd4142ff0f29fe1
[ "MIT" ]
1
2020-10-07T16:32:53.000Z
2020-10-07T16:32:53.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int search(int start, int end, vector <int> &inorder, int val) { for(int i=start; i<=end; i++) { if(inorder[i]==val) return i; } } TreeNode* build(int &preindex,vector<int> &pre, vector<int>&in, int startin, int endin) { if(startin>endin)return NULL; // cout<<"build?"<<endl; int val=pre[preindex]; preindex--; TreeNode* x= new TreeNode(val); if(startin==endin) return x; int position=search(startin, endin, in, val); x->right=build(preindex, pre, in, position+1, endin); x->left=build(preindex, pre, in, startin, position-1); return x; } TreeNode* Solution::buildTree(vector<int> &A, vector<int> &B){ int preindex=A.size()-1; int size=A.size(); TreeNode *ans= build(preindex, B, A, 0, size-1); // cout<<s; return ans; }
22.884615
87
0.582353
e57fbaf38376bfb6b8788e60265427cd6c14091e
3,882
hpp
C++
include/cynodelic/mulinum/detail/split_helpers.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
include/cynodelic/mulinum/detail/split_helpers.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
include/cynodelic/mulinum/detail/split_helpers.hpp
cynodelic/mulinum
fc7b9e750aadaede2cee8d840e65fa3832787764
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file split_helpers.hpp * * @brief Helpers for the `split` metafunction. */ #ifndef CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP #define CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP #include <cstddef> #include <cynodelic/mulinum/config.hpp> #include <cynodelic/mulinum/if.hpp> #include <cynodelic/mulinum/string.hpp> #include <cynodelic/mulinum/concat.hpp> #include <cynodelic/mulinum/make_from_tag.hpp> namespace cynodelic { namespace mulinum { namespace detail { /** * @brief Helper for @ref split. */ template <char, typename> struct split_remove_front_delims; /** * @brief Helper for @ref split. */ template <char Delim, char First_, char... Others_> struct split_remove_front_delims<Delim, string<First_, Others_...>> { using type = if_< (Delim == First_), typename split_remove_front_delims<Delim, string<Others_...>>::type, string<First_, Others_...> >; }; /** * @brief Helper for @ref split. */ template <char Delim, char Last_> struct split_remove_front_delims<Delim, string<Last_>> { using type = if_< (Delim == Last_), string<>, string<Last_> >; }; /** * @brief Helper for @ref split. */ template <char, std::size_t, typename, bool> struct split_make_delims_unique; /** * @brief Helper for @ref split. */ template <char Delim, std::size_t N, char First_, char Second_> struct split_make_delims_unique<Delim, N, string<First_, Second_>, true> { using type = if_< (First_ == Delim) && (Second_ == Delim), string<>, string<First_> >; }; /** * @brief Helper for @ref split. */ template <char Delim, std::size_t N, char First_, char Second_, char... Others_> struct split_make_delims_unique<Delim, N, string<First_, Second_, Others_...>, false> { using type = concat< if_< (First_ == Delim) && (Second_ == Delim), string<>, string<First_> >, typename split_make_delims_unique<Delim, N - 1, string<Second_, Others_...>, (N - 1) == 0>::type >; }; /** * @brief Helper for @ref split. */ template <char, typename> struct split_take_first_item; /** * @brief Helper for @ref split. */ template <char Delim, char First_, char... Others_> struct split_take_first_item<Delim, string<First_, Others_...>> { using type = if_< (First_ == Delim), string<>, concat< string<First_>, typename split_take_first_item<Delim, string<Others_...>>::type > >; }; /** * @brief Helper for @ref split. */ template <char Delim, char Last_> struct split_take_first_item<Delim, string<Last_>> { using type = if_< Last_ == Delim, string<>, string<Last_> >; }; /** * @brief Helper for @ref split. */ template <char Delim, typename StringT_, std::size_t From> using split_take_item = typename detail::split_take_first_item<Delim, take_c<StringT_, From, StringT_::size - From>>::type; /** * @brief Helper for @ref split. */ template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count, bool = (Count == StringT_::size)> struct splitter { using type = concat< make_from_tag<TypeContainerTag, split_take_item<Delim, StringT_, Count>>, typename splitter< TypeContainerTag, Delim, StringT_, (Count + split_take_item<Delim, StringT_, Count>::size + 1) >::type >; }; /** * @brief Helper for @ref split. */ template <typename TypeContainerTag, char Delim, typename StringT_, std::size_t Count> struct splitter<TypeContainerTag, Delim, StringT_, Count, true> { using type = make_from_tag<TypeContainerTag>; }; } // end of "detail" namespace }} // end of "cynodelic::mulinum" namespace #endif // CYNODELIC_MULINUM_DETAIL_SPLIT_HELPERS_HPP
21.687151
124
0.676455
e582a8d0fc49f20af9374fe9a7e4fda2278e60e7
129
cc
C++
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/google/protobuf/stubs/atomicops_internals_x86_msvc.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:516879d2c1b04ff8b7ba32487c8446e3241805e4352f374533aa6756863b4cad size 4366
32.25
75
0.883721
e5847e79f40e20540105d7d68c2b19de80dc5ceb
4,115
cpp
C++
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/FORA/TypedFora/ABI/MutableVectorHandleCodegen.cpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #include "MutableVectorHandleCodegen.hpp" #include "NativeLayoutType.hppml" #include "../../Judgment/JudgmentOnValue.hppml" #include "../../../core/SymbolExport.hpp" #include "../../../core/Logging.hpp" #include "../../Native/NativeCode.hppml" #include "../../Native/NativeTypeFor.hpp" #include "../../Native/NativeExpressionBuilder.hppml" #include "../../Native/TypedNativeLibraryFunction.hpp" #include "DestructorsAndConstructors.hppml" using TypedFora::Abi::MutableVectorHandle; NativeType NativeTypeForImpl<MutableVectorHandle>::get() { return NativeType::Composite("mRefcount", NativeType::uword()) + NativeType::Composite("mSize", NativeType::uword()) + NativeType::Composite("mRawDataPtr", NativeType::uint8().ptr()) + NativeType::Composite("mOwningMemoryPool", NativeType::Nothing().ptr()) + NativeType::Composite("mElementJOV", NativeTypeFor<JudgmentOnValue>::get()) + NativeType::Composite("mVectorHash", NativeTypeFor<hash_type>::get()) ; } extern "C" { BSA_DLLEXPORT void FORA_clib_incrementMutableVectorHandleRefcount(MutableVectorHandle* handle) { handle->incrementRefcount(); } BSA_DLLEXPORT uint8_t FORA_clib_decrementMutableVectorHandleRefcount(MutableVectorHandle* handle) { return handle->decrementRefcount(); } } namespace TypedFora { namespace Abi { namespace MutableVectorHandleCodegen { NativeExpression sizeExpression( const NativeExpression& arrayPtrE ) { lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr()); return arrayPtrE["mSize"].load(); } NativeExpression incrementRefcountExpr( const NativeExpression& arrayPtrE ) { lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr()); return makeTypedNativeLibraryFunction( &FORA_clib_incrementMutableVectorHandleRefcount )(arrayPtrE).getExpression() ; } NativeExpression decrementRefcountExpr( const NativeExpression& arrayPtrE ) { lassert(*arrayPtrE.type() == NativeTypeFor<MutableVectorHandle>::get().ptr()); return makeTypedNativeLibraryFunction( &FORA_clib_decrementMutableVectorHandleRefcount )(arrayPtrE).getExpression() ; } NativeExpression basePointerExpressionAsRawPtr( const NativeExpression& arrayPtrE ) { return arrayPtrE["mRawDataPtr"] .load() ; } NativeExpression getItemExpr( const NativeExpression& arrayPtrE, const NativeExpression& indexE, const JudgmentOnValue& elementJov ) { if (elementJov.constant()) return NativeExpression(); return TypedFora::Abi::duplicate( elementJov, arrayPtrE["mRawDataPtr"] .load() .cast(nativeLayoutType(elementJov).ptr(), true) [indexE].load() ); } NativeExpression setItemExpr( const NativeExpression& arrayPtrE, const NativeExpression& indexE, const NativeExpression& dataE, const JudgmentOnValue& elementJov ) { NativeExpressionBuilder builder; if (elementJov.constant()) return NativeExpression(); NativeExpression eltPtr = builder.add( arrayPtrE["mRawDataPtr"].load() .cast(nativeLayoutType(elementJov).ptr(), false) [indexE] ); NativeExpression duplicatedVal = builder.add( TypedFora::Abi::duplicate(elementJov, dataE) ); builder.add( TypedFora::Abi::destroy(elementJov, eltPtr.load()) ); builder.add( eltPtr.store(duplicatedVal) ); return builder(NativeExpression()); } } } }
25.401235
83
0.710814
e586cb9547fbb7a410e2af42433496cd9ae6ab0c
3,417
cxx
C++
private/inet/mshtml/src/site/ole/frame.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/site/ole/frame.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/site/ole/frame.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------- // // File: frame.cxx // // Contents: frame tag implementation // // Classes: CFrameSite, etc.. // //------------------------------------------------------------------------ #include "headers.hxx" #ifndef X_FORMKRNL_HXX_ #define X_FORMKRNL_HXX_ #include "formkrnl.hxx" #endif #ifndef X_FRAME_HXX_ #define X_FRAME_HXX_ #include "frame.hxx" #endif #ifndef X_FRAMESET_HXX_ #define X_FRAMESET_HXX_ #include "frameset.hxx" #endif #ifndef X_PROPS_HXX_ #define X_PROPS_HXX_ #include "props.hxx" #endif #define _cxx_ #include "frame.hdl" MtDefine(CFrameElement, Elements, "CFrameElement") MtDefine(CIFrameElement, Elements, "CIFrameElement") const CElement::CLASSDESC CFrameElement::s_classdesc = { { &CLSID_HTMLFrameElement, // _pclsid 0, // _idrBase #ifndef NO_PROPERTY_PAGE s_apclsidPages, // _apClsidPages #endif // NO_PROPERTY_PAGE s_acpi, // _pcpi ELEMENTDESC_NEVERSCROLL | ELEMENTDESC_OLESITE, // _dwFlags &IID_IHTMLFrameElement, // _piidDispinterface &s_apHdlDescs, // _apHdlDesc }, (void *)s_apfnpdIHTMLFrameElement, // _pfnTearOff NULL, // _pAccelsDesign NULL // _pAccelsRun }; //+--------------------------------------------------------------------------- // // element creator used by parser // //---------------------------------------------------------------------------- HRESULT CFrameElement::CreateElement(CHtmTag *pht, CDoc *pDoc, CElement **ppElementResult) { Assert(ppElementResult); *ppElementResult = new CFrameElement(pDoc); RRETURN ( (*ppElementResult) ? S_OK : E_OUTOFMEMORY); } //+--------------------------------------------------------------------------- // // Member: CFrameElement constructor // //---------------------------------------------------------------------------- CFrameElement::CFrameElement(CDoc *pDoc) : CFrameSite(ETAG_FRAME, pDoc) { } //+---------------------------------------------------------------------------- // // Member: CFrameElement:get_height // //----------------------------------------------------------------------------- STDMETHODIMP CFrameElement::get_height(VARIANT * p) { HRESULT hr = S_OK; if (p) { V_VT(p) = VT_I4; CLayout * pLayout = GetCurLayout(); V_I4(p) = pLayout->GetHeight(); } RRETURN(SetErrorInfo(hr)); } STDMETHODIMP CFrameElement::put_height(VARIANT p) { RRETURN(SetErrorInfo(CTL_E_METHODNOTAPPLICABLE)); } //+---------------------------------------------------------------------------- // // Member: CFrameElement:get_width // //----------------------------------------------------------------------------- STDMETHODIMP CFrameElement::get_width(VARIANT * p) { HRESULT hr = S_OK; if (p) { V_VT(p) = VT_I4; CLayout * pLayout = GetCurLayout(); V_I4(p) = pLayout->GetWidth(); } RRETURN(SetErrorInfo(hr)); } STDMETHODIMP CFrameElement::put_width(VARIANT p) { RRETURN(SetErrorInfo(CTL_E_METHODNOTAPPLICABLE)); }
26.083969
80
0.458589
e5887ce1debe7449e1edd420a14fcb83002b21a4
12,076
cpp
C++
angsd/abcGL.cpp
peterdfields/angsd-wrapper
199abf0b513a763114511f08dfce742305f41a91
[ "MIT" ]
6
2015-07-25T02:05:07.000Z
2021-05-27T08:37:01.000Z
angsd/abcGL.cpp
peterdfields/angsd-wrapper
199abf0b513a763114511f08dfce742305f41a91
[ "MIT" ]
60
2015-01-10T20:46:25.000Z
2018-09-19T22:32:02.000Z
angsd/abcGL.cpp
peterdfields/angsd-wrapper
199abf0b513a763114511f08dfce742305f41a91
[ "MIT" ]
8
2015-04-12T09:37:58.000Z
2017-04-25T19:30:39.000Z
/* thorfinn thorfinn@binf.ku.dk dec17 2012 part of angsd This class will calculate the GL in 4 differnt ways 1) SAMtools 0.1.16+ version 2) Simple GATK model 3) SOAPsnp 4) SYK 4 different output formats are supplied 1) binary 10xdouble persample 2) beagle output (requires estimation of major/minor)\ 3) binary beagle 4) text output of the 10 llhs persample */ #include <cmath> #include <zlib.h> #include <assert.h> #include "kstring.h"//<-used for buffered output when dumping beagle 0.204 #include "bfgs.h" #include "analysisFunction.h" #include "abc.h" #include "abcGL.h" #include "abcError.h" extern int refToInt[256]; static float *logfactorial=NULL; void readError(double **errors,const char *fname){ fprintf(stderr,"will try to read errorestimates from file:%s\n",fname); FILE *fp=NULL; if(NULL==(fp=fopen(fname,"r"))){ fprintf(stderr,"Error opening file: %s\n",fname); exit(0); } char buf[LENS]; double res[16]; for(int i=0;i<16;i++) res[i] = 0; int nLines =0; while(fgets(buf,LENS,fp)){ res[0] += atof(strtok(buf," \t\n")); for(int i=1;i<16;i++) res[i] += atof(strtok(NULL," \t\n")); nLines ++; } for(int j=0;j<16;j++) fprintf(stderr,"%f\t",res[j]); fprintf(stderr,"\nEstimating errors using nChunks:%d\n",nLines); int pos =0; for(int i=0;i<4;i++) for(int j=0;j<4;j++) errors[i][j] = res[pos++]/(1.0*nLines); if(fp) fclose(fp); } void abcGL::printArg(FILE *argFile){ fprintf(argFile,"---------------------\n%s:\n",__FILE__); fprintf(argFile,"\t-GL=%d: \n",GL); fprintf(argFile,"\t1: SAMtools\n"); fprintf(argFile,"\t2: GATK\n"); fprintf(argFile,"\t3: SOAPsnp\n"); fprintf(argFile,"\t4: SYK\n"); fprintf(argFile,"\t-trim\t\t%d\t\t(zero means no trimming)\n",trim); fprintf(argFile,"\t-tmpdir\t\t%s/\t(used by SOAPsnp)\n",angsd_tmpdir); fprintf(argFile,"\t-errors\t\t%s\t\t(used by SYK)\n",errorFname); fprintf(argFile,"\t-minInd\t\t%d\t\t(0 indicates no filtering)\n",minInd); fprintf(argFile,"\n"); fprintf(argFile,"Filedumping:\n"); fprintf(argFile,"\t-doGlf\t%d\n",doGlf); fprintf(argFile,"\t1: binary glf (10 log likes)\t%s\n",postfix); fprintf(argFile,"\t2: beagle likelihood file\t%s\n",beaglepostfix); fprintf(argFile,"\t3: binary 3 times likelihood\t%s\n",postfix); fprintf(argFile,"\t4: text version (10 log likes)\t%s\n",postfix); fprintf(argFile,"\n"); } void abcGL::getOptions(argStruct *arguments){ //parse all parameters that this class could use GL=angsd::getArg("-GL",GL,arguments); trim = angsd::getArg("-trim",trim,arguments); angsd_tmpdir = angsd::getArg("-tmpdir",angsd_tmpdir,arguments); doGlf=angsd::getArg("-doGlf",doGlf,arguments); errorFname = angsd::getArg("-errors",errorFname,arguments); minInd = angsd::getArg("-minInd",minInd,arguments); int doCounts=0; int doMajorMinor =0; doCounts=angsd::getArg("-doCounts",doCounts,arguments); doMajorMinor=angsd::getArg("-doMajorMinor",doMajorMinor,arguments); if(arguments->inputtype==INPUT_GLF&&GL!=0){ fprintf(stderr,"Can't calculate genotype likelihoods from glf files\n"); exit(0); } if(arguments->inputtype==INPUT_GLF) return; if(doGlf&&GL==0){ fprintf(stderr,"\t-> You need to choose a genotype likelihood model -GL for dumping genotype likelihoods\n"); exit(0); } if(GL==0&&doGlf==0){ shouldRun[index] =0; return; } if(GL==0) return; if(GL<0||GL>4){ fprintf(stderr,"\t-> You've choosen a GL model=%d, only 1,2,3,4 are implemented\n",GL); exit(0); } if(GL==4&&(doCounts==0)){ fprintf(stderr,"\t-> Must supply -doCounts for SYK model\n"); exit(0); } if((doGlf==2||doGlf==3) && doMajorMinor==0){ fprintf(stderr,"\t-> For dumping beaglestyle output you need to estimate major/minor: -doMajorMinor\n"); exit(0); } if(arguments->inputtype==INPUT_BEAGLE&&doGlf){ fprintf(stderr,"\t-> cannot output likelihoods (doGlf) when input is beagle\n"); exit(0); } if(arguments->inputtype!=INPUT_BAM&&arguments->inputtype!=INPUT_PILEUP){ fprintf(stderr,"Error: Likelihoods can only be estimated based on SOAP input and uppile input\n"); exit(0); } printArg(arguments->argumentFile); } abcGL::abcGL(const char *outfiles,argStruct *arguments,int inputtype){ errors = NULL; postfix = ".glf.gz"; beaglepostfix = ".beagle.gz"; trim =0; GL=0; doGlf=0; errorFname = NULL; errorProbs = NULL; GL=0; minInd=0; angsd_tmpdir = strdup("angsd_tmpdir"); if(arguments->argc==2){ if(!strcasecmp(arguments->argv[1],"-GL")){ printArg(stdout); exit(0); }else return; } getOptions(arguments); printArg(arguments->argumentFile); // if(GL==0) // return; if(GL==1) bam_likes_init(); else if(GL==2) gatk_init(); else if(GL==3){ soap.init(arguments->nInd,angsd_tmpdir); if(soap.doRecal) fprintf(stderr,"[%s] Will calculate recalibration matrices, please don't do any other analysis\n",__FILE__); else fprintf(stderr,"[%s] Will use precalculated calibration matrices\n",__FILE__); }else if(GL==4) { //default errormatrix double errorsDefault[4][4]={{0 ,0.00031 , 0.00373 , 0.000664}, {0.000737, 0 , 0.000576, 0.001702}, {0.001825,0.000386, 0 , 0.000653}, {0.00066 ,0.003648, 0.000321, 0 }, }; //allocate and plug in default values errors = new double *[4]; for(int i=0;i<4;i++){ errors[i] = new double[4]; for(int j=0;j<4;j++) errors[i][j] = errorsDefault[i][j]; } if(errorFname!=NULL) readError(errors,errorFname); errorProbs = abcError::generateErrorPointers(errors,3,4); } gzoutfile = Z_NULL; bufstr.s=NULL; bufstr.l=bufstr.m=0;// <- used for buffered output bufstr.l=0; if(doGlf){ if(doGlf!=2) gzoutfile = aio::openFileGz(outfiles,postfix,GZOPT); else{ gzoutfile = aio::openFileGz(outfiles,beaglepostfix,GZOPT); kputs("marker\tallele1\tallele2",&bufstr); for(int i=0;i<arguments->nInd;i++){ kputs("\tInd",&bufstr); kputw(i,&bufstr); kputs("\tInd",&bufstr); kputw(i,&bufstr); kputs("\tInd",&bufstr); kputw(i,&bufstr); } kputc('\n',&bufstr); gzwrite(gzoutfile,bufstr.s,bufstr.l); } } } abcGL::~abcGL(){ free(angsd_tmpdir); if(GL==0&&doGlf==0) return; else if(GL==1) bam_likes_destroy(); else if(GL==2) gatk_destroy(); else if(GL==4) abcError::killGlobalErrorProbs(errorProbs); if(doGlf) gzclose(gzoutfile); if(bufstr.s!=NULL) free(bufstr.s); if(errors){ for(int i=0;i<4;i++) delete [] errors[i]; delete [] errors; } delete [] logfactorial; } void abcGL::clean(funkyPars *pars){ if(pars->likes!=NULL){ for(int i=0;i<pars->numSites;i++) delete [] pars->likes[i]; delete [] pars->likes; } } void abcGL::print(funkyPars *pars){ if(doGlf) printLike(pars); } void abcGL::run(funkyPars *pars){ assert(pars!=NULL); if(GL==0) return; //assert(pars->chk!=NULL); double **likes = NULL; if(soap.doRecal!=1) likes = new double*[pars->chk->nSites]; if(GL==1) call_bam(pars->chk,likes,trim); else if(GL==2) call_gatk(pars->chk,likes,trim); else if(GL==3){ soap.run(pars->chk,likes,pars->ref,trim); //we dont estimate GL but make a calibration matrix if(soap.doRecal==1) return; }else if(GL==4) getLikesFullError10Genotypes(pars->numSites,pars->nInd,pars->counts,errorProbs,pars->keepSites,likes); pars->likes = likes; /* if trimming has been requested, then some site might not contain data, we therefore set keepsites to zero for these sites while we are at it, lets also count the effective sample size persite */ if(1){ for(int s=0;s<pars->numSites;s++){ // fprintf(stderr,"keepSites[%d]=%d\n",s,pars->keepSites[s]); if(pars->keepSites[s]==0) continue; int efSize=0; for(int i=0;i<pars->nInd;i++){ for(int ii=1;ii<10;ii++){ if(pars->likes[s][i*10+ii]!=pars->likes[s][i*10+0]){ efSize++; // break; } } } pars->keepSites[s] = efSize; if(minInd!=0&&minInd>efSize) pars->keepSites[s] = 0; } } //rescale the genotype likelihoods to loglike ratios. if(1){ for(int s=0;s<pars->numSites;s++){ if(pars->keepSites[s]==0) continue; for(int i=0;i<pars->nInd;i++) angsd::logrescale(pars->likes[s] +i*10,10); } } } void abcGL::getLikesFullError10Genotypes(int numSites,int nInd,suint **counts,double ****errorProbs,int *keepSites,double **loglikes) { //only calculate this once if(logfactorial==NULL)//dont bother populating if exists. logfactorial=abcError::logfact(LOGMAX); //calculate log factorials double *logError; for(int s=0;s<numSites;s++){ loglikes[s] = new double [10*nInd]; if(keepSites[s]==0) continue; for(int allele1=0;allele1<4;allele1++) { for(int allele2=allele1;allele2<4;allele2++){ int Gindex=angsd::majorminor[allele1][allele2]; int geno=0; int m2=allele2; if(allele1!=allele2) geno++; else{//total grimt must redo m2++; if(m2>3) m2=0; } logError=errorProbs[geno][allele1][m2]; for(int i=0;i<nInd;i++){ loglikes[s][i*10+Gindex]=logfactorial[counts[s][i*4+0]+counts[s][i*4+1]+counts[s][i*4+2]+counts[s][i*4+3]]; //should be computed before these loops for faster implimentation for(int j=0;j<4;j++) loglikes[s][i*10+Gindex]+=-logfactorial[counts[s][i*4+j]]+counts[s][i*4+j]*logError[j]; } } } } } void abcGL::printLike(funkyPars *pars) { assert(pars->likes!=NULL); if(doGlf==1){ //glffinn format for(int i=0;i<pars->numSites;i++){ if(pars->keepSites[i]==0) continue; gzwrite(gzoutfile,pars->likes[i],sizeof(double)*10*pars->nInd); } } else if(doGlf==2){ //beagle format bufstr.l = 0; //set tmpbuf beginning to zero for(int s=0;s<pars->numSites;s++) { if(pars->keepSites[s]==0) continue; kputs(header->name[pars->refId],&bufstr); kputc('_',&bufstr); kputw(pars->posi[s]+1,&bufstr); kputc('\t',&bufstr); kputw(pars->major[s],&bufstr); kputc('\t',&bufstr); kputw(pars->minor[s],&bufstr); int major = pars->major[s]; int minor = pars->minor[s]; assert(major!=4&&minor!=4); for(int i=0;i<pars->nInd;i++) { double norm=exp(pars->likes[s][i*10+angsd::majorminor[major][major]])+exp(pars->likes[s][i*10+angsd::majorminor[major][minor]])+exp(pars->likes[s][i*10+angsd::majorminor[minor][minor]]); double val1 = exp(pars->likes[s][i*10+angsd::majorminor[major][major]])/norm; double val2 = exp(pars->likes[s][i*10+angsd::majorminor[major][minor]])/norm; double val3 = exp(pars->likes[s][i*10+angsd::majorminor[minor][minor]])/norm; ksprintf(&bufstr, "\t%f",val1); ksprintf(&bufstr, "\t%f",val2); ksprintf(&bufstr, "\t%f",val3); } kputc('\n',&bufstr); } gzwrite(gzoutfile,bufstr.s,bufstr.l); } else if(doGlf==3) { //FGV v0.208 Aug,28 for(int s=0;s<pars->numSites;s++) { if(pars->keepSites[s]==0) //TSK 0.441 sep 25 continue; int major = pars->major[s]; int minor = pars->minor[s] ; assert(major!=4&&minor!=4); for(int i=0;i<pars->nInd;i++) { double dump[3]; dump[0] = pars->likes[s][i*10+angsd::majorminor[major][major]] ; dump[1] = pars->likes[s][i*10+angsd::majorminor[major][minor]] ; dump[2] = pars->likes[s][i*10+angsd::majorminor[minor][minor]] ; gzwrite(gzoutfile,dump,3*sizeof(double)); } } } else if(doGlf==4){ bufstr.l=0; //otherwise print textoutput for(int s=0;s<pars->numSites;s++){ if(pars->keepSites[s]==0) continue; kputs(header->name[pars->refId],&bufstr); kputc('\t',&bufstr); kputw(pars->posi[s]+1,&bufstr); for(int i=0;i<10*pars->nInd;i++) ksprintf(&bufstr, "\t%f",pars->likes[s][i]); kputc('\n',&bufstr); } gzwrite(gzoutfile,bufstr.s,bufstr.l); } }
25.748401
187
0.622226
e588ba30a9a4c0dc44a82cb38413c711dd3b5fc2
14,602
cpp
C++
src/qt-console/tray-monitor/runjob.cpp
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
src/qt-console/tray-monitor/runjob.cpp
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
src/qt-console/tray-monitor/runjob.cpp
tech-niche-biz/bacula-9.4.4
5e74458b612354f6838652dac9ddff94be1bbce6
[ "BSD-2-Clause" ]
null
null
null
/* Bacula(R) - The Network Backup Solution Copyright (C) 2000-2018 Kern Sibbald The original author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. You may use this file and others of this release according to the license defined in the LICENSE file, which includes the Affero General Public License, v3.0 ("AGPLv3") and some additional permissions and terms pursuant to its AGPLv3 Section 7. This notice must be preserved when any source code is conveyed and/or propagated. Bacula(R) is a registered trademark of Kern Sibbald. */ #include "runjob.h" #include <QMessageBox> static void fillcombo(QComboBox *cb, alist *lst, bool addempty=true) { if (lst && lst->size() > 0) { QStringList list; char *str; if (addempty) { list << QString(""); } foreach_alist(str, lst) { list << QString(str); } cb->addItems(list); } else { cb->setEnabled(false); } } RunJob::RunJob(RESMON *r): QDialog(), res(r), tabAdvanced(NULL) { int nbjob; if (res->jobs->size() == 0) { QMessageBox msgBox; msgBox.setText(_("This restricted console does not have access to Backup jobs")); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); deleteLater(); return; } ui.setupUi(this); setModal(true); connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(close_cb())); connect(ui.okButton, SIGNAL(clicked()), this, SLOT(runjob())); connect(ui.jobCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(jobChanged(int))); connect(ui.levelCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(levelChanged(int))); ui.dateTimeEdit->setMinimumDate(QDate::currentDate()); ui.dateTimeEdit->setMaximumDate(QDate::currentDate().addDays(7)); ui.dateTimeEdit->setDate(QDate::currentDate()); ui.dateTimeEdit->setTime(QTime::currentTime()); ui.boxEstimate->setVisible(false); res->mutex->lock(); nbjob = res->jobs->size(); fillcombo(ui.jobCombo, res->jobs, (nbjob > 1)); fillcombo(ui.clientCombo, res->clients); fillcombo(ui.filesetCombo,res->filesets); fillcombo(ui.poolCombo, res->pools); fillcombo(ui.storageCombo,res->storages); fillcombo(ui.catalogCombo,res->catalogs); res->mutex->unlock(); connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChange(int))); QStringList levels; levels << "" << "Incremental" << "Differential" << "Full"; ui.levelCombo->addItems(levels); MONITOR *m = (MONITOR*) GetNextRes(R_MONITOR, NULL); if (!m->display_advanced_options) { tabAdvanced = ui.tabWidget->widget(1); ui.tabWidget->removeTab(1); } show(); } void RunJob::tabChange(int idx) { QString q = ui.tabWidget->tabText(idx); if (q.contains("Advanced")) { if (ui.jobCombo->currentText().compare("") == 0) { pm_strcpy(curjob, ""); ui.tab2->setEnabled(false); } else if (ui.jobCombo->currentText().compare(curjob.c_str()) != 0) { task *t = new task(); char *job = bstrdup(ui.jobCombo->currentText().toUtf8().data()); pm_strcpy(curjob, job); // Keep the job name to not refresh the Advanced tab the next time Dmsg1(10, "get defaults for %s\n", job); res->mutex->lock(); bfree_and_null(res->defaults.job); res->defaults.job = job; res->mutex->unlock(); ui.tab2->setEnabled(false); connect(t, SIGNAL(done(task *)), this, SLOT(fill_defaults(task *)), Qt::QueuedConnection); t->init(res, TASK_DEFAULTS); res->wrk->queue(t); } } } void RunJob::runjob() { POOL_MEM tmp; char *p; p = ui.jobCombo->currentText().toUtf8().data(); if (!p || !*p) { QMessageBox msgBox; msgBox.setText(_("Nothing selected")); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); return; } Mmsg(command, "run job=\"%s\" yes", p); if (strcmp(p, NPRTB(res->defaults.job)) == 0 || strcmp("", NPRTB(res->defaults.job)) == 0) { p = ui.storageCombo->currentText().toUtf8().data(); if (p && *p && strcmp(p, NPRTB(res->defaults.storage)) != 0) { Mmsg(tmp, " storage=\"%s\"", p); pm_strcat(command, tmp.c_str()); } p = ui.clientCombo->currentText().toUtf8().data(); if (p && *p && strcmp(p, NPRTB(res->defaults.client)) != 0) { Mmsg(tmp, " client=\"%s\"", p); pm_strcat(command, tmp.c_str()); } p = ui.levelCombo->currentText().toUtf8().data(); if (p && *p && strcmp(p, NPRTB(res->defaults.level)) != 0) { Mmsg(tmp, " level=\"%s\"", p); pm_strcat(command, tmp.c_str()); } p = ui.poolCombo->currentText().toUtf8().data(); if (p && *p && strcmp(p, NPRTB(res->defaults.pool)) != 0) { Mmsg(tmp, " pool=\"%s\"", p); pm_strcat(command, tmp.c_str()); } p = ui.filesetCombo->currentText().toUtf8().data(); if (p && *p && strcmp(p, NPRTB(res->defaults.fileset)) != 0) { Mmsg(tmp, " fileset=\"%s\"", p); pm_strcat(command, tmp.c_str()); } if (res->defaults.priority && res->defaults.priority != ui.prioritySpin->value()) { Mmsg(tmp, " priority=\"%d\"", res->defaults.priority); pm_strcat(command, tmp.c_str()); } } QDate dnow = QDate::currentDate(); QTime tnow = QTime::currentTime(); QDate dval = ui.dateTimeEdit->date(); QTime tval = ui.dateTimeEdit->time(); if (dval > dnow || (dval == dnow && tval > tnow)) { Mmsg(tmp, " when=\"%s %s\"", dval.toString("yyyy-MM-dd").toUtf8().data(), tval.toString("hh:mm:00").toUtf8().data()); pm_strcat(command, tmp.c_str()); } if (res->type == R_CLIENT) { pm_strcat(command, " fdcalled=1"); } // Build the command and run it! task *t = new task(); t->init(res, TASK_RUN); connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection); t->arg = command.c_str(); res->wrk->queue(t); } void RunJob::jobStarted(task *t) { Dmsg1(10, "%s\n", command.c_str()); Dmsg1(10, "-> jobid=%d\n", t->result.i); deleteLater(); delete t; } void RunJob::close_cb(task *t) { deleteLater(); delete t; } void RunJob::close_cb() { task *t = new task(); connect(t, SIGNAL(done(task *)), this, SLOT(close_cb(task *)), Qt::QueuedConnection); t->init(res, TASK_DISCONNECT); res->wrk->queue(t); } void RunJob::jobChanged(int) { char *p; ui.levelCombo->setCurrentIndex(0); ui.storageCombo->setCurrentIndex(0); ui.filesetCombo->setCurrentIndex(0); ui.clientCombo->setCurrentIndex(0); ui.storageCombo->setCurrentIndex(0); ui.poolCombo->setCurrentIndex(0); ui.catalogCombo->setCurrentIndex(0); p = ui.jobCombo->currentText().toUtf8().data(); if (p && *p) { task *t = new task(); t->init(res, TASK_INFO); pm_strcpy(info, p); connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection); t->arg = info.c_str(); // Jobname t->arg2 = NULL; // Level res->wrk->queue(t); } } void RunJob::levelChanged(int) { char *p; p = ui.jobCombo->currentText().toUtf8().data(); if (p && *p) { pm_strcpy(info, p); p = ui.levelCombo->currentText().toUtf8().data(); if (p && *p) { task *t = new task(); pm_strcpy(level, p); connect(t, SIGNAL(done(task *)), this, SLOT(jobInfo(task *)), Qt::QueuedConnection); t->init(res, TASK_INFO); t->arg = info.c_str(); // Jobname t->arg2 = level.c_str(); // Level res->wrk->queue(t); } } } void RunJob::jobInfo(task *t) { char ed1[50]; res->mutex->lock(); if (res->infos.CorrNbJob == 0) { ui.boxEstimate->setVisible(false); } else { QString t; edit_uint64_with_suffix(res->infos.JobBytes, ed1); strncat(ed1, "B", sizeof(ed1)); ui.labelJobBytes->setText(QString(ed1)); ui.labelJobFiles->setText(QString(edit_uint64_with_commas(res->infos.JobFiles, ed1))); ui.labelJobLevel->setText(QString(job_level_to_str(res->infos.JobLevel))); t = tr("Computed over %1 job%2, the correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobBytes); ui.labelJobBytes_2->setToolTip(t); t = tr("Computed over %1 job%2, The correlation is %3/100.").arg(res->infos.CorrNbJob).arg(res->infos.CorrNbJob>1?"s":"").arg(res->infos.CorrJobFiles); ui.labelJobFiles_2->setToolTip(t); ui.boxEstimate->setVisible(true); } res->mutex->unlock(); t->deleteLater(); } static void set_combo(QComboBox *dest, char *str) { if (str) { int idx = dest->findText(QString(str), Qt::MatchExactly); if (idx >= 0) { dest->setCurrentIndex(idx); } } } void RunJob::fill_defaults(task *t) { if (t->status == true) { res->mutex->lock(); set_combo(ui.levelCombo, res->defaults.level); set_combo(ui.filesetCombo, res->defaults.fileset); set_combo(ui.clientCombo, res->defaults.client); set_combo(ui.storageCombo, res->defaults.storage); set_combo(ui.poolCombo, res->defaults.pool); set_combo(ui.catalogCombo, res->defaults.catalog); res->mutex->unlock(); } ui.tab2->setEnabled(true); t->deleteLater(); } RunJob::~RunJob() { Dmsg0(10, "~RunJob()\n"); if (tabAdvanced) { delete tabAdvanced; } } void TSched::init(const char *cmd_dir) { bool started = (timer >= 0); if (started) { stop(); } bfree_and_null(command_dir); command_dir = bstrdup(cmd_dir); if (started) { start(); } } TSched::TSched() { timer = -1; command_dir = NULL; } TSched::~TSched() { if (timer >= 0) { stop(); } bfree_and_null(command_dir); } #include <dirent.h> int breaddir(DIR *dirp, POOLMEM *&dname); bool TSched::read_command_file(const char *file, alist *lst, btime_t mtime) { POOLMEM *line; bool ret=false; char *p; TSchedJob *s; Dmsg1(50, "open command file %s\n", file); FILE *fp = fopen(file, "r"); if (!fp) { return false; } line = get_pool_memory(PM_FNAME); /* Get the first line, client/component:command */ while (bfgets(line, fp) != NULL) { strip_trailing_junk(line); Dmsg1(50, "%s\n", line); if (line[0] == '#') { continue; } if ((p = strchr(line, ':')) != NULL) { *p=0; s = new TSchedJob(line, p+1, mtime); lst->append(s); ret = true; } } free_pool_memory(line); fclose(fp); return ret; } #include "lib/plugins.h" #include "lib/cmd_parser.h" void TSched::timerEvent(QTimerEvent *event) { Q_UNUSED(event) POOL_MEM tmp, command; TSchedJob *j; alist lst(10, not_owned_by_alist); arg_parser parser; int i; task *t; RESMON *res; scan_for_commands(&lst); foreach_alist(j, (&lst)) { if (parser.parse_cmd(j->command) == bRC_OK) { if ((i = parser.find_arg_with_value("job")) > 0) { QMessageBox msgbox; foreach_res(res, R_CLIENT) { if (strcmp(res->hdr.name, j->component) == 0) { break; } } if (!res) { foreach_res(res, R_DIRECTOR) { if (strcmp(res->hdr.name, j->component) == 0) { break; } } } if (!res) { msgbox.setIcon(QMessageBox::Information); msgbox.setText(QString("Unable to find the component \"%1\" to run the job \"%2\".").arg(j->component, j->command)); msgbox.setStandardButtons(QMessageBox::Ignore); } else { msgbox.setIcon(QMessageBox::Information); msgbox.setText(QString("The job \"%1\" will start automatically in few seconds...").arg(parser.argv[i])); msgbox.setStandardButtons(QMessageBox::Ok | QMessageBox::Ignore); msgbox.setDefaultButton(QMessageBox::Ok); msgbox.button(QMessageBox::Ok)->animateClick(6000); } switch(msgbox.exec()) { case QMessageBox::Ok: Mmsg(command, "%s yes", j->command); if (res->type == R_CLIENT) { pm_strcat(command, " fdcalled=1"); } // Build the command and run it! t = new task(); t->init(res, TASK_RUN); connect(t, SIGNAL(done(task *)), this, SLOT(jobStarted(task *)), Qt::QueuedConnection); t->arg = command.c_str(); res->wrk->queue(t); break; case QMessageBox::Cancel: case QMessageBox::Ignore: break; } } } delete j; } } void TSched::jobStarted(task *t) { Dmsg1(10, "-> jobid=%d\n", t->result.i); t->deleteLater(); } bool TSched::scan_for_commands(alist *commands) { int name_max, len; DIR* dp = NULL; POOL_MEM fname(PM_FNAME), fname2(PM_FNAME); POOL_MEM dir_entry; bool ret=false, found=false; struct stat statp; name_max = pathconf(".", _PC_NAME_MAX); if (name_max < 1024) { name_max = 1024; } if (!(dp = opendir(command_dir))) { berrno be; Dmsg2(0, "Failed to open directory %s: ERR=%s\n", command_dir, be.bstrerror()); goto bail_out; } for ( ;; ) { if (breaddir(dp, dir_entry.addr()) != 0) { if (!found) { goto bail_out; } break; } if (strcmp(dir_entry.c_str(), ".") == 0 || strcmp(dir_entry.c_str(), "..") == 0) { continue; } len = strlen(dir_entry.c_str()); if (len <= 5) { continue; } if (strcmp(dir_entry.c_str() + len - 5, ".bcmd") != 0) { continue; } Mmsg(fname, "%s/%s", command_dir, dir_entry.c_str()); if (lstat(fname.c_str(), &statp) != 0 || !S_ISREG(statp.st_mode)) { continue; /* ignore directories & special files */ } if (read_command_file(fname.c_str(), commands, statp.st_mtime)) { Mmsg(fname2, "%s.ok", fname.c_str()); unlink(fname2.c_str()); rename(fname.c_str(), fname2.c_str()); // TODO: We should probably unlink the file } } bail_out: if (dp) { closedir(dp); } return ret; }
28.631373
157
0.571566
e58c9e92abb9149e44fdef1940720e0adde09a69
4,425
hpp
C++
ramus/patch/ips.hpp
qwertymodo/Mercurial-Magic
e5ce65510d12ac04e7ebea4ce11d200276baa141
[ "ISC" ]
2
2019-01-20T13:05:10.000Z
2021-03-31T14:09:03.000Z
ramus/patch/ips.hpp
qwertymodo/Mercurial-Magic
e5ce65510d12ac04e7ebea4ce11d200276baa141
[ "ISC" ]
null
null
null
ramus/patch/ips.hpp
qwertymodo/Mercurial-Magic
e5ce65510d12ac04e7ebea4ce11d200276baa141
[ "ISC" ]
1
2018-10-12T02:47:57.000Z
2018-10-12T02:47:57.000Z
#pragma once #include <nall/file.hpp> #include <nall/filemap.hpp> #include <nall/stdint.hpp> #include <nall/string.hpp> namespace ramus { struct ipspatch { inline auto modify(const uint8_t* data, uint size) -> bool; inline auto source(const uint8_t* data, uint size) -> void; inline auto target(uint8_t* data, uint size) -> void; inline auto modify(const string& filename) -> bool; inline auto source(const string& filename) -> bool; inline auto target(const string& filename) -> bool; inline auto size() const -> uint; enum result : uint { unknown, success, patch_too_small, patch_invalid_header, target_too_small, }; inline auto apply() -> result; protected: filemap modifyFile; const uint8_t* modifyData; uint modifySize; filemap sourceFile; const uint8_t* sourceData; uint sourceSize; filemap targetFile; uint8_t* targetData; uint targetSize; uint modifyTargetSize; bool truncate; }; auto ipspatch::modify(const uint8_t* data, uint size) -> bool { if(size < 8) return false; modifyData = data; modifySize = size; uint offset = 5; auto read8 = [&]() -> uint8_t { uint8_t data = modifyData[offset++]; return data; }; auto read16 = [&]() -> uint16_t { return read8() << 8 | read8(); }; auto read24 = [&]() -> uint32_t { return read8() << 16 | read16(); }; uint blockAddr, blockSize, rleSize; uint maxBlockAddr = 0; modifyTargetSize = 0; while(offset < modifySize) { blockAddr = read24(); if(blockAddr == 0x454f46) break; //"EOF" maxBlockAddr = max(maxBlockAddr, blockAddr); blockSize = read16(); if(blockSize == 0) { //RLE rleSize = read16(); modifyTargetSize = max(modifyTargetSize, blockAddr + rleSize); offset++; } else { modifyTargetSize = max(modifyTargetSize, blockAddr + blockSize); offset += blockSize; } } if(size - offset != 0 && size - offset != 3) return false; truncate = size - offset == 3; if(truncate) modifyTargetSize = read24(); return true; } auto ipspatch::source(const uint8_t* data, uint size) -> void { sourceData = data; sourceSize = size; if(!truncate) modifyTargetSize = max(modifyTargetSize, sourceSize); } auto ipspatch::target(uint8_t* data, uint size) -> void { targetData = data; targetSize = size; } auto ipspatch::modify(const string& filename) -> bool { if(modifyFile.open(filename, filemap::mode::read) == false) return false; return modify(modifyFile.data(), modifyFile.size()); } auto ipspatch::source(const string& filename) -> bool { if(sourceFile.open(filename, filemap::mode::read) == false) return false; source(sourceFile.data(), sourceFile.size()); return true; } auto ipspatch::target(const string& filename) -> bool { file fp; if(fp.open(filename, file::mode::write) == false) return false; fp.truncate(modifyTargetSize); fp.close(); if(targetFile.open(filename, filemap::mode::readwrite) == false) return false; target(targetFile.data(), targetFile.size()); return true; } auto ipspatch::size() const -> uint { return modifyTargetSize; } auto ipspatch::apply() -> result { if(modifySize < 8) return result::patch_too_small; uint modifyOffset = 0, sourceRelativeOffset = 0, targetRelativeOffset = 0; auto read8 = [&]() -> uint8_t { uint8_t data = modifyData[modifyOffset++]; return data; }; auto read16 = [&]() -> uint16_t { return read8() << 8 | read8(); }; auto read24 = [&]() -> uint32_t { return read8() << 16 | read16(); }; if(read8() != 'P') return result::patch_invalid_header; if(read8() != 'A') return result::patch_invalid_header; if(read8() != 'T') return result::patch_invalid_header; if(read8() != 'C') return result::patch_invalid_header; if(read8() != 'H') return result::patch_invalid_header; if(modifyTargetSize > targetSize) return result::target_too_small; memory::copy(targetData, sourceData, sourceSize); uint blockAddr, blockSize, rleSize; while(modifyOffset < modifySize) { blockAddr = read24(); if(blockAddr == 0x454f46) break; //"EOF" blockSize = read16(); if(blockSize == 0) { //RLE rleSize = read16(); memory::fill(targetData + blockAddr, rleSize, read8()); } else { memory::copy(targetData + blockAddr, modifyData + modifyOffset, blockSize); modifyOffset += blockSize; } } return result::success; } }
25.726744
81
0.660339
e5916831f922f5efaa3a87ce01db382c07a90c38
2,472
hpp
C++
Assignments/P01/Menu.hpp
Landon-Brown1/2143-OOP-Brown
fded2b021b588bced3ba2a5c67e8e29694d42b2e
[ "MIT" ]
null
null
null
Assignments/P01/Menu.hpp
Landon-Brown1/2143-OOP-Brown
fded2b021b588bced3ba2a5c67e8e29694d42b2e
[ "MIT" ]
null
null
null
Assignments/P01/Menu.hpp
Landon-Brown1/2143-OOP-Brown
fded2b021b588bced3ba2a5c67e8e29694d42b2e
[ "MIT" ]
null
null
null
/* * AUTHOR: Landon Brown * FILE TITLE: Menu.hpp * FILE DESCRIPTION: Menu for the beginning of the game * DUE DATE: TBD * DATE CREATED: 03/26/2020 */ #include <iostream> #include <string> using namespace std; struct Menu{ Menu(){ } void printIntro(){ cout << endl << " @@----------------------------------------------------@@ " << endl << " @@ Welcome to Pokemon: Brown Version! @@ " << endl << " @@ If you would like to play, please press 'y'. @@ " << endl << "(( ))" << endl << " @@ @@ " << endl << " @@ @@ " << endl << " @@----------------------------------------------------@@ " << endl; } void firstSelect(){ cout << endl << " @@----------------------------------------------------@@ " << endl << " @@ Player One, please select your Pokemon by typing @@ " << endl << " @@ The respective Pokedex number of each Pokemon @@ " << endl << "(( you would like in your party (up to 6). The first ))" << endl << " @@ Pokemon you choose will be the first in your @@ " << endl << " @@ lineup to be sent to battle! @@ " << endl << " @@----------------------------------------------------@@ " << endl; } void secondSelect(){ cout << endl << " @@----------------------------------------------------@@ " << endl << " @@ @@ " << endl << " @@ @@ " << endl << "(( ))" << endl << " @@ @@ " << endl << " @@ @@ " << endl << " @@----------------------------------------------------@@ " << endl; } };
51.5
101
0.222492
e59532543eb5ced40994ebd6ca67ef20a52ec6f1
4,093
hpp
C++
include/mtao/geometry/prune_vertices.hpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
include/mtao/geometry/prune_vertices.hpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
4
2020-04-18T16:16:05.000Z
2020-04-18T16:17:36.000Z
include/mtao/geometry/prune_vertices.hpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
#pragma once #include "mtao/geometry/kdtree.hpp" #include <map> #include "mtao/iterator/enumerate.hpp" #include "mtao/eigen/stl2eigen.hpp" namespace mtao { namespace geometry { //expects a mtao::vector<mtao::Vector<T,D>> template <typename Container , typename T > auto prune(const Container& V, T eps = T(1e-8)) -> std::tuple<Container, std::map<int,int>> { using Vec = typename Container::value_type; constexpr static int D = Vec::RowsAtCompileTime; using Scalar = typename Vec::Scalar; std::map<int,int> remap; Container ret_vec; if(eps == 0 && V.size() > 0) { constexpr static bool static_size = D != Eigen::Dynamic; using StlVec= std::conditional_t<static_size,std::array<Scalar,D>,std::vector<Scalar>>; ret_vec.reserve(V.size()); int rows = V[0].rows(); std::map<StlVec,int> vmap; StlVec tmp; if constexpr(!static_size) { tmp.resize(rows); } for(size_t i=0; i<V.size(); ++i) { mtao::eigen::stl2eigen(tmp) = V[i]; if(auto it = vmap.find(tmp); it == vmap.end()) { remap[i] = vmap.size(); vmap[tmp] = vmap.size(); } else { remap[i] = it->second; } } ret_vec.resize(vmap.size()); for(auto&& [v,i]: vmap) { ret_vec[i] = mtao::eigen::stl2eigen(v); } } else { KDTree<Scalar,D> tree; tree.reserve(V.size()); std::map<size_t,size_t> remap; for(size_t i=0; i<V.size(); ++i) { remap[i] = tree.pruning_insertion(V[i],eps); } ret_vec = tree.points(); } return std::make_tuple(ret_vec,remap); } template <typename DerivedV, typename DerivedF, typename T > auto prune_with_map(const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, T eps = T(1e-8)) { constexpr static int D = DerivedV::RowsAtCompileTime; using Scalar = typename DerivedV::Scalar; mtao::vector<typename mtao::Vector<Scalar,D>> stlV(V.cols()); for(int i = 0; i < V.cols(); ++i) { stlV[i] = V.col(i); } auto pr = prune(stlV,eps); //auto [P,m] = prune(stlV,eps); const mtao::vector<typename mtao::Vector<Scalar,D>>& P = std::get<0>(pr); const std::map<int,int>& m = std::get<1>(pr); mtao::ColVectors<Scalar,D> RV(V.rows(),P.size()); for(int i = 0; i < RV.cols(); ++i) { RV.col(i) = P[i]; } using IndexType = typename DerivedF::Scalar; auto RFp = F.unaryExpr([&](const IndexType& idx) -> IndexType { return m.at(idx); }).eval(); std::set<int> good_idx; for(int i = 0; i < RFp.cols(); ++i) { auto v = RFp.col(i); std::set<IndexType> indx; for(int j = 0; j < RFp.rows(); ++j) { indx.insert(v(j)); } if(indx.size() == RFp.rows()) { good_idx.insert(i); } } decltype(RFp) RF(RFp.rows(),good_idx.size()); for(auto&& [i,j]: iterator::enumerate(good_idx) ){ RF.col(i) = RFp.col(j); } return std::make_tuple(RV,RF,m); } template <typename DerivedV, typename DerivedF ,typename T = typename DerivedV::Scalar> auto prune(const Eigen::MatrixBase<DerivedV>& V, const Eigen::MatrixBase<DerivedF>& F, T eps = T(1e-8)) { auto [RV,RF,m] = prune_with_map(V,F,eps); return std::make_tuple(RV,RF); } }}
38.252336
122
0.469094
e59611b4bc72740b511887ce25eecfd36758d720
439
hpp
C++
security/include/InvalidKeyException.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
27
2019-04-27T00:51:22.000Z
2022-03-30T04:05:44.000Z
security/include/InvalidKeyException.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
9
2020-05-03T12:17:50.000Z
2021-10-15T02:18:47.000Z
security/include/InvalidKeyException.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
1
2019-04-16T01:45:36.000Z
2019-04-16T01:45:36.000Z
#ifndef __OBOTCHA_INVALID_KEY_EXCEPTION_HPP__ #define __OBOTCHA_INVALID_KEY_EXCEPTION_HPP__ #include <fstream> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "Object.hpp" #include "Exception.hpp" #include "String.hpp" namespace obotcha { DECLARE_EXCEPTION(InvalidKeyException){ public: InvalidKeyException(const char *str):Exception(str){} InvalidKeyException(String str):Exception(str){} }; } #endif
17.56
55
0.779043
e59d226aad84cfaaabe3b77e6cc3312910d3b4bd
45,566
cpp
C++
libBKPLPlot/plbuf.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
libBKPLPlot/plbuf.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
libBKPLPlot/plbuf.cpp
rsuchecki/biokanga
ef0fa1cf58fb2903ae18d14e5b0f84de7b7e744e
[ "MIT" ]
null
null
null
// $Id: plbuf.c 12636 2013-10-26 20:47:49Z airwin $ // // Handle plot buffer. // // Copyright (C) 1992 Maurice LeBrun // Copyright (C) 2004 Alan W. Irwin // Copyright (C) 2005 Thomas J. Duck // Copyright (C) 2006 Jim Dishaw // // This file is part of PLplot. // // PLplot is free software; you can redistribute it and/or modify // it under the terms of the GNU Library General Public License as published // by the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // PLplot 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 Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with PLplot; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #include "stdafx.h" #define NEED_PLDEBUG #include "plplotP.h" #include "drivers.h" #include "metadefs.h" #include <string.h> typedef unsigned char U_CHAR; // Function prototypes void * plbuf_save( PLStream *pls, void *state ); static int rd_command( PLStream *pls, U_CHAR *p_c ); static void rd_data( PLStream *pls, void *buf, size_t buf_size ); static void wr_command( PLStream *pls, U_CHAR c ); static void wr_data( PLStream *pls, void *buf, size_t buf_size ); static void plbuf_control( PLStream *pls, U_CHAR c ); static void rdbuf_init( PLStream *pls ); static void rdbuf_line( PLStream *pls ); static void rdbuf_polyline( PLStream *pls ); static void rdbuf_eop( PLStream *pls ); static void rdbuf_bop( PLStream *pls ); static void rdbuf_state( PLStream *pls ); static void rdbuf_esc( PLStream *pls ); static void plbuf_fill( PLStream *pls ); static void rdbuf_fill( PLStream *pls ); static void plbuf_swin( PLStream *pls, PLWindow *plwin ); static void rdbuf_swin( PLStream *pls ); //-------------------------------------------------------------------------- // plbuf_init() // // Initialize device. // Actually just disables writes if plot buffer is already open (occurs // when one stream is cloned, as in printing). //-------------------------------------------------------------------------- void plbuf_init( PLStream *pls ) { dbug_enter( "plbuf_init" ); pls->plbuf_read = FALSE; #ifdef BUFFERED_FILE if ( pls->plbufFile != NULL ) pls->plbuf_write = FALSE; #else if ( pls->plbuf_buffer != NULL ) pls->plbuf_write = FALSE; #endif } //-------------------------------------------------------------------------- // plbuf_line() // // Draw a line in the current color from (x1,y1) to (x2,y2). //-------------------------------------------------------------------------- void plbuf_line( PLStream *pls, short x1a, short y1a, short x2a, short y2a ) { short xpl[2], ypl[2]; dbug_enter( "plbuf_line" ); wr_command( pls, (U_CHAR) LINE ); xpl[0] = x1a; xpl[1] = x2a; ypl[0] = y1a; ypl[1] = y2a; wr_data( pls, xpl, sizeof ( short ) * 2 ); wr_data( pls, ypl, sizeof ( short ) * 2 ); } //-------------------------------------------------------------------------- // plbuf_polyline() // // Draw a polyline in the current color. //-------------------------------------------------------------------------- void plbuf_polyline( PLStream *pls, short *xa, short *ya, PLINT npts ) { dbug_enter( "plbuf_polyline" ); wr_command( pls, (U_CHAR) POLYLINE ); wr_data( pls, &npts, sizeof ( PLINT ) ); wr_data( pls, xa, sizeof ( short ) * (size_t) npts ); wr_data( pls, ya, sizeof ( short ) * (size_t) npts ); } //-------------------------------------------------------------------------- // plbuf_eop() // // End of page. //-------------------------------------------------------------------------- void plbuf_eop( PLStream * PL_UNUSED( pls ) ) { dbug_enter( "plbuf_eop" ); } //-------------------------------------------------------------------------- // plbuf_bop() // // Set up for the next page. // To avoid problems redisplaying partially filled pages, on each BOP the // old file is thrown away and a new one is obtained. This way we can just // read up to EOF to get everything on the current page. // // Also write state information to ensure the next page is correct. //-------------------------------------------------------------------------- void plbuf_bop( PLStream *pls ) { dbug_enter( "plbuf_bop" ); plbuf_tidy( pls ); #ifdef BUFFERED_FILE pls->plbufFile = pl_create_tempfile( NULL ); if ( pls->plbufFile == NULL ) plexit( "plbuf_bop: Error opening plot data storage file." ); #else // Need a better place to initialize this value pls->plbuf_buffer_grow = 128 * 1024; if ( pls->plbuf_buffer == NULL ) { // We have not allocated a buffer, so do it now if ( ( pls->plbuf_buffer = malloc( pls->plbuf_buffer_grow ) ) == NULL ) plexit( "plbuf_bop: Error allocating plot buffer." ); pls->plbuf_buffer_size = pls->plbuf_buffer_grow; pls->plbuf_top = 0; pls->plbuf_readpos = 0; } else { // Buffer is allocated, move the top to the beginning pls->plbuf_top = 0; } #endif wr_command( pls, (U_CHAR) BOP ); plbuf_state( pls, PLSTATE_COLOR0 ); plbuf_state( pls, PLSTATE_WIDTH ); } //-------------------------------------------------------------------------- // plbuf_tidy() // // Close graphics file //-------------------------------------------------------------------------- void plbuf_tidy( PLStream * PL_UNUSED( pls ) ) { dbug_enter( "plbuf_tidy" ); #ifdef BUFFERED_FILE if ( pls->plbufFile == NULL ) return; fclose( pls->plbufFile ) pls->plbufFile = NULL; #endif } //-------------------------------------------------------------------------- // plbuf_state() // // Handle change in PLStream state (color, pen width, fill attribute, etc). //-------------------------------------------------------------------------- void plbuf_state( PLStream *pls, PLINT op ) { dbug_enter( "plbuf_state" ); wr_command( pls, (U_CHAR) CHANGE_STATE ); wr_command( pls, (U_CHAR) op ); switch ( op ) { case PLSTATE_WIDTH: wr_data( pls, &( pls->width ), sizeof ( pls->width ) ); break; case PLSTATE_COLOR0: wr_data( pls, &( pls->icol0 ), sizeof ( pls->icol0 ) ); if ( pls->icol0 == PL_RGB_COLOR ) { wr_data( pls, &( pls->curcolor.r ), sizeof ( pls->curcolor.r ) ); wr_data( pls, &( pls->curcolor.g ), sizeof ( pls->curcolor.g ) ); wr_data( pls, &( pls->curcolor.b ), sizeof ( pls->curcolor.b ) ); } break; case PLSTATE_COLOR1: wr_data( pls, &( pls->icol1 ), sizeof ( pls->icol1 ) ); break; case PLSTATE_FILL: wr_data( pls, &( pls->patt ), sizeof ( pls->patt ) ); break; } } //-------------------------------------------------------------------------- // plbuf_image() // // write image described in points pls->dev_x[], pls->dev_y[], pls->dev_z[]. // pls->nptsX, pls->nptsY. //-------------------------------------------------------------------------- static void plbuf_image( PLStream *pls, IMG_DT *img_dt ) { PLINT npts = pls->dev_nptsX * pls->dev_nptsY; dbug_enter( "plbuf_image" ); wr_data( pls, &pls->dev_nptsX, sizeof ( PLINT ) ); wr_data( pls, &pls->dev_nptsY, sizeof ( PLINT ) ); wr_data( pls, &img_dt->xmin, sizeof ( PLFLT ) ); wr_data( pls, &img_dt->ymin, sizeof ( PLFLT ) ); wr_data( pls, &img_dt->dx, sizeof ( PLFLT ) ); wr_data( pls, &img_dt->dy, sizeof ( PLFLT ) ); wr_data( pls, &pls->dev_zmin, sizeof ( short ) ); wr_data( pls, &pls->dev_zmax, sizeof ( short ) ); wr_data( pls, pls->dev_ix, sizeof ( short ) * (size_t) npts ); wr_data( pls, pls->dev_iy, sizeof ( short ) * (size_t) npts ); wr_data( pls, pls->dev_z, sizeof ( unsigned short ) * (size_t) ( ( pls->dev_nptsX - 1 ) * ( pls->dev_nptsY - 1 ) ) ); } //-------------------------------------------------------------------------- // plbuf_text() // // Handle text call. //-------------------------------------------------------------------------- static void plbuf_text( PLStream *pls, EscText *text ) { PLUNICODE fci; dbug_enter( "plbuf_text" ); // Retrieve the font characterization integer plgfci( &fci ); // Write the text information wr_data( pls, &fci, sizeof ( PLUNICODE ) ); wr_data( pls, &pls->chrht, sizeof ( PLFLT ) ); wr_data( pls, &pls->diorot, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpxmi, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpxma, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpymi, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpyma, sizeof ( PLFLT ) ); wr_data( pls, &text->base, sizeof ( PLINT ) ); wr_data( pls, &text->just, sizeof ( PLFLT ) ); wr_data( pls, text->xform, sizeof ( PLFLT ) * 4 ); wr_data( pls, &text->x, sizeof ( PLINT ) ); wr_data( pls, &text->y, sizeof ( PLINT ) ); wr_data( pls, &text->refx, sizeof ( PLINT ) ); wr_data( pls, &text->refy, sizeof ( PLINT ) ); wr_data( pls, &text->unicode_array_len, sizeof ( PLINT ) ); if ( text->unicode_array_len ) wr_data( pls, text->unicode_array, sizeof ( PLUNICODE ) * text->unicode_array_len ); } //-------------------------------------------------------------------------- // plbuf_text_unicode() // // Handle text buffering for the new unicode pathway. //-------------------------------------------------------------------------- static void plbuf_text_unicode( PLStream *pls, EscText *text ) { PLUNICODE fci; dbug_enter( "plbuf_text" ); // Retrieve the font characterization integer plgfci( &fci ); // Write the text information wr_data( pls, &fci, sizeof ( PLUNICODE ) ); wr_data( pls, &pls->chrht, sizeof ( PLFLT ) ); wr_data( pls, &pls->diorot, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpxmi, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpxma, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpymi, sizeof ( PLFLT ) ); wr_data( pls, &pls->clpyma, sizeof ( PLFLT ) ); wr_data( pls, &text->base, sizeof ( PLINT ) ); wr_data( pls, &text->just, sizeof ( PLFLT ) ); wr_data( pls, text->xform, sizeof ( PLFLT ) * 4 ); wr_data( pls, &text->x, sizeof ( PLINT ) ); wr_data( pls, &text->y, sizeof ( PLINT ) ); wr_data( pls, &text->refx, sizeof ( PLINT ) ); wr_data( pls, &text->refy, sizeof ( PLINT ) ); wr_data( pls, &text->n_fci, sizeof ( PLUNICODE ) ); wr_data( pls, &text->n_char, sizeof ( PLUNICODE ) ); wr_data( pls, &text->n_ctrl_char, sizeof ( PLINT ) ); wr_data( pls, &text->unicode_array_len, sizeof ( PLINT ) ); } //-------------------------------------------------------------------------- // plbuf_esc() // // Escape function. Note that any data written must be in device // independent form to maintain the transportability of the metafile. // // Functions: // // PLESC_FILL Fill polygon // PLESC_SWIN Set plot window parameters // PLESC_IMAGE Draw image // PLESC_HAS_TEXT Draw PostScript text // PLESC_CLEAR Clear Background // PLESC_START_RASTERIZE // PLESC_END_RASTERIZE Start and stop rasterization //-------------------------------------------------------------------------- void plbuf_esc( PLStream *pls, PLINT op, void *ptr ) { dbug_enter( "plbuf_esc" ); wr_command( pls, (U_CHAR) ESCAPE ); wr_command( pls, (U_CHAR) op ); switch ( op ) { case PLESC_FILL: plbuf_fill( pls ); break; case PLESC_SWIN: plbuf_swin( pls, (PLWindow *) ptr ); break; case PLESC_IMAGE: plbuf_image( pls, (IMG_DT *) ptr ); break; case PLESC_HAS_TEXT: if ( ptr != NULL ) // Check required by GCW driver, please don't remove plbuf_text( pls, (EscText *) ptr ); break; case PLESC_BEGIN_TEXT: case PLESC_TEXT_CHAR: case PLESC_CONTROL_CHAR: case PLESC_END_TEXT: plbuf_text_unicode( pls, (EscText *) ptr ); break; #if 0 // These are a no-op. They just need an entry in the buffer. case PLESC_CLEAR: case PLESC_START_RASTERIZE: case PLESC_END_RASTERIZE: break; #endif } } //-------------------------------------------------------------------------- // plbuf_fill() // // Fill polygon described in points pls->dev_x[] and pls->dev_y[]. //-------------------------------------------------------------------------- static void plbuf_fill( PLStream *pls ) { dbug_enter( "plbuf_fill" ); wr_data( pls, &pls->dev_npts, sizeof ( PLINT ) ); wr_data( pls, pls->dev_x, sizeof ( short ) * (size_t) pls->dev_npts ); wr_data( pls, pls->dev_y, sizeof ( short ) * (size_t) pls->dev_npts ); } //-------------------------------------------------------------------------- // plbuf_swin() // // Set up plot window parameters. //-------------------------------------------------------------------------- static void plbuf_swin( PLStream *pls, PLWindow *plwin ) { wr_data( pls, &plwin->dxmi, sizeof ( PLFLT ) ); wr_data( pls, &plwin->dxma, sizeof ( PLFLT ) ); wr_data( pls, &plwin->dymi, sizeof ( PLFLT ) ); wr_data( pls, &plwin->dyma, sizeof ( PLFLT ) ); wr_data( pls, &plwin->wxmi, sizeof ( PLFLT ) ); wr_data( pls, &plwin->wxma, sizeof ( PLFLT ) ); wr_data( pls, &plwin->wymi, sizeof ( PLFLT ) ); wr_data( pls, &plwin->wyma, sizeof ( PLFLT ) ); } //-------------------------------------------------------------------------- // Routines to read from & process the plot buffer. //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // rdbuf_init() // // Initialize device. //-------------------------------------------------------------------------- static void rdbuf_init( PLStream * PL_UNUSED( pls ) ) { dbug_enter( "rdbuf_init" ); } //-------------------------------------------------------------------------- // rdbuf_line() // // Draw a line in the current color from (x1,y1) to (x2,y2). //-------------------------------------------------------------------------- static void rdbuf_line( PLStream *pls ) { short xpl[2], ypl[2]; PLINT npts = 2; dbug_enter( "rdbuf_line" ); rd_data( pls, xpl, sizeof ( short ) * (size_t) npts ); rd_data( pls, ypl, sizeof ( short ) * (size_t) npts ); plP_line( xpl, ypl ); } //-------------------------------------------------------------------------- // rdbuf_polyline() // // Draw a polyline in the current color. //-------------------------------------------------------------------------- static void rdbuf_polyline( PLStream *pls ) { short _xpl[PL_MAXPOLY], _ypl[PL_MAXPOLY]; short *xpl, *ypl; PLINT npts; dbug_enter( "rdbuf_polyline" ); rd_data( pls, &npts, sizeof ( PLINT ) ); if ( npts > PL_MAXPOLY ) { xpl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) ); ypl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) ); if ( ( xpl == NULL ) || ( ypl == NULL ) ) { plexit( "rdbuf_polyline: Insufficient memory for large polyline" ); } } else { xpl = _xpl; ypl = _ypl; } rd_data( pls, xpl, sizeof ( short ) * (size_t) npts ); rd_data( pls, ypl, sizeof ( short ) * (size_t) npts ); plP_polyline( xpl, ypl, npts ); if ( npts > PL_MAXPOLY ) { free( xpl ); free( ypl ); } } //-------------------------------------------------------------------------- // rdbuf_eop() // // End of page. //-------------------------------------------------------------------------- static void rdbuf_eop( PLStream * PL_UNUSED( pls ) ) { dbug_enter( "rdbuf_eop" ); } //-------------------------------------------------------------------------- // rdbuf_bop() // // Set up for the next page. //-------------------------------------------------------------------------- static void rdbuf_bop( PLStream *pls ) { dbug_enter( "rdbuf_bop" ); pls->nplwin = 0; } //-------------------------------------------------------------------------- // rdbuf_state() // // Handle change in PLStream state (color, pen width, fill attribute, etc). //-------------------------------------------------------------------------- static void rdbuf_state( PLStream *pls ) { U_CHAR op; dbug_enter( "rdbuf_state" ); rd_data( pls, &op, sizeof ( U_CHAR ) ); switch ( op ) { case PLSTATE_WIDTH: { U_CHAR width; rd_data( pls, &width, sizeof ( U_CHAR ) ); pls->width = width; plP_state( PLSTATE_WIDTH ); break; } case PLSTATE_COLOR0: { short icol0; U_CHAR r, g, b; PLFLT a; rd_data( pls, &icol0, sizeof ( short ) ); if ( icol0 == PL_RGB_COLOR ) { rd_data( pls, &r, sizeof ( U_CHAR ) ); rd_data( pls, &g, sizeof ( U_CHAR ) ); rd_data( pls, &b, sizeof ( U_CHAR ) ); a = 1.0; } else { if ( (int) icol0 >= pls->ncol0 ) { char buffer[256]; snprintf( buffer, 256, "rdbuf_state: Invalid color map entry: %d", (int) icol0 ); plabort( buffer ); return; } r = pls->cmap0[icol0].r; g = pls->cmap0[icol0].g; b = pls->cmap0[icol0].b; a = pls->cmap0[icol0].a; } pls->icol0 = icol0; pls->curcolor.r = r; pls->curcolor.g = g; pls->curcolor.b = b; pls->curcolor.a = a; plP_state( PLSTATE_COLOR0 ); break; } case PLSTATE_COLOR1: { short icol1; rd_data( pls, &icol1, sizeof ( short ) ); pls->icol1 = icol1; pls->curcolor.r = pls->cmap1[icol1].r; pls->curcolor.g = pls->cmap1[icol1].g; pls->curcolor.b = pls->cmap1[icol1].b; pls->curcolor.a = pls->cmap1[icol1].a; plP_state( PLSTATE_COLOR1 ); break; } case PLSTATE_FILL: { signed char patt; rd_data( pls, &patt, sizeof ( signed char ) ); pls->patt = patt; plP_state( PLSTATE_FILL ); break; } } } //-------------------------------------------------------------------------- // rdbuf_esc() // // Escape function. // Must fill data structure with whatever data that was written, // then call escape function. // // Note: it is best to only call the escape function for op-codes that // are known to be supported. // // Functions: // // PLESC_FILL Fill polygon // PLESC_SWIN Set plot window parameters // PLESC_IMAGE Draw image // PLESC_HAS_TEXT Draw PostScript text // PLESC_BEGIN_TEXT Commands for the alternative unicode text handling path // PLESC_TEXT_CHAR // PLESC_CONTROL_CHAR // PLESC_END_TEXT // PLESC_CLEAR Clear Background //-------------------------------------------------------------------------- static void rdbuf_image( PLStream *pls ); static void rdbuf_text( PLStream *pls ); static void rdbuf_text_unicode( PLINT op, PLStream *pls ); static void rdbuf_esc( PLStream *pls ) { U_CHAR op; dbug_enter( "rdbuf_esc" ); rd_data( pls, &op, sizeof ( U_CHAR ) ); switch ( op ) { case PLESC_FILL: rdbuf_fill( pls ); break; case PLESC_SWIN: rdbuf_swin( pls ); break; case PLESC_IMAGE: rdbuf_image( pls ); break; case PLESC_HAS_TEXT: rdbuf_text( pls ); break; case PLESC_BEGIN_TEXT: case PLESC_TEXT_CHAR: case PLESC_CONTROL_CHAR: case PLESC_END_TEXT: rdbuf_text_unicode( op, pls ); break; case PLESC_CLEAR: plP_esc( PLESC_CLEAR, NULL ); break; case PLESC_START_RASTERIZE: plP_esc( PLESC_START_RASTERIZE, NULL ); break; case PLESC_END_RASTERIZE: plP_esc( PLESC_END_RASTERIZE, NULL ); break; } } //-------------------------------------------------------------------------- // rdbuf_fill() // // Fill polygon described by input points. //-------------------------------------------------------------------------- static void rdbuf_fill( PLStream *pls ) { short _xpl[PL_MAXPOLY], _ypl[PL_MAXPOLY]; short *xpl, *ypl; PLINT npts; dbug_enter( "rdbuf_fill" ); rd_data( pls, &npts, sizeof ( PLINT ) ); if ( npts > PL_MAXPOLY ) { xpl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) ); ypl = (short *) malloc( (size_t) ( npts + 1 ) * sizeof ( short ) ); if ( ( xpl == NULL ) || ( ypl == NULL ) ) { plexit( "rdbuf_polyline: Insufficient memory for large polyline" ); } } else { xpl = _xpl; ypl = _ypl; } rd_data( pls, xpl, sizeof ( short ) * (size_t) npts ); rd_data( pls, ypl, sizeof ( short ) * (size_t) npts ); plP_fill( xpl, ypl, npts ); if ( npts > PL_MAXPOLY ) { free( xpl ); free( ypl ); } } //-------------------------------------------------------------------------- // rdbuf_image() // // . //-------------------------------------------------------------------------- static void rdbuf_image( PLStream *pls ) { // Unnecessarily initialize dev_iy and dev_z to quiet -O1 // -Wuninitialized warnings which are false alarms. (If something // goes wrong with the dev_ix malloc below any further use of // dev_iy and dev_z does not occur. Similarly, if something goes // wrong with the dev_iy malloc below any further use of dev_z // does not occur.) short *dev_ix, *dev_iy = NULL; unsigned short *dev_z = NULL, dev_zmin, dev_zmax; PLINT nptsX, nptsY, npts; PLFLT xmin, ymin, dx, dy; dbug_enter( "rdbuf_image" ); rd_data( pls, &nptsX, sizeof ( PLINT ) ); rd_data( pls, &nptsY, sizeof ( PLINT ) ); npts = nptsX * nptsY; rd_data( pls, &xmin, sizeof ( PLFLT ) ); rd_data( pls, &ymin, sizeof ( PLFLT ) ); rd_data( pls, &dx, sizeof ( PLFLT ) ); rd_data( pls, &dy, sizeof ( PLFLT ) ); rd_data( pls, &dev_zmin, sizeof ( short ) ); rd_data( pls, &dev_zmax, sizeof ( short ) ); // NOTE: Even though for memory buffered version all the data is in memory, // we still allocate and copy the data because I think that method works // better in a multithreaded environment. I could be wrong. // if ( ( ( dev_ix = (short *) malloc( (size_t) npts * sizeof ( short ) ) ) == NULL ) || ( ( dev_iy = (short *) malloc( (size_t) npts * sizeof ( short ) ) ) == NULL ) || ( ( dev_z = (unsigned short *) malloc( (size_t) ( ( nptsX - 1 ) * ( nptsY - 1 ) ) * sizeof ( unsigned short ) ) ) == NULL ) ) plexit( "rdbuf_image: Insufficient memory" ); rd_data( pls, dev_ix, sizeof ( short ) * (size_t) npts ); rd_data( pls, dev_iy, sizeof ( short ) * (size_t) npts ); rd_data( pls, dev_z, sizeof ( unsigned short ) * (size_t) ( ( nptsX - 1 ) * ( nptsY - 1 ) ) ); // // COMMENTED OUT by Hezekiah Carty // Commented (hopefullly temporarily) until the dev_fastimg rendering // path can be updated to support the new plimage internals. In the // meantime this function is not actually used so the issue of how to // update the code to support the new interface can be ignored. // //plP_image(dev_ix, dev_iy, dev_z, nptsX, nptsY, xmin, ymin, dx, dy, dev_zmin, dev_zmax); free( dev_ix ); free( dev_iy ); free( dev_z ); } //-------------------------------------------------------------------------- // rdbuf_swin() // // Set up plot window parameters. //-------------------------------------------------------------------------- static void rdbuf_swin( PLStream *pls ) { PLWindow plwin; rd_data( pls, &plwin.dxmi, sizeof ( PLFLT ) ); rd_data( pls, &plwin.dxma, sizeof ( PLFLT ) ); rd_data( pls, &plwin.dymi, sizeof ( PLFLT ) ); rd_data( pls, &plwin.dyma, sizeof ( PLFLT ) ); rd_data( pls, &plwin.wxmi, sizeof ( PLFLT ) ); rd_data( pls, &plwin.wxma, sizeof ( PLFLT ) ); rd_data( pls, &plwin.wymi, sizeof ( PLFLT ) ); rd_data( pls, &plwin.wyma, sizeof ( PLFLT ) ); plP_swin( &plwin ); } //-------------------------------------------------------------------------- // rdbuf_text() // // Draw PostScript text. //-------------------------------------------------------------------------- static void rdbuf_text( PLStream *pls ) { PLUNICODE( fci ); EscText text; PLFLT xform[4]; PLUNICODE* unicode; text.xform = xform; // Read in the data rd_data( pls, &fci, sizeof ( PLUNICODE ) ); rd_data( pls, &pls->chrht, sizeof ( PLFLT ) ); rd_data( pls, &pls->diorot, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpxmi, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpxma, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpymi, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpyma, sizeof ( PLFLT ) ); rd_data( pls, &text.base, sizeof ( PLINT ) ); rd_data( pls, &text.just, sizeof ( PLFLT ) ); rd_data( pls, text.xform, sizeof ( PLFLT ) * 4 ); rd_data( pls, &text.x, sizeof ( PLINT ) ); rd_data( pls, &text.y, sizeof ( PLINT ) ); rd_data( pls, &text.refx, sizeof ( PLINT ) ); rd_data( pls, &text.refy, sizeof ( PLINT ) ); rd_data( pls, &text.unicode_array_len, sizeof ( PLINT ) ); if ( text.unicode_array_len ) { if ( ( unicode = (PLUNICODE *) malloc( text.unicode_array_len * sizeof ( PLUNICODE ) ) ) == NULL ) plexit( "rdbuf_text: Insufficient memory" ); rd_data( pls, unicode, sizeof ( PLUNICODE ) * text.unicode_array_len ); text.unicode_array = unicode; } else text.unicode_array = NULL; // Make the call for unicode devices if ( pls->dev_unicode ) { plsfci( fci ); plP_esc( PLESC_HAS_TEXT, &text ); } } //-------------------------------------------------------------------------- // rdbuf_text_unicode() // // Draw text for the new unicode handling pathway. //-------------------------------------------------------------------------- static void rdbuf_text_unicode( PLINT op, PLStream *pls ) { PLUNICODE( fci ); EscText text; PLFLT xform[4]; text.xform = xform; // Read in the data rd_data( pls, &fci, sizeof ( PLUNICODE ) ); rd_data( pls, &pls->chrht, sizeof ( PLFLT ) ); rd_data( pls, &pls->diorot, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpxmi, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpxma, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpymi, sizeof ( PLFLT ) ); rd_data( pls, &pls->clpyma, sizeof ( PLFLT ) ); rd_data( pls, &text.base, sizeof ( PLINT ) ); rd_data( pls, &text.just, sizeof ( PLFLT ) ); rd_data( pls, text.xform, sizeof ( PLFLT ) * 4 ); rd_data( pls, &text.x, sizeof ( PLINT ) ); rd_data( pls, &text.y, sizeof ( PLINT ) ); rd_data( pls, &text.refx, sizeof ( PLINT ) ); rd_data( pls, &text.refy, sizeof ( PLINT ) ); rd_data( pls, &text.n_fci, sizeof ( PLUNICODE ) ); rd_data( pls, &text.n_char, sizeof ( PLUNICODE ) ); rd_data( pls, &text.n_ctrl_char, sizeof ( PLINT ) ); rd_data( pls, &text.unicode_array_len, sizeof ( PLINT ) ); if ( pls->dev_unicode ) { plsfci( fci ); plP_esc( op, &text ); } } //-------------------------------------------------------------------------- // plRemakePlot() // // Rebuilds plot from plot buffer, usually in response to a window // resize or exposure event. //-------------------------------------------------------------------------- void plRemakePlot( PLStream *pls ) { U_CHAR c; int plbuf_status; PLStream *save_pls; dbug_enter( "plRemakePlot" ); // Change the status of the flags before checking for a buffer. // Actually, more thought is needed if we want to support multithreaded // code correctly, specifically the case where two threads are using // the same plot stream (e.g. one thread is drawing the plot and another // thread is processing window manager messages). // plbuf_status = pls->plbuf_write; pls->plbuf_write = FALSE; pls->plbuf_read = TRUE; #ifdef BUFFERED_FILE if ( pls->plbufFile ) { rewind( pls->plbufFile ); #else if ( pls->plbuf_buffer ) { pls->plbuf_readpos = 0; #endif // Need to change where m_plsc points to before processing the commands. // If we have multiple plot streams, this will prevent the commands from // going to the wrong plot stream. // save_pls = m_plsc; m_plsc = pls; while ( rd_command( pls, &c ) ) { plbuf_control( pls, c ); } m_plsc = save_pls; } pls->plbuf_read = FALSE; pls->plbuf_write = plbuf_status; } //-------------------------------------------------------------------------- // plbuf_control() // // Processes commands read from the plot buffer. //-------------------------------------------------------------------------- static void plbuf_control( PLStream *pls, U_CHAR c ) { static U_CHAR c_old = 0; dbug_enter( "plbuf_control" ); switch ( (int) c ) { case INITIALIZE: rdbuf_init( pls ); break; case EOP: rdbuf_eop( pls ); break; case BOP: rdbuf_bop( pls ); break; case CHANGE_STATE: rdbuf_state( pls ); break; case LINE: rdbuf_line( pls ); break; case POLYLINE: rdbuf_polyline( pls ); break; case ESCAPE: rdbuf_esc( pls ); break; default: pldebug( "plbuf_control", "Unrecognized command %d, previous %d\n", c, c_old ); } c_old = c; } //-------------------------------------------------------------------------- // rd_command() // // Read & return the next command //-------------------------------------------------------------------------- static int rd_command( PLStream *pls, U_CHAR *p_c ) { int count; #ifdef BUFFERED_FILE count = fread( p_c, sizeof ( U_CHAR ), 1, pls->plbufFile ); #else if ( pls->plbuf_readpos < pls->plbuf_top ) { *p_c = *(U_CHAR *) ( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_readpos ); pls->plbuf_readpos += sizeof ( U_CHAR ); count = sizeof ( U_CHAR ); } else { count = 0; } #endif return ( count ); } //-------------------------------------------------------------------------- // rd_data() // // Read the data associated with the command //-------------------------------------------------------------------------- static void rd_data( PLStream *pls, void *buf, size_t buf_size ) { #ifdef BUFFERED_FILE plio_fread( buf, buf_size, 1, pls->plbufFile ); #else // If U_CHAR is not the same size as what memcpy() expects (typically 1 byte) // then this code will have problems. A better approach might be to use // uint8_t from <stdint.h> but I do not know how portable that approach is // memcpy( buf, (U_CHAR *) pls->plbuf_buffer + pls->plbuf_readpos, buf_size ); pls->plbuf_readpos += buf_size; #endif } //-------------------------------------------------------------------------- // wr_command() // // Write the next command //-------------------------------------------------------------------------- static void wr_command( PLStream *pls, U_CHAR c ) { #ifdef BUFFERED_FILE plio_fwrite( &c1, sizeof ( U_CHAR ), 1, pls->plbufFile ); #else if ( ( pls->plbuf_top + sizeof ( U_CHAR ) ) >= pls->plbuf_buffer_size ) { // Not enough space, need to grow the buffer pls->plbuf_buffer_size += pls->plbuf_buffer_grow; if ( pls->verbose ) printf( "Growing buffer to %d KB\n", (int) ( pls->plbuf_buffer_size / 1024 ) ); if ( ( pls->plbuf_buffer = realloc( pls->plbuf_buffer, pls->plbuf_buffer_size ) ) == NULL ) plexit( "plbuf wr_data: Plot buffer grow failed" ); } *(U_CHAR *) ( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_top ) = c; pls->plbuf_top += sizeof ( U_CHAR ); #endif } //-------------------------------------------------------------------------- // wr_data() // // Write the data associated with a command //-------------------------------------------------------------------------- static void wr_data( PLStream *pls, void *buf, size_t buf_size ) { #ifdef BUFFERED_FILE plio_fwrite( buf, buf_size, 1, pls->plbufFile ); #else if ( ( pls->plbuf_top + buf_size ) >= pls->plbuf_buffer_size ) { // Not enough space, need to grow the buffer // Must make sure the increase is enough for this data pls->plbuf_buffer_size += pls->plbuf_buffer_grow * ( ( pls->plbuf_top + buf_size - pls->plbuf_buffer_size ) / pls->plbuf_buffer_grow + 1 ); while ( pls->plbuf_top + buf_size >= pls->plbuf_buffer_size ) ; if ( ( pls->plbuf_buffer = realloc( pls->plbuf_buffer, pls->plbuf_buffer_size ) ) == NULL ) plexit( "plbuf wr_data: Plot buffer grow failed" ); } // If U_CHAR is not the same size as what memcpy() expects (typically 1 byte) // then this code will have problems. A better approach might be to use // uint8_t from <stdint.h> but I do not know how portable that approach is // memcpy( (U_CHAR *) pls->plbuf_buffer + pls->plbuf_top, buf, buf_size ); pls->plbuf_top += buf_size; #endif } // plbuf_save(state) // // Saves the current state of the plot into a save buffer. // This code was originally in gcw.c and gcw-lib.c. The original // code used a temporary file for the plot buffer and memory // to perserve colormaps. That method does not offer a clean // break between using memory buffers and file buffers. This // function preserves the same functionality by returning a data // structure that saves the plot buffer and colormaps seperately. // // The caller passes an existing save buffer for reuse or NULL // to force the allocation of a new buffer. Since one malloc() // is used for everything, the entire save buffer can be freed // with one free() call. // // struct _color_map { PLColor *cmap; PLINT icol; PLINT ncol; }; struct _state { size_t size; // Size of the save buffer int valid; // Flag to indicate a valid save state #ifdef BUFFERED_FILE FILE *plbufFile; #else void *plbuf_buffer; size_t plbuf_buffer_size; size_t plbuf_top; size_t plbuf_readpos; #endif struct _color_map *color_map; }; void * plbuf_save( PLStream *pls, void *state ) { size_t save_size; struct _state *plot_state = (struct _state *) state; PLINT i; U_CHAR *buf; // Assume that this is byte-sized if ( pls->plbuf_write ) { pls->plbuf_write = FALSE; pls->plbuf_read = TRUE; // Determine the size of the buffer required to save everything. We // assume that there are only two colormaps, but have written the code // that more than two can be handled with minimal changes. // save_size = sizeof ( struct _state ) + 2 * sizeof ( struct _color_map ) + (size_t) ( pls->ncol0 ) * sizeof ( PLColor ) + (size_t) ( pls->ncol1 ) * sizeof ( PLColor ); #ifndef BUFFERED_FILE // Only copy as much of the plot buffer that is being used save_size += pls->plbuf_top; #endif // If a buffer exists, determine if we need to resize it if ( state != NULL ) { // We have a save buffer, is it smaller than the current size requirement? if ( plot_state->size < save_size ) { // Yes, reallocate a larger one if ( ( plot_state = (struct _state *) realloc( state, save_size ) ) == NULL ) { // NOTE: If realloc fails, then plot_state ill be NULL. // This will leave the original buffer untouched, thus we // mark it as invalid and return it back to the caller. // plwarn( "plbuf: Unable to reallocate sufficient memory to save state" ); plot_state->valid = 0; return state; } plot_state->size = save_size; } } else { // A buffer does not exist, so we need to allocate one if ( ( plot_state = (struct _state *) malloc( save_size ) ) == NULL ) { plwarn( "plbuf: Unable to allocate sufficient memory to save state" ); return NULL; } plot_state->size = save_size; #ifdef BUFFERED_FILE // Make sure the FILE pointer is NULL in order to preven bad things from happening... plot_state->plbufFile = NULL; #endif } // At this point we have an appropriately sized save buffer. // We need to invalidate the state of the save buffer, since it // will not be valid until after everything is copied. We use // this approach vice freeing the memory and returning a NULL pointer // in order to prevent allocating and freeing memory needlessly. // plot_state->valid = 0; // Point buf to the space after the struct _state buf = (U_CHAR *) ( plot_state + 1 ); #ifdef BUFFERED_FILE // Remove the old tempfile, if it exists if ( plot_state->plbufFile != NULL ) { fclose( plot_state->plbufFile ); } // Copy the plot buffer to a tempfile if ( ( plot_state->plbufFile = pl_create_tempfile( NULL ) ) == NULL ) { // Throw a warning since this might be a permissions problem // and we may not want to force an exit // plwarn( "plbuf: Unable to open temporary file to save state" ); return (void *) plot_state; } else { U_CHAR tmp; rewind( pls->plbufFile ); while ( count = fread( &tmp, sizeof ( U_CHAR ), 1, pls->plbufFile ) ) { if ( fwrite( &tmp, sizeof ( U_CHAR ), 1, plot_state->plbufFile ) != count ) { // Throw a warning since this might be a permissions problem // and we may not want to force an exit // plwarn( "plbuf: Unable to write to temporary file" ); fclose( plot_state->plbufFile ); plot_state->plbufFile = NULL; return (void *) plot_state; } } } #else // Again, note, that we only copy the portion of the plot buffer that is being used plot_state->plbuf_buffer_size = pls->plbuf_top; plot_state->plbuf_top = pls->plbuf_top; plot_state->plbuf_readpos = 0; // Create a pointer that points in the space we allocated after struct _state plot_state->plbuf_buffer = (void *) buf; buf += pls->plbuf_top; // Copy the plot buffer to our new buffer. Again, I must stress, that we only // are copying the portion of the plot buffer that is being used // if ( memcpy( plot_state->plbuf_buffer, pls->plbuf_buffer, pls->plbuf_top ) == NULL ) { // This should never be NULL plwarn( "plbuf: Got a NULL in memcpy!" ); return (void *) plot_state; } #endif pls->plbuf_write = TRUE; pls->plbuf_read = FALSE; // Save the colormaps. First create a pointer that points in the space we allocated // after the plot buffer plot_state->color_map = (struct _color_map *) buf; buf += sizeof ( struct _color_map ) * 2; // Then we need to make space for the colormaps themselves plot_state->color_map[0].cmap = (PLColor *) buf; buf += sizeof ( PLColor ) * (size_t) ( pls->ncol0 ); plot_state->color_map[1].cmap = (PLColor *) buf; buf += sizeof ( PLColor ) * (size_t) ( pls->ncol1 ); // Save cmap 0 plot_state->color_map[0].icol = pls->icol0; plot_state->color_map[0].ncol = pls->ncol0; for ( i = 0; i < pls->ncol0; i++ ) { pl_cpcolor( &( plot_state->color_map[0].cmap[i] ), &pls->cmap0[i] ); } // Save cmap 1 plot_state->color_map[1].icol = pls->icol1; plot_state->color_map[1].ncol = pls->ncol1; for ( i = 0; i < pls->ncol1; i++ ) { pl_cpcolor( &( plot_state->color_map[1].cmap[i] ), &pls->cmap1[i] ); } plot_state->valid = 1; return (void *) plot_state; } return NULL; } // plbuf_restore(PLStream *, state) // // Restores the passed state // void plbuf_restore( PLStream *pls, void *state ) { struct _state *new_state = (struct _state *) state; #ifdef BUFFERED_FILE pls->plbufFile = new_state->save_file; #else pls->plbuf_buffer = new_state->plbuf_buffer; pls->plbuf_buffer_size = new_state->plbuf_buffer_size; pls->plbuf_top = new_state->plbuf_top; pls->plbuf_readpos = new_state->plbuf_readpos; #endif // cmap 0 pls->cmap0 = new_state->color_map[0].cmap; pls->icol0 = new_state->color_map[0].icol; pls->ncol0 = new_state->color_map[0].ncol; // cmap 1 pls->cmap1 = new_state->color_map[1].cmap; pls->icol1 = new_state->color_map[1].icol; pls->ncol1 = new_state->color_map[1].ncol; } // plbuf_switch(PLStream *, state) // // Makes the passed state the current one. Preserves the previous state // by returning a save buffer. // // NOTE: The current implementation can cause a memory leak under the // following scenario: // 1) plbuf_save() is called // 2) plbuf_switch() is called // 3) Commands are called which cause the plot buffer to grow // 4) plbuf_swtich() is called // void * plbuf_switch( PLStream *pls, void *state ) { struct _state *new_state = (struct _state *) state; struct _state *prev_state; size_t save_size; // No saved state was passed, return a NULL--we hope the caller // is smart enough to notice // if ( state == NULL ) return NULL; if ( !new_state->valid ) { plwarn( "plbuf: Attempting to switch to an invalid saved state" ); return NULL; } save_size = sizeof ( struct _state ) + 2 * sizeof ( struct _color_map ); if ( ( prev_state = (struct _state *) malloc( save_size ) ) == NULL ) { plwarn( "plbuf: Unable to allocate memory to save state" ); return NULL; } // Set some housekeeping variables prev_state->size = save_size; prev_state->valid = 1; // Preserve the existing state #ifdef BUFFERED_FILE prev_state->plbufFile = pls->plbufFile; #else prev_state->plbuf_buffer = pls->plbuf_buffer; prev_state->plbuf_buffer_size = pls->plbuf_buffer_size; prev_state->plbuf_top = pls->plbuf_top; prev_state->plbuf_readpos = pls->plbuf_readpos; #endif // cmap 0 prev_state->color_map[0].cmap = pls->cmap0; prev_state->color_map[0].icol = pls->icol0; prev_state->color_map[0].ncol = pls->ncol0; // cmap 1 prev_state->color_map[1].cmap = pls->cmap1; prev_state->color_map[1].icol = pls->icol1; prev_state->color_map[1].ncol = pls->ncol1; plbuf_restore( pls, new_state ); return (void *) prev_state; }
30.976207
135
0.510073
e59fdf2108f8a9cc91b033460bb0e43df2c9850d
1,251
cpp
C++
misc/longincsubseq.cpp
plilja/algolib
84b1e3115f18bac02632b6bef4ca11c3392e76a4
[ "Apache-2.0" ]
null
null
null
misc/longincsubseq.cpp
plilja/algolib
84b1e3115f18bac02632b6bef4ca11c3392e76a4
[ "Apache-2.0" ]
null
null
null
misc/longincsubseq.cpp
plilja/algolib
84b1e3115f18bac02632b6bef4ca11c3392e76a4
[ "Apache-2.0" ]
null
null
null
#include "longincsubseq.h" #include <cmath> using std::vector; /* * Do a binary search for the integer j. Such that lowerBound<=j<=upperBound * and that maximizes seq[M[j]] while keeping seq[M[j]]<x. */ int binSearch(vector<int> &M, const vector<int> &seq, int x, int lowerBound, int upperBound) { int lo = lowerBound; int hi = upperBound; while (lo <= hi) { int middle = ceil((lo + hi) / 2.0); if (seq[M[middle]] < x) { lo = middle + 1; } else { hi = middle - 1; } } return lo; } vector<int> recreateSolution(vector<int> &P, int ans_length, int final_idx) { vector<int> result(ans_length); int tmp = final_idx; for (int i = ans_length - 1; i >= 0; --i) { result[i] = tmp; tmp = P[tmp]; } return result; } vector<int> longincsubseq(const vector<int> &seq) { int len = seq.size(); vector<int> M(len + 1); vector<int> P(len); int ans_length = 0; M[0] = 0; for (int i = 0; i < len; ++i) { int lo = binSearch(M, seq, seq[i], 1, ans_length); P[i] = M[lo - 1]; M[lo] = i; ans_length = std::max(ans_length, lo); } return recreateSolution(P, ans_length, M[ans_length]); }
22.745455
92
0.54996
e59fe0557fffaea876c7d5aecde27a3afe0f5c40
1,034
cpp
C++
codeforces/N - Egg Drop/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/N - Egg Drop/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/N - Egg Drop/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: JU_AAA: prdx9_abir, aniks2645, kzvd4729 created: Sep/15/2017 22:21 * solution_verdict: Accepted language: GNU C++14 * run_time: 15 ms memory_used: 0 KB * problem: https://codeforces.com/gym/100819/problem/N ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long n,k,x; string s; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n>>k; long sf=1,br=k; for(long i=1; i<=n; i++) { cin>>x>>s; if(s=="SAFE") { sf=max(sf,x); } if(s=="BROKEN") { br=min(br,x); } } cout<<sf+1<<" "; cout<<br-1<<endl; return 0; }
30.411765
111
0.352998
e5a236aecc80419a14be0d7747cb1aec36bfe2c4
2,314
hpp
C++
include/ESPSerial.hpp
willson556/avr-2807
6bbb73072d94ab0cae2808d67aed5651c91a74b6
[ "MIT" ]
null
null
null
include/ESPSerial.hpp
willson556/avr-2807
6bbb73072d94ab0cae2808d67aed5651c91a74b6
[ "MIT" ]
null
null
null
include/ESPSerial.hpp
willson556/avr-2807
6bbb73072d94ab0cae2808d67aed5651c91a74b6
[ "MIT" ]
null
null
null
#pragma once #include "Transport.hpp" #include <driver/uart.h> #include <esp_timer.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> namespace AVR { class ESPSerial : public Transport { public: ESPSerial(uart_port_t port, uart_config_t config, size_t buffer_size, int timeout, int tx_pin, int rx_pin, int rts_pin, int cts_pin) : port{port}, config{config}, buffer_size{buffer_size}, timeout{timeout}, tx_pin{tx_pin}, rx_pin{rx_pin}, rts_pin{rts_pin}, cts_pin{cts_pin} { } void connect() const override { ESP_ERROR_CHECK(uart_param_config(port, &config)); ESP_ERROR_CHECK(uart_set_pin(port, tx_pin, rx_pin, rts_pin, cts_pin)); ESP_ERROR_CHECK(uart_driver_install(port, buffer_size, buffer_size, 10, (void**)&queue, 0)); } void write(const std::vector<uint8_t> &data) const override { ESP_ERROR_CHECK(uart_write_bytes(port, reinterpret_cast<const char *>(data.data()), data.size())); } std::vector<uint8_t> read(size_t max_length, bool wait_for_all) const override { unsigned long start_time = esp_timer_get_time(); size_t data_available; bool ready_to_read = false; do { ESP_ERROR_CHECK(uart_get_buffered_data_len(port, &data_available)); if (data_available >= max_length) { ready_to_read = true; } else if (!wait_for_all && data_available > 0) { ready_to_read = true; } } while ( esp_timer_get_time() - start_time < timeout * 1000 && !ready_to_read ); if (!ready_to_read) { return std::vector<uint8_t>{}; } std::vector<uint8_t> data(data_available); auto read_length = uart_read_bytes(port, data.data(), data.size(), timeout * portTICK_PERIOD_MS); data.resize(read_length < 0 ? 0 : read_length); return data; } void flush() const override { uart_flush(port); } private: const uart_port_t port; const uart_config_t config; const size_t buffer_size; const int timeout; // ms const int tx_pin; const int rx_pin; const int rts_pin; const int cts_pin; QueueHandle_t queue; }; } // namespace AVR
26.295455
136
0.627053
e5a54cd2ebd54f02c76a28d3131a827eeba66201
31,884
cpp
C++
enduser/windows.com/wuau/wuauclt/customlb.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/windows.com/wuau/wuauclt/customlb.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/windows.com/wuau/wuauclt/customlb.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "pch.h" #pragma hdrstop void SetMYLBAcc(HWND hListWin); void DrawMYLBFocus(HWND hListWin, LPDRAWITEMSTRUCT lpdis, MYLBFOCUS enCurFocus, INT nCurFocusId); void DrawItem(LPDRAWITEMSTRUCT lpdis, BOOL fSelectionDisabled); void DrawTitle(HDC hDC, LBITEM * plbi, RECT rc); void DrawRTF(HDC hDC, LBITEM * plbi, const RECT & rc /*, BOOL bHit*/); void DrawDescription(HDC hDC, LBITEM * plbi, RECT & rc); void DrawBitmap(HDC hDC, LBITEM * plbi, const RECT & rc, BOOL fSel, BOOL fSelectionDisabled); void CalcTitleFocusRect(const RECT &rcIn, RECT & rcOut); void CalcRTFFocusRect(const RECT &rcIn, RECT & rcOut); int CalcDescHeight(HDC hDC, LPTSTR ptszDescription, int cx); int CalcRTFHeight(HDC hDC, LPTSTR ptszRTF); int CalcRTFWidth(HDC hDC, LPTSTR ptszRTF); int CalcTitleHeight(HDC hDC, LPTSTR ptszTitle, int cx); int CalcItemHeight(HDC hDC, LPTSTR ptszTitle, LPTSTR ptszDescription, LPTSTR ptszRTF, int cx); void CalcItemLocation(HDC hDC, LBITEM * plbi, const RECT & rc); void ToggleSelection(HWND hDlg, HWND hListWin, LBITEM *pItem); void AddItem(LPTSTR tszTitle, LPTSTR tszDesc, LPTSTR tszRTF, int index, BOOL fSelected, BOOL fRTF); BOOL CurItemHasRTF(HWND hListWin); void RedrawMYLB(HWND hwndLB); void LaunchRTF(HWND hListWin); HBITMAP ghBmpGrayOut; //=NULL; HBITMAP ghBmpCheck; // = NULL; HBITMAP ghBmpClear; // = NULL; HFONT ghFontUnderline; // = NULL; HFONT ghFontBold; // = NULL; HFONT ghFontNormal; // = NULL; HWND ghWndList; //=NULL; MYLBFOCUS gFocus; INT gFocusItemId; TCHAR gtszRTFShortcut[MAX_RTFSHORTCUTDESC_LENGTH]; void LaunchRTF(HWND hListWin) { HWND hDlg = GetParent(hListWin); int i = (LONG)SendMessage(ghWndList, LB_GETCURSEL, 0, 0); if(i != LB_ERR) { LBITEM* pItem = (LBITEM*)SendMessage(hListWin, LB_GETITEMDATA, i, 0); if (pItem && pItem->bRTF) { DEBUGMSG("MYLB show RTF for item %S", pItem->szTitle); PostMessage(GetParent(hDlg), AUMSG_SHOW_RTF, LOWORD(pItem->m_index), 0); } } } //////////////////////////////////////////////////////////////////////////////// // Overwrite hListWin's accessibility behavior using dynamic annotation server //////////////////////////////////////////////////////////////////////////////// void SetMYLBAcc(HWND hListWin) { IAccPropServices * pAccPropSvc = NULL; HRESULT hr = CoCreateInstance(CLSID_AccPropServices, NULL, CLSCTX_INPROC_SERVER, IID_IAccPropServices, (void **) &pAccPropSvc); if( hr == S_OK && pAccPropSvc ) { MYLBAccPropServer* pMYLBPropSrv = new MYLBAccPropServer( pAccPropSvc ); if( pMYLBPropSrv ) { MSAAPROPID propids[4]; propids[0] = PROPID_ACC_NAME; propids[1] = PROPID_ACC_STATE; propids[2] = PROPID_ACC_ROLE; propids[3] = PROPID_ACC_DESCRIPTION; pAccPropSvc->SetHwndPropServer( hListWin, OBJID_CLIENT, 0, propids, 4, pMYLBPropSrv, ANNO_CONTAINER); pMYLBPropSrv->Release(); } pAccPropSvc->Release(); } else { DEBUGMSG("WANRING: WUAUCLT Fail to create object AccPropServices with error %#lx", hr); } // Mark the listbox so that the server can tell if it alive SetProp(hListWin, MYLBALIVEPROP, (HANDLE)TRUE); } /*void DumpRect(LPCTSTR tszName, RECT rc) { DEBUGMSG("DumpRect %S at (%d, %d, %d, %d)", tszName, rc.left, rc.top, rc.right, rc.bottom); } */ void DrawItem(LPDRAWITEMSTRUCT lpdis, BOOL fSelectionDisabled) { LRESULT lResult = SendMessage(lpdis->hwndItem, LB_GETITEMDATA, lpdis->itemID, 0); if (LB_ERR == lResult) { return; } LBITEM * plbi = (LBITEM*) lResult; CalcItemLocation(lpdis->hDC, plbi, lpdis->rcItem); // Draw the title of the item DrawTitle(lpdis->hDC, plbi, plbi->rcTitle); // Draw the text of the item DrawDescription(lpdis->hDC, plbi, plbi->rcText); // Draw the bitmap DrawBitmap(lpdis->hDC, plbi, plbi->rcBitmap, plbi->bSelect, fSelectionDisabled); // draw the Read this First DrawRTF(lpdis->hDC, plbi, plbi->rcRTF); } BOOL CurItemHasRTF(HWND hListWin) { int i = (LONG)SendMessage(hListWin, LB_GETCURSEL, 0, 0); if (LB_ERR == i) { return FALSE; } LBITEM *pItem = (LBITEM*)SendMessage(hListWin, LB_GETITEMDATA, (WPARAM)i, 0); return pItem->bRTF; } BOOL fDisableSelection(void) { AUOPTION auopt; if (SUCCEEDED(gInternals->m_getServiceOption(&auopt)) && auopt.fDomainPolicy && AUOPTION_SCHEDULED == auopt.dwOption) { return TRUE; } return FALSE; } void ToggleSelection(HWND hDlg, HWND hListWin, LBITEM *pItem) { //DEBUGMSG("ToggleSelection()"); if (NULL == hDlg || NULL == hListWin || NULL == pItem || pItem->m_index >= gInternals->m_ItemList.Count()) { AUASSERT(FALSE); //should never reach here. return; } HDC hDC = GetDC(hListWin); if (NULL == hDC) { return; } pItem->bSelect = !pItem->bSelect; DrawBitmap(hDC, pItem, pItem->rcBitmap, pItem->bSelect, FALSE); //obviously selection is allowed #ifndef TESTUI gInternals->m_ItemList[pItem->m_index].SetStatus(pItem->bSelect ? AUCATITEM_SELECTED : AUCATITEM_UNSELECTED); #endif PostMessage(GetParent(hDlg), AUMSG_SELECTION_CHANGED, 0, 0); ReleaseDC(hListWin, hDC); } void RedrawMYLB(HWND hwndLB) { //DEBUGMSG("REDRAW MYLB "); InvalidateRect(ghWndList, NULL, TRUE); UpdateWindow(ghWndList); } void CalcTitleFocusRect(const RECT &rcIn, RECT & rcOut) { rcOut = rcIn; rcOut.right -= TITLE_MARGIN * 2/3; rcOut.top += SECTION_SPACING * 2/3; rcOut.bottom -= SECTION_SPACING*2/3 ; } void CalcRTFFocusRect(const RECT &rcIn, RECT & rcOut) { rcOut = rcIn; rcOut.left -=3; rcOut.right +=3; rcOut.top -= 2; rcOut.bottom += 2; } void DrawMYLBFocus(HWND hListWin, LPDRAWITEMSTRUCT lpdis, MYLBFOCUS enCurFocus, INT nCurFocusId) { LBITEM * pItem; LRESULT lResult; //DEBUGMSG("DrawMYLBFocus for current focus %d with Item %d", enCurFocus, nCurFocusId); RECT rcNew; if (nCurFocusId != lpdis->itemID) { return; } if (GetFocus() != ghWndList ) { // DEBUGMSG("CustomLB doesn't have focus"); return; } lResult = SendMessage(hListWin, LB_GETITEMDATA, lpdis->itemID, 0); if (LB_ERR == lResult) { DEBUGMSG("DrawMYLBFocus() fail to get item data"); goto done; } pItem = (LBITEM*) lResult; if (!EqualRect(&lpdis->rcItem, &pItem->rcItem)) { CalcItemLocation(lpdis->hDC, pItem, lpdis->rcItem); } if (enCurFocus == MYLB_FOCUS_RTF) { CalcRTFFocusRect(pItem->rcRTF, rcNew); } if (enCurFocus == MYLB_FOCUS_TITLE) { CalcTitleFocusRect(pItem->rcTitle, rcNew); } DrawFocusRect(lpdis->hDC, &rcNew); //set new focus rect done: return; } LRESULT CallDefLBWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static WNDPROC s_defLBWndProc = NULL; if (NULL == s_defLBWndProc) { s_defLBWndProc = (WNDPROC) GetWindowLongPtr(hWnd, GWLP_USERDATA); } return CallWindowProc(s_defLBWndProc, hWnd, message, wParam, lParam); } LRESULT CALLBACK newLBWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_GETDLGCODE: return DLGC_WANTALLKEYS; case WM_KEYDOWN: switch(wParam) { case VK_RIGHT: case VK_LEFT: if (MYLB_FOCUS_RTF == gFocus) { DEBUGMSG("LB change focus to Title"); gFocus = MYLB_FOCUS_TITLE; RedrawMYLB(ghWndList); } else if (MYLB_FOCUS_TITLE == gFocus && CurItemHasRTF(hWnd)) { DEBUGMSG("LB change focus to RTF"); gFocus = MYLB_FOCUS_RTF; RedrawMYLB(ghWndList); } break; case VK_F1: if (GetKeyState(VK_SHIFT)<0) {//SHIFT down LaunchRTF(hWnd); return 0; } break; case VK_RETURN: if (MYLB_FOCUS_RTF == gFocus) { DEBUGMSG("MYLB show RTF "); LaunchRTF(hWnd); } break; case VK_TAB: PostMessage(GetParent(hWnd), WM_NEXTDLGCTL, 0, 0L); break; default: return CallDefLBWndProc(hWnd, message, wParam, lParam); } return 0; case WM_KEYUP: switch(wParam) { case VK_RIGHT: case VK_LEFT: break; case VK_RETURN: break; default: return CallDefLBWndProc(hWnd, message, wParam, lParam); } return 0; default: break; } return CallDefLBWndProc(hWnd, message, wParam, lParam); } // Message handler for Custom List box. LRESULT CALLBACK CustomLBWndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { static int lenx; int clb; LBITEM *item; static BOOL s_fSelectionDisabled; switch (message) { case WM_CREATE: { RECT rcLst, rcDlg; LOGFONT lf; HFONT parentFont; TCHAR tszRTF[MAX_RTF_LENGTH] = _T(""); GetClientRect(hDlg, &rcDlg); rcDlg.top += 2; rcDlg.bottom -= 3; rcDlg.left += 2; rcDlg.right -= 2; s_fSelectionDisabled = fDisableSelection(); ghWndList = CreateWindow(_T("listbox"), NULL, WS_CHILD | WS_VISIBLE | LBS_NOTIFY | LBS_OWNERDRAWVARIABLE | LBS_NOINTEGRALHEIGHT | LBS_HASSTRINGS | LBS_WANTKEYBOARDINPUT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP, rcDlg.left, rcDlg.top, rcDlg.right - rcDlg.left, rcDlg.bottom - rcDlg.top, hDlg, NULL, ghInstance, NULL); if (NULL == ghWndList) { return -1; } WNDPROC defLBWndProc = (WNDPROC) GetWindowLongPtr(ghWndList, GWLP_WNDPROC); SetWindowLongPtr(ghWndList, GWLP_USERDATA, (LONG_PTR) defLBWndProc); SetWindowLongPtr(ghWndList, GWLP_WNDPROC, (LONG_PTR) newLBWndProc); HDC hDC = GetDC(ghWndList); GetWindowRect(hDlg, &rcDlg); GetClientRect(ghWndList, &rcLst); lenx = rcLst.right - rcLst.left; // Load read this first text from resource file LoadString(ghInstance, IDS_READTHISFIRST, tszRTF, MAX_RTF_LENGTH); // load keyboard shortcut description for Read this First LoadString(ghInstance, IDS_RTFSHORTCUT, gtszRTFShortcut, MAX_RTFSHORTCUTDESC_LENGTH); // Load the bitmaps ghBmpClear = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_CLEAR), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION); ghBmpCheck = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_CHECK), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION); ghBmpGrayOut = (HBITMAP)LoadImage(ghInstance, MAKEINTRESOURCE(IDB_GRAYOUT), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS | LR_CREATEDIBSECTION); // Create BOLD and Italic fonts ZeroMemory(&lf, sizeof(lf)); //fixcode: check return value of GetCurrentObject() GetObject(GetCurrentObject(hDC, OBJ_FONT), sizeof(lf), &lf); //fixcode: check return value of GetParent() parentFont = (HFONT)SendMessage(GetParent(hDlg), WM_GETFONT, 0, 0); SendMessage(hDlg, WM_SETFONT, (WPARAM)parentFont, FALSE); SelectObject(hDC, parentFont); //fixcode: check return value of GetCurrentObject() GetObject(GetCurrentObject(hDC, OBJ_FONT), sizeof(lf), &lf); lf.lfUnderline = TRUE; lf.lfWeight = FW_NORMAL; //fixcode: check return value of CreateFontIndirect() ghFontUnderline = CreateFontIndirect(&lf); lf.lfUnderline = FALSE; lf.lfWeight = FW_NORMAL; //fixcode: check return value of CreateFontIndirect() ghFontNormal = CreateFontIndirect(&lf); lf.lfUnderline = FALSE; lf.lfWeight = FW_HEAVY; //fixcode: check return value of CreateFontIndirect() ghFontBold = CreateFontIndirect(&lf); ReleaseDC(ghWndList, hDC); #ifdef TESTUI { AddItem(_T("Test 1 Very long title Test 1 Very long title Test 1 Very long title Test 1 Very long title "), _T("Description"), tszRTF, 0, TRUE, TRUE); AddItem(_T("Test 2"), _T("Another description. No RTF"), tszRTF,0, TRUE, FALSE); } #else #if 0 DEBUGMSG("WM_CREATE: before add item rcLst=(%d, %d)-(%d, %d)", rcLst.left, rcLst.top, rcLst.right, rcLst.bottom); #endif { for (UINT i = 0; i < gInternals->m_ItemList.Count(); i++) { DEBUGMSG("selected[%d] = %lu", i, gInternals->m_ItemList[i].dwStatus()); if ( !gInternals->m_ItemList[i].fHidden() ) { AddItem(gInternals->m_ItemList[i].bstrTitle(), gInternals->m_ItemList[i].bstrDescription(), tszRTF, i, gInternals->m_ItemList[i].fSelected(), IsRTFDownloaded(gInternals->m_ItemList[i].bstrRTFPath(), GetSystemDefaultLangID())); } } } GetClientRect(ghWndList, &rcLst); #if 0 DEBUGMSG("WM_CREATE: after add item rcLst=(%d, %d)-(%d, %d)", rcLst.left, rcLst.top, rcLst.right, rcLst.bottom); #endif if (rcLst.right - rcLst.left != lenx) { lenx = rcLst.right - rcLst.left; hDC = GetDC(ghWndList); int nListIndex = 0; for (UINT i = 0; i < gInternals->m_ItemList.Count(); i++) { DEBUGMSG("selected[%d] = %lu", i, gInternals->m_ItemList[i].dwStatus()); if ( !gInternals->m_ItemList[i].fHidden() ) { if (LB_ERR == SendMessage( ghWndList, LB_SETITEMHEIGHT, nListIndex, CalcItemHeight( hDC, gInternals->m_ItemList[i].bstrTitle(), gInternals->m_ItemList[i].bstrDescription(), tszRTF, lenx))) { DEBUGMSG("failed to recalc height of item %u", i); break; } nListIndex++; } } ReleaseDC(ghWndList, hDC); } #endif SendMessage(ghWndList, LB_SETCURSEL, 0, 0); gFocus = MYLB_FOCUS_TITLE; gFocusItemId = 0; SetMYLBAcc(ghWndList); return 0; } case WM_MOVE: { RECT rcList; GetWindowRect(ghWndList, &rcList); // need this to force LB to realize it got moved return(TRUE); } case WM_SETCURSOR: { if (ghWndList == (HWND)wParam && LOWORD(lParam) == HTCLIENT && HIWORD(lParam) == WM_MOUSEMOVE) { POINT pt; RECT rc; GetCursorPos(&pt); if (0 == MapWindowPoints(NULL, ghWndList, &pt, 1)) { DEBUGMSG("MYLBWndProc MapWindowPoints failed"); return FALSE; } DWORD dwPos; dwPos = MAKELONG( pt.x, pt.y); DWORD dwItem = (LONG)SendMessage(ghWndList, LB_ITEMFROMPOINT, 0, dwPos); if (LOWORD(dwItem) == -1) return(FALSE); item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, LOWORD(dwItem), 0); SendMessage(ghWndList, LB_GETITEMRECT, LOWORD(dwItem), (LPARAM)&rc); if (!EqualRect(&rc, &item->rcItem)) { HDC hDC = GetDC(ghWndList); CalcItemLocation(hDC, item, rc); ReleaseDC(ghWndList, hDC); } if (item->bRTF && PtInRect(&item->rcRTF, pt)) { // DEBUGMSG("Change Cursor to hand in MOUSEMOVE"); SetCursor(ghCursorHand); return TRUE; } return FALSE; } else if (ghWndList == (HWND)wParam && LOWORD(lParam) == HTCLIENT && HIWORD(lParam) == WM_LBUTTONDOWN) { POINT pt; RECT rc; GetCursorPos(&pt); if (0 == MapWindowPoints(NULL, ghWndList, &pt, 1)) { DEBUGMSG("MYLBWndProc MapWindowPoints failed"); return FALSE; } DWORD dwPos; dwPos = MAKELONG( pt.x, pt.y); DWORD dwItem = (LONG)SendMessage(ghWndList, LB_ITEMFROMPOINT, 0, dwPos); if (LOWORD(dwItem) == -1) return(FALSE); item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, LOWORD(dwItem), 0); SendMessage(ghWndList, LB_GETITEMRECT, LOWORD(dwItem), (LPARAM)&rc); if (!EqualRect(&rc, &item->rcItem)) { HDC hDC = GetDC(ghWndList); CalcItemLocation(hDC, item, rc); ReleaseDC(ghWndList, hDC); } // Are we clicking on the Title? if (PtInRect(&item->rcBitmap, pt)) { if (!s_fSelectionDisabled) { ToggleSelection(hDlg, ghWndList, item); } // DEBUGMSG("WM_SETCURSOR change gFocus to TITLE"); gFocus = MYLB_FOCUS_TITLE; gFocusItemId = dwItem; RedrawMYLB(ghWndList); return TRUE; } // or are we clicking on the RTF? if (item->bRTF && PtInRect(&item->rcRTF, pt)) { PostMessage(GetParent(hDlg), AUMSG_SHOW_RTF, LOWORD(item->m_index), 0); SetCursor(ghCursorHand); //DEBUGMSG("WM_SETCURSOR change gFocus to RTF"); gFocus = MYLB_FOCUS_RTF; gFocusItemId = dwItem; RedrawMYLB(ghWndList); return TRUE; } return FALSE; } return FALSE; } case WM_MEASUREITEM: { LPMEASUREITEMSTRUCT lpmis = (LPMEASUREITEMSTRUCT) lParam ; #if 0 DEBUGMSG("WM_MEASUREITEM: ctlId=%u, itemId=%u, itemWidth=%u, itemHeight=%u", lpmis->CtlID, lpmis->itemID, lpmis->itemWidth, lpmis->itemHeight); #endif HDC hdc = GetDC(ghWndList); LBITEM * plbi = (LBITEM*)lpmis->itemData; lpmis->itemHeight = CalcItemHeight(hdc, plbi->szTitle, plbi->pszDescription, plbi->szRTF, lenx); ReleaseDC(ghWndList, hdc); return TRUE; } case WM_PAINT: PAINTSTRUCT ps; RECT borderRect; BeginPaint(hDlg, &ps); GetClientRect(hDlg, &borderRect); DrawEdge(ps.hdc, &borderRect, EDGE_ETCHED, BF_RECT); EndPaint(hDlg, &ps); break; case WM_NEXTDLGCTL: PostMessage(GetParent(hDlg), WM_NEXTDLGCTL, 0, 0L); return 0; case WM_KEYUP: //DEBUGMSG("MYLB got KEYUP key %d", wParam); switch(wParam) { case VK_TAB: case VK_DOWN: case VK_UP: SetFocus(ghWndList); return 0; default: break; } break; case WM_VKEYTOITEM: { //DEBUGMSG("WM_VKEYTOITEM got char %d", LOWORD(wParam)); if (LOWORD(wParam) != VK_SPACE) { return -1; } if (MYLB_FOCUS_TITLE == gFocus) { int i = (LONG)SendMessage(ghWndList, LB_GETCURSEL, 0, 0); if (LB_ERR == i) { return -2; } item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, i, 0); if (!s_fSelectionDisabled) { ToggleSelection(hDlg, ghWndList, item); } return -2; } if (MYLB_FOCUS_RTF == gFocus) { LaunchRTF(ghWndList); } return -2; } case WM_DRAWITEM: { LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) lParam; #if 0 DEBUGMSG("WM_DRAWITEM: ctlId=%u, itemId=%u, rcItem=(%d, %d)-(%d, %d)", lpdis->CtlID, lpdis->itemID, lpdis->rcItem.left, lpdis->rcItem.top, lpdis->rcItem.right, lpdis->rcItem.bottom); #endif // If there are no list box items, skip this message. if (lpdis->itemID == -1) { break; } // Draw the bitmap and text for the list box item. Draw a // rectangle around the bitmap if it is selected. switch (lpdis->itemAction) { case ODA_SELECT: case ODA_DRAWENTIRE: //DEBUGMSG("MYLB WM_DRAWITEM ODA_DRAWENTIRE for %d", lpdis->itemID); DrawItem(lpdis, s_fSelectionDisabled); DrawMYLBFocus(ghWndList, lpdis, gFocus, gFocusItemId); break; case ODA_FOCUS: if (lpdis->itemID != gFocusItemId) { gFocusItemId = lpdis->itemID; gFocus = MYLB_FOCUS_TITLE; } //DEBUGMSG("MYLB ODA_FOCUS change focus to %d", gFocusItemId); DrawItem(lpdis, s_fSelectionDisabled); DrawMYLBFocus(ghWndList, lpdis, gFocus, gFocusItemId); break; } return TRUE; } case WM_DESTROY: // need to cleanup the fonts if (ghFontBold) DeleteObject(ghFontBold); if (ghFontUnderline) DeleteObject(ghFontUnderline); if (ghFontNormal) DeleteObject(ghFontNormal); if (ghBmpCheck) DeleteObject(ghBmpCheck); if (ghBmpGrayOut) DeleteObject(ghBmpGrayOut); if (ghBmpClear) DeleteObject(ghBmpClear); ghFontNormal = NULL; ghFontBold = NULL; ghFontUnderline = NULL; ghBmpCheck = NULL; ghBmpGrayOut = NULL; ghBmpClear = NULL; EnterCriticalSection(&gcsClient); RemoveProp( ghWndList, MYLBALIVEPROP ); clb = (LONG)SendMessage(ghWndList, LB_GETCOUNT, 0, 0); for(int i = 0; i < clb; i++) { item = (LBITEM*)SendMessage(ghWndList, LB_GETITEMDATA, i, 0); delete(item); } LeaveCriticalSection(&gcsClient); return 0; } return DefWindowProc(hDlg, message, wParam, lParam); } void DrawTitle(HDC hDC, LBITEM * plbi, RECT rc) { // we want the bitmap to be on the same background as the title, let's do this here since we // already have all the measures. RECT rcTop = rc; rcTop.left = 0; // draw menu background rectangle for the title and bitmap HBRUSH hBrush; if (! (hBrush = CreateSolidBrush(GetSysColor(COLOR_MENU)))) { DEBUGMSG("WUAUCLT CreateSolidBrush failure in DrawTitle, GetLastError=%lu", GetLastError()); return; } FillRect(hDC, (LPRECT)&rcTop, hBrush); if (NULL != hBrush) { DeleteObject(hBrush); } // draw 3d look DrawEdge(hDC, &rcTop, EDGE_ETCHED, BF_RECT); // change text and back ground color of list box's selection DWORD dwOldTextColor = SetTextColor(hDC, GetSysColor(COLOR_MENUTEXT)); // black text color DWORD dwOldBkColor = SetBkColor(hDC, GetSysColor(COLOR_MENU)); // text cell light gray background HFONT hFontPrev = (HFONT)SelectObject(hDC, ghFontBold); rc.left += TITLE_MARGIN; rc.top += SECTION_SPACING; rc.right -= TITLE_MARGIN; rc.bottom -= SECTION_SPACING; DrawText(hDC, (LPTSTR)plbi->szTitle, -1, &rc, DT_WORDBREAK | DT_NOPREFIX); // restore text and back ground color of list box's selection SetTextColor(hDC, dwOldTextColor); SetBkColor(hDC, dwOldBkColor); SelectObject(hDC, hFontPrev); return; } void DrawRTF(HDC hDC, LBITEM * plbi, const RECT & rc /*,BOOL fHit*/) { if (!plbi->bRTF) return; //draw RTF background RECT rcBackGround; CalcRTFFocusRect(rc, rcBackGround); HBRUSH hBrush; if (!(hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW)))) { DEBUGMSG("WUAUCLT CreateSolidBrush failure in DrawRTF, GetLastError=%lu", GetLastError()); return; } if (!FillRect(hDC, (LPRECT)&rcBackGround, hBrush)) { DEBUGMSG("Fail to erase RTF background"); } if (NULL != hBrush) { DeleteObject(hBrush); } HFONT hFontPrev = (HFONT) SelectObject(hDC, ghFontUnderline); DWORD dwOldTextColor = SetTextColor(hDC, GetSysColor(ATTENTION_COLOR)); SetBkMode(hDC, TRANSPARENT); // add the read this first TextOut(hDC, (int)(rc.left), (int)(rc.top), (LPTSTR)plbi->szRTF, lstrlen(plbi->szRTF)); // restore text and back ground color of list box's selection SetTextColor(hDC, dwOldTextColor); SelectObject(hDC, hFontPrev); return; } void DrawDescription(HDC hDC, LBITEM * plbi, RECT & rc) { #if 0 DEBUGMSG("draw \"%S\" (%d, %d) - (%d, %d)", (LPTSTR)plbi->pszDescription, rc.left, rc.top, rc.right, rc.bottom); #endif HFONT hFontPrev = (HFONT)SelectObject(hDC, ghFontNormal); DrawText(hDC, (LPTSTR)plbi->pszDescription, -1, &rc, DT_BOTTOM | DT_EXPANDTABS | DT_WORDBREAK | DT_EDITCONTROL | DT_NOPREFIX); SelectObject(hDC, hFontPrev); return; } void DrawBitmap(HDC hDC, LBITEM * plbi, const RECT & rc, BOOL fSel, BOOL fSelectionDisabled) { HDC hdcMem; plbi->bSelect = fSel; if (hdcMem = CreateCompatibleDC(hDC)) { HGDIOBJ hBmp; if (fSelectionDisabled) { hBmp = ghBmpGrayOut; // DEBUGMSG("Set bitmap to grayout"); } else { // DEBUGMSG("Set bitmap to selectable"); hBmp = (plbi->bSelect ? ghBmpCheck : ghBmpClear); } HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcMem, hBmp); BitBlt(hDC, rc.left + 3, rc.top + SECTION_SPACING, rc.right - rc.left, rc.bottom - rc.top, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmpOld); DeleteDC(hdcMem); } } BOOL GetBmpSize(HANDLE hBmp, SIZE *psz) { if (NULL == hBmp || NULL == psz) { DEBUGMSG("Error: GetBmpSize() invalid parameter"); return FALSE; } BITMAP bm; ZeroMemory(&bm, sizeof(bm)); if (0 == GetObject(hBmp, sizeof(bm), &bm)) { return FALSE; } psz->cx = bm.bmWidth; psz->cy = bm.bmHeight; return TRUE; } //fixcode: should return error code void AddItem(LPTSTR tszTitle, LPTSTR tszDesc, LPTSTR tszRTF, int index, BOOL fSelected, BOOL fRTF) { LBITEM *newItem = new(LBITEM); if (! newItem) { DEBUGMSG("WUAUCLT new() failed in AddItem, GetLastError=%lu", GetLastError()); goto Failed; } DWORD dwDescLen = max(lstrlen(tszDesc), MAX_DESC_LENGTH); newItem->pszDescription = (LPTSTR) malloc((dwDescLen+1) * sizeof(TCHAR)); if (NULL == newItem->pszDescription) { DEBUGMSG("AddItem() fail to alloc memory for description"); goto Failed; } (void)StringCchCopyEx(newItem->szTitle, ARRAYSIZE(newItem->szTitle), tszTitle, NULL, NULL, MISTSAFE_STRING_FLAGS); (void)StringCchCopyEx(newItem->pszDescription, dwDescLen+1, tszDesc, NULL, NULL, MISTSAFE_STRING_FLAGS); (void)StringCchCopyEx(newItem->szRTF, ARRAYSIZE(newItem->szRTF), tszRTF, NULL, NULL, MISTSAFE_STRING_FLAGS); newItem->m_index = index; newItem->bSelect = fSelected; newItem->bRTF = fRTF; LRESULT i = SendMessage(ghWndList, LB_GETCOUNT, 0, 0); if (LB_ERR == i || LB_ERR == (i = SendMessage(ghWndList, LB_INSERTSTRING, (WPARAM) i, (LPARAM) newItem->szTitle)) || LB_ERRSPACE == i || LB_ERR == SendMessage(ghWndList, LB_SETITEMDATA, (WPARAM) i, (LPARAM) newItem)) { DEBUGMSG("WUAUCLT AddItem() fail to add item to listbox"); goto Failed; } return; Failed: SafeDelete(newItem); QuitNRemind(TIMEOUT_INX_TOMORROW); } //////////////////////////////////////////////////// // utility function // calculate the height of a paragraph in current // device context //////////////////////////////////////////////////// UINT GetParagraphHeight(HDC hDC, LPTSTR tszPara, int nLineWidth, UINT uExtraFormat = 0) { UINT y = 0; if (0 == nLineWidth) { return 0; } RECT rc; ZeroMemory(&rc, sizeof(rc)); rc.right = nLineWidth; if (0 == DrawText(hDC, tszPara, -1, &rc, DT_WORDBREAK | DT_NOPREFIX | DT_NOCLIP | DT_CALCRECT | uExtraFormat)) { DEBUGMSG("failed to calc paragraph height w/ error %ld", GetLastError()); return 0; } #if 0 else { DEBUGMSG("para \"%S\" line-width=%lu (%d, %d) - (%d, %d)", tszPara, nLineWidth, rc.left, rc.top, rc.right, rc.bottom); } #endif return rc.bottom - rc.top + 1; } int CalcDescHeight(HDC hDC, LPTSTR ptszDescription, int cx) { int y = 0; HFONT hPrevFont = NULL; hPrevFont = (HFONT) SelectObject(hDC, ghFontNormal); y = GetParagraphHeight(hDC, ptszDescription, cx, DT_BOTTOM | DT_EXPANDTABS | DT_EDITCONTROL); SelectObject(hDC, hPrevFont); return y; } int CalcRTFHeight(HDC hDC, LPTSTR ptszRTF) { SIZE sz ; ZeroMemory(&sz, sizeof(sz)); HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontUnderline); //fixcode: check return value of GetTextExtentPoint32() GetTextExtentPoint32(hDC, ptszRTF, lstrlen(ptszRTF), &sz); SelectObject(hDC, hPrevFont); return sz.cy; } int CalcRTFWidth(HDC hDC, LPTSTR ptszRTF) { SIZE sz; HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontUnderline); //fixcode: check return value of GetTextExtentPoint32() GetTextExtentPoint32(hDC, ptszRTF, lstrlen(ptszRTF), &sz); SelectObject(hDC, hPrevFont); return sz.cx; } int CalcTitleHeight(HDC hDC, LPTSTR ptszTitle, int cx) { INT y = 0; INT iBmpHeight = 0; HFONT hPrevFont = (HFONT) SelectObject(hDC, ghFontBold); y = GetParagraphHeight(hDC, ptszTitle, cx); SelectObject(hDC, hPrevFont); // get checkbox size if (NULL != ghBmpCheck && NULL != ghBmpClear && NULL != ghBmpGrayOut) { SIZE sz1 ; SIZE sz2 ; SIZE sz3 ; sz1.cy = sz2.cy = sz3.cy = DEF_CHECK_HEIGHT; GetBmpSize(ghBmpCheck, &sz1); GetBmpSize(ghBmpClear, &sz2); GetBmpSize(ghBmpGrayOut, &sz3); iBmpHeight = max(sz1.cy, sz2.cy); iBmpHeight = max(iBmpHeight, sz3.cy); } return max(y, iBmpHeight); //make title height a little bigger for clearer focus rect } int CalcItemHeight(HDC hdc, LPTSTR ptszTitle, LPTSTR ptszDescription, LPTSTR ptszRTF, int cx) { return CalcTitleHeight(hdc, ptszTitle, cx - XBITMAP - 2* TITLE_MARGIN) + CalcDescHeight(hdc, ptszDescription, cx - XBITMAP ) + CalcRTFHeight(hdc, ptszRTF) + 4 * SECTION_SPACING; } //////////////////////////////////////////////////////////// /// Layout of listbox item: /// spacing /// bitmap margin TITLE margin /// spacing /// DESCRIPTION /// spacing /// RTF rtf_margin /// spacing /////////////////////////////////////////////////////////// void CalcItemLocation(HDC hDC, LBITEM * plbi, const RECT & rc) { // Calculate the positon of each element plbi->rcItem = rc; plbi->rcTitle = rc; plbi->rcTitle.left += XBITMAP ; plbi->rcTitle.bottom = plbi->rcTitle.top + CalcTitleHeight(hDC, plbi->szTitle, plbi->rcTitle.right - plbi->rcTitle.left - 2* TITLE_MARGIN) + 2 * SECTION_SPACING; plbi->rcText = rc; plbi->rcText.left = plbi->rcTitle.left; plbi->rcText.right = plbi->rcTitle.right; plbi->rcText.top = plbi->rcTitle.bottom; int nRtfHeight = CalcRTFHeight(hDC, plbi->szRTF); plbi->rcText.bottom -= nRtfHeight + SECTION_SPACING; // plbi->rcRTF = plbi->rcText; plbi->rcRTF.top = plbi->rcText.bottom; plbi->rcRTF.bottom = plbi->rcRTF.top + nRtfHeight; plbi->rcRTF.right = plbi->rcText.right - RTF_MARGIN; plbi->rcRTF.left = plbi->rcRTF.right - CalcRTFWidth(hDC, plbi->szRTF); plbi->rcBitmap = rc; plbi->rcBitmap.bottom = plbi->rcTitle.bottom; return; }
30.164617
188
0.59475
e5a9272774f3c2af98b49b6bc3803df1d49c988e
3,815
cpp
C++
src/renderEffects/auraCompositing.cpp
mfirmin/xray-vision
c40fc300d95d55c15f0dffa484b7123eb69238b5
[ "MIT" ]
1
2021-09-13T20:22:29.000Z
2021-09-13T20:22:29.000Z
src/renderEffects/auraCompositing.cpp
mfirmin/xray-vision
c40fc300d95d55c15f0dffa484b7123eb69238b5
[ "MIT" ]
null
null
null
src/renderEffects/auraCompositing.cpp
mfirmin/xray-vision
c40fc300d95d55c15f0dffa484b7123eb69238b5
[ "MIT" ]
1
2021-09-13T20:22:31.000Z
2021-09-13T20:22:31.000Z
#include "auraCompositing.hpp" #include "gl/shaderUtils.hpp" #include "light/light.hpp" #include <array> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <string> #include <sstream> AuraCompositingEffect::AuraCompositingEffect(int w, int h) : width(w), height(h) { } void AuraCompositingEffect::initialize() { createDebugProgram(); createProgram(); createArrayObjects(); } AuraCompositingEffect::~AuraCompositingEffect() { // TODO: Free buffers } void AuraCompositingEffect::createArrayObjects() { glGenVertexArrays(1, &vao); glGenBuffers(1, &vertexBuffer); glGenBuffers(1, &uvBuffer); glBindVertexArray(vao); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // NDC Coords std::vector<float> vertices = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f }; glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GL_FLOAT), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); std::vector<float> uvs = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(GL_FLOAT), uvs.data(), GL_STATIC_DRAW); } void AuraCompositingEffect::createDebugProgram() { std::string vertexShaderSource = R"( #version 330 layout(location = 0) in vec2 position; layout(location = 1) in vec2 uv; out vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position, 0.0, 1.0); } )"; std::string fragmentShaderSource = R"( #version 330 uniform sampler2D input; in vec2 vUv; out vec4 fragColor; void main() { vec3 color = texture(input, vUv).rgb; color = color + vec3(1.0) * 0.5; fragColor = vec4(color, 1.0); } )"; debugProgram = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource); } void AuraCompositingEffect::createProgram() { std::string vertexShaderSource = R"( #version 330 layout(location = 0) in vec2 position; layout(location = 1) in vec2 uv; out vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position, 0.0, 1.0); } )"; std::string fragmentShaderSource = R"( #version 330 uniform mat4 viewMatrix; uniform sampler2D scene; uniform sampler2D aura; in vec2 vUv; out vec4 fragColor; void main() { vec4 sceneColor = texture(scene, vUv); vec4 auraColor = texture(aura, vUv); fragColor = vec4(mix(sceneColor.rgb, auraColor.rgb, auraColor.a), 1.0); } )"; program = ShaderUtils::compile(vertexShaderSource, fragmentShaderSource); } void AuraCompositingEffect::render(GLuint sceneTexture, GLuint auraTexture) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(0.0, 0.0, 0.0, 1.0); // Clear it glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render the screen object to it glBindVertexArray(vao); auto prog = program; // use the debug program from the deferred target (just render 1 property) glUseProgram(prog); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sceneTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, auraTexture); glUniform1i(glGetUniformLocation(prog, "scene"), 0); glUniform1i(glGetUniformLocation(prog, "aura"), 1); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glUseProgram(0); }
23.404908
103
0.627785
e5b01e0b2838076f577fed8c236caabd12886b77
1,409
cpp
C++
src/drone_marker_pub.cpp
i3drobotics/kimera_rviz_markers
e1de992b98dc28f508376dc5736e48efa894c90d
[ "MIT" ]
2
2019-09-22T09:20:56.000Z
2019-12-12T11:40:03.000Z
src/drone_marker_pub.cpp
i3drobotics/kimera_rviz_markers
e1de992b98dc28f508376dc5736e48efa894c90d
[ "MIT" ]
2
2020-01-16T12:56:04.000Z
2020-05-21T17:19:44.000Z
src/drone_marker_pub.cpp
i3drobotics/kimera_rviz_markers
e1de992b98dc28f508376dc5736e48efa894c90d
[ "MIT" ]
5
2019-09-23T18:16:40.000Z
2021-07-03T14:21:29.000Z
#include "kimera_rviz_markers/kimera_rviz_markers.h" int main(int argc, char** argv) { // Initialize ROS node ros::init(argc, argv, "drone_marker_pub"); ros::NodeHandle nh_; ros::NodeHandle nh_private_ ("~"); krm::DroneParams quad_params; nh_private_.getParam("frame_id", quad_params.frame_id); nh_private_.getParam("scale", quad_params.scale); nh_private_.getParam("num_rotors", quad_params.num_rotors); nh_private_.getParam("arm_len", quad_params.arm_len); nh_private_.getParam("body_width", quad_params.body_width); nh_private_.getParam("body_height", quad_params.body_height); nh_private_.getParam("r_color", quad_params.r_color); nh_private_.getParam("g_color", quad_params.g_color); nh_private_.getParam("b_color", quad_params.b_color); tf::Vector3 position (0, 0, 0); ros::Time timestamp = ros::Time(); std::vector<visualization_msgs::Marker> drone_markers = krm::makeDroneMarkers(timestamp, quad_params); ros::Rate rate (20); ros::Publisher drone_marker_pub = nh_.advertise<visualization_msgs::MarkerArray>("drone_markers", 10, true); while(ros::ok()) { if (drone_marker_pub.getNumSubscribers() > 0) { visualization_msgs::MarkerArray msg; msg.markers = drone_markers; drone_marker_pub.publish(msg); } ros::spinOnce(); rate.sleep(); } ROS_INFO("Exiting drone marker publisher."); return EXIT_SUCCESS; }
32.767442
80
0.726757
e5b2c5518f46c1344445a67cd64dc67eb029a489
5,117
cpp
C++
test/block.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
test/block.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
test/block.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
// This file is part of Asteria. // Copyleft 2018, LH_Mouse. All wrongs reserved. #include "_test_init.hpp" #include "../asteria/src/block.hpp" #include "../asteria/src/xpnode.hpp" #include "../asteria/src/statement.hpp" #include "../asteria/src/global_context.hpp" #include "../asteria/src/executive_context.hpp" using namespace Asteria; int main() { Vector<Statement> text; // var res = 0; Vector<Xpnode> expr; expr.emplace_back(Xpnode::S_literal { D_integer(0) }); text.emplace_back(Statement::S_var_def { String::shallow("res"), false, std::move(expr) }); // const data = [ 1, 2, 3, 2 * 5 ]; expr.clear(); expr.emplace_back(Xpnode::S_literal { D_integer(1) }); expr.emplace_back(Xpnode::S_literal { D_integer(2) }); expr.emplace_back(Xpnode::S_literal { D_integer(3) }); expr.emplace_back(Xpnode::S_literal { D_integer(2) }); expr.emplace_back(Xpnode::S_literal { D_integer(5) }); expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false }); expr.emplace_back(Xpnode::S_unnamed_array { 4 }); text.emplace_back(Statement::S_var_def { String::shallow("data"), true, std::move(expr) }); // for(each k, v in data) { // res += k * v; // } Vector<Xpnode> range; range.emplace_back(Xpnode::S_named_reference { String::shallow("data") }); expr.clear(); expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") }); expr.emplace_back(Xpnode::S_named_reference { String::shallow("k") }); expr.emplace_back(Xpnode::S_named_reference { String::shallow("v") }); expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_mul, false }); expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true }); Vector<Statement> body; body.emplace_back(Statement::S_expr { std::move(expr) }); text.emplace_back(Statement::S_for_each { String::shallow("k"), String::shallow("v"), std::move(range), std::move(body) }); // for(var j = 0; j <= 3; ++j) { // res += data[j]; // if(data[j] == 2) { // break; // } // } body.clear(); expr.clear(); expr.emplace_back(Xpnode::S_named_reference { String::shallow("res") }); expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") }); expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") }); expr.emplace_back(Xpnode::S_subscript { String::shallow("") }); expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_add, true }); body.emplace_back(Statement::S_expr { std::move(expr) }); expr.clear(); expr.emplace_back(Xpnode::S_named_reference { String::shallow("data") }); expr.emplace_back(Xpnode::S_named_reference { String::shallow("j") }); expr.emplace_back(Xpnode::S_subscript { String::shallow("") }); expr.emplace_back(Xpnode::S_literal { D_integer(2) }); expr.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_eq, false }); Vector<Statement> branch_true; branch_true.emplace_back(Statement::S_break { Statement::target_unspec }); body.emplace_back(Statement::S_if { std::move(expr), std::move(branch_true), Block() }); expr.clear(); expr.emplace_back(Xpnode::S_literal { D_integer(0) }); Vector<Statement> init; init.emplace_back(Statement::S_var_def { String::shallow("j"), false, std::move(expr) }); Vector<Xpnode> cond; cond.emplace_back(Xpnode::S_named_reference { String::shallow("j") }); cond.emplace_back(Xpnode::S_literal { D_integer(3) }); cond.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_infix_cmp_lte, false }); Vector<Xpnode> step; step.emplace_back(Xpnode::S_named_reference { String::shallow("j") }); step.emplace_back(Xpnode::S_operator_rpn { Xpnode::xop_prefix_inc, false }); text.emplace_back(Statement::S_for { std::move(init), std::move(cond), std::move(step), std::move(body) }); auto block = Block(std::move(text)); Global_context global; Executive_context ctx; Reference ref; auto status = block.execute_in_place(ref, ctx, global); ASTERIA_TEST_CHECK(status == Block::status_next); auto qref = ctx.get_named_reference_opt(String::shallow("res")); ASTERIA_TEST_CHECK(qref != nullptr); ASTERIA_TEST_CHECK(qref->read().check<D_integer>() == 41); qref = ctx.get_named_reference_opt(String::shallow("data")); ASTERIA_TEST_CHECK(qref != nullptr); ASTERIA_TEST_CHECK(qref->read().check<D_array>().size() == 4); ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(0).check<D_integer>() == 1); ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(1).check<D_integer>() == 2); ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(2).check<D_integer>() == 3); ASTERIA_TEST_CHECK(qref->read().check<D_array>().at(3).check<D_integer>() == 10); qref = ctx.get_named_reference_opt(String::shallow("k")); ASTERIA_TEST_CHECK(qref == nullptr); qref = ctx.get_named_reference_opt(String::shallow("v")); ASTERIA_TEST_CHECK(qref == nullptr); qref = ctx.get_named_reference_opt(String::shallow("j")); ASTERIA_TEST_CHECK(qref == nullptr); }
49.679612
127
0.676959
e5b43b0d04d451301c947834e44ca57613a98c10
1,829
cpp
C++
KeylightDiscover.cpp
failex234/MyKeylight
88ba49c378ccabf07920c1b571ce15c3aa9e5bd2
[ "MIT" ]
null
null
null
KeylightDiscover.cpp
failex234/MyKeylight
88ba49c378ccabf07920c1b571ce15c3aa9e5bd2
[ "MIT" ]
null
null
null
KeylightDiscover.cpp
failex234/MyKeylight
88ba49c378ccabf07920c1b571ce15c3aa9e5bd2
[ "MIT" ]
null
null
null
#include <netinet/in.h> #include <sys/socket.h> #include <vector> #include <arpa/inet.h> #include "Keylight.h" #include "thirdparty/zeroconf.hpp" void* get_in_addr(sockaddr_storage* sa) { if (sa->ss_family == AF_INET) return &reinterpret_cast<sockaddr_in*>(sa)->sin_addr; if (sa->ss_family == AF_INET6) return &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr; return nullptr; } bool discoverKeylights(std::vector<Keylight> *keylights) { std::vector<Zeroconf::mdns_responce> keylights_zeroconf; //Search for elgato keylights in the local network using mDNS (Keylights announce their service via _elg._tcp.local) bool st = Zeroconf::Resolve("_elg._tcp.local", /*scanTime*/ 3, &keylights_zeroconf); //This should never happen but should be accounted for if (!st) { std::cerr << "Unable to query to local network (MDNS query failed)" << std::endl; return false; } //Go through all dns records of a response to extract the contents of the SRV record for (auto item : keylights_zeroconf) { //Buffer for the ip address char buffer[INET6_ADDRSTRLEN + 1] = {0}; inet_ntop(item.peer.ss_family, get_in_addr(&item.peer), buffer, INET6_ADDRSTRLEN); std::string name; if (!item.records.empty()) { for (auto & rr : item.records) { switch(rr.type) { //SRV record case 33: //The SRV record contains the given name of this particular keylight name = std::string(rr.name); break; } } } Keylight *ke = new Keylight(name, std::string(buffer)); keylights->push_back(*ke); } return true; }
30.483333
120
0.594861
e5b47aedd92161daa823caa61d248330e8358f2f
17,987
cpp
C++
src/app/screens/application/main_menu_screen.cpp
lili2012/BarbersAndRebarbs
8a3c10cebded55dabaf6f8673735c6f3606cb4af
[ "MIT" ]
4
2016-04-26T20:25:07.000Z
2021-12-15T06:58:57.000Z
src/app/screens/application/main_menu_screen.cpp
lili2012/BarbersAndRebarbs
8a3c10cebded55dabaf6f8673735c6f3606cb4af
[ "MIT" ]
2
2016-07-29T22:52:12.000Z
2016-09-22T08:30:29.000Z
src/app/screens/application/main_menu_screen.cpp
lili2012/BarbersAndRebarbs
8a3c10cebded55dabaf6f8673735c6f3606cb4af
[ "MIT" ]
1
2020-10-31T10:20:32.000Z
2020-10-31T10:20:32.000Z
// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // 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 "main_menu_screen.hpp" #include "../../../game/firearm/firearm.hpp" #include "../../../reference/container.hpp" #include "../../../reference/joystick_info.hpp" #include "../../../util/file.hpp" #include "../../../util/sound.hpp" #include "../../../util/url.hpp" #include "../../../util/zstd.hpp" #include "../../application.hpp" #include "../game/main_game_screen.hpp" #include <cmath> #include <fmt/format.h> #include <iostream> #include <jsonpp/parser.hpp> #include <semver/semver200.h> using namespace std::literals; void main_menu_screen::move_selection(main_menu_screen::direction dir, bool end = false) { const auto max_idx = main_buttons.size() - 1; auto desired_selection = selected; switch(dir) { case direction::up: if(end) desired_selection = max_idx; else desired_selection = selected + 1; break; case direction::down: if(selected && !end) desired_selection = selected - 1; else desired_selection = 0; break; } desired_selection = std::min(max_idx, desired_selection); if(app_configuration.play_sounds) { if(desired_selection != selected) selected_option_switch_sound->play(); else selected_option_unchanged_sound->play(); } selected = desired_selection; } void main_menu_screen::press_button() { if(app_configuration.play_sounds) selected_option_select_sound->play(); auto itr = main_buttons.begin(); advance(itr, selected); (itr->second)(itr->first); } void main_menu_screen::try_drawings() { if(!(control_frames_counter++ % 10)) { control_frames_counter = 0; if(joystick_drawing.first != sf::Joystick::isConnected(0)) { joystick_drawing.first ^= 1; joystick_drawing.second.move(0, joystick_drawing.second.size().y * .55f * (joystick_drawing.first ? 1 : -1)); keys_drawing.move(0, joystick_drawing.second.size().y * .55f * (joystick_drawing.first ? -1 : 1)); } } } void main_menu_screen::load_game(sf::Text & txt, const std::string & save_path) { const auto data = decompress_file_to_string(save_path); if(!std::get<1>(data)) txt.setString(global_iser.translate_key("gui.main_menu.text.load_file_inaccessible")); else if(const auto err_s = std::get<2>(data)) txt.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.load_decompression_error"), err_s)); else { json::value save; json::parse(std::get<0>(data), save); app.schedule_screen<main_game_screen>(save.as<json::object>()); } } void main_menu_screen::set_default_menu_items() { main_buttons.clear(); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.start"), font_swirly), [&](sf::Text &) { app.schedule_screen<main_game_screen>(); }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.load"), font_swirly), [&](sf::Text & txt) { main_buttons.clear(); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly), [&](sf::Text &) { set_default_menu_items(); }); for(auto && fname : [] { auto saves = list_files(saves_root); std::sort(saves.begin(), saves.end()); return saves; }()) main_buttons.emplace_front(sf::Text(fname.substr(0, fname.rfind('.')), font_swirly), [&, fname = fname ](sf::Text &) { load_game(txt, saves_root + '/' + fname); }); selected = main_buttons.size() - 1; }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text."s + (app_configuration.play_sounds ? "" : "un") + "mute"), font_swirly), [&](sf::Text & txt) { app_configuration.play_sounds = !app_configuration.play_sounds; txt.setString(global_iser.translate_key("gui.main_menu.text."s + (app_configuration.play_sounds ? "" : "un") + "mute")); app.retry_music(); }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.configure"), font_swirly), [&](sf::Text &) { set_config_menu_items(); }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.quit"), font_swirly), [&](sf::Text &) { app.window.close(); }); selected = main_buttons.size() - 1; } void main_menu_screen::set_config_menu_items() { main_buttons.clear(); bool music_volume_changed = false; const auto langs = config::available_languages(); const std::size_t cur_lang_idx = std::distance(langs.begin(), std::find(langs.begin(), langs.end(), app_configuration.language)); const auto volume_func = [&](const char * key, float & volume, auto additional) { return [&, key, additional](sf::Text & text) { volume += .05f; if(volume > 1.f) volume = 0.f; additional(volume); text.setString(fmt::format(global_iser.translate_key(key), volume * 100.f)); }; }; main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly), [&](sf::Text &) { local_iser = cpp_localiser::localiser(localization_root, app_configuration.language); global_iser = cpp_localiser::localiser(local_iser, fallback_iser); if(music_volume_changed) app.retry_music(); set_default_menu_items(); }); main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_lang"), app_configuration.language), font_pixelish, 20), [&, langs = std::move(langs), idx = cur_lang_idx ](sf::Text & text) mutable { ++idx; if(idx == langs.size()) idx = 0; app_configuration.language = langs[idx]; text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_lang"), app_configuration.language)); }); main_buttons.emplace_front( sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_controller_deadzone"), app_configuration.controller_deadzone), font_pixelish, 20), [&](sf::Text & text) { app_configuration.controller_deadzone += 5; if(app_configuration.controller_deadzone > 100) app_configuration.controller_deadzone = 0; text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_controller_deadzone"), app_configuration.controller_deadzone)); }); main_buttons.emplace_front( sf::Text(global_iser.translate_key("gui.main_menu.text.config_vsync_"s + (app_configuration.vsync ? "on" : "off")), font_pixelish, 20), [&](sf::Text & text) { app_configuration.vsync ^= 1; text.setString(global_iser.translate_key("gui.main_menu.text.config_vsync_"s + (app_configuration.vsync ? "on" : "off"))); }); main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_fps"), app_configuration.FPS), font_pixelish, 20), [&](sf::Text & text) { app_configuration.FPS += 30; if(app_configuration.FPS > 120) app_configuration.FPS = 0; text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_fps"), app_configuration.FPS)); }); main_buttons.emplace_front( sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_music_volume"), app_configuration.music_volume * 100.f), font_pixelish, 20), volume_func("gui.main_menu.text.config_music_volume", app_configuration.music_volume, [&](auto) { music_volume_changed = true; })); main_buttons.emplace_front( sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_sound_effect_volume"), app_configuration.sound_effect_volume * 100.f), font_pixelish, 20), volume_func("gui.main_menu.text.config_sound_effect_volume", app_configuration.sound_effect_volume, [&](auto vol) { selected_option_switch_sound->setVolume(output_volume(vol * .8)); selected_option_select_sound->setVolume(output_volume(vol * .8)); update_ready_sound->setVolume(output_volume(vol * .8)); })); main_buttons.emplace_front(sf::Text(fmt::format(global_iser.translate_key("gui.main_menu.text.config_default_firearm"), firearm::properties().at(app_configuration.player_default_firearm).name), font_pixelish, 20), [&, itr = firearm::properties().find(app_configuration.player_default_firearm) ](sf::Text & text) mutable { ++itr; if(itr == firearm::properties().end()) itr = firearm::properties().begin(); app_configuration.player_default_firearm = itr->first; text.setString(fmt::format(global_iser.translate_key("gui.main_menu.text.config_default_firearm"), itr->second.name)); }); selected = main_buttons.size() - 1; } void main_menu_screen::setup() { screen::setup(); } int main_menu_screen::loop() { const auto & winsize = app.window.getSize(); unsigned int buttid = 0; for(auto & button : main_buttons) { const auto & btnbds = button.first.getGlobalBounds(); button.first.setPosition((winsize.x * (59.f / 60.f)) - btnbds.width, (winsize.y * (7.f / 8.f)) - (buttid + 1) * btnbds.height - (winsize.y * ((buttid * 1.f) / 90.f))); button.first.setFillColor((buttid == selected) ? sf::Color::Red : sf::Color::White); ++buttid; } if(std::get<3>(update) && std::get<0>(update).valid()) { std::get<3>(update) = false; std::get<1>(update) = std::thread([&] { auto result = std::get<0>(update).get(); std::cout << result.header["X-RateLimit-Remaining"] << " GitHub API accesses left\n"; if(!(result.status_code >= 200 && result.status_code < 300)) std::get<2>(update).setString(fmt::format(global_iser.translate_key("gui.main_menu.text.update_connection_fail"), result.status_code)); else { json::value newest_update; json::parse(result.text, newest_update); auto new_version_s = newest_update["tag_name"].as<std::string>(); new_version_s = new_version_s.substr(new_version_s.find_first_of("0123456789")); if(version::Semver200_version(new_version_s) <= version::Semver200_version(BARBERSANDREBARBS_VERSION)) std::get<2>(update).setString(global_iser.translate_key("gui.main_menu.text.update_none_found")); else { if(app_configuration.play_sounds) update_ready_sound->play(); std::get<2>(update).setString(fmt::format(global_iser.translate_key("gui.main_menu.text.update_found"), new_version_s)); main_buttons.emplace_back( sf::Text(global_iser.translate_key("gui.main_menu.text.update"), font_swirly), [&, url = newest_update["html_url"].as<std::string>() ](sf::Text &) { if(!launch_browser(url)) { main_buttons.clear(); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.back"), font_swirly), [&](sf::Text &) { set_default_menu_items(); }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.update_browser_fail_0"), font_pixelish, 20), [&](sf::Text &) {}); main_buttons.emplace_front(sf::Text(url, font_pixelish, 20), [&](sf::Text & txt) { copy_to_clipboard(txt.getString()); }); main_buttons.emplace_front(sf::Text(global_iser.translate_key("gui.main_menu.text.update_browser_fail_1"), font_pixelish, 20), [&](sf::Text &) {}); selected = main_buttons.size() - 1; } }); } } }); } return 0; } int main_menu_screen::draw() { for(const auto & button : main_buttons) app.window.draw(button.first); try_drawings(); if(joystick_drawing.first) app.window.draw(joystick_drawing.second); app.window.draw(keys_drawing); app.window.draw(std::get<2>(update)); return 0; } int main_menu_screen::handle_event(const sf::Event & event) { if(int i = screen::handle_event(event)) return i; switch(static_cast<int>(event.type)) { case sf::Event::MouseMoved: { unsigned int buttid = 0; for(const auto & button : main_buttons) { if(button.first.getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y)) { if(app_configuration.play_sounds && selected != buttid) selected_option_switch_sound->play(); selected = buttid; break; } ++buttid; } } break; case sf::Event::MouseButtonPressed: if(event.mouseButton.button == sf::Mouse::Left) for(const auto & button : main_buttons) if(button.first.getGlobalBounds().contains(event.mouseButton.x, event.mouseButton.y)) { press_button(); break; } break; case sf::Event::MouseWheelMoved: move_selection((event.mouseWheel.delta > 0) ? direction::up : direction::down); break; case sf::Event::KeyPressed: switch(static_cast<int>(event.key.code)) { case sf::Keyboard::Key::Home: move_selection(direction::up, true); break; case sf::Keyboard::Key::End: move_selection(direction::down, true); break; case sf::Keyboard::Key::Up: move_selection(direction::up); break; case sf::Keyboard::Key::Down: move_selection(direction::down); break; case sf::Keyboard::Key::Return: case sf::Keyboard::Key::Space: press_button(); break; } break; case sf::Event::JoystickMoved: if(event.joystickMove.axis == X360_axis_mappings::LeftStickVertical || event.joystickMove.axis == X360_axis_mappings::DPadVertical) { if(event.joystickMove.position && (event.joystickMove.position >= 25 || event.joystickMove.position <= -25)) { if(joystick_up) break; joystick_up = true; const int sign = event.joystickMove.position / std::abs(event.joystickMove.position); move_selection((sign == ((event.joystickMove.axis == X360_axis_mappings::LeftStickVertical) ? X360_axis_up_right_mappings::LeftStickVertical : X360_axis_up_right_mappings::DPadVertical)) ? direction::up : direction::down); } else joystick_up = false; } break; case sf::Event::JoystickButtonPressed: if(event.joystickButton.button == X360_button_mappings::A) press_button(); break; } return 0; } main_menu_screen::main_menu_screen(application & theapp) : screen(theapp), control_frames_counter(0), joystick_up(false), joystick_drawing(false, drawing("xbox", app.window.getSize())), keys_drawing("keyboard", app.window.getSize()), update(std::future<cpr::Response>(), std::thread(), sf::Text("", font_monospace, 10), app_configuration.use_network), selected_option_switch_sound( audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/mouse_over.wav").c_str(), audiere::SoundEffectType::MULTIPLE)), selected_option_unchanged_sound( audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/Alt_Fire_Switch.mp3").c_str(), audiere::SoundEffectType::MULTIPLE)), selected_option_select_sound( audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/mouse_click.wav").c_str(), audiere::SoundEffectType::MULTIPLE)), update_ready_sound(audiere::OpenSoundEffect(audio_device, (sound_root + "/main_menu/update.wav").c_str(), audiere::SoundEffectType::SINGLE)) { selected_option_switch_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8)); selected_option_unchanged_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8)); selected_option_select_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8)); update_ready_sound->setVolume(output_volume(app_configuration.sound_effect_volume * .8)); if(app_configuration.use_network) std::get<0>(update) = cpr::GetAsync(cpr::Url("https://api.github.com/repos/nabijaczleweli/BarbersAndRebarbs/releases/latest"), cpr::Parameters{{"anon", "true"}}); keys_drawing.move(app.window.getSize().x / 4 - keys_drawing.size().x / 2, app.window.getSize().y / 2 - keys_drawing.size().y / 2); joystick_drawing.second.move(app.window.getSize().x / 4 - joystick_drawing.second.size().x / 2, app.window.getSize().y / 2 - joystick_drawing.second.size().y / 2); set_default_menu_items(); } main_menu_screen::~main_menu_screen() { if(std::get<1>(update).joinable()) std::get<1>(update).join(); }
44.743781
158
0.666148
e5b4ebd57e1b88ac6da16124de2c7ea201245b2a
59,846
cpp
C++
src/bitmask.cpp
leannejdong/MGOSDT
29559e5feb19490e77b11d0382558cd8529feba4
[ "BSD-3-Clause" ]
1
2022-03-09T03:17:35.000Z
2022-03-09T03:17:35.000Z
src/bitmask.cpp
leannejdong/MGOSDT
29559e5feb19490e77b11d0382558cd8529feba4
[ "BSD-3-Clause" ]
null
null
null
src/bitmask.cpp
leannejdong/MGOSDT
29559e5feb19490e77b11d0382558cd8529feba4
[ "BSD-3-Clause" ]
null
null
null
#include "bitmask.hpp" // ******************************** // ** Function Module Definition ** // ******************************** std::vector< std::vector<codeblock> > Bitmask::ranges = std::vector< std::vector<codeblock> >(); std::vector<size_t> Bitmask::hashes = std::vector<size_t>(); std::vector<char> Bitmask::counts = std::vector<char>(); // Pre-computed number of set bits for 4-bit sequences // unsigned int Bitmask::bit_count[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; const bitblock Bitmask::bits_per_block = 8 * sizeof(bitblock); const bitblock Bitmask::ranges_per_code = 8 * sizeof(codeblock) / log2((double)(8 * sizeof(rangeblock))); const bitblock Bitmask::bits_per_range = log2((double)(8 * sizeof(rangeblock))); tbb::scalable_allocator< bitblock > Bitmask::allocator = tbb::scalable_allocator< bitblock >(); bool Bitmask::integrity_check = true; bool Bitmask::precomputed = false; // @param blocks: the blocks containing bits // @param size: the number of bits which are represented in blocks // @modifies blocks will be set to have all bits be 1 void Bitmask::ones(bitblock * const blocks, unsigned int size) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); for (unsigned int i = 0; i < number_of_blocks; ++i) { blocks[i] = ~((bitblock)(0)); } Bitmask::clean(blocks, number_of_blocks, block_offset); } // @param blocks: the blocks containing bits // @param size: the number of bits which are represented in blocks // @modifies blocks will be set to have all bits be 0 void Bitmask::zeros(bitblock * const blocks, unsigned int size) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); for (unsigned int i = 0; i < number_of_blocks; ++i) { blocks[i] = (bitblock)(0); } Bitmask::clean(blocks, number_of_blocks, block_offset); } void Bitmask::copy(bitblock * const blocks, bitblock * const other_blocks, unsigned int size) { if (blocks == other_blocks) { return; } unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); Bitmask::clean(other_blocks, number_of_blocks, block_offset); for (unsigned int i = 0; i < number_of_blocks; ++i) { other_blocks[i] = blocks[i]; } } void Bitmask::block_layout(unsigned int size, unsigned int * number_of_blocks, unsigned int * block_offset) { if (size == 0) { * number_of_blocks = 1; } else { * number_of_blocks = size / (Bitmask::bits_per_block) + (int)(size % Bitmask::bits_per_block != 0); } *block_offset = size % (Bitmask::bits_per_block); } void Bitmask::clean(bitblock * const blocks, unsigned int number_of_blocks, unsigned int offset) { if (offset == 0) { return; } bitblock mask = ~((bitblock)(0)) >> (Bitmask::bits_per_block - offset); blocks[number_of_blocks - 1] = blocks[number_of_blocks - 1] & mask; } unsigned int Bitmask::count(bitblock * const blocks, unsigned int size) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); return mpn_popcount(blocks, number_of_blocks); } // @note this returns the number of contiguous sequences of 1's unsigned int Bitmask::words(bitblock * const blocks, unsigned int size) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); bool sign = Bitmask::get(blocks, size, 0); unsigned int i = 0; unsigned int j = Bitmask::scan(blocks, size, i, !sign); unsigned int words = 0; while (j <= size) { if (sign) { ++words; } if (j == size) { break; } i = j; sign = !sign; j = Bitmask::scan(blocks, size, i, !sign); } return words; } void Bitmask::bit_and(bitblock * const blocks, bitblock * other_blocks, unsigned int size, bool flip) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); if (!flip) { // Special Offload to GMP Implementation mpn_and_n(other_blocks, other_blocks, blocks, number_of_blocks); } else { // Special Offload to GMP Implementation mpn_nior_n(other_blocks, other_blocks, other_blocks, number_of_blocks); mpn_nior_n(other_blocks, other_blocks, blocks, number_of_blocks); } } void Bitmask::bit_or(bitblock * blocks, bitblock * other_blocks, unsigned int size, bool flip) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); if (!flip) { // Special Offload to GMP Implementation mpn_ior_n(other_blocks, other_blocks, blocks, number_of_blocks); } else { // Special Offload to GMP Implementation mpn_nand_n(other_blocks, other_blocks, other_blocks, number_of_blocks); mpn_nand_n(other_blocks, other_blocks, blocks, number_of_blocks); } } void Bitmask::bit_xor(bitblock * const blocks, bitblock * other_blocks, unsigned int size, bool flip) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); if (!flip) { // Special Offload to GMP Implementation mpn_xor_n(other_blocks, other_blocks, blocks, number_of_blocks); } else { // Special Offload to GMP Implementation mpn_xnor_n(other_blocks, other_blocks, blocks, number_of_blocks); } } bool Bitmask::equals(bitblock * const blocks, bitblock * const other_blocks, unsigned int size, bool flip) { if (blocks == other_blocks) { return true; } unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); Bitmask::clean(other_blocks, number_of_blocks, block_offset); if (!flip) { return mpn_cmp(blocks, other_blocks, number_of_blocks) == 0; } else { mpn_nand_n(blocks, blocks, blocks, number_of_blocks); Bitmask::clean(blocks, number_of_blocks, block_offset); bool equals = mpn_cmp(blocks, other_blocks, number_of_blocks) == 0; mpn_nand_n(blocks, blocks, blocks, number_of_blocks); Bitmask::clean(blocks, number_of_blocks, block_offset); return equals; } } int Bitmask::compare(bitblock * const left, bitblock * const right, unsigned int size) { if (left == right) { return false; } unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(left, number_of_blocks, block_offset); Bitmask::clean(right, number_of_blocks, block_offset); return mpn_cmp(left, right, number_of_blocks); } bool Bitmask::less_than(bitblock * const left, bitblock * const right, unsigned int size) { return Bitmask::compare(left, right, size) < 0; } bool Bitmask::greater_than(bitblock * const left, bitblock * const right, unsigned int size) { return Bitmask::compare(left, right, size) > 0; } size_t Bitmask::hash(bitblock * const blocks, unsigned int size) { unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); bool sign = Bitmask::get(blocks, size, 0); unsigned int i = 0; unsigned int j = Bitmask::scan(blocks, size, i, !sign); size_t seed = 1 * sign; while (j <= size) { seed ^= j - i + 0x9e3779b9 + (seed << 6) + (seed >> 2); if (j == size) { break; } i = j; sign = !sign; j = Bitmask::scan(blocks, size, i, !sign); } return seed; } unsigned int Bitmask::get(bitblock * const blocks, unsigned int size, unsigned int index) { if (Bitmask::integrity_check && (index < 0 || index >= size)) { std::stringstream reason; reason << "Index " << index << " is outside the valid range [" << 0 << "," << size - 1 << "]."; throw IntegrityViolation("Bitmask::get", reason.str()); } unsigned int block_index = index / Bitmask::bits_per_block; unsigned int bit_index = index % Bitmask::bits_per_block; bitblock block = blocks[block_index]; return (block >> bit_index) & 1; } void Bitmask::set(bitblock * const blocks, unsigned int size, unsigned int index, bool value) { if (Bitmask::integrity_check && (index < 0 || index >= size)) { std::stringstream reason; reason << "Index " << index << " is outside the valid range [" << 0 << "," << size - 1 << "]."; throw IntegrityViolation("Bitmask::get", reason.str()); } unsigned int block_index = index / Bitmask::bits_per_block; unsigned int bit_index = index % Bitmask::bits_per_block; bitblock mask = (bitblock)(1) << bit_index; if (value) { blocks[block_index] = blocks[block_index] | mask; } else { blocks[block_index] = blocks[block_index] & ~mask; } } int Bitmask::scan(bitblock * const blocks, int size, int start, bool value) { if (start >= size) { return size; } unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); unsigned int block_index = start / Bitmask::bits_per_block; if (block_index >= number_of_blocks) { return size; } if (value) { bitblock skip_block = (bitblock)(0); bitblock mask_block = ~((bitblock)(0)) << (start % Bitmask::bits_per_block); bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them while (block == skip_block) { ++block_index; if (block_index >= number_of_blocks) { return size; } block = blocks[block_index]; } int bit_index = mpn_scan1(& block, 0); return block_index * Bitmask::bits_per_block + bit_index; } else { bitblock skip_block = ~((bitblock)(0)); bitblock mask_block = ((bitblock)(1) << (start % Bitmask::bits_per_block)) - (bitblock)(1); bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them while (block == skip_block) { ++block_index; if (block_index >= number_of_blocks) { return size; } block = blocks[block_index]; } int bit_index = mpn_scan0(& block, 0); return block_index * Bitmask::bits_per_block + bit_index; } } int Bitmask::rscan(bitblock * const blocks, int size, int start, bool value) { if (start < 0) { return -1; } unsigned int number_of_blocks, block_offset; Bitmask::block_layout(size, & number_of_blocks, & block_offset); Bitmask::clean(blocks, number_of_blocks, block_offset); int block_index = start / Bitmask::bits_per_block; if (block_index < 0) { return -1; } if (value) { bitblock skip_block = (bitblock)(0); bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block)); bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them while (block == skip_block) { --block_index; if (block_index < 0) { return -1; } block = blocks[block_index]; } unsigned int count = sizeof(block) * 8 - 1; bitblock reverse_block = block; block >>= 1; while (block) { reverse_block <<= 1; reverse_block |= block & 1; block >>= 1; count--; } reverse_block <<= count; int bit_index = mpn_scan1(& reverse_block, 0); return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index; } else { bitblock skip_block = ~((bitblock)(0)); bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block)); mask_block = ~mask_block; bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them while (block == skip_block) { --block_index; if (block_index < 0) { return -1; } block = blocks[block_index]; } unsigned int count = sizeof(block) * 8 - 1; bitblock reverse_block = block; block >>= 1; while (block) { reverse_block <<= 1; reverse_block |= block & 1; block >>= 1; count--; } reverse_block <<= count; int bit_index = mpn_scan0(& reverse_block, 0); return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index; } } bool Bitmask::scan_range(bool value, int & begin, int & end) const { if (begin >= this -> _size) { return false; } begin = this -> scan(begin, value); if (begin >= this -> _size) { return false; } end = this -> scan(begin, !value); return true; } bool Bitmask::rscan_range(bool value, int & begin, int & end) const { if (begin < 0) { return false; } begin = this -> rscan(begin, value); if (begin < 0) { return false; } end = this -> rscan(begin, !value); return true; } std::string Bitmask::to_string(bitblock * const blocks, unsigned int size, bool reverse) { std::string bitstring; bitstring.resize(size); char zero = '0'; char one = '1'; if (reverse) { // Copy the bits for (unsigned int i = 0; i < size; ++i) { bitstring[i] = Bitmask::get(blocks, size, size - 1 - i) ? one : zero; } } else { for (unsigned int i = 0; i < size; ++i) { bitstring[i] = Bitmask::get(blocks, size, i) ? one : zero; } } return bitstring; }; void Bitmask::precompute() { if (Bitmask::precomputed) { return; } Bitmask::precomputed = true; std::map< rangeblock, std::vector<char> > collection; char block_size = 8 * sizeof(rangeblock); rangeblock max = ~((rangeblock)0); for (rangeblock key = 0; key <= max; ++key) { std::vector<char> code; if (key == (rangeblock)0) { code.emplace_back((char)(-block_size)); } else if (key == (rangeblock)1) { code.emplace_back((char)1); code.emplace_back((char)(-block_size+1)); } else { unsigned int prefix_length = std::floor(log2((double)key)); unsigned int suffix_length = block_size - prefix_length; unsigned int prefix_mask = ~(~0 << prefix_length); rangeblock prefix_key = key & prefix_mask; unsigned int prior = (key >> (prefix_length-1)) & 1; unsigned int bit = (key >> prefix_length) & 1; std::vector<char> const & prefix = collection.at(prefix_key); code = prefix; if (bit == 1) { if (prior == 0) { char suffix = code.at(code.size()-1); code[code.size() - 1] = suffix + suffix_length; code.emplace_back(1); if (1 - suffix_length != 0) { code.emplace_back(1 - suffix_length); } } else if (prior == 1) { code[code.size() - 2] += 1; code[code.size() - 1] += 1; if (code[code.size() - 1] == 0) { code.pop_back(); } } } } collection.emplace(key, code); if (key == max) { break; } } for (auto iterator = collection.begin(); iterator != collection.end(); iterator++) { std::vector<char> const & encoding = iterator -> second; std::vector<codeblock> packed_encoding; unsigned int counter = 0; codeblock packed_code = 0; unsigned int offset = 0; for (auto subiterator = encoding.begin(); subiterator != encoding.end(); ++subiterator) { short code = * subiterator; // some char representing anywhere from 1 to 16 bits if (code > 0) { counter += code; } if (offset == Bitmask::ranges_per_code) { packed_encoding.emplace_back(packed_code); packed_code = 0; offset = 0; } unsigned int shift = offset * Bitmask::bits_per_range; packed_code = packed_code | ((codeblock)(std::abs(code) - 1) << shift); ++offset; } if (offset > 0) { packed_encoding.emplace_back(packed_code); } Bitmask::ranges.emplace_back(packed_encoding); Bitmask::counts.emplace_back(counter); bool leading_sign = ((iterator -> first) & 1) == 1; size_t seed = leading_sign; std::vector<codeblock> const & codes = packed_encoding; for (auto code_iterator = codes.begin(); code_iterator != codes.end(); ++code_iterator) { seed ^= * code_iterator + 0x9e3779b9 + (seed << 6) + (seed >> 2); if ((int)(* code_iterator) > 0) { counter += * code_iterator; } } Bitmask::hashes.emplace_back(seed); } } // ********************** // ** Class Definition ** // ********************** Bitmask::Bitmask() {} Bitmask::Bitmask(unsigned int size, bool filler, bitblock * local_buffer) { initialize(size, local_buffer); if (filler) { fill(); } else { clear(); } Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } Bitmask::Bitmask(bitblock * source_blocks, unsigned int size, bitblock * local_buffer) { if (Bitmask::integrity_check && source_blocks == NULL) { std::stringstream reason; reason << "Attempt to construct Bitmask from null source"; throw IntegrityViolation("Bitmask::Bitmask", reason.str()); } initialize(size, local_buffer); memcpy(this -> content, source_blocks, this -> _used_blocks * sizeof(bitblock)); Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } Bitmask::Bitmask(dynamic_bitset const & source, bitblock * local_buffer) { initialize(source.size(), local_buffer); // Initialize content using the blocks of this bitset std::vector< bitblock > source_blocks; source_blocks.resize(source.num_blocks()); boost::to_block_range(source, source_blocks.begin()); memcpy(this -> content, source_blocks.data(), this -> _used_blocks * sizeof(bitblock)); Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } Bitmask::Bitmask(Bitmask const & source, bitblock * local_buffer) { if (source._size == 0) { return; } if (Bitmask::integrity_check && !source.valid()) { std::stringstream reason; reason << "Attempt to construct Bitmask from null source"; throw IntegrityViolation("Bitmask::Bitmask", reason.str()); } initialize(source.size(), local_buffer); memcpy(this -> content, source.data(), this -> _used_blocks * sizeof(bitblock)); Bitmask::clean(this->content, this->_used_blocks, this->_offset); } Bitmask::~Bitmask() { if (this -> shallow == false && valid()) { Bitmask::allocator.deallocate(this -> content, this -> _max_blocks); } } void Bitmask::initialize(unsigned int size, bitblock * local_buffer) { this -> _size = size; unsigned int num_blocks; Bitmask::block_layout(this -> _size, & num_blocks, & (this -> _offset)); this -> _used_blocks = this -> _max_blocks = num_blocks; if (local_buffer == NULL) { this -> content = (bitblock *) Bitmask::allocator.allocate(this -> _max_blocks); } else { this -> content = local_buffer; this -> shallow = true; } Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } void Bitmask::resize(unsigned int new_size) { if (this -> _size == new_size) { return; } if (this -> content == NULL) { initialize(new_size); } else if (Bitmask::integrity_check && new_size > (this -> capacity())) { std::cout << "Resize: " << new_size << ", Capacity: " << this -> capacity() << "\n"; std::stringstream reason; reason << "Attempt to resize beyond allocated capacity"; throw IntegrityViolation("Bitmask::resize", reason.str()); } this -> _size = new_size; Bitmask::block_layout(new_size, & (this -> _used_blocks), & (this -> _offset)); Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } void Bitmask::copy_to(bitblock * dest_blocks) const { if (this -> _size == 0) { return; } if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Attempt to copy from null source"; throw IntegrityViolation("Bitmask::copy_to", reason.str()); } if (Bitmask::integrity_check && dest_blocks == NULL) { std::stringstream reason; reason << "Attempt to copy to null destination"; throw IntegrityViolation("Bitmask::copy_to", reason.str()); } Bitmask::copy(this -> content, dest_blocks, this -> _size); } void Bitmask::copy_from(bitblock * src_blocks) { if (Bitmask::integrity_check && src_blocks == NULL) { std::stringstream reason; reason << "Attempt to copy from null source"; throw IntegrityViolation("Bitmask::copy_from", reason.str()); } if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Attempt to copy to null destination"; throw IntegrityViolation("Bitmask::copy_from", reason.str()); } Bitmask::copy(src_blocks, this -> content, this -> _size); } Bitmask & Bitmask::operator=(Bitmask const & other) { if (other.size() == 0) { return * this; } if (this -> content == NULL) { initialize(other.size()); } // resize this instance to match if (this -> _size != other.size()) { resize(other.size()); } // resize this instance to match bitblock * blocks = this -> content; bitblock * other_blocks = other.content; memcpy(blocks, other_blocks, this -> _used_blocks * sizeof(bitblock)); return * this; } bitblock * Bitmask::data() const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::data", reason.str()); } return this -> content; } unsigned int Bitmask::operator[](unsigned int index) const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::operator[]", reason.str()); } return get(index); } unsigned int Bitmask::get(unsigned int index) const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::get", reason.str()); } bitblock * blocks = this -> content; unsigned int block_index = index / Bitmask::bits_per_block; unsigned int bit_index = index % Bitmask::bits_per_block; bitblock block = blocks[block_index]; return (int)((block >> bit_index) % 2); } void Bitmask::set(unsigned int index, bool value) { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::set", reason.str()); } bitblock * blocks = this -> content; unsigned int block_index = index / Bitmask::bits_per_block; unsigned int bit_index = index % Bitmask::bits_per_block; bitblock mask = (bitblock)(1) << bit_index; if (value) { blocks[block_index] = blocks[block_index] | mask; } else { blocks[block_index] = blocks[block_index] & ~mask; } } unsigned int Bitmask::size() const { return this -> _size; } unsigned int Bitmask::capacity() const { return this -> _max_blocks * Bitmask::bits_per_block; } unsigned int Bitmask::count() const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::count", reason.str()); } return mpn_popcount(this -> content, this -> _used_blocks); } bool Bitmask::empty() const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::empty", reason.str()); } return mpn_zero_p(this -> content, this -> _used_blocks); } bool Bitmask::full() const { if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::full", reason.str()); } return this -> count() == this -> size(); } int Bitmask::scan(int start, bool value) const { if (start >= size()) { return size(); } bitblock * blocks = this -> content; unsigned int block_index = start / Bitmask::bits_per_block; if (block_index >= this -> _used_blocks) { return size(); } if (value) { bitblock skip_block = (bitblock)(0); bitblock mask_block = ~((bitblock)(0)) << (start % Bitmask::bits_per_block); bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them while (block == skip_block) { ++block_index; if (block_index >= this -> _used_blocks) { return size(); } block = blocks[block_index]; } int bit_index = mpn_scan1(& block, 0); return block_index * Bitmask::bits_per_block + bit_index; } else { bitblock skip_block = ~((bitblock)(0)); bitblock mask_block = ((bitblock)(1) << (start % Bitmask::bits_per_block)) - (bitblock)(1); bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them while (block == skip_block) { ++block_index; if (block_index >= this -> _used_blocks) { return size(); } block = blocks[block_index]; } int bit_index = mpn_scan0(& block, 0); return block_index * Bitmask::bits_per_block + bit_index; } } int Bitmask::rscan(int start, bool value) const { if (start < 0) { return -1; } bitblock * blocks = this -> content; int block_index = start / Bitmask::bits_per_block; if (block_index < 0) { return -1; } if (value) { bitblock skip_block = (bitblock)(0); bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block)); bitblock block = blocks[block_index] & mask_block; // clear lower bits to ignore them while (block == skip_block) { --block_index; if (block_index < 0) { return -1; } block = blocks[block_index]; } unsigned int count = sizeof(block) * 8 - 1; bitblock reverse_block = block; block >>= 1; while (block) { reverse_block <<= 1; reverse_block |= block & 1; block >>= 1; count--; } reverse_block <<= count; int bit_index = mpn_scan1(& reverse_block, 0); return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index; } else { bitblock skip_block = ~((bitblock)(0)); bitblock mask_block = ~((bitblock)(0)) >> (Bitmask::bits_per_block - 1 - (start % Bitmask::bits_per_block)); mask_block = ~mask_block; bitblock block = blocks[block_index] | mask_block; // Set lower bits to ignore them while (block == skip_block) { --block_index; if (block_index < 0) { return -1; } block = blocks[block_index]; } unsigned int count = sizeof(block) * 8 - 1; bitblock reverse_block = block; block >>= 1; while (block) { reverse_block <<= 1; reverse_block |= block & 1; block >>= 1; count--; } reverse_block <<= count; int bit_index = mpn_scan0(& reverse_block, 0); return (block_index + 1) * Bitmask::bits_per_block - 1 - bit_index; } } unsigned int Bitmask::words() const { if (this -> _size == 0) { return 0; } if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Accessing invalid data"; throw IntegrityViolation("Bitmask::words", reason.str()); } unsigned int max = size(); bool sign = get(0); unsigned int i = 0; unsigned int j = scan(i, !sign); unsigned int words = 0; while (j <= max) { if (sign) { ++words; } if (j == max) { break; } i = j; sign = !sign; j = scan(i, !sign); } return words; } void Bitmask::bit_and(bitblock * other_blocks, bool flip) const { if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_and", reason.str()); } Bitmask::bit_and(content, other_blocks, _size, flip); } void Bitmask::bit_and(Bitmask const & other, bool flip) const { if (this -> _size == 0 && other._size == 0) { return; } if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_and", reason.str()); } bitblock * blocks = this -> content; bitblock * other_blocks = other.content; unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks); if (!flip) { // Special Offload to GMP Implementation mpn_and_n(other_blocks, blocks, other_blocks, block_count); } else { // Special Offload to GMP Implementation mpn_nior_n(other_blocks, other_blocks, other_blocks, block_count); mpn_nior_n(other_blocks, blocks, other_blocks, block_count); } }; void Bitmask::bit_or(bitblock * other_blocks, bool flip) const { if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_or", reason.str()); } Bitmask::bit_or(content, other_blocks, _size, flip); } void Bitmask::bit_or(Bitmask const & other, bool flip) const { if (this -> _size == 0 && other._size == 0) { return; } if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_or", reason.str()); } bitblock * blocks = this -> content; bitblock * other_blocks = other.content; unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks); if (!flip) { // Special Offload to GMP Implementation mpn_ior_n(other_blocks, blocks, other_blocks, block_count); } else { // Special Offload to GMP Implementation mpn_nand_n(other_blocks, other_blocks, other_blocks, block_count); mpn_nand_n(other_blocks, blocks, other_blocks, block_count); } }; void Bitmask::bit_xor(bitblock * other_blocks, bool flip) const { if (Bitmask::integrity_check && (!valid() || other_blocks == NULL)) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_xor", reason.str()); } Bitmask::bit_xor(content, other_blocks, _size, flip); } void Bitmask::bit_xor(Bitmask const & other, bool flip) const { if (this -> _size == 0 && other._size == 0) { return; } if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::bit_xor", reason.str()); } bitblock * blocks = this -> content; bitblock * other_blocks = other.content; unsigned int block_count = std::min(this -> _used_blocks, other._used_blocks); if (!flip) { // Special Offload to GMP Implementation mpn_xor_n(other_blocks, blocks, other_blocks, block_count); } else { // Special Offload to GMP Implementation mpn_xnor_n(other_blocks, blocks, other_blocks, block_count); } }; void Bitmask::clear() { if (this -> _size == 0) { return; } bitblock * blocks = this -> content; for (unsigned int i = 0; i < this -> _used_blocks; ++i) { blocks[i] = (bitblock)(0); } } void Bitmask::fill() { if (this -> _size == 0) { return; } bitblock * blocks = this -> content; for (unsigned int i = 0; i < this -> _used_blocks; ++i) { blocks[i] = ~((bitblock)(0)); } Bitmask::clean(this -> content, this -> _used_blocks, this -> _offset); } bool Bitmask::operator==(bitblock * other) const { if (Bitmask::integrity_check && (!valid() || other == NULL)) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::operator==", reason.str()); } return Bitmask::equals(this -> content, other, this -> _size); } bool Bitmask::operator==(Bitmask const & other) const { if (this -> _size == 0 && other._size == 0) { return true; } if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::operator==", reason.str()); } if (size() != other.size()) { return false; } return mpn_cmp(this -> content, other.data(), this -> _used_blocks) == 0; } bool Bitmask::operator<(Bitmask const & other) const { if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::operator<", reason.str()); } return Bitmask::less_than(this -> content, other.data(), this -> _size); } bool Bitmask::operator>(Bitmask const & other) const { if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::operator>", reason.str()); } return Bitmask::greater_than(this -> content, other.data(), this -> _size); } bool Bitmask::operator!=(Bitmask const & other) const { if (this -> _size == 0 && other._size == 0) { return false; } if (Bitmask::integrity_check && (!valid() || !other.valid())) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::operator==", reason.str()); } return !(* this == other); } bool Bitmask::operator<=(Bitmask const & other) const { return !(* this > other); } bool Bitmask::operator>=(Bitmask const & other) const { return !(* this < other); } size_t Bitmask::hash(bool bitwise) const { size_t seed = this -> _size; if (this -> _size == 0) { return seed; } if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Operating with invalid data"; throw IntegrityViolation("Bitmask::hash", reason.str()); } // unsigned int max = size(); // bool sign = get(0); // unsigned int i = 0; // unsigned int j = scan(i, !sign); // size_t seed = 1 * sign; // while (j <= max) { // seed ^= j - i + 0x9e3779b9 + (seed << 6) + (seed >> 2); // if (j == max) { break; } // i = j; // sign = !sign; // j = scan(i, !sign); // } bitblock * blocks = this -> content; for (unsigned int i = 0; i < this -> _used_blocks; ++i) { seed ^= blocks[i] + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } std::string Bitmask::to_string(bool reverse) const { if (this -> _size == 0) { return ""; } if (Bitmask::integrity_check && !valid()) { std::stringstream reason; reason << "Rendering with invalid data"; throw IntegrityViolation("Bitmask::to_string", reason.str()); } return Bitmask::to_string(this -> content, this -> _size); } bool Bitmask::valid() const { return this -> content != NULL; } void Bitmask::benchmark(unsigned int size) { unsigned int trials = 100; unsigned int samples = 1000; unsigned int length = size; unsigned int blocks, offset; Bitmask::block_layout(length, & blocks, & offset); unsigned int bytes = blocks * Bitmask::bits_per_block / 8; // unsigned int nails = Bitmask::bits_per_block - offset - 1; unsigned int nails = 0; float custom_copy = 0.0; float custom_compare = 0.0; float custom_count = 0.0; float custom_and = 0.0; float custom_or = 0.0; float custom_xor = 0.0; float custom_hash = 0.0; float custom_iterate = 0.0; float std_copy = 0.0; float std_compare = 0.0; float gmp_copy = 0.0; float gmp_compare = 0.0; float gmp_count = 0.0; float gmp_and = 0.0; float gmp_or = 0.0; float gmp_xor = 0.0; float gmp_hash = 0.0; float gmp_iterate = 0.0; std::cout << "Benchmarking Memory Copy..." << "\n"; for (unsigned int i = 10; i < trials; ++i) { Bitmask expectation(length); for (unsigned int j = 0; j < length; ++j) { expectation.set(j, j % 100 < i); } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Memory Copy: Custom auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { beta = alpha; } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_copy += duration; if (beta != expectation) { std::cout << "Custom copy is incorrect." << "\n"; std::cout << "Expected: " << expectation.to_string() << "\n"; std::cout << "Got: " << beta.to_string() << "\n"; exit(1); } } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Memory Copy: STD auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { memcpy(beta.data(), alpha.data(), bytes); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); std_copy += duration; if (beta != expectation) { std::cout << "STD copy is incorrect." << "\n"; std::cout << "Expected: " << expectation.to_string() << "\n"; std::cout << "Got: " << beta.to_string() << "\n"; exit(1); } } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_t mpz_beta; mpz_init2(mpz_alpha, length); mpz_init2(mpz_beta, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data()); // Memory Copy: GMP auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_copy += duration; // Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared) alpha.clear(); beta.clear(); // Translation from mpz objects mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha); mpz_export(beta.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_beta); if (beta != expectation) { std::cout << "GMP copy is incorrect." << "\n"; std::cout << "Expected: " << expectation.to_string() << "\n"; std::cout << "Got: " << beta.to_string() << "\n"; exit(1); } } } std::cout << "Results:" << "\n"; std::cout << " Custom Copy Average Runtime: " << (float)custom_copy / (float)(trials * samples) << " ns" << "\n"; std::cout << " STD Copy Average Runtime: " << (float)std_copy / (float)(trials * samples) << " ns" << "\n"; std::cout << " GMP Copy Average Runtime: " << (float)gmp_copy / (float)(trials * samples) << " ns" << "\n"; std::cout << "Benchmarking Memory Compare..." << "\n"; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, j % 100 < i); } // Memory Compare: Custom auto start = std::chrono::high_resolution_clock::now(); bool eq; for (unsigned int k = 0; k < samples; ++k) { eq = alpha == beta; } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_compare += duration; if (!eq) { std::cout << "Custom compare is incorrect." << std::endl; exit(1); } } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, j % 100 < i); } // Memory Compare: STD auto start = std::chrono::high_resolution_clock::now(); int eq; for (unsigned int k = 0; k < samples; ++k) { eq = memcmp(alpha.data(), beta.data(), bytes); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); std_compare += duration; if (eq != 0) { std::cout << "STD compare is incorrect." << std::endl; exit(1); } } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, j % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_t mpz_beta; mpz_init2(mpz_alpha, length); mpz_init2(mpz_beta, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data()); // Memory Compare: GMP auto start = std::chrono::high_resolution_clock::now(); int eq; for (unsigned int k = 0; k < samples; ++k) { eq = mpz_cmp(mpz_alpha, mpz_beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_compare += duration; // Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared) alpha.clear(); beta.clear(); // Translation from mpz objects mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha); mpz_export(beta.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_beta); if (eq != 0) { std::cout << "GMP compare is incorrect." << std::endl; std::cout << "Alpha: " << alpha.to_string() << std::endl; std::cout << "Beta: " << beta.to_string() << std::endl; exit(1); } } } std::cout << "Results:" << std::endl; std::cout << " Custom Compare Average Runtime: " << (float)custom_compare / (float)(trials * samples) << " ns" << std::endl; std::cout << " STD Compare Average Runtime: " << (float)std_compare / (float)(trials * samples) << " ns" << std::endl; std::cout << " GMP Compare Average Runtime: " << (float)gmp_compare / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Bit Counting..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { unsigned int expectation = 0; for (unsigned int j = 0; j < length; ++j) { if (j % 100 < i) { ++expectation; } } { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Bit Count: Custom auto start = std::chrono::high_resolution_clock::now(); unsigned int cnt; for (unsigned int k = 0; k < samples; ++k) { cnt = alpha.count(); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_count += duration; if (cnt != expectation) { std::cout << "Custom count is incorrect." << std::endl; exit(1); } } { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_init2(mpz_alpha, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); // Bit Count: GMP auto start = std::chrono::high_resolution_clock::now(); unsigned int cnt; for (unsigned int k = 0; k < samples; ++k) { cnt = mpz_popcount(mpz_alpha); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_count += duration; // Clear necessary since mpz_export does not copy zero words (it assumes the destination memory has be cleared) alpha.clear(); // Translation from mpz objects mpz_export(alpha.data(), NULL, -1, sizeof(bitblock), -1, nails, mpz_alpha); if (cnt != expectation) { std::cout << "GMP compare is incorrect." << std::endl; std::cout << "Alpha: " << alpha.to_string() << std::endl; exit(1); } } } std::cout << "Results:" << std::endl; std::cout << " Custom Count Average Runtime: " << (float)custom_count / (float)(trials * samples) << " ns" << std::endl; std::cout << " GMP Count Average Runtime: " << (float)gmp_count / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Logical AND..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Logical AND: Custom auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { alpha.bit_and(beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_and += duration; } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_t mpz_beta; mpz_t mpz_gamma; mpz_init2(mpz_alpha, length); mpz_init2(mpz_beta, length); mpz_init2(mpz_gamma, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data()); // Logical AND: GMP auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { mpz_and(mpz_gamma, mpz_alpha, mpz_beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_and += duration; } } std::cout << "Results:" << std::endl; std::cout << " Custom Logical AND Average Runtime: " << (float)custom_and / (float)(trials * samples) << " ns" << std::endl; std::cout << " GMP Logical AND Average Runtime: " << (float)gmp_and / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Logical OR..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Logical OR: Custom auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { alpha.bit_or(beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_or += duration; } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_t mpz_beta; mpz_t mpz_gamma; mpz_init2(mpz_alpha, length); mpz_init2(mpz_beta, length); mpz_init2(mpz_gamma, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data()); // Logical OR: GMP auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { mpz_ior(mpz_gamma, mpz_alpha, mpz_beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_or += duration; } } std::cout << "Results:" << std::endl; std::cout << " Custom Logical OR Average Runtime: " << (float)custom_or / (float)(trials * samples) << " ns" << std::endl; std::cout << " GMP Logical OR Average Runtime: " << (float)gmp_or / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Logical XOR..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Logical XOR: Custom auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { alpha.bit_xor(beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_xor += duration; } { // Set-up Bitmask alpha(length); Bitmask beta(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); beta.set(j, (j+i) % 100 < i); } // Translation to mpz objects mpz_t mpz_alpha; mpz_t mpz_beta; mpz_t mpz_gamma; mpz_init2(mpz_alpha, length); mpz_init2(mpz_beta, length); mpz_init2(mpz_gamma, length); mpz_import(mpz_alpha, blocks, -1, sizeof(bitblock), -1, nails, alpha.data()); mpz_import(mpz_beta, blocks, -1, sizeof(bitblock), -1, nails, beta.data()); // Logical XOR: GMP auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { mpz_xor(mpz_gamma, mpz_alpha, mpz_beta); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_xor += duration; } } std::cout << "Results:" << std::endl; std::cout << " Custom Logical XOR Average Runtime: " << (float)custom_xor / (float)(trials * samples) << " ns" << std::endl; std::cout << " GMP Logical XOR Average Runtime: " << (float)gmp_xor / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Hash Function..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Hash Function: Custom auto start = std::chrono::high_resolution_clock::now(); size_t code; for (unsigned int k = 0; k < samples; ++k) { code = alpha.hash(false); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_hash += duration; } { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Hash Function: GMP auto start = std::chrono::high_resolution_clock::now(); size_t code; for (unsigned int k = 0; k < samples; ++k) { code = alpha.hash(true); } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_hash += duration; } } std::cout << "Results:" << std::endl; std::cout << " Full Scan Hash Function Average Runtime: " << (float)custom_hash / (float)(trials * samples) << " ns" << std::endl; std::cout << " Bit Scan Hash Function Average Runtime: " << (float)gmp_hash / (float)(trials * samples) << " ns" << std::endl; std::cout << "Benchmarking Iteration..." << std::endl; for (unsigned int i = 10; i < trials; ++i) { { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Iteration: Custom unsigned int cnt = 0; auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { cnt = 0; for (unsigned q = 0; q < length; ++q) { if (alpha.get(q)) { ++cnt; } } } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); custom_iterate += duration; if (cnt != alpha.count()) { std::cout << "Custom iteration is incorrect." << std::endl; std::cout << "Alpha: " << alpha.to_string() << std::endl; exit(1); } } { // Set-up Bitmask alpha(length); for (unsigned int j = 0; j < length; ++j) { alpha.set(j, j % 100 < i); } // Iteration: GMP unsigned int cnt; auto start = std::chrono::high_resolution_clock::now(); for (unsigned int k = 0; k < samples; ++k) { cnt = 0; bool sign = alpha.get(0); unsigned int p = 0; unsigned int q = alpha.scan(p, !sign); unsigned int max = length; while (q <= max) { if (sign) { cnt += q - p; } if (q == max) { break; } p = q; sign = !sign; q = alpha.scan(p, !sign); } } auto finish = std::chrono::high_resolution_clock::now(); float duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count(); gmp_iterate += duration; if (cnt != alpha.count()) { std::cout << "GMP iteration is incorrect." << std::endl; std::cout << "Expected: " << alpha.count() << ", Got: " << cnt << std::endl; std::cout << "Alpha: " << alpha.to_string() << std::endl; exit(1); } } } std::cout << "Results:" << std::endl; std::cout << " Full Scan Iteration Average Runtime: " << (float)custom_hash / (float)(trials * samples) << " ns" << std::endl; std::cout << " Bit Scan Iteration Average Runtime: " << (float)gmp_hash / (float)(trials * samples) << " ns" << std::endl; }
40.246133
135
0.56764
e5b512b0fc43c8350dd4d4f782937f3cc617d7dd
29,034
cpp
C++
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/gfx/thebes/gfxPlatformFontList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MOZ_LOGGING #define FORCE_PR_LOG /* Allow logging in the release build */ #endif #include "prlog.h" #include "gfxPlatformFontList.h" #include "nsUnicharUtils.h" #include "nsUnicodeRange.h" #include "nsUnicodeProperties.h" #include "mozilla/Preferences.h" #include "mozilla/Telemetry.h" #include "mozilla/TimeStamp.h" #include "mozilla/Attributes.h" using namespace mozilla; // font info loader constants static const uint32_t kDelayBeforeLoadingCmaps = 8 * 1000; // 8secs static const uint32_t kIntervalBetweenLoadingCmaps = 150; // 150ms static const uint32_t kNumFontsPerSlice = 10; // read in info 10 fonts at a time #ifdef PR_LOGGING #define LOG_FONTLIST(args) PR_LOG(gfxPlatform::GetLog(eGfxLog_fontlist), \ PR_LOG_DEBUG, args) #define LOG_FONTLIST_ENABLED() PR_LOG_TEST( \ gfxPlatform::GetLog(eGfxLog_fontlist), \ PR_LOG_DEBUG) #endif // PR_LOGGING gfxPlatformFontList *gfxPlatformFontList::sPlatformFontList = nullptr; static const char* kObservedPrefs[] = { "font.", "font.name-list.", "intl.accept_languages", // hmmmm... nullptr }; class gfxFontListPrefObserver MOZ_FINAL : public nsIObserver { public: NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER }; static gfxFontListPrefObserver* gFontListPrefObserver = nullptr; NS_IMPL_ISUPPORTS1(gfxFontListPrefObserver, nsIObserver) NS_IMETHODIMP gfxFontListPrefObserver::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { NS_ASSERTION(!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID), "invalid topic"); // XXX this could be made to only clear out the cache for the prefs that were changed // but it probably isn't that big a deal. gfxPlatformFontList::PlatformFontList()->ClearPrefFonts(); gfxFontCache::GetCache()->AgeAllGenerations(); return NS_OK; } NS_IMPL_ISUPPORTS1(gfxPlatformFontList::MemoryReporter, nsIMemoryMultiReporter) NS_MEMORY_REPORTER_MALLOC_SIZEOF_FUN(FontListMallocSizeOf, "font-list") NS_IMETHODIMP gfxPlatformFontList::MemoryReporter::GetName(nsACString &aName) { aName.AssignLiteral("font-list"); return NS_OK; } NS_IMETHODIMP gfxPlatformFontList::MemoryReporter::CollectReports (nsIMemoryMultiReporterCallback* aCb, nsISupports* aClosure) { FontListSizes sizes; sizes.mFontListSize = 0; sizes.mFontTableCacheSize = 0; sizes.mCharMapsSize = 0; gfxPlatformFontList::PlatformFontList()->SizeOfIncludingThis(&FontListMallocSizeOf, &sizes); aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING("explicit/gfx/font-list"), nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, sizes.mFontListSize, NS_LITERAL_CSTRING("Memory used to manage the list of font families and faces."), aClosure); aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING("explicit/gfx/font-charmaps"), nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, sizes.mCharMapsSize, NS_LITERAL_CSTRING("Memory used to record the character coverage of individual fonts."), aClosure); if (sizes.mFontTableCacheSize) { aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING("explicit/gfx/font-tables"), nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, sizes.mFontTableCacheSize, NS_LITERAL_CSTRING("Memory used for cached font metrics and layout tables."), aClosure); } return NS_OK; } NS_IMETHODIMP gfxPlatformFontList::MemoryReporter::GetExplicitNonHeap(int64_t* aAmount) { // This reporter only measures heap memory. *aAmount = 0; return NS_OK; } gfxPlatformFontList::gfxPlatformFontList(bool aNeedFullnamePostscriptNames) : mNeedFullnamePostscriptNames(aNeedFullnamePostscriptNames), mStartIndex(0), mIncrement(kNumFontsPerSlice), mNumFamilies(0) { mFontFamilies.Init(100); mOtherFamilyNames.Init(30); mOtherFamilyNamesInitialized = false; if (mNeedFullnamePostscriptNames) { mFullnames.Init(100); mPostscriptNames.Init(100); } mFaceNamesInitialized = false; mPrefFonts.Init(10); mBadUnderlineFamilyNames.Init(10); LoadBadUnderlineList(); // pref changes notification setup NS_ASSERTION(!gFontListPrefObserver, "There has been font list pref observer already"); gFontListPrefObserver = new gfxFontListPrefObserver(); NS_ADDREF(gFontListPrefObserver); Preferences::AddStrongObservers(gFontListPrefObserver, kObservedPrefs); mSharedCmaps.Init(16); } gfxPlatformFontList::~gfxPlatformFontList() { mSharedCmaps.Clear(); NS_ASSERTION(gFontListPrefObserver, "There is no font list pref observer"); Preferences::RemoveObservers(gFontListPrefObserver, kObservedPrefs); NS_RELEASE(gFontListPrefObserver); } nsresult gfxPlatformFontList::InitFontList() { mFontFamilies.Clear(); mOtherFamilyNames.Clear(); mOtherFamilyNamesInitialized = false; if (mNeedFullnamePostscriptNames) { mFullnames.Clear(); mPostscriptNames.Clear(); } mFaceNamesInitialized = false; mPrefFonts.Clear(); CancelLoader(); // initialize ranges of characters for which system-wide font search should be skipped mCodepointsWithNoFonts.reset(); mCodepointsWithNoFonts.SetRange(0,0x1f); // C0 controls mCodepointsWithNoFonts.SetRange(0x7f,0x9f); // C1 controls NS_RegisterMemoryMultiReporter(new MemoryReporter); sPlatformFontList = this; return NS_OK; } void gfxPlatformFontList::GenerateFontListKey(const nsAString& aKeyName, nsAString& aResult) { aResult = aKeyName; ToLowerCase(aResult); } void gfxPlatformFontList::InitOtherFamilyNames() { mOtherFamilyNamesInitialized = true; Telemetry::AutoTimer<Telemetry::FONTLIST_INITOTHERFAMILYNAMES> timer; // iterate over all font families and read in other family names mFontFamilies.Enumerate(gfxPlatformFontList::InitOtherFamilyNamesProc, this); } PLDHashOperator gfxPlatformFontList::InitOtherFamilyNamesProc(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void* userArg) { gfxPlatformFontList *fc = static_cast<gfxPlatformFontList*>(userArg); aFamilyEntry->ReadOtherFamilyNames(fc); return PL_DHASH_NEXT; } void gfxPlatformFontList::InitFaceNameLists() { mFaceNamesInitialized = true; // iterate over all font families and read in other family names Telemetry::AutoTimer<Telemetry::FONTLIST_INITFACENAMELISTS> timer; mFontFamilies.Enumerate(gfxPlatformFontList::InitFaceNameListsProc, this); } PLDHashOperator gfxPlatformFontList::InitFaceNameListsProc(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void* userArg) { gfxPlatformFontList *fc = static_cast<gfxPlatformFontList*>(userArg); aFamilyEntry->ReadFaceNames(fc, fc->NeedFullnamePostscriptNames()); return PL_DHASH_NEXT; } void gfxPlatformFontList::PreloadNamesList() { nsAutoTArray<nsString, 10> preloadFonts; gfxFontUtils::GetPrefsFontList("font.preload-names-list", preloadFonts); uint32_t numFonts = preloadFonts.Length(); for (uint32_t i = 0; i < numFonts; i++) { nsAutoString key; GenerateFontListKey(preloadFonts[i], key); // only search canonical names! gfxFontFamily *familyEntry = mFontFamilies.GetWeak(key); if (familyEntry) { familyEntry->ReadOtherFamilyNames(this); } } } void gfxPlatformFontList::SetFixedPitch(const nsAString& aFamilyName) { gfxFontFamily *family = FindFamily(aFamilyName); if (!family) return; family->FindStyleVariations(); nsTArray<nsRefPtr<gfxFontEntry> >& fontlist = family->GetFontList(); uint32_t i, numFonts = fontlist.Length(); for (i = 0; i < numFonts; i++) { fontlist[i]->mFixedPitch = 1; } } void gfxPlatformFontList::LoadBadUnderlineList() { nsAutoTArray<nsString, 10> blacklist; gfxFontUtils::GetPrefsFontList("font.blacklist.underline_offset", blacklist); uint32_t numFonts = blacklist.Length(); for (uint32_t i = 0; i < numFonts; i++) { nsAutoString key; GenerateFontListKey(blacklist[i], key); mBadUnderlineFamilyNames.PutEntry(key); } } bool gfxPlatformFontList::ResolveFontName(const nsAString& aFontName, nsAString& aResolvedFontName) { gfxFontFamily *family = FindFamily(aFontName); if (family) { aResolvedFontName = family->Name(); return true; } return false; } struct FontListData { FontListData(nsIAtom *aLangGroup, const nsACString& aGenericFamily, nsTArray<nsString>& aListOfFonts) : mLangGroup(aLangGroup), mGenericFamily(aGenericFamily), mListOfFonts(aListOfFonts) {} nsIAtom *mLangGroup; const nsACString& mGenericFamily; nsTArray<nsString>& mListOfFonts; }; PLDHashOperator gfxPlatformFontList::HashEnumFuncForFamilies(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void *aUserArg) { FontListData *data = static_cast<FontListData*>(aUserArg); // use the first variation for now. This data should be the same // for all the variations and should probably be moved up to // the Family gfxFontStyle style; style.language = data->mLangGroup; bool needsBold; nsRefPtr<gfxFontEntry> aFontEntry = aFamilyEntry->FindFontForStyle(style, needsBold); NS_ASSERTION(aFontEntry, "couldn't find any font entry in family"); if (!aFontEntry) return PL_DHASH_NEXT; /* skip symbol fonts */ if (aFontEntry->IsSymbolFont()) return PL_DHASH_NEXT; if (aFontEntry->SupportsLangGroup(data->mLangGroup) && aFontEntry->MatchesGenericFamily(data->mGenericFamily)) { nsAutoString localizedFamilyName; aFamilyEntry->LocalizedName(localizedFamilyName); data->mListOfFonts.AppendElement(localizedFamilyName); } return PL_DHASH_NEXT; } void gfxPlatformFontList::GetFontList(nsIAtom *aLangGroup, const nsACString& aGenericFamily, nsTArray<nsString>& aListOfFonts) { FontListData data(aLangGroup, aGenericFamily, aListOfFonts); mFontFamilies.Enumerate(gfxPlatformFontList::HashEnumFuncForFamilies, &data); aListOfFonts.Sort(); aListOfFonts.Compact(); } struct FontFamilyListData { FontFamilyListData(nsTArray<nsRefPtr<gfxFontFamily> >& aFamilyArray) : mFamilyArray(aFamilyArray) {} static PLDHashOperator AppendFamily(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void *aUserArg) { FontFamilyListData *data = static_cast<FontFamilyListData*>(aUserArg); data->mFamilyArray.AppendElement(aFamilyEntry); return PL_DHASH_NEXT; } nsTArray<nsRefPtr<gfxFontFamily> >& mFamilyArray; }; void gfxPlatformFontList::GetFontFamilyList(nsTArray<nsRefPtr<gfxFontFamily> >& aFamilyArray) { FontFamilyListData data(aFamilyArray); mFontFamilies.Enumerate(FontFamilyListData::AppendFamily, &data); } gfxFontEntry* gfxPlatformFontList::SystemFindFontForChar(const uint32_t aCh, int32_t aRunScript, const gfxFontStyle* aStyle) { gfxFontEntry* fontEntry = nullptr; // is codepoint with no matching font? return null immediately if (mCodepointsWithNoFonts.test(aCh)) { return nullptr; } // try to short-circuit font fallback for U+FFFD, used to represent // encoding errors: just use a platform-specific fallback system // font that is guaranteed (or at least highly likely) to be around, // or a cached family from last time U+FFFD was seen. this helps // speed up pages with lots of encoding errors, binary-as-text, etc. if (aCh == 0xFFFD && mReplacementCharFallbackFamily.Length() > 0) { bool needsBold; // ignored in the system fallback case fontEntry = FindFontForFamily(mReplacementCharFallbackFamily, aStyle, needsBold); if (fontEntry && fontEntry->TestCharacterMap(aCh)) return fontEntry; } TimeStamp start = TimeStamp::Now(); // search commonly available fonts bool common = true; fontEntry = CommonFontFallback(aCh, aRunScript, aStyle); // if didn't find a font, do system-wide fallback (except for specials) uint32_t cmapCount = 0; if (!fontEntry) { common = false; fontEntry = GlobalFontFallback(aCh, aRunScript, aStyle, cmapCount); } TimeDuration elapsed = TimeStamp::Now() - start; #ifdef PR_LOGGING PRLogModuleInfo *log = gfxPlatform::GetLog(eGfxLog_textrun); if (NS_UNLIKELY(log)) { uint32_t charRange = gfxFontUtils::CharRangeBit(aCh); uint32_t unicodeRange = FindCharUnicodeRange(aCh); int32_t script = mozilla::unicode::GetScriptCode(aCh); PR_LOG(log, PR_LOG_WARNING,\ ("(textrun-systemfallback-%s) char: u+%6.6x " "char-range: %d unicode-range: %d script: %d match: [%s]" " time: %dus cmaps: %d\n", (common ? "common" : "global"), aCh, charRange, unicodeRange, script, (fontEntry ? NS_ConvertUTF16toUTF8(fontEntry->Name()).get() : "<none>"), int32_t(elapsed.ToMicroseconds()), cmapCount)); } #endif // no match? add to set of non-matching codepoints if (!fontEntry) { mCodepointsWithNoFonts.set(aCh); } else if (aCh == 0xFFFD && fontEntry) { mReplacementCharFallbackFamily = fontEntry->FamilyName(); } // track system fallback time static bool first = true; int32_t intElapsed = int32_t(first ? elapsed.ToMilliseconds() : elapsed.ToMicroseconds()); Telemetry::Accumulate((first ? Telemetry::SYSTEM_FONT_FALLBACK_FIRST : Telemetry::SYSTEM_FONT_FALLBACK), intElapsed); first = false; // track the script for which fallback occurred (incremented one make it // 1-based) Telemetry::Accumulate(Telemetry::SYSTEM_FONT_FALLBACK_SCRIPT, aRunScript + 1); return fontEntry; } PLDHashOperator gfxPlatformFontList::FindFontForCharProc(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void *userArg) { GlobalFontMatch *data = static_cast<GlobalFontMatch*>(userArg); // evaluate all fonts in this family for a match aFamilyEntry->FindFontForChar(data); return PL_DHASH_NEXT; } #define NUM_FALLBACK_FONTS 8 gfxFontEntry* gfxPlatformFontList::CommonFontFallback(const uint32_t aCh, int32_t aRunScript, const gfxFontStyle* aMatchStyle) { nsAutoTArray<const char*,NUM_FALLBACK_FONTS> defaultFallbacks; uint32_t i, numFallbacks; gfxPlatform::GetPlatform()->GetCommonFallbackFonts(aCh, aRunScript, defaultFallbacks); numFallbacks = defaultFallbacks.Length(); for (i = 0; i < numFallbacks; i++) { nsAutoString familyName; const char *fallbackFamily = defaultFallbacks[i]; familyName.AppendASCII(fallbackFamily); gfxFontFamily *fallback = gfxPlatformFontList::PlatformFontList()->FindFamily(familyName); if (!fallback) continue; gfxFontEntry *fontEntry; bool needsBold; // ignored in the system fallback case // use first font in list that supports a given character fontEntry = fallback->FindFontForStyle(*aMatchStyle, needsBold); if (fontEntry && fontEntry->TestCharacterMap(aCh)) { return fontEntry; } } return nullptr; } gfxFontEntry* gfxPlatformFontList::GlobalFontFallback(const uint32_t aCh, int32_t aRunScript, const gfxFontStyle* aMatchStyle, uint32_t& aCmapCount) { // otherwise, try to find it among local fonts GlobalFontMatch data(aCh, aRunScript, aMatchStyle); // iterate over all font families to find a font that support the character mFontFamilies.Enumerate(gfxPlatformFontList::FindFontForCharProc, &data); aCmapCount = data.mCmapsTested; return data.mBestMatch; } #ifdef XP_WIN #include <windows.h> // crude hack for using when monitoring process static void LogRegistryEvent(const wchar_t *msg) { HKEY dummyKey; HRESULT hr; wchar_t buf[512]; wsprintfW(buf, L" log %s", msg); hr = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buf, 0, KEY_READ, &dummyKey); if (SUCCEEDED(hr)) { RegCloseKey(dummyKey); } } #endif gfxFontFamily* gfxPlatformFontList::FindFamily(const nsAString& aFamily) { nsAutoString key; gfxFontFamily *familyEntry; GenerateFontListKey(aFamily, key); NS_ASSERTION(mFontFamilies.Count() != 0, "system font list was not initialized correctly"); // lookup in canonical (i.e. English) family name list if ((familyEntry = mFontFamilies.GetWeak(key))) { return familyEntry; } // lookup in other family names list (mostly localized names) if ((familyEntry = mOtherFamilyNames.GetWeak(key)) != nullptr) { return familyEntry; } // name not found and other family names not yet fully initialized so // initialize the rest of the list and try again. this is done lazily // since reading name table entries is expensive. // although ASCII localized family names are possible they don't occur // in practice so avoid pulling in names at startup if (!mOtherFamilyNamesInitialized && !IsASCII(aFamily)) { InitOtherFamilyNames(); if ((familyEntry = mOtherFamilyNames.GetWeak(key)) != nullptr) { return familyEntry; } } return nullptr; } gfxFontEntry* gfxPlatformFontList::FindFontForFamily(const nsAString& aFamily, const gfxFontStyle* aStyle, bool& aNeedsBold) { gfxFontFamily *familyEntry = FindFamily(aFamily); aNeedsBold = false; if (familyEntry) return familyEntry->FindFontForStyle(*aStyle, aNeedsBold); return nullptr; } bool gfxPlatformFontList::GetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<gfxFontFamily> > *array) { return mPrefFonts.Get(uint32_t(aLangGroup), array); } void gfxPlatformFontList::SetPrefFontFamilyEntries(eFontPrefLang aLangGroup, nsTArray<nsRefPtr<gfxFontFamily> >& array) { mPrefFonts.Put(uint32_t(aLangGroup), array); } void gfxPlatformFontList::AddOtherFamilyName(gfxFontFamily *aFamilyEntry, nsAString& aOtherFamilyName) { nsAutoString key; GenerateFontListKey(aOtherFamilyName, key); if (!mOtherFamilyNames.GetWeak(key)) { mOtherFamilyNames.Put(key, aFamilyEntry); #ifdef PR_LOGGING LOG_FONTLIST(("(fontlist-otherfamily) canonical family: %s, " "other family: %s\n", NS_ConvertUTF16toUTF8(aFamilyEntry->Name()).get(), NS_ConvertUTF16toUTF8(aOtherFamilyName).get())); #endif if (mBadUnderlineFamilyNames.Contains(key)) aFamilyEntry->SetBadUnderlineFamily(); } } void gfxPlatformFontList::AddFullname(gfxFontEntry *aFontEntry, nsAString& aFullname) { if (!mFullnames.GetWeak(aFullname)) { mFullnames.Put(aFullname, aFontEntry); #ifdef PR_LOGGING LOG_FONTLIST(("(fontlist-fullname) name: %s, fullname: %s\n", NS_ConvertUTF16toUTF8(aFontEntry->Name()).get(), NS_ConvertUTF16toUTF8(aFullname).get())); #endif } } void gfxPlatformFontList::AddPostscriptName(gfxFontEntry *aFontEntry, nsAString& aPostscriptName) { if (!mPostscriptNames.GetWeak(aPostscriptName)) { mPostscriptNames.Put(aPostscriptName, aFontEntry); #ifdef PR_LOGGING LOG_FONTLIST(("(fontlist-postscript) name: %s, psname: %s\n", NS_ConvertUTF16toUTF8(aFontEntry->Name()).get(), NS_ConvertUTF16toUTF8(aPostscriptName).get())); #endif } } bool gfxPlatformFontList::GetStandardFamilyName(const nsAString& aFontName, nsAString& aFamilyName) { aFamilyName.Truncate(); ResolveFontName(aFontName, aFamilyName); return !aFamilyName.IsEmpty(); } gfxCharacterMap* gfxPlatformFontList::FindCharMap(gfxCharacterMap *aCmap) { aCmap->CalcHash(); gfxCharacterMap *cmap = AddCmap(aCmap); cmap->mShared = true; return cmap; } // add a cmap to the shared cmap set gfxCharacterMap* gfxPlatformFontList::AddCmap(const gfxCharacterMap* aCharMap) { CharMapHashKey *found = mSharedCmaps.PutEntry(const_cast<gfxCharacterMap*>(aCharMap)); return found->GetKey(); } // remove the cmap from the shared cmap set void gfxPlatformFontList::RemoveCmap(const gfxCharacterMap* aCharMap) { // skip lookups during teardown if (mSharedCmaps.Count() == 0) { return; } // cmap needs to match the entry *and* be the same ptr before removing CharMapHashKey *found = mSharedCmaps.GetEntry(const_cast<gfxCharacterMap*>(aCharMap)); if (found && found->GetKey() == aCharMap) { mSharedCmaps.RemoveEntry(const_cast<gfxCharacterMap*>(aCharMap)); } } void gfxPlatformFontList::InitLoader() { GetFontFamilyList(mFontFamiliesToLoad); mStartIndex = 0; mNumFamilies = mFontFamiliesToLoad.Length(); } bool gfxPlatformFontList::RunLoader() { uint32_t i, endIndex = (mStartIndex + mIncrement < mNumFamilies ? mStartIndex + mIncrement : mNumFamilies); bool loadCmaps = !UsesSystemFallback() || gfxPlatform::GetPlatform()->UseCmapsDuringSystemFallback(); // for each font family, load in various font info for (i = mStartIndex; i < endIndex; i++) { gfxFontFamily* familyEntry = mFontFamiliesToLoad[i]; // find all faces that are members of this family familyEntry->FindStyleVariations(); if (familyEntry->GetFontList().Length() == 0) { // failed to load any faces for this family, so discard it nsAutoString key; GenerateFontListKey(familyEntry->Name(), key); mFontFamilies.Remove(key); continue; } // load the cmaps if needed if (loadCmaps) { familyEntry->ReadAllCMAPs(); } // read in face names familyEntry->ReadFaceNames(this, mNeedFullnamePostscriptNames); // check whether the family can be considered "simple" for style matching familyEntry->CheckForSimpleFamily(); } mStartIndex = endIndex; return (mStartIndex >= mNumFamilies); } void gfxPlatformFontList::FinishLoader() { mFontFamiliesToLoad.Clear(); mNumFamilies = 0; } // Support for memory reporting static size_t SizeOfFamilyEntryExcludingThis(const nsAString& aKey, const nsRefPtr<gfxFontFamily>& aFamily, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { FontListSizes *sizes = static_cast<FontListSizes*>(aUserArg); aFamily->SizeOfExcludingThis(aMallocSizeOf, sizes); sizes->mFontListSize += aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf); // we return zero here because the measurements have been added directly // to the relevant fields of the FontListSizes record return 0; } // this is also used by subclasses that hold additional hashes of family names /*static*/ size_t gfxPlatformFontList::SizeOfFamilyNameEntryExcludingThis (const nsAString& aKey, const nsRefPtr<gfxFontFamily>& aFamily, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { // we don't count the size of the family here, because this is an *extra* // reference to a family that will have already been counted in the main list return aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf); } static size_t SizeOfFontNameEntryExcludingThis(const nsAString& aKey, const nsRefPtr<gfxFontEntry>& aFont, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { // the font itself is counted by its owning family; here we only care about // the name stored in the hashtable key return aKey.SizeOfExcludingThisIfUnshared(aMallocSizeOf); } static size_t SizeOfPrefFontEntryExcludingThis (const uint32_t& aKey, const nsTArray<nsRefPtr<gfxFontFamily> >& aList, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { // again, we only care about the size of the array itself; we don't follow // the refPtrs stored in it, because they point to entries already owned // and accounted-for by the main font list return aList.SizeOfExcludingThis(aMallocSizeOf); } static size_t SizeOfStringEntryExcludingThis(nsStringHashKey* aHashEntry, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { return aHashEntry->GetKey().SizeOfExcludingThisIfUnshared(aMallocSizeOf); } static size_t SizeOfSharedCmapExcludingThis(CharMapHashKey* aHashEntry, nsMallocSizeOfFun aMallocSizeOf, void* aUserArg) { FontListSizes *sizes = static_cast<FontListSizes*>(aUserArg); uint32_t size = aHashEntry->GetKey()->SizeOfIncludingThis(aMallocSizeOf); sizes->mCharMapsSize += size; // we return zero here because the measurements have been added directly // to the relevant fields of the FontListSizes record return 0; } void gfxPlatformFontList::SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf, FontListSizes* aSizes) const { aSizes->mFontListSize += mFontFamilies.SizeOfExcludingThis(SizeOfFamilyEntryExcludingThis, aMallocSizeOf, aSizes); aSizes->mFontListSize += mOtherFamilyNames.SizeOfExcludingThis(SizeOfFamilyNameEntryExcludingThis, aMallocSizeOf); if (mNeedFullnamePostscriptNames) { aSizes->mFontListSize += mFullnames.SizeOfExcludingThis(SizeOfFontNameEntryExcludingThis, aMallocSizeOf); aSizes->mFontListSize += mPostscriptNames.SizeOfExcludingThis(SizeOfFontNameEntryExcludingThis, aMallocSizeOf); } aSizes->mFontListSize += mCodepointsWithNoFonts.SizeOfExcludingThis(aMallocSizeOf); aSizes->mFontListSize += mReplacementCharFallbackFamily.SizeOfExcludingThisIfUnshared(aMallocSizeOf); aSizes->mFontListSize += mFontFamiliesToLoad.SizeOfExcludingThis(aMallocSizeOf); aSizes->mFontListSize += mPrefFonts.SizeOfExcludingThis(SizeOfPrefFontEntryExcludingThis, aMallocSizeOf); aSizes->mFontListSize += mBadUnderlineFamilyNames.SizeOfExcludingThis(SizeOfStringEntryExcludingThis, aMallocSizeOf); aSizes->mFontListSize += mSharedCmaps.SizeOfExcludingThis(SizeOfSharedCmapExcludingThis, aMallocSizeOf, aSizes); } void gfxPlatformFontList::SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf, FontListSizes* aSizes) const { aSizes->mFontListSize += aMallocSizeOf(this); SizeOfExcludingThis(aMallocSizeOf, aSizes); }
33.257732
114
0.661604
e5b5c80434acda90be4e02bfcc27736f0c17d656
2,910
cpp
C++
11. DP 2/Maximum_sum_rect.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
11. DP 2/Maximum_sum_rect.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
11. DP 2/Maximum_sum_rect.cpp
bhavinvirani/Competitive-Programming-coding-ninjas
5e50ae7ad3fc969a4970f91f8d895c986353bb71
[ "MIT" ]
null
null
null
/* Maximum Sum Rectangle Send Feedback Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix. Input Format: First line of input will contain T(number of test case), each test case follows as. First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm. Output Format: Output a single integer, maximum sum rectangle for each test case in a newline. Constraints 1 <= T <= 50 1<=n,m<=100 -10^5 <= mat[i][j] <= 10^5 Sample Input 1 4 5 1 2 -1 -4 -20 -8 -3 4 2 1 3 8 10 1 3 -4 -1 1 7 -6 Sample Output 29 */ #include <bits/stdc++.h> using namespace std; int kadane(vector<int> vec) { int maxSum = INT_MIN, curSum = 0; for (int i = 0; i < vec.size(); i++) { curSum += vec[i]; maxSum = max(maxSum, curSum); curSum = (curSum < 0) ? 0 : curSum; } return maxSum; } int findMaxSum(vector<vector<int>> arr, int row, int col) { // int ans = 0; // int startx = 0, starty = 0, endx = 0, endy = 0; // for (int i = 0; i < row; i++) // { // startx = i; // for (int j = 0; j < col; j++) // { // starty = j; // for (int m = 0; m < row; m++) // { // endx = m; // for (int n = 0; n < col; n++) // { // endy = n; // int sum = 0; // for (int a = startx; a <= endx; a++) // { // for (int b = starty; b <= endy; b++) // { // sum += arr[a][b]; // } // } // if (sum > ans) // ans = sum; // } // } // } // } //? 2nd approch int max_sum_soFar = INT_MIN; for(int i = 0; i < row; i++){ vector<int> temp(row); for (int j = i; j < col; j++) { for (int k = 0; k < row; k++){ temp[k] += arr[k][j]; } max_sum_soFar = max(max_sum_soFar, kadane(temp)); } } return max_sum_soFar; } int main() { freopen("/home/spy/Desktop/input.txt", "r", stdin); freopen("/home/spy/Desktop/output.txt", "w", stdout); int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<vector<int>> arr; for (int i = 0; i < n; i++) { vector<int> tmp; for (int j = 0; j < m; j++) { int x; cin >> x; tmp.push_back(x); } arr.push_back(tmp); } int ans; ans = findMaxSum(arr, n, m); cout << ans << endl; } return 0; }
24.453782
165
0.434021
e5c0f68c90c0999dfe19a01d29d9c0ff54282c05
3,491
cpp
C++
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
fsaintjacques/cstore
3300a81c359c4a48e13ad397e3eb09384f57ccd7
[ "BSD-2-Clause" ]
14
2016-07-11T04:08:09.000Z
2022-03-11T05:56:59.000Z
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
ibrarahmad/cstore
3300a81c359c4a48e13ad397e3eb09384f57ccd7
[ "BSD-2-Clause" ]
null
null
null
src/OptPlan/Opt_SnowflakeInterestingOrders.cpp
ibrarahmad/cstore
3300a81c359c4a48e13ad397e3eb09384f57ccd7
[ "BSD-2-Clause" ]
13
2016-06-01T10:41:15.000Z
2022-01-06T09:01:15.000Z
/* * Opt_SnowflakeInterestingOrders.h * OptDev * * Created by Nga Tran on 11/10/05. * Questions, ask Nga Tran at nga@brandeis.edu or Tien Hoang at hoangt@brandeis.edu * * This class keeps interesting orders of a snowflake query */ #include "Opt_SnowflakeInterestingOrders.h" // Default constructor Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders() { m_sQueryName = ""; } // Provide query name Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName) { m_sQueryName = sQueryName; } // Provide query names and 1 object Opt_SnowflakeInterestingOrders::Opt_SnowflakeInterestingOrders(string sQueryName, list<Opt_Column*> order) { m_sQueryName = sQueryName; mOrderList.push_back(order); } // Destructor Opt_SnowflakeInterestingOrders::~Opt_SnowflakeInterestingOrders() { } // String presentation of this class string Opt_SnowflakeInterestingOrders::toStringNoTableDot(string sIndent) { string sReturn = sIndent; sReturn.append(m_sQueryName); sReturn.append(": \n"); sIndent += "\t"; list<InterestingOrder>::iterator orderIt; for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++) { sReturn.append(sIndent); InterestingOrder order = *orderIt; list<Opt_Column*>::iterator colIt; for (colIt = order.begin(); colIt != order.end(); colIt++) { sReturn.append((*colIt)->toStringNoTableDot()); sReturn.append(" "); } sReturn.append("\n"); } return sReturn; } // String presentation of this class string Opt_SnowflakeInterestingOrders::toString(string sIndent) { string sReturn = sIndent; sReturn.append(m_sQueryName); sReturn.append(": \n"); sIndent += "\t"; list<InterestingOrder>::iterator orderIt; for (orderIt = mOrderList.begin(); orderIt != mOrderList.end(); orderIt++) { sReturn.append(sIndent); InterestingOrder order = *orderIt; list<Opt_Column*>::iterator colIt; for (colIt = order.begin(); colIt != order.end(); colIt++) { sReturn.append((*colIt)->toString()); sReturn.append(" "); } sReturn.append("\n"); } return sReturn; } void Opt_SnowflakeInterestingOrders::setQueryName(string sQueryName) { m_sQueryName = sQueryName; } string Opt_SnowflakeInterestingOrders::getQueryName() { return m_sQueryName; } list<InterestingOrder> Opt_SnowflakeInterestingOrders::getOrderList() { return mOrderList; } // Add an order // return true (1) if the order added bool Opt_SnowflakeInterestingOrders::addOrder(string sQueryName, list<Opt_Column*> order) { if (m_sQueryName.compare(sQueryName) == 0) { // Check if the order already existed list<InterestingOrder>::iterator it; for (it = mOrderList.begin(); it != mOrderList.end(); it++) { list<Opt_Column*> intertestingOrder = *it; // Check if number of columns in the orders are the same if (intertestingOrder.size() != order.size()) { continue; } // Compare if orders are exactly the same bool isTheSame = 1; list<Opt_Column*>::iterator existColIt = intertestingOrder.begin(); list<Opt_Column*>::iterator colIt = order.begin(); while( (existColIt != intertestingOrder.end()) && (colIt != order.end()) ) { if (((*existColIt)->getColumnName()).compare((*colIt)->getColumnName()) != 0) { isTheSame = 0; } existColIt++; colIt++; } if (isTheSame) { // the order already existed return 1; } } mOrderList.push_back(order); return 1; } return 0; }
22.967105
106
0.696649
e5c3467258e82f5fb0ba2c296149d9a250bf4d61
1,964
cpp
C++
tools/faodel-stress/serdes/SerdesStringObject.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
tools/faodel-stress/serdes/SerdesStringObject.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
tools/faodel-stress/serdes/SerdesStringObject.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #include <iostream> #include "lunasa/common/GenericSequentialDataBundle.hh" #include "SerdesStringObject.hh" using namespace std; SerdesStringObject::SerdesStringObject(JobSerdes::params_t params, std::function<int ()> f_prng) { //Populate our string list for(int i=0; i<params.num_items; i++) { strings.emplace_back(faodel::RandomString( f_prng() )); } } typedef lunasa::GenericSequentialBundle<uint64_t> bundle_t; lunasa::DataObject SerdesStringObject::pup() const { // Since this is a series of random length strings, the easiest thing to // do is just pack them into an LDO using the GenericSequentialBundler // class. You allocate space for all the strings, and then use a // bundle_offsets_t to keep track of where you are in the LDO. //Figure out how much space our strings need. Note: each item as a 32b length uint32_t payload_size=0; for(auto &s: strings) { payload_size += s.size() + sizeof(uint32_t); } //Allocate an LDO, overlay our bundle structure on it, and wipe the header lunasa::DataObject ldo(sizeof(bundle_t), payload_size,lunasa::DataObject::AllocatorType::eager); auto *msg = ldo.GetMetaPtr<bundle_t *>(); msg->Init(); //Use the offsets to track where we are so we don't overflow lunasa::bundle_offsets_t counters(&ldo); for(auto &s : strings) { bool ok=msg->AppendBack(counters, s); if(!ok) std::cerr<<"Serialization problems in SerdesStringObject\n"; } return ldo; } void SerdesStringObject::pup(const lunasa::DataObject &ldo) { auto *msg = ldo.GetMetaPtr<bundle_t *>(); lunasa::bundle_offsets_t counters(&ldo); strings.resize(0); string s; while(msg->GetNext(counters, &s)) { strings.emplace_back(s); } }
31.174603
98
0.709776
e5c3df8ba4595b3c658c146a3ff58059345fd197
679
cpp
C++
src/classes/Ciudad.cpp
mattaereal/AntColonyOptimization
b45df28cb181395d290d6c6accbc9297fa863aff
[ "MIT" ]
null
null
null
src/classes/Ciudad.cpp
mattaereal/AntColonyOptimization
b45df28cb181395d290d6c6accbc9297fa863aff
[ "MIT" ]
null
null
null
src/classes/Ciudad.cpp
mattaereal/AntColonyOptimization
b45df28cb181395d290d6c6accbc9297fa863aff
[ "MIT" ]
null
null
null
/* * Ciudad.cpp * * Created on: May 3, 2014 * Author: matt */ #include "Ciudad.h" Ciudad::Ciudad(double c, string n, double p) { this->pheromone = p; this->cost = c; this->name = n; } Ciudad::Ciudad() { this->cost = 0; this->pheromone = 0; this->name = "Undefined, please define city"; } Ciudad::~Ciudad() { } double Ciudad::getCost() const { return cost; } void Ciudad::setCost(double c) { this->cost = c; } const string & Ciudad::getName() const { return name; } void Ciudad::setName(const string& n) { this->name = n; } double Ciudad::getPheromone() const { return pheromone; } void Ciudad::setPheromone(double ph) { this->pheromone = ph; }
13.58
46
0.630339
e5c71a4a32057faabff0ea40bcba8665a95d7538
2,072
cpp
C++
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/net/vcn/VcnGatewayConnectionConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JLongArray.hpp" #include "../ipsec/ike/IkeTunnelConnectionParams.hpp" #include "./VcnGatewayConnectionConfig.hpp" #include "../../../JString.hpp" #include "./VcnGatewayConnectionConfig_Builder.hpp" namespace android::net::vcn { // Fields // QJniObject forward VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(QJniObject obj) : JObject(obj) {} // Constructors VcnGatewayConnectionConfig_Builder::VcnGatewayConnectionConfig_Builder(JString arg0, android::net::ipsec::ike::IkeTunnelConnectionParams arg1) : JObject( "android.net.vcn.VcnGatewayConnectionConfig$Builder", "(Ljava/lang/String;Landroid/net/ipsec/ike/IkeTunnelConnectionParams;)V", arg0.object<jstring>(), arg1.object() ) {} // Methods android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::addExposedCapability(jint arg0) const { return callObjectMethod( "addExposedCapability", "(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;", arg0 ); } android::net::vcn::VcnGatewayConnectionConfig VcnGatewayConnectionConfig_Builder::build() const { return callObjectMethod( "build", "()Landroid/net/vcn/VcnGatewayConnectionConfig;" ); } android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::removeExposedCapability(jint arg0) const { return callObjectMethod( "removeExposedCapability", "(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;", arg0 ); } android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setMaxMtu(jint arg0) const { return callObjectMethod( "setMaxMtu", "(I)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;", arg0 ); } android::net::vcn::VcnGatewayConnectionConfig_Builder VcnGatewayConnectionConfig_Builder::setRetryIntervalsMillis(JLongArray arg0) const { return callObjectMethod( "setRetryIntervalsMillis", "([J)Landroid/net/vcn/VcnGatewayConnectionConfig$Builder;", arg0.object<jlongArray>() ); } } // namespace android::net::vcn
31.876923
143
0.770753
e5caa02a9570fe3d651f75716711e14ad46223c2
1,559
cpp
C++
src/materials/HomogeneousMedia.cpp
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
6
2020-02-06T03:30:25.000Z
2021-10-12T11:38:24.000Z
src/materials/HomogeneousMedia.cpp
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
1
2021-07-29T17:38:23.000Z
2021-07-29T17:38:23.000Z
src/materials/HomogeneousMedia.cpp
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
1
2020-02-14T06:42:03.000Z
2020-02-14T06:42:03.000Z
#include "materials/HomogeneousMedia.h" namespace narvalengine { HomogeneousMedia::HomogeneousMedia(glm::vec3 scattering, glm::vec3 absorption, float density) { this->scattering = scattering; this->absorption = absorption; this->extinction = absorption + scattering; this->density = density; } HomogeneousMedia::~HomogeneousMedia() { } glm::vec3 HomogeneousMedia::Tr(float distance) { glm::vec3 v = extinction * distance * density; return exp(-v); } glm::vec3 HomogeneousMedia::Tr(Ray incoming, RayIntersection ri) { return Tr(ri.tFar - ri.tNear); } /* intersection must be inside or at the boundary of the volume */ glm::vec3 HomogeneousMedia::sample(Ray incoming, Ray &scattered, RayIntersection intersection) { float t = -std::log(1 - random()) / avg(extinction); float distInsideVolume = intersection.tFar - intersection.tNear; t = t / distInsideVolume; bool sampledMedia = t < distInsideVolume; //point is inside volume if (sampledMedia) { //move ray to near intersection at voxel scattered.o = incoming.getPointAt(t); scattered.d = intersection.primitive->material->bsdf->sample(incoming.d, intersection.normal); } else { scattered.o = incoming.getPointAt(distInsideVolume + 0.001f); scattered.d = incoming.d; //return glm::vec3(0, 1, 0); } glm::vec3 Tr = this->Tr(t); glm::vec3 density = sampledMedia ? (extinction * Tr) : Tr; float pdf = avg(density); if (pdf == 0) pdf = 1; glm::vec3 result = sampledMedia ? (Tr * scattering / pdf) : Tr / pdf; return result; } }
27.350877
97
0.695318
e5cdc4d1f569a0ed885f165863170e5e1a0ebb24
764
cpp
C++
InsertionSortList.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
3
2017-11-27T03:01:50.000Z
2021-03-13T08:14:00.000Z
InsertionSortList.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
InsertionSortList.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* insertionSortList(ListNode* head) { ListNode *new_head = NULL; while (head) { ListNode *next = head->next; if (new_head == NULL || new_head->val > head->val) { head->next = new_head; new_head = head; } else { ListNode *p = new_head; while (p->next != NULL && p->next->val < head->val) p = p->next; head->next = p->next; p->next = head; } head = next; } return new_head; } };
27.285714
80
0.458115
e5ce2a278b7fa537fb6b659eb8eef03be5b92c98
10,538
cpp
C++
Powertools/SysInfo.cpp
saintsrowmods/SaintsRow2Tools
38db36fcabe892959e936b7c259c9ca1e3cf4003
[ "MIT" ]
null
null
null
Powertools/SysInfo.cpp
saintsrowmods/SaintsRow2Tools
38db36fcabe892959e936b7c259c9ca1e3cf4003
[ "MIT" ]
null
null
null
Powertools/SysInfo.cpp
saintsrowmods/SaintsRow2Tools
38db36fcabe892959e936b7c259c9ca1e3cf4003
[ "MIT" ]
null
null
null
#include <intrin.h> #include <tchar.h> #include <vector> #include <windows.h> #include "SysInfo.h" #include "Globals.h" #include <powrprof.h> #pragma comment(lib, "powrprof.lib") ULONG crc32_table[256]; int SR2_EXE_CRC = 0; VOID WINAPI LogSystemInfo() { WriteToLog(_T("SysInfo"), _T("Detecting Processor...\n")); if (!ProcessorDetect()) WriteToLog(_T("SysInfo"), _T("Failed to detect processor.\n")); WriteToLog(_T("SysInfo"), _T("Detecting Operating System...\n")); if (!LogOSDetect()) WriteToLog(_T("SysInfo"), _T("Failed to detect OS.\n")); } BOOL WINAPI ProcessorDetect() { char CPUString[0x20]; char CPUBrandString[0x40]; int CPUInfo[4] = {-1}; int nSteppingID = 0; int nModel = 0; int nFamily = 0; int nProcessorType = 0; int nExtendedmodel = 0; int nExtendedfamily = 0; int nBrandIndex = 0; unsigned int nIds = 0; __cpuid(CPUInfo, 0); nIds = CPUInfo[0]; memset(CPUString, 0, sizeof(CPUString)); *((int*)CPUString) = CPUInfo[1]; *((int*)(CPUString+4)) = CPUInfo[3]; *((int*)(CPUString+8)) = CPUInfo[2]; if (sizeof(TCHAR) == sizeof(char)) WriteToLog(_T("CPU Info"), _T("Current CPU manufacturer string: %s\n"), (TCHAR*)CPUString); else { TCHAR* CPUStringW = NULL; DWORD CPUStringLen = MultiByteToWideChar(CP_ACP, 0, CPUString, -1, NULL, 0); CPUStringW = (TCHAR*)malloc(CPUStringLen * sizeof(TCHAR)); MultiByteToWideChar(CP_ACP, 0, CPUString, -1, (LPWSTR)CPUStringW, CPUStringLen); WriteToLog(_T("CPU Info"), _T("Current CPU manufacturer string: %s\n"), (TCHAR*)CPUStringW); free(CPUStringW); } __cpuid(CPUInfo, 1); nSteppingID = CPUInfo[0] & 0xf; nModel = (CPUInfo[0] >> 4) & 0xf; nFamily = (CPUInfo[0] >> 8) & 0xf; nProcessorType = (CPUInfo[0] >> 12) & 0x3; nExtendedmodel = (CPUInfo[0] >> 16) & 0xf; nExtendedfamily = (CPUInfo[0] >> 20) & 0xff; nBrandIndex = CPUInfo[1] & 0xff; WriteToLog(_T("CPU Info"), _T("Family: %d, Model: %d, Stepping: %d, Type: %d, ExtendedModel: %d, ExtendedFamily: %d, BrandIndex: %d\n"), nFamily, nModel, nSteppingID, nProcessorType, nExtendedmodel, nExtendedfamily, nBrandIndex); __cpuid(CPUInfo, 0x80000000); memset(CPUBrandString, 0, sizeof(CPUBrandString)); if (CPUInfo[0] >= 0x80000004) { __cpuid(CPUInfo, 0x80000002); memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); __cpuid(CPUInfo, 0x80000003); memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo)); __cpuid(CPUInfo, 0x80000004); memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo)); if (sizeof(TCHAR) == sizeof(char)) WriteToLog(_T("CPU Info"), _T("Current CPU Brand string: %s\n"), (TCHAR*)CPUBrandString); else { TCHAR* CPUStringW = NULL; DWORD CPUStringLen = MultiByteToWideChar(CP_ACP, 0, CPUBrandString, -1, NULL, 0); CPUStringW = (TCHAR*)malloc(CPUStringLen * sizeof(TCHAR)); MultiByteToWideChar(CP_ACP, 0, CPUBrandString, -1, (LPWSTR)CPUStringW, CPUStringLen); WriteToLog(_T("CPU Info"), _T("Current CPU Brand string: %s\n"), (TCHAR*)CPUStringW); free(CPUStringW); } } else { WriteToLog(_T("CPU Info"), _T("Cannot get CPU Brand String.")); return false; } SYSTEM_INFO sys_info; PPIVector ppis; // find out how many processors we have in the system GetSystemInfo(&sys_info); ppis.resize(sys_info.dwNumberOfProcessors); // get CPU stats if (CallNtPowerInformation(ProcessorInformation, NULL, 0, &ppis[0], sizeof(PROCESSOR_POWER_INFORMATION) * ppis.size()) != ERROR_SUCCESS) { WriteToLog(_T("CPU Info"), _T("Unable to get CPU information.\n")); return false; } for (PPIVector::iterator it = ppis.begin(); it != ppis.end(); ++it) { WriteToLog(_T("CPU Info"), _T("stats for CPU %d: max: %d MHz, current: %d MHz\n"), it->Number, it->MaxMhz, it->CurrentMhz); } return true; } BOOL WINAPI LogOSDetect() { OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; BOOL bOSVersionInfoEx; ZeroMemory(&si, sizeof(SYSTEM_INFO)); ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); bOSVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi); if(!bOSVersionInfoEx) { return false; } pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if(NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si); WriteToLog(_T("OS Info"), _T("OS information: PlatformId: %d, Version: %d.%d, Build: %d, Service Pack: %d.%d (%s), Suite Mask: 0x%08X, Processor Architecture: %s\n"), osvi.dwPlatformId, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.wServicePackMajor, osvi.wServicePackMinor, osvi.szCSDVersion, osvi.wSuiteMask, (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 ? _T("Itanium") : (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ? _T("x86_64") : _T("x86")))); if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (osvi.dwMajorVersion == 5) { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) WriteToLog(_T("OS Info"), _T("OS is Windows 2000 Professional.\n")); else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) WriteToLog(_T("OS Info"), _T("OS is Windows 2000 Datacenter Server.\n")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) WriteToLog(_T("OS Info"), _T("OS is Windows 2000 Enterprise Server.\n")); else WriteToLog(_T("OS Info"), _T("OS is Windows 2000 Server.\n")); } else if (osvi.dwMinorVersion == 1) { if (osvi.wSuiteMask & VER_SUITE_PERSONAL) WriteToLog(_T("OS Info"), _T("OS is Windows XP Home.\n")); else WriteToLog(_T("OS Info"), _T("OS is Windows XP Professional.\n")); } else if (osvi.dwMinorVersion == 2) { if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) WriteToLog(_T("OS Info"), _T("OS is Windows XP Professional x64 Edition.\n")); else if (GetSystemMetrics(SM_SERVERR2)) WriteToLog(_T("OS Info"), _T("OS is Windows Server 2003 R2.\n")); else if (osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER) WriteToLog(_T("OS Info"), _T("OS is Windows Storage Server 2003.\n")); else if (osvi.wSuiteMask & VER_SUITE_WH_SERVER) WriteToLog(_T("OS Info"), _T("OS is Windows Home Server.\n")); else WriteToLog(_T("OS Info"), _T("OS is Windows Server 2003.\n")); } else { WriteToLog(_T("OS Info"), _T("Unknown minor version.\n")); return false; } } else if (osvi.dwMajorVersion == 6) { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) WriteToLog(_T("OS Info"), _T("OS is Windows Vista.\n")); else WriteToLog(_T("OS Info"), _T("OS is Windows Server 2008.\n")); } else if (osvi.dwMinorVersion == 1) { if (osvi.wProductType == VER_NT_WORKSTATION) WriteToLog(_T("OS Info"), _T("OS is Windows 7.\n")); else WriteToLog(_T("OS Info"), _T("OS is Windows Server 2008 R2.\n")); } else { WriteToLog(_T("OS Info"), _T("Unknown minor version.\n")); return false; } } else if (osvi.dwMajorVersion < 5) { WriteToLog(_T("OS Info"), _T("Unknown (old?) Windows version.\n")); return false; } else if (osvi.dwMajorVersion > 6) { WriteToLog(_T("OS Info"), _T("Unknown (future?) Windows version.\n")); return false; } } else { WriteToLog(_T("OS Info"), _T("OS platform is unknown.\n"), osvi.dwPlatformId); return false; } return true; } BOOL WINAPI CheckSaintsRow2Integrity() { HANDLE sr2Exe; DWORD exeLength; LPVOID* buffer; DWORD totalBytesRead = 0; DWORD bytesRead = 0; DWORD crc; Init_CRC32_Table(); sr2Exe = CreateFileW(TEXT("SR2_pc.exe"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); exeLength = GetFileSize(sr2Exe, NULL); buffer = (LPVOID*)malloc(exeLength); while (totalBytesRead < exeLength) { if (!ReadFile(sr2Exe, buffer + totalBytesRead, exeLength - totalBytesRead, &bytesRead, NULL)) { CloseHandle(sr2Exe); return false; } totalBytesRead += bytesRead; } CloseHandle(sr2Exe); crc = Get_CRC((char*)buffer, exeLength); free(buffer); if (crc == CRC_STEAM_VER_1_2) { WriteToLog(_T("Powertools"), _T("Found Steam SR2_pc.exe version 1.2, CRC32: 0x%08X\n"), crc); SR2_EXE_CRC = crc; return true; } else { WriteToLog(_T("Powertools"), _T("Unrecognised SR2_pc.exe found. CRC32: 0x%08X\n"), crc); return false; } return false; } void Init_CRC32_Table() {// Call this function only once to initialize the CRC table. // This is the official polynomial used by CRC-32 // in PKZip, WinZip and Ethernet. ULONG ulPolynomial = 0x04c11db7; // 256 values representing ASCII character codes. for(int i = 0; i <= 0xFF; i++) { crc32_table[i]=Reflect(i, 8) << 24; for (int j = 0; j < 8; j++) crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0); crc32_table[i] = Reflect(crc32_table[i], 32); } } ULONG Reflect(ULONG ref, char ch) {// Used only by Init_CRC32_Table(). ULONG value(0); // Swap bit 0 for bit 7 // bit 1 for bit 6, etc. for(int i = 1; i < (ch + 1); i++) { if(ref & 1) value |= 1 << (ch - i); ref >>= 1; } return value; } int Get_CRC(char* text, int len) {// Pass a text string to this function and it will return the CRC. // Once the lookup table has been filled in by the two functions above, // this function creates all CRCs using only the lookup table. // Be sure to use unsigned variables, // because negative values introduce high bits // where zero bits are required. // Start out with all bits set high. ULONG ulCRC(0xffffffff); unsigned char* buffer; // Save the text in the buffer. buffer = (unsigned char*)text; // Perform the algorithm on each character // in the string, using the lookup table values. while(len--) ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer++]; // Exclusive OR the result with the beginning value. return ulCRC ^ 0xffffffff; }
31.740964
168
0.633991
e5d5698fd37e77a6821d26a04bb9c8aa4ce06e25
48
hpp
C++
include/EnglishLogicConfig.hpp
mikhov-ivan/english-logic
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
[ "MIT" ]
null
null
null
include/EnglishLogicConfig.hpp
mikhov-ivan/english-logic
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
[ "MIT" ]
null
null
null
include/EnglishLogicConfig.hpp
mikhov-ivan/english-logic
1554cb42d816bc8446ec3be3ba35509fb3dfe0d0
[ "MIT" ]
null
null
null
#define VERSION_MAJOR 1 #define VERSION_MINOR 0
16
23
0.833333
e5d5f4730db4ae23fed4f1331cfe1f7b949c1554
4,806
hh
C++
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
kunal71091/Depth_Normal_Fusion
407e204abfbd6c8efe2f98a07415bd623ad84422
[ "MIT" ]
1
2019-10-23T06:32:40.000Z
2019-10-23T06:32:40.000Z
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
kunal71091/Depth_Normal_Fusion
407e204abfbd6c8efe2f98a07415bd623ad84422
[ "MIT" ]
null
null
null
3DVision_SourceCode_Group12/IsoExMod/IsoEx/Extractors/ExtendedMarchingCubesT.hh
kunal71091/Depth_Normal_Fusion
407e204abfbd6c8efe2f98a07415bd623ad84422
[ "MIT" ]
1
2021-09-23T03:35:30.000Z
2021-09-23T03:35:30.000Z
/*===========================================================================*\ * * * IsoEx * * Copyright (C) 2002 by Computer Graphics Group, RWTH Aachen * * www.rwth-graphics.de * * * *---------------------------------------------------------------------------* * * * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*===========================================================================*/ //============================================================================= // // CLASS ExtendedMarchingCubesT // //============================================================================= #ifndef ISOEX_EXTMARCHINGCUBEST_HH #define ISOEX_EXTMARCHINGCUBEST_HH //== INCLUDES ================================================================= #include <IsoEx/Extractors/Edge2VertexMapT.hh> #include <IsoEx/Grids/Grid.hh> #include <vector> //== NAMESPACES =============================================================== namespace IsoEx { //== CLASS DEFINITION ========================================================= /** \class ExtendedMarchingCubesT ExtendedMarchingCubesT.hh <IsoEx/Extractors/ExtendedMarchingCubesT.hh> This class implements the Extended Marching Cubes of Kobbelt et al, Siggraph 2001. The 0-level iso-surface is extracted in the constructor. Use it through the convenience function <b>IsoEx::extended_marching_cubes()</b>. \ingroup extractors */ template <class Mesh, class Grid> class ExtendedMarchingCubesT { public: ExtendedMarchingCubesT(const Grid& _grid, Mesh& _mesh, double _feature_angle); private: typedef typename Grid::PointIdx PointIdx; typedef typename Grid::CubeIdx CubeIdx; typedef typename Grid::CubeIterator CubeIterator; typedef typename Mesh::VertexHandle VertexHandle; typedef std::vector<VertexHandle> VertexHandleVector; void process_cube(CubeIdx _idx); VertexHandle add_vertex(PointIdx _p0, PointIdx _p1); VertexHandle find_feature(const VertexHandleVector& _vhandles); void flip_edges(); const Grid& grid_; Mesh& mesh_; float feature_angle_; unsigned int n_edges_, n_corners_; // maps an edge to the sample vertex generated on it Edge2VertexMapT<PointIdx, VertexHandle> edge2vertex_; }; //----------------------------------------------------------------------------- /** Convenience wrapper for the Extended Marching Cubes algorithm. \see IsoEx::ExtendedMarchingCubesT \ingroup extractors */ template <class Mesh, class Grid> void extended_marching_cubes(const Grid& _grid, Mesh& _mesh, double _feature_angle) { ExtendedMarchingCubesT<Mesh,Grid> emc(_grid, _mesh, _feature_angle); } //============================================================================= } // namespace IsoEx //============================================================================= #if defined(INCLUDE_TEMPLATES) && !defined(ISOEX_EXTMARCHINGCUBEST_C) #define ISOEX_EXTMARCHINGCUBEST_TEMPLATES #include "ExtendedMarchingCubesT.cc" #endif //============================================================================= #endif // ISOEX_EXTMARCHINGCUBEST_HH defined //=============================================================================
38.142857
104
0.445901
e5d8081d82ed686cf3cc2ee5be3492a853de7911
3,909
hpp
C++
include/mbgl/style/filter.hpp
TanJay/mapbox-gl-native
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
include/mbgl/style/filter.hpp
TanJay/mapbox-gl-native
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
include/mbgl/style/filter.hpp
TanJay/mapbox-gl-native
6348fe9f4acccce65d1396aa9eab79e6c44bcfc2
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#pragma once #include <mbgl/util/variant.hpp> #include <mbgl/util/feature.hpp> #include <mbgl/util/geometry.hpp> #include <string> #include <vector> #include <tuple> namespace mbgl { namespace style { class Filter; class NullFilter { public: friend bool operator==(const NullFilter&, const NullFilter&) { return true; } }; class EqualsFilter { public: std::string key; Value value; friend bool operator==(const EqualsFilter& lhs, const EqualsFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class NotEqualsFilter { public: std::string key; Value value; friend bool operator==(const NotEqualsFilter& lhs, const NotEqualsFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class LessThanFilter { public: std::string key; Value value; friend bool operator==(const LessThanFilter& lhs, const LessThanFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class LessThanEqualsFilter { public: std::string key; Value value; friend bool operator==(const LessThanEqualsFilter& lhs, const LessThanEqualsFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class GreaterThanFilter { public: std::string key; Value value; friend bool operator==(const GreaterThanFilter& lhs, const GreaterThanFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class GreaterThanEqualsFilter { public: std::string key; Value value; friend bool operator==(const GreaterThanEqualsFilter& lhs, const GreaterThanEqualsFilter& rhs) { return std::tie(lhs.key, lhs.value) == std::tie(rhs.key, rhs.value); } }; class InFilter { public: std::string key; std::vector<Value> values; friend bool operator==(const InFilter& lhs, const InFilter& rhs) { return std::tie(lhs.key, lhs.values) == std::tie(rhs.key, rhs.values); } }; class NotInFilter { public: std::string key; std::vector<Value> values; friend bool operator==(const NotInFilter& lhs, const NotInFilter& rhs) { return std::tie(lhs.key, lhs.values) == std::tie(rhs.key, rhs.values); } }; class AnyFilter { public: std::vector<Filter> filters; friend bool operator==(const AnyFilter& lhs, const AnyFilter& rhs) { return lhs.filters == rhs.filters; } }; class AllFilter { public: std::vector<Filter> filters; friend bool operator==(const AllFilter& lhs, const AllFilter& rhs) { return lhs.filters == rhs.filters; } }; class NoneFilter { public: std::vector<Filter> filters; friend bool operator==(const NoneFilter& lhs, const NoneFilter& rhs) { return lhs.filters == rhs.filters; } }; class HasFilter { public: std::string key; friend bool operator==(const HasFilter& lhs, const HasFilter& rhs) { return lhs.key == rhs.key; } }; class NotHasFilter { public: std::string key; friend bool operator==(const NotHasFilter& lhs, const NotHasFilter& rhs) { return lhs.key == rhs.key; } }; using FilterBase = variant< class NullFilter, class EqualsFilter, class NotEqualsFilter, class LessThanFilter, class LessThanEqualsFilter, class GreaterThanFilter, class GreaterThanEqualsFilter, class InFilter, class NotInFilter, class AnyFilter, class AllFilter, class NoneFilter, class HasFilter, class NotHasFilter>; class Filter : public FilterBase { public: using FilterBase::FilterBase; bool operator()(const Feature&) const; template <class PropertyAccessor> bool operator()(FeatureType type, optional<FeatureIdentifier> id, PropertyAccessor accessor) const; }; } // namespace style } // namespace mbgl
22.210227
103
0.665643
e5d9066ad1106be9e446fbc5f940183ea2859206
3,455
cpp
C++
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackServer/AddressSpaceModel/BaseNodeClass.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2015-2017 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include "OpcUaStackServer/AddressSpaceModel/BaseNodeClass.h" namespace OpcUaStackServer { BaseNodeClass::BaseNodeClass(void) : nodeId_() , nodeClass_() , browseName_() , displayName_() , description_() , writeMask_() , userWriteMask_() , forwardNodeSync_() { } BaseNodeClass::BaseNodeClass(NodeClassType nodeClass) : nodeId_() , nodeClass_(nodeClass) , browseName_() , displayName_() , description_() , writeMask_() , userWriteMask_() , forwardNodeSync_() { } BaseNodeClass::~BaseNodeClass(void) { } NodeIdAttribute& BaseNodeClass::nodeId(void) { return nodeId_; } NodeClassAttribute& BaseNodeClass::nodeClass(void) { return nodeClass_; } BrowseNameAttribute& BaseNodeClass::browseName(void) { return browseName_; } DisplayNameAttribute& BaseNodeClass::displayName(void) { return displayName_; } DescriptionAttribute& BaseNodeClass::description(void) { return description_; } WriteMaskAttribute& BaseNodeClass::writeMask(void) { return writeMask_; } UserWriteMaskAttribute& BaseNodeClass::userWriteMask(void) { return userWriteMask_; } Attribute* BaseNodeClass::nodeIdAttribute(void) { return &nodeId_; } Attribute* BaseNodeClass::nodeClassAttribute(void) { return &nodeClass_; } Attribute* BaseNodeClass::browseNameAttribute(void) { return &browseName_; } Attribute* BaseNodeClass::displayNameAttribute(void) { return &displayName_; } Attribute* BaseNodeClass::descriptionAttribute(void) { return &description_; } Attribute* BaseNodeClass::writeMaskAttribute(void) { return &writeMask_; } Attribute* BaseNodeClass::userWriteMaskAttribute(void) { return &userWriteMask_; } ReferenceItemMap& BaseNodeClass::referenceItemMap(void) { return referenceItemMap_; } void BaseNodeClass::copyTo(BaseNodeClass::SPtr baseNodeClass) { copyTo(*baseNodeClass); } void BaseNodeClass::copyTo(BaseNodeClass& baseNodeClass) { nodeIdAttribute()->copyTo(baseNodeClass.nodeIdAttribute()); nodeClassAttribute()->copyTo(baseNodeClass.nodeClassAttribute()); browseNameAttribute()->copyTo(baseNodeClass.browseNameAttribute()); displayNameAttribute()->copyTo(baseNodeClass.displayNameAttribute()); descriptionAttribute()->copyTo(baseNodeClass.descriptionAttribute()); writeMaskAttribute()->copyTo(baseNodeClass.writeMaskAttribute()); userWriteMaskAttribute()->copyTo(baseNodeClass.userWriteMaskAttribute()); referenceItemMap_.copyTo(baseNodeClass.referenceItemMap()); } void BaseNodeClass::forwardNodeSync(ForwardNodeSync::SPtr forwardNodeSync) { forwardNodeSync_ = forwardNodeSync; } ForwardNodeSync::SPtr BaseNodeClass::forwardNodeSync(void) { return forwardNodeSync_; } }
19.971098
86
0.754269
e5db1ceefa47fb1c63edd6f59d89695fab5ebf8a
1,860
hpp
C++
code/include/boids2D/Boid.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
4
2016-06-24T09:22:18.000Z
2019-06-13T13:50:53.000Z
code/include/boids2D/Boid.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
null
null
null
code/include/boids2D/Boid.hpp
Shutter-Island-Team/Shutter-island
c5e7c0b2c60c34055e64104dcbc396b9e1635f33
[ "MIT" ]
2
2016-06-10T12:46:17.000Z
2018-10-14T06:37:21.000Z
#ifndef BOID_HPP #define BOID_HPP #include <glm/glm.hpp> #include <memory> #include <vector> #include "BoidType.hpp" /** * @class Boid * @brief Parent class for a Boid (can be rooted or movable) */ class Boid { public: /** * @brief Constructor for a Boid * @param[in] location The initial position * @param[in] t Type of the boid */ Boid(glm::vec3 location, BoidType t); /** * @brief Getter for the location */ const glm::vec3 & getLocation() const; /** * @brief Setter for the location * @param[in] location The new location */ void setLocation(const glm::vec3 & location); /** * @brief Getter of the angle */ const float & getAngle() const; /** * @brief Setter of the angle * @param[in] angle The new angle */ void setAngle(const float & angle); /** * @brief Getter of the type of the boid * @return Type of the boid */ const BoidType & getBoidType() const; /** * @brief Getter of the size of the boid */ const float & getScale() const; /** * @brief Setter of the size of the boid */ void setScale(const float & scale); void disapear(); const bool & toDisplay() const; bool isFoodRemaining() const; void decreaseFoodRemaining(); bool isDecomposed() const; void bodyDecomposition(); protected: /** * @brief Constructor for a Boid * @param[in] location The initial position * @param[in] t Type of the boid */ Boid(glm::vec3 location, BoidType t, int amountFood); glm::vec3 m_location; ///< Position of the boid private: BoidType m_boidType; ///< Type of the boid @see BoidType.hpp float m_angle; ///< Angle of position of the boid float m_scale; ///< Size of the boid bool m_display; int m_amountFood; float m_decomposition; }; typedef std::shared_ptr<Boid> BoidPtr; #endif
19.375
62
0.639247
e5db32d10e0d6bb07f5501200886eda9f3445bcb
1,433
cxx
C++
direct/src/plugin/run_p3dpython.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
direct/src/plugin/run_p3dpython.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
direct/src/plugin/run_p3dpython.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: run_p3dpython.cxx // Created by: drose (29Aug09) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "p3dPythonRun.h" #include "run_p3dpython.h" //////////////////////////////////////////////////////////////////// // Function: run_p3dpython // Description: This externally-visible function is the main entry // point to this DLL, and it starts the whole thing // running. Returns true on success, false on failure. //////////////////////////////////////////////////////////////////// bool run_p3dpython(const char *program_name, const char *archive_file, FHandle input_handle, FHandle output_handle, const char *log_pathname, bool interactive_console) { P3DPythonRun::_global_ptr = new P3DPythonRun(program_name, archive_file, input_handle, output_handle, log_pathname, interactive_console); bool result = P3DPythonRun::_global_ptr->run_python(); delete P3DPythonRun::_global_ptr; P3DPythonRun::_global_ptr = NULL; return result; }
39.805556
78
0.571528
e5dbc06954d6a35ea13235b91c158246ea1a534a
287
cpp
C++
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
OztGod/DarkestTowerServer
65043e1e7b158727f7f6ad7c008f1f2847174542
[ "MIT" ]
null
null
null
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
OztGod/DarkestTowerServer
65043e1e7b158727f7f6ad7c008f1f2847174542
[ "MIT" ]
2
2015-09-23T17:17:52.000Z
2015-09-23T18:16:46.000Z
DarkestTowerServer/DarkestTowerServer/Fighter.cpp
OztGod/DarkestTowerServer
65043e1e7b158727f7f6ad7c008f1f2847174542
[ "MIT" ]
null
null
null
#include "Fighter.h" #include "FighterAttack.h" #include "Charge.h" Fighter::Fighter(int idx) :Hero(HeroClass::FIGHTER, 17 + rand() % 4, 5 + rand() % 2, idx) { skills.push_back(SkillInfo(std::make_unique<FighterAttack>())); skills.push_back(SkillInfo(std::make_unique<Charge>())); }
26.090909
64
0.700348
e5de1c12a0f2f37847a3bf7b8f1b83a25aa37ca3
202
hpp
C++
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
4
2018-04-28T16:09:21.000Z
2021-08-24T12:51:55.000Z
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
29
2018-04-01T23:31:33.000Z
2020-01-02T17:02:11.000Z
addons/CBRN_sounds/sounds/assaultboy/cfgVehicles.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
10
2018-07-13T15:02:06.000Z
2021-04-06T17:12:11.000Z
class Sound_CBRN_cough_assaultboy:Sound_CBRN_coughBase {sound = "CBRN_cough_assaultboy";}; class Sound_CBRN_coughMuffled_assaultboy:Sound_CBRN_coughMuffledBase {sound = "CBRN_coughMuffled_assaultboy";};
101
111
0.876238
e5de8c7bde5e7838158f776a68a38781533229f6
8,252
cpp
C++
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
VishnuPrem/multi_robot_restaurant
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
[ "MIT" ]
7
2020-06-23T23:34:33.000Z
2020-12-11T20:08:11.000Z
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
VishnuPrem/multi_robot_restaurant
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
[ "MIT" ]
null
null
null
catkin_ws/src/control_stack/src/sim/simulator_node.cpp
VishnuPrem/multi_robot_restaurant
6aea83a3c7acd9b7d25e1a2c6e05ef3a5c28a876
[ "MIT" ]
4
2020-09-02T20:17:22.000Z
2020-10-19T01:51:29.000Z
// Copyright 2019 kvedder@seas.upenn.edu // School of Engineering and Applied Sciences, // University of Pennsylvania // // // 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 <geometry_msgs/Twist.h> #include <nav_msgs/Odometry.h> #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <visualization_msgs/MarkerArray.h> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Geometry> #include <algorithm> #include <cmath> #include <random> #include <string> #include <vector> #include "cs/util/constants.h" #include "cs/util/map.h" #include "cs/util/pose.h" #include "cs/util/util.h" #include "cs/util/visualization.h" #include "shared/math/geometry.h" #include "shared/math/math_util.h" #include "config_reader/config_reader.h" namespace sim { CONFIG_FLOAT(kLaserStdDev, "sim.kLaserStdDev"); CONFIG_FLOAT(kArcExecStdDev, "sim.kArcExecStdDev"); CONFIG_FLOAT(kArcReadStdDev, "sim.kArcReadStdDev"); CONFIG_FLOAT(kRotateExecStdDev, "sim.kRotateExecStdDev"); CONFIG_FLOAT(kRotateReadStdDev, "sim.kRotateReadStdDev"); CONFIG_FLOAT(kStartPositionX, "sim.kStartPositionX"); CONFIG_FLOAT(kStartPositionY, "sim.kStartPositionY"); CONFIG_FLOAT(kStartPositionTheta, "sim.kStartPositionTheta"); CONFIG_STRING(kMap, "sim.kMap"); CONFIG_FLOAT(laser_min_angle, "sim.laser.min_angle"); CONFIG_FLOAT(laser_max_angle, "sim.laser.max_angle"); CONFIG_INT(laser_num_readings, "sim.laser.num_readings"); CONFIG_FLOAT(laser_angle_delta, "sim.laser.angle_delta"); CONFIG_FLOAT(laser_min_reading, "sim.laser.min_reading"); CONFIG_FLOAT(laser_max_reading, "sim.laser.max_reading"); } // namespace sim // std::random_device rd; std::mt19937 gen(0); std_msgs::Header MakeHeader(const std::string& frame_id) { static uint32_t seq = 0; std_msgs::Header header; header.seq = (++seq); header.frame_id = frame_id; header.stamp = ros::Time::now(); return header; } sensor_msgs::LaserScan MakeScan(const util::Pose& robot_pose, const util::Map& map, const float noise_stddev) { std::normal_distribution<> noise_dist(0.0f, noise_stddev); sensor_msgs::LaserScan scan; scan.header = MakeHeader("laser"); scan.angle_min = sim::CONFIG_laser_min_angle; scan.angle_max = sim::CONFIG_laser_max_angle; scan.angle_increment = sim::CONFIG_laser_angle_delta; scan.range_min = sim::CONFIG_laser_min_reading; scan.range_max = sim::CONFIG_laser_max_reading; scan.scan_time = 0; scan.time_increment = 0; for (int ray_idx = 0; ray_idx < sim::CONFIG_laser_num_readings; ++ray_idx) { const float angle = math_util::AngleMod(sim::CONFIG_laser_min_angle + sim::CONFIG_laser_angle_delta * static_cast<float>(ray_idx) + robot_pose.rot); const util::Pose ray(robot_pose.tra, angle); const float dist = map.MinDistanceAlongRay(ray, sim::CONFIG_laser_min_reading, sim::CONFIG_laser_max_reading - kEpsilon); scan.ranges.push_back(dist + noise_dist(gen)); } return scan; } util::Twist AddExecutionOdomNoise(util::Twist move) { std::normal_distribution<> along_arc_dist( 0.0f, sim::CONFIG_kArcExecStdDev * move.tra.norm()); std::normal_distribution<> rotation_dist( 0.0f, sim::CONFIG_kRotateExecStdDev * move.rot + 0.005); move.tra.x() += along_arc_dist(gen); move.rot += rotation_dist(gen); return move; } util::Twist AddReadingOdomNoise(util::Twist move) { std::normal_distribution<> along_arc_dist( 0.0f, sim::CONFIG_kArcReadStdDev * move.tra.norm()); std::normal_distribution<> rotation_dist( 0.0f, sim::CONFIG_kRotateReadStdDev * move.rot); move.tra.x() += along_arc_dist(gen); move.rot += rotation_dist(gen); return move; } template <typename T> util::Pose FollowTrajectory(const util::Pose& pose_global_frame, const T& distance_along_arc, const T& rotation) { const Eigen::Rotation2Df robot_to_global_frame(pose_global_frame.rot); const Eigen::Matrix<T, 2, 1> robot_forward_global_frame = robot_to_global_frame * Eigen::Matrix<T, 2, 1>(1, 0); if (rotation == 0) { util::Pose updated_pose = pose_global_frame; updated_pose.tra += robot_forward_global_frame * distance_along_arc; return updated_pose; } const T circle_radius = distance_along_arc / rotation; const T move_x_dst = std::sin(rotation) * circle_radius; const T move_y_dst = std::cos(fabs(rotation)) * circle_radius - circle_radius; const Eigen::Matrix<T, 2, 1> movement_arc_robot_frame(move_x_dst, move_y_dst); const Eigen::Matrix<T, 2, 1> movement_arc_global_frame = robot_to_global_frame * movement_arc_robot_frame; return {movement_arc_global_frame + pose_global_frame.tra, math_util::AngleMod(rotation + pose_global_frame.rot)}; } util::Twist commanded_velocity; void CommandedVelocityCallback(const geometry_msgs::Twist& nv) { commanded_velocity = util::Twist(nv); } int main(int argc, char** argv) { util::PrintCurrentWorkingDirectory(); config_reader::ConfigReader reader( {"src/ServiceRobotControlStack/control_stack/config/nav_config.lua", "src/ServiceRobotControlStack/control_stack/config/sim_config.lua"}); ros::init(argc, argv, "simulator"); ros::NodeHandle n; ros::Publisher initial_pose_pub = n.advertise<geometry_msgs::Twist>("true_pose", 1); ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>(constants::kLaserTopic, 10); ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>(constants::kOdomTopic, 10); ros::Publisher map_pub = n.advertise<visualization_msgs::Marker>("map", 10); ros::Publisher initial_pose_vis_pub = n.advertise<visualization_msgs::MarkerArray>("true_pose_vis", 1); ros::Subscriber command_sub = n.subscribe( constants::kCommandVelocityTopic, 10, &CommandedVelocityCallback); static constexpr float kLoopRate = 10; ros::Rate loop_rate(kLoopRate); const util::Map map(sim::CONFIG_kMap); util::Pose current_pose(sim::CONFIG_kStartPositionX, sim::CONFIG_kStartPositionY, sim::CONFIG_kStartPositionTheta); while (ros::ok()) { const util::Twist executed_move = AddExecutionOdomNoise(commanded_velocity / kLoopRate); const util::Twist reported_move = AddReadingOdomNoise(executed_move); current_pose = FollowTrajectory( current_pose, executed_move.tra.x(), executed_move.rot); scan_pub.publish(MakeScan(current_pose, map, sim::CONFIG_kLaserStdDev)); nav_msgs::Odometry odom_msg; odom_msg.header = MakeHeader("base_link"); odom_msg.twist.twist = (reported_move * kLoopRate).ToTwist(); odom_pub.publish(odom_msg); initial_pose_pub.publish(current_pose.ToTwist()); visualization_msgs::MarkerArray arr; visualization::DrawPose( current_pose, "map", "true_pose_vis", 1, 1, 1, 1, &arr); initial_pose_vis_pub.publish(arr); ros::spinOnce(); loop_rate.sleep(); } return 0; }
37.853211
80
0.708434
e5e2f8c12b0619c93f7c1c593f6b0041157ba9ff
28,540
cpp
C++
src/TinyTinyJPG.cpp
avrock123/ttjpg
eb1be2f389653f9056b035211cb8c0c3e09a42d1
[ "BSD-3-Clause" ]
null
null
null
src/TinyTinyJPG.cpp
avrock123/ttjpg
eb1be2f389653f9056b035211cb8c0c3e09a42d1
[ "BSD-3-Clause" ]
null
null
null
src/TinyTinyJPG.cpp
avrock123/ttjpg
eb1be2f389653f9056b035211cb8c0c3e09a42d1
[ "BSD-3-Clause" ]
null
null
null
/* TinyTinyJPG library Copyright (c) 2011, Rasmus Neckelmann (neckelmann@gmail.com) All rights reserved. This source code is released under the terms of the BSD license; see the file LICENSE.TXT for details. */ #include <math.h> #if defined(EMMINTRIN) #include <emmintrin.h> #endif #include "TinyTinyJPG.h" /* Clamp x to 0-255 */ #define BYTECLAMP(x) ((static_cast<unsigned int>(x) > 255)?(((~x) >> 31) & 0xff):x) namespace ttjpg { /*=========================================================================== Global stuff ===========================================================================*/ /* MCU layout description */ struct MCULayoutDesc { int nXSampleFactor[3],nYSampleFactor[3]; /* This is used to lookup a layout */ int nDataUnitsPerMCU; /* Number of DCT blocks in a MCU */ int nDUComponents[6]; /* Component-index of each data unit */ int nMCUXSize,nMCUYSize; /* Size of MCU in pixels */ }; /* These MCU layouts hold information needed to map block to the final image. Actual positioning in hardcoded for each layout in the _UpdateMCU() function */ MCULayoutDesc g_MCULayouts[JPG_NUM_MCU_LAYOUTS] = { 1,1,1,1,1,1,3,0,1,2,0,0,0,8,8, /* JPG_MCU_LAYOUT_YCBCR_444 */ 2,1,1,1,1,1,4,0,0,1,2,0,0,16,8, /* JPG_MCU_LAYOUT_YCBCR_422 */ 2,1,1,2,1,1,6,0,0,0,0,1,2,16,16 /* JPG_MCU_LAYOUT_YCBCR_420 */ }; /* Function for looking up MCU layouts in the above table */ int _LookupMCULayout(ComponentInfo *p) { for(int i=0;i<JPG_NUM_MCU_LAYOUTS;i++) { bool bMatch = true; for(int j=0;j<3;j++) { if(g_MCULayouts[i].nXSampleFactor[j] != p[j].nXSampleFactor || g_MCULayouts[i].nYSampleFactor[j] != p[j].nYSampleFactor) { bMatch = false; break; } } /* This' the one? */ if(bMatch) return i; } throw DecodeError(ERR_UNSUPPORTED_MCU_LAYOUT); } /*=========================================================================== Shared input stream functionality ===========================================================================*/ int InputStream::readWord(void) { /* Big endian 16-bit word */ return (readByte() << 8) | readByte(); } int InputStream::readMarker(void) { /* Read until we get a marker */ while(!isEndOfStream()) { if(readByte() == 0xff) { int nMarker = 0; do { nMarker = readByte(); if(isEndOfStream()) return 0; } while(nMarker == 0xff); /* If it's an APP0 marker (EXIF, etc) skip it */ if(nMarker == 0xE1) { int nSkipLen = readWord() - 2; skip(nSkipLen); return readMarker(); } return nMarker; } } return 0; } uint32 InputStream::readBits(int nNum) { /* Read the next nNum bits, if we hit a 0xFFxx marker take a note of it (embedded marker) */ if(nNum == 0) return 0; if(m_nBits < nNum) { /* We don't have enough bits buffered, need to read some more */ int c1 = readByte(); if(c1 == 0xff) readByte(); int c2 = readByte(); if(c2 == 0xff) { m_nEmbeddedMarker = readByte(); } m_nBitBuf |= c2 << (16 - m_nBits); m_nBitBuf |= c1 << (24 - m_nBits); m_nBits += 16; } /* Grab the bits we need from the buffer */ uint32 n = m_nBitBuf >> (32 - nNum); m_nBitBuf <<= nNum; m_nBits -= nNum; return n; } void InputStream::flushBitStream(void) { /* Discard any remaining buffered bits */ m_nBits = 0; m_nBitBuf = 0; m_nEmbeddedMarker = 0; } /*=========================================================================== Huffman decoding tree implementation ===========================================================================*/ void HuffmanTable::buildTree(void) { /* Build huffman decoding tree -- create initial tree */ Tree.grow(3); Tree[0].pChildren[0] = &Tree[1]; Tree[0].pChildren[1] = &Tree[2]; nNextFreeNode = 1; nNumFreeNodes = 2; /* For each level of the tree... */ for(int i=0;i<nMaxBits;i++) { /* Add all symbols at this level... */ int *pnSymbols = &nTable[i * 256]; for(int j=0;j<nL[i];j++) { if(nNumFreeNodes > 0) { /* Insert symbol here */ Tree[nNextFreeNode].nSymbol = pnSymbols[j]; nNextFreeNode++; nNumFreeNodes--; } else { /* Invalid tree... can't possible build it like this */ bDefined = false; throw DecodeError(ERR_INVALID_HUFFMAN_TREE); } } /* Every remaining node at this level will be a splitter */ int nNextLevelNode = nNextFreeNode + nNumFreeNodes; int nNewNodes = 0; if(nNumFreeNodes > 0) { /* Every new splitter will have 2 children... */ nNewNodes = nNumFreeNodes * 2; Tree.grow(nNewNodes); } while(nNumFreeNodes > 0) { Tree[nNextFreeNode].pChildren[0] = &Tree[nNextLevelNode++]; Tree[nNextFreeNode].pChildren[1] = &Tree[nNextLevelNode++]; nNextFreeNode++; nNumFreeNodes--; } nNextFreeNode = Tree.size() - nNewNodes; nNumFreeNodes = nNewNodes; } } int HuffmanTable::decode(InputStream *pIn,int *pnLeadingZeros) { /* Decode the next value. If pnLeadingZeros is NULL, we'll decode a DC value, AC otherwise */ int nCurrentNode = 0; HuffmanNode *pCurrentNode = &Tree[0]; if(pnLeadingZeros != NULL) *pnLeadingZeros = 0; while(pCurrentNode != NULL) { if(pCurrentNode->nSymbol >= 0) { /* Leaf node */ int nL = pCurrentNode->nSymbol; if(nL == 0) return JPG_HUFFMAN_EOB; /* EOB */ if(nL == 0xf0) return JPG_HUFFMAN_ZRL; /* 16 zeros */ int nAmp = nL; if(pnLeadingZeros != NULL) { *pnLeadingZeros = (nAmp & 0xf0) >> 4; nAmp &= 0x0f; } uint32 n = pIn->readBits(nAmp); if(nAmp == 1) return n ? 1 : -1; int nS = 1 << (nAmp - 1); if(n & nS) return nS + (n & (nS-1)); return -(1 << nAmp) + (n & (nS-1)) + 1; } else { /* Read bit to determine which way to go in tree */ pCurrentNode = pCurrentNode->pChildren[pIn->readBits(1)]; } } throw DecodeError(ERR_INVALID_HUFFMAN_CODE); } /*=========================================================================== JPEG decoder class implementation ===========================================================================*/ Decoder::Decoder() { /* Initialize ZZ-ordering */ _InitZZOrdering(); /* Make YCBCR->RGB tables */ _InitRGBTables(); } Decoder::~Decoder() { } void Decoder::readImageInfo(InputStream *pIn,RGBImage *pRGB) { Info Info; /* Parse stream just for image info */ _Parse(pIn,pRGB,&Info,true); } void Decoder::readImage(InputStream *pIn,RGBImage *pRGB) { Info Info; /* Parse JPG file incl. full image */ _Parse(pIn,pRGB,&Info,false); } void Decoder::decodeScan(InputStream *pIn,RGBImage *pRGB,Info *pi,Scan *ps) { /* Calculate number of restart intervals */ int nRestartIntervalsLeft = pi->nTotalMCUs / pi->nRestartInterval; if(pi->nTotalMCUs % pi->nRestartInterval) nRestartIntervalsLeft++; /* Allocate memory for MCU buffer */ if(pi->pcMCUBuffer != NULL) delete [] pi->pcMCUBuffer; pi->pcMCUBuffer = new uint8[g_MCULayouts[pi->nMCULayout].nMCUXSize * g_MCULayouts[pi->nMCULayout].nMCUYSize * 3]; /* Continue until out of restart intervals */ while(nRestartIntervalsLeft > 0) { /* Decode restart interval */ int nMarker = _DecodeRestartInterval(pIn,pRGB,pi,ps); if(nMarker == 0xD9) { /* End Of Image marker */ break; } else if(nMarker >= 0xD0 && nMarker <= 0xD7) { /* Restart marker. If we were pedantic we'd check that they come in the right order :P */ nRestartIntervalsLeft--; } else if(nMarker == 0) { /* End of stream */ break; } else { /* Unexpected marker */ throw DecodeError(ERR_UNEXPECTED_MARKER); } } } void Decoder::_Parse(InputStream *pIn,RGBImage *pRGB,Info *pi,bool bGetInfoOnly) { /* SOI marker must be first */ if(pIn->readMarker() != 0xD8) throw DecodeError(ERR_NOT_JPEG); /* Read markers until start of frame */ bool bSOF = false; while(!pIn->isEndOfStream()) { int nMarker = pIn->readMarker(); if(nMarker == 0xC0) { /* Start Of Frame */ _ParseSOF(pIn,pRGB,pi); pi->nMCUIndex = 0; bSOF = true; break; } else if(!bGetInfoOnly) { _InterpretMarker(pIn,pRGB,pi,nMarker); } } if(!bSOF) throw DecodeError(ERR_NO_FRAME); /* If we're only getting image info stop here */ if(!bGetInfoOnly) { /* Allocate room for image */ pRGB->release(); pRGB->pc = new uint8[pRGB->nWidth * pRGB->nHeight * 3]; memset(pRGB->pc,0,pRGB->nWidth * pRGB->nHeight * 3); /* Decode frame */ _DecodeFrame(pIn,pRGB,pi); } } void Decoder::_InterpretMarker(InputStream *pIn,RGBImage *pRGB,Info *pi,int nMarker) { switch(nMarker) { case 0xC4: /* Define Huffman Tables */ _ParseDHT(pIn,pRGB,pi); break; case 0xDB: /* Define Quantization Tables */ _ParseDQT(pIn,pRGB,pi); break; case 0xDD: /* Define Restart Interval */ _ParseDRI(pIn,pRGB,pi); break; } } void Decoder::_DecodeFrame(InputStream *pIn,RGBImage *pRGB,Info *pi) { bool bEOI = false; while(!pIn->isEndOfStream()) { /* Get next marker */ int nMarker = pIn->readMarker(); switch(nMarker) { case 0xDA: /* Start Of Scan */ { Scan Scan; _ParseSOS(pIn,pRGB,pi,&Scan); decodeScan(pIn,pRGB,pi,&Scan); break; } case 0xD9: /* End Of Image */ { /* Under normal circumstances we'll never get here, since the EOI is processed by _DecodeScan(). Only if there's no scan (unlikely) we'll get here */ bEOI = true; break; } default: { _InterpretMarker(pIn,pRGB,pi,nMarker); break; } } /* Reached end of image? */ if(bEOI) break; } } int Decoder::_DecodeRestartInterval(InputStream *pIn,RGBImage *pRGB,Info *pi,Scan *ps) { /* Reset decoder */ for(int i=0;i<3;i++) ps->Components[i].nDCPred = 0; /* 8x8 block buffer */ ALIGN16 short nBlock[64]; /* Start decoding bitstream */ pIn->flushBitStream(); int nMCUsLeft = pi->nRestartInterval; while(nMCUsLeft > 0) { /* For each data unit in the MCU... */ for(int i=0;i<g_MCULayouts[pi->nMCULayout].nDataUnitsPerMCU;i++) { /* Decode a 8x8 DCT block */ memset(nBlock,0,sizeof(nBlock)); int nComponent = g_MCULayouts[pi->nMCULayout].nDUComponents[i]; /* Resolve huffman tables */ HuffmanTable *pDC = ps->Components[nComponent].pDCTable; HuffmanTable *pAC = ps->Components[nComponent].pACTable; /* Decode DC value (within restart intervals, each DC value is coded as a delta from the previous one of the specific component) */ nBlock[0] = ps->Components[nComponent].nDCPred + pDC->decode(pIn,NULL); ps->Components[nComponent].nDCPred = nBlock[0]; /* Decode AC values */ for(int j=1;j<64;j++) { int nLeadingZeros; int n = pAC->decode(pIn,&nLeadingZeros); if(n == JPG_HUFFMAN_EOB) { /* End-of-block symbol (remaining AC values are zero) */ break; } else if(n == JPG_HUFFMAN_ZRL) { /* 16 zeros */ j += 15; /* last one is added implicitly by the for-loop */ } else { /* 0-15 zeros followed by a value */ j += nLeadingZeros; /* AC coefficients are stored in diagonal zig-zag order, starting at top left */ nBlock[m_nZZOrder[j]] = n; } } /* Resolve quantization matrix */ int nQTableIndex = pi->Components[nComponent].nQuantizationTable; QuantizationTable *pQ = &pi->QuantizationTables[nQTableIndex]; /* Perform dequantization -- note that we already de-zigzagged the quantization matrix */ #if defined(EMMINTRIN) /* Use SIMD (only slightly faster since a lot of time is wasted loading registers) */ const __m128i *pQRow = (const __m128i *)pQ->nTable; __m128i *pBRow = (__m128i *)nBlock; for(int j=0;j<8;j++) pBRow[j] = _mm_mullo_epi16(pBRow[j],pQRow[j]); #else /* No SIMD */ for(int j=0;j<64;j++) nBlock[j] *= pQ->nTable[j]; #endif /* Perform IDCT on block */ _InverseDCT(nBlock); /* Merge 8x8 block into MCU */ _UpdateMCU(pi,i,nBlock); } /* Merge MCU into image */ _MergeMCU(pRGB,pi); /* Next MCU... */ nMCUsLeft--; pi->nMCUIndex++; } /* Go to next marker and return its value */ if(pIn->getEmbeddedMarker() != 0) return pIn->getEmbeddedMarker(); return pIn->readMarker(); } void Decoder::_ParseDRI(InputStream *pIn,RGBImage *pRGB,Info *pi) { /* The DRI marker defines how many MCUs should be decoded at a time in a single run (the restart interval). This marker is optional, if it's not present we'll just do all MCUs in one run */ int nLen = pIn->readWord(); pi->nRestartInterval = pIn->readWord(); } void Decoder::_ParseSOF(InputStream *pIn,RGBImage *pRGB,Info *pi) { int nLen = pIn->readWord(); int nBitsPerComponent = pIn->readByte(); if(nBitsPerComponent != 8) throw DecodeError(ERR_MUST_BE_8BIT); /* Get image dimensions */ pRGB->nHeight = pIn->readWord(); pRGB->nWidth = pIn->readWord(); if(pRGB->nHeight == 0 || pRGB->nWidth == 0) throw DecodeError(ERR_INVALID_FRAME); int nNumComponents = pIn->readByte(); if(nNumComponents != 3) throw DecodeError(ERR_UNSUPPORTED_MCU_LAYOUT); /* Must be 3-component */ /* For each component... */ for(int i=0;i<3;i++) { /* Get component index */ int nId = pIn->readByte() - 1; if(nId != i) throw DecodeError(ERR_INVALID_FRAME); /* Get component info */ int nSamplingFactors = pIn->readByte(); pi->Components[i].nXSampleFactor = (nSamplingFactors & 0xf0) >> 4; pi->Components[i].nYSampleFactor = nSamplingFactors & 0x0f; pi->Components[i].nQuantizationTable = pIn->readByte(); /* Check if it's a valid quantization table index */ if(pi->Components[i].nQuantizationTable < 0 || pi->Components[i].nQuantizationTable > 3) throw DecodeError(ERR_INVALID_FRAME); } /* Figure out the MCU layout... */ pi->nMCULayout = _LookupMCULayout(pi->Components); /* Calculate total number of MCUs and default restart interval */ pi->nHorizontalMCUs = pRGB->nWidth / g_MCULayouts[pi->nMCULayout].nMCUXSize; pi->nVerticalMCUs = pRGB->nHeight / g_MCULayouts[pi->nMCULayout].nMCUYSize; if(pRGB->nWidth % g_MCULayouts[pi->nMCULayout].nMCUXSize) pi->nHorizontalMCUs++; if(pRGB->nHeight % g_MCULayouts[pi->nMCULayout].nMCUYSize) pi->nVerticalMCUs++; pi->nTotalMCUs = pi->nHorizontalMCUs * pi->nVerticalMCUs; pi->nRestartInterval = pi->nTotalMCUs; } void Decoder::_ParseDHT(InputStream *pIn,RGBImage *pRGB,Info *pi) { int nLen = pIn->readWord() - 2; /* Read huffman tables */ while(nLen > 0) { int n = pIn->readByte(); nLen--; int nId = n & 0x0f; if(nId < 0 || nId >= 3) throw DecodeError(ERR_INVALID_HUFFMAN_TABLE_ID); HuffmanTable *pTable; if((n & 0xf0) >> 4) pTable = &pi->ACHuffmanTables[nId]; else pTable = &pi->DCHuffmanTables[nId]; /* A huffman table is stored like this: First there's 16 numbers, each specifying the number of codes of the given length */ for(int i=0;i<16;i++) pTable->nL[i] = pIn->readByte(); nLen -= 16; /* Second, all the codes are stored */ for(int i=0;i<16;i++) { if(pTable->nL[i] > 0) pTable->nMaxBits = i + 1; for(int j=0;j<pTable->nL[i];j++) { pTable->nTable[i*256+j] = pIn->readByte(); } nLen -= pTable->nL[i]; } /* Build tree from table */ pTable->buildTree(); pTable->bDefined = true; } } void Decoder::_ParseDQT(InputStream *pIn,RGBImage *pRGB,Info *pi) { int nLen = pIn->readWord() - 2; /* Read quantization table definitions */ while(nLen > 0) { int n = pIn->readByte(); nLen--; int nId = n & 0x0f; if(nId < 0 || nId >= 3) throw DecodeError(ERR_INVALID_QUANTIZATION_TABLE); int nPrecission = (n & 0xf0) >> 4; if(nPrecission != 0) throw DecodeError(ERR_INVALID_QUANTIZATION_TABLE); pi->QuantizationTables[nId].bDefined = true; for(int i=0;i<64;i++) { /* Un-zigzag the order */ pi->QuantizationTables[nId].nTable[m_nZZOrder[i]] = pIn->readByte(); } nLen -= 64; } } void Decoder::_ParseSOS(InputStream *pIn,RGBImage *pRGB,Info *pi,Scan *ps) { int nLen = pIn->readWord(); int nNumComponents = pIn->readByte(); if(nNumComponents != 3) throw DecodeError(ERR_INVALID_SCAN); /* For each component... */ for(int i=0;i<3;i++) { int nId = pIn->readByte() - 1; if(i != nId) throw DecodeError(ERR_INVALID_SCAN); /* Get the indices of the huffman tables and check if they're valid */ int nEncodingTables = pIn->readByte(); int nACTable = nEncodingTables & 0x0f; int nDCTable = (nEncodingTables & 0xf0) >> 4; if(nACTable < 0 || nACTable > 3 || nDCTable < 0 || nDCTable > 3) throw DecodeError(ERR_INVALID_SCAN); /* Resolve huffman tables */ ps->Components[i].pACTable = &pi->ACHuffmanTables[nACTable]; ps->Components[i].pDCTable = &pi->DCHuffmanTables[nDCTable]; if(!ps->Components[i].pACTable->bDefined || !ps->Components[i].pDCTable->bDefined) throw DecodeError(ERR_INVALID_SCAN); } /* DCT start/end and AH/AL follows, but we'll ignore those */ int nDCTStart = pIn->readByte(); int nDCTEnd = pIn->readByte(); int nA = pIn->readByte(); /* AH/AL */ } void Decoder::_MergeMCU(RGBImage *pRGB,Info *pi) { /* Merge MCU into the image while making sure it's clipped against the right/bottom edges */ int nMCUClippedXSize = g_MCULayouts[pi->nMCULayout].nMCUXSize; int nMCUClippedYSize = g_MCULayouts[pi->nMCULayout].nMCUYSize;; int nX = (pi->nMCUIndex % pi->nHorizontalMCUs) * nMCUClippedXSize; int nY = (pi->nMCUIndex / pi->nHorizontalMCUs) * nMCUClippedYSize; if(nX + g_MCULayouts[pi->nMCULayout].nMCUXSize > pRGB->nWidth) nMCUClippedXSize -= (nX + g_MCULayouts[pi->nMCULayout].nMCUXSize) - pRGB->nWidth; if(nY + g_MCULayouts[pi->nMCULayout].nMCUYSize > pRGB->nHeight) nMCUClippedYSize -= (nY + g_MCULayouts[pi->nMCULayout].nMCUYSize) - pRGB->nHeight; int nPitchDest = pRGB->nWidth * 3; int nPitchSrc = g_MCULayouts[pi->nMCULayout].nMCUXSize * 3; uint8 *pcDest = &pRGB->pc[nPitchDest * nY + nX * 3]; uint8 *pcSrc = pi->pcMCUBuffer; for(int i=0;i<nMCUClippedYSize;i++) { uint8 *pcD = pcDest; uint8 *pcS = pcSrc; for(int j=0;j<nMCUClippedXSize;j++) { /* Convert from YCBCR to RGB */ int r = pcS[0] + m_nRTable[pcS[2]]; int g = pcS[0] + m_nGTable[((int)pcS[1]<<8)+pcS[2]]; int b = pcS[0] + m_nBTable[pcS[1]]; pcD[0] = BYTECLAMP(r); pcD[1] = BYTECLAMP(g); pcD[2] = BYTECLAMP(b); pcD+=3; pcS+=3; } pcDest += nPitchDest; pcSrc += nPitchSrc; } } void Decoder::_UpdateMCU8x8(uint8 *pcMCUBuffer,int nMCUXSize,int nMCUYSize,short *pnBlock,int nComponent,int nXOffset,int nYOffset) { /* This function merges an unscaled 8x8 block into an arbitrary sized MCU/channel */ uint8 *pc = &pcMCUBuffer[(nYOffset * nMCUXSize + nXOffset) * 3 + nComponent]; short *pnD = pnBlock; for(int i=0;i<8;i++) { uint8 *pcC = pc; for(int j=0;j<8;j++) { int n = BYTECLAMP(*pnD); pnD++; pcC[0] = n; pcC += 3; } pc += nMCUXSize * 3; } } void Decoder::_UpdateMCU16x8(uint8 *pcMCUBuffer,short *pnBlock,int nComponent) { /* This function stretches a 8x8 block to 16x8 */ uint8 *pc = &pcMCUBuffer[nComponent]; short *pnD = pnBlock; for(int i=0;i<8;i++) { uint8 *pcC = pc; for(int j=0;j<8;j++) { int n = BYTECLAMP(*pnD); pnD++; pcC[0] = n; pcC[3] = n; pcC += 6; } pc += 48; } } void Decoder::_UpdateMCU16x16(uint8 *pcMCUBuffer,short *pnBlock,int nComponent) { /* This function stretches a 8x8 block to 16x16 */ uint8 *pc = &pcMCUBuffer[nComponent]; short *pnD = pnBlock; for(int i=0;i<8;i++) { uint8 *pcC = pc; for(int j=0;j<8;j++) { int n = BYTECLAMP(*pnD); pnD++; pcC[0] = n; pcC[3] = n; pcC[48] = n; pcC[51] = n; pcC += 6; } pc += 96; } } void Decoder::_UpdateMCU(Info *pi,int nDataUnit,short *pnBlock) { /* Updates the current MCU with the given data unit */ switch(pi->nMCULayout) { case JPG_MCU_LAYOUT_YCBCR_420: switch(nDataUnit) { case 0: _UpdateMCU8x8(pi->pcMCUBuffer,16,16,pnBlock,0,0,0); break; case 1: _UpdateMCU8x8(pi->pcMCUBuffer,16,16,pnBlock,0,8,0); break; case 2: _UpdateMCU8x8(pi->pcMCUBuffer,16,16,pnBlock,0,0,8); break; case 3: _UpdateMCU8x8(pi->pcMCUBuffer,16,16,pnBlock,0,8,8); break; case 4: _UpdateMCU16x16(pi->pcMCUBuffer,pnBlock,1); break; case 5: _UpdateMCU16x16(pi->pcMCUBuffer,pnBlock,2); break; } break; case JPG_MCU_LAYOUT_YCBCR_422: switch(nDataUnit) { case 0: _UpdateMCU8x8(pi->pcMCUBuffer,16,8,pnBlock,0,0,0); break; case 1: _UpdateMCU8x8(pi->pcMCUBuffer,16,8,pnBlock,0,8,0); break; case 2: _UpdateMCU16x8(pi->pcMCUBuffer,pnBlock,1); break; case 3: _UpdateMCU16x8(pi->pcMCUBuffer,pnBlock,2); break; } break; case JPG_MCU_LAYOUT_YCBCR_444: switch(nDataUnit) { case 0: _UpdateMCU8x8(pi->pcMCUBuffer,8,8,pnBlock,0,0,0); break; case 1: _UpdateMCU8x8(pi->pcMCUBuffer,8,8,pnBlock,1,0,0); break; case 2: _UpdateMCU8x8(pi->pcMCUBuffer,8,8,pnBlock,2,0,0); break; } break; } } void Decoder::_InitRGBTables(void) { /* Init tables for fast YCBCR-to-RGB conversion */ for(int i=0;i<256;i++) { m_nRTable[i] = ((91881 * (i - 128)) >> 16); /* Min=-180, Max=180 */ m_nBTable[i] = ((116129 * (i - 128)) >> 16); /* Min=-227, Max=227 */ for(int j=0;j<256;j++) m_nGTable[(i<<8) + j] = ((-22553 * (i - 128) - 46801 * (j - 128)) >> 16); /* Min=-135, Max=135 */ } } void Decoder::_InitZZOrdering(void) { /* DCT matrices are stored in a diagonal zig-zag order, starting at the upper left corner (the DC value). This function initializes a table which convert a sequential index to a zig-zag'd index */ int q = 0; for(int x=0;x<8;x++) { for(int i=0;i<8;i++) { if(x % 2 == 0) { int xx = i; int yy = x - i; if(yy < 0) break; m_nZZOrder[q++] = xx + yy * 8; } else { int xx = x - i; int yy = i; if(xx < 0) break; m_nZZOrder[q++] = xx + yy * 8; } } } for(int y=1;y<8;y++) { for(int i=0;i<8;i++) { if(y % 2 == 0) { int xx = 7 - i; int yy = y + i; if(yy >= 8) break; m_nZZOrder[q++] = xx + yy * 8; } else { int xx = y + i; int yy = 7 - i; if(xx >= 8) break; m_nZZOrder[q++] = xx + yy * 8; } } } } /*=========================================================================== 2D IDCTs are calculated in two passes of 1D IDCTs, first on the rows and then the columns. ===========================================================================*/ template <int _Half,int _FinalRShift,int _FinalOffset> void _IDCT_1D(const short *pnIn,short *pnOut) { /* 1D IDCT butterfly solution (LLM) */ int p, n; int x0 = pnIn[0] << 9; int x1 = pnIn[1] << 7; int x2 = pnIn[2]; int x3 = pnIn[3] * 181; int x4 = pnIn[4] << 9; int x5 = pnIn[5] * 181; int x6 = pnIn[6]; int x7 = pnIn[7] << 7; n = 277*(x6+x2); p = x6; x6 = n + 392*x2; x2 = n - 946*p; p = x0 + x4; n = x0 - x4; x0 = p + x6 + _Half; x4 = n + x2 + _Half; x6 = p - x6 + _Half; x2 = n - x2 + _Half; p = x1 + x7; n = x1 - x7; x1 = p + x3; x7 = n + x5; x3 = p - x3; x5 = n - x5; n = 251*(x5+x3); p = x5; x5 = (n - 201*x3) >> 6; x3 = (n - 301*p) >> 6; n = 213*(x1+x7); p = x1; x1 = (n - 71*x7) >> 6; x7 = (n - 355*p) >> 6; pnOut[0] = (short)((x0 + x1) >> _FinalRShift) + _FinalOffset; pnOut[8] = (short)((x4 + x5) >> _FinalRShift) + _FinalOffset; pnOut[16] = (short)((x2 + x3) >> _FinalRShift) + _FinalOffset; pnOut[24] = (short)((x6 + x7) >> _FinalRShift) + _FinalOffset; pnOut[32] = (short)((x6 - x7) >> _FinalRShift) + _FinalOffset; pnOut[40] = (short)((x2 - x3) >> _FinalRShift) + _FinalOffset; pnOut[48] = (short)((x4 - x5) >> _FinalRShift) + _FinalOffset; pnOut[56] = (short)((x0 - x1) >> _FinalRShift) + _FinalOffset; } void Decoder::_InverseDCT(short *pnBlock) { /* Calculate inverse DCT */ short nTemp[64]; /* First perform 1D IDCT on each row */ for(int i=0;i<8;i++) _IDCT_1D<256,9,0>(&pnBlock[i*8],&nTemp[i]); /* Now do the same 1D IDCT on each column -- first pass generated a transposed matrix so we can use the same algorithm again */ for(int i=0;i<8;i++) _IDCT_1D<2048,12,128>(&nTemp[i*8],&pnBlock[i]); } }
32.431818
136
0.516468
e5e7a30ebbffc75b417222539fae251a92732333
2,747
cpp
C++
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
obivan43/pawnengine
ec092fa855d41705f3fb55fcf1aa5e515d093405
[ "MIT" ]
null
null
null
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
obivan43/pawnengine
ec092fa855d41705f3fb55fcf1aa5e515d093405
[ "MIT" ]
null
null
null
Editor/gui/InspectorWidget/widget/impl/CameraComponentWidget.cpp
obivan43/pawnengine
ec092fa855d41705f3fb55fcf1aa5e515d093405
[ "MIT" ]
null
null
null
#include "CameraComponentWidget.h" #include <QVBoxLayout> #include <QHBoxLayout> namespace editor::impl { CameraComponentWidget::CameraComponentWidget(QWidget* parent) : QWidget(parent) , m_Camera(nullptr) , m_Projection(nullptr) , m_ProjectionLabel(nullptr) , m_IsActiveCamera(nullptr) , m_IsActiveCameraLabel(nullptr) { QVBoxLayout* layout = new QVBoxLayout(this); QHBoxLayout* projectionLayout = new QHBoxLayout(); m_Projection = new QComboBox(this); m_Projection->addItem("Perspective", pawn::math::CameraType::Perspective); m_Projection->addItem("Orthographic", pawn::math::CameraType::Orthographic); m_ProjectionLabel = new QLabel("Projection", this); m_ProjectionLabel->setMinimumWidth(80); projectionLayout->addWidget(m_ProjectionLabel); projectionLayout->addWidget(m_Projection); QHBoxLayout* activeCameraLayout = new QHBoxLayout(); m_IsActiveCamera = new QCheckBox(this); m_IsActiveCameraLabel = new QLabel("Active camera", this); m_IsActiveCameraLabel->setMinimumWidth(80); activeCameraLayout->addWidget(m_IsActiveCameraLabel); activeCameraLayout->addWidget(m_IsActiveCamera); layout->addLayout(projectionLayout); layout->addLayout(activeCameraLayout); setLayout(layout); InitConnections(); } void CameraComponentWidget::OnProjectionChanged(int index) { if (m_Camera) { pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera); pawn::math::CameraType type = qvariant_cast<pawn::math::CameraType>(m_Projection->itemData(index)); switch (type) { case pawn::math::CameraType::Perspective: { camera.SetPerspective(); break; } case pawn::math::CameraType::Orthographic: { camera.SetOrthographic(); break; } default: break; } } } void CameraComponentWidget::OnActiveCameraStateChanged(bool state) { if (m_Camera) { m_Camera->IsActiveCamera = state; } } void CameraComponentWidget::SetCamera(pawn::engine::CameraComponent* camera) { m_Camera = camera; if (m_Camera) { pawn::math::Camera& camera = static_cast<pawn::math::Camera&>(*m_Camera); pawn::math::CameraType type = camera.GetType(); int index = m_Projection->findData(type); if (index != -1) { m_Projection->setCurrentIndex(index); } m_IsActiveCamera->setChecked(m_Camera->IsActiveCamera); } } void CameraComponentWidget::InitConnections() { connect( m_Projection, SIGNAL(currentIndexChanged(int)), this, SLOT(OnProjectionChanged(int)) ); connect( m_IsActiveCamera, SIGNAL(clicked(bool)), this, SLOT(OnActiveCameraStateChanged(bool)) ); } }
25.201835
103
0.69312