hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | 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 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20b64950ecf8b7236b3a81cb6538d130cbdcdfc9 | 350 | cpp | C++ | Algorithms/Warmup/Staircase.cpp | pavstar619/HackerRank | 697ee46b6e621ad884a064047461d7707b1413cd | [
"MIT"
] | 61 | 2017-04-27T13:45:12.000Z | 2022-01-27T11:40:15.000Z | Algorithms/Warmup/Staircase.cpp | fahad0193/HackerRank | eb6c95e16688c02921c1df6b6ea613667a251457 | [
"MIT"
] | 1 | 2017-06-24T14:16:06.000Z | 2017-06-24T14:16:28.000Z | Algorithms/Warmup/Staircase.cpp | fahad0193/HackerRank | eb6c95e16688c02921c1df6b6ea613667a251457 | [
"MIT"
] | 78 | 2017-07-05T11:48:20.000Z | 2022-02-08T08:04:22.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
int n;
cin >> n;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++)
cout << " ";
for(int j = 0; j < i + 1; j++)
cout << "#";
cout << endl;
}
}
| 15.909091 | 38 | 0.445714 | [
"vector"
] |
20c068933192745ab51b8c2b39286a1b74947fee | 2,410 | cpp | C++ | damc_common/Osc/OscVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | 5 | 2021-10-02T03:01:56.000Z | 2022-01-24T20:59:19.000Z | damc_common/Osc/OscVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | null | null | null | damc_common/Osc/OscVariable.cpp | amurzeau/waveplay | e0fc097137138c4a6985998db502468074bf739f | [
"MIT"
] | null | null | null | #include "OscVariable.h"
#include "OscRoot.h"
#include <spdlog/spdlog.h>
EXPLICIT_INSTANCIATE_OSC_VARIABLE(template, OscVariable)
template<typename T>
OscVariable<T>::OscVariable(OscContainer* parent, std::string name, T initialValue, bool fixedSize) noexcept
: OscReadOnlyVariable<T>(parent, name, initialValue), fixedSize(fixedSize) {
if(fixedSize)
return;
this->getRoot()->addPendingConfigNode(this);
this->addChangeCallback([this](T) { this->getRoot()->notifyValueChanged(); });
if constexpr(std::is_same_v<T, bool>) {
subEndpoint.emplace_back(new OscEndpoint(this, "toggle"))->setCallback([this](auto) {
SPDLOG_INFO("{}: Toggling", this->getFullAddress());
this->setFromOsc(!this->getToOsc());
});
} else if constexpr(std::is_same_v<T, std::string>) {
// No toggle/increment/decrement
} else {
incrementAmount = (T) 1;
subEndpoint.emplace_back(new OscEndpoint(this, "increment"))
->setCallback([this](const std::vector<OscArgument>& arguments) {
T amount = incrementAmount;
if(!arguments.empty()) {
OscNode::getArgumentAs<T>(arguments[0], amount);
}
SPDLOG_INFO("{}: Incrementing by {}", this->getFullAddress(), amount);
this->setFromOsc(this->getToOsc() + amount);
});
subEndpoint.emplace_back(new OscEndpoint(this, "decrement"))
->setCallback([this](const std::vector<OscArgument>& arguments) {
T amount = incrementAmount;
if(!arguments.empty()) {
OscNode::getArgumentAs<T>(arguments[0], amount);
}
SPDLOG_INFO("{}: Decrementing by {}", this->getFullAddress(), amount);
this->setFromOsc(this->getToOsc() - amount);
});
}
}
template<typename T> OscVariable<T>& OscVariable<T>::operator=(const OscVariable<T>& v) {
this->set(v.get());
return *this;
}
template<typename T> void OscVariable<T>::execute(const std::vector<OscArgument>& arguments) {
if(fixedSize) {
SPDLOG_WARN("{}: variable is fixed, ignoring OSC write", this->getFullAddress());
return;
}
if(!arguments.empty()) {
T v;
if(this->template getArgumentAs<T>(arguments[0], v)) {
this->setFromOsc(std::move(v));
}
}
}
template<typename T> std::string OscVariable<T>::getAsString() const {
if(this->isDefault())
return {};
if constexpr(std::is_same_v<T, std::string>) {
return "\"" + this->getToOsc() + "\"";
} else {
return std::to_string(this->getToOsc());
}
}
| 30.125 | 108 | 0.666805 | [
"vector"
] |
20c958b8a954ee598ba0dd0e438a76589f51a3e0 | 3,268 | hpp | C++ | src/scene/sample/rectangle.hpp | IsraelEfraim/cpp-engine | 039bcad97d55635a7a8f31d0d80ce59095ebb6cb | [
"MIT"
] | null | null | null | src/scene/sample/rectangle.hpp | IsraelEfraim/cpp-engine | 039bcad97d55635a7a8f31d0d80ce59095ebb6cb | [
"MIT"
] | null | null | null | src/scene/sample/rectangle.hpp | IsraelEfraim/cpp-engine | 039bcad97d55635a7a8f31d0d80ce59095ebb6cb | [
"MIT"
] | 2 | 2021-03-15T18:51:32.000Z | 2021-07-19T23:45:49.000Z | #ifndef CPP_ENGINE_RECTANGLE_HPP
#define CPP_ENGINE_RECTANGLE_HPP
#include <numbers>
#include <array>
#include <SFML/Graphics.hpp>
#include "../../geometry/core.hpp"
#include "../../pixel-buffer.hpp"
#include "../../draw.hpp"
template <std::size_t width, std::size_t height, class T = double>
class Rectangle_Runner {
engine::Basic_RGBA_Buffer pixels;
sf::Texture pixels_texture;
sf::Sprite pixels_sprite;
/* Example data */
engine::Rectangle<T> rect;
engine::Vector_2D<T> click;
T shift;
T angle;
public:
Rectangle_Runner() :
pixels(width, height, 255u),
pixels_texture{},
pixels_sprite{},
rect{ {{ {100, 100}, {300, 100}, {300, 300}, {100, 300} }} },
click{0, 0},
shift{10},
angle{30}
{
pixels_texture.create(width, height);
pixels_texture.update(std::data(pixels));
pixels_sprite.setTexture(pixels_texture);
update_pixels();
}
template <class W, class E>
auto event_hook(W const& window, E event) -> void {
if (event.type == sf::Event::KeyPressed) {
/* Treat rect input */
auto transform = [&]() -> engine::Mat3 {
/* Translate */
if (event.key.code == sf::Keyboard::Left) {
return engine::Mat3::translate(-shift, 0);
} else if (event.key.code == sf::Keyboard::Right) {
return engine::Mat3::translate(shift, 0);
} else if (event.key.code == sf::Keyboard::Up) {
return engine::Mat3::translate(0, -shift);
} else if (event.key.code == sf::Keyboard::Down) {
return engine::Mat3::translate(0, shift);
}
/* Rotate */
if (event.key.code == sf::Keyboard::A) {
return engine::Mat3::rotate(angle * (std::numbers::pi / 180.0));
} else if (event.key.code == sf::Keyboard::S) {
return engine::Mat3::rotate(-angle * (std::numbers::pi / 180.0));
}
return engine::Mat3::identity();
}();
auto axis = [&]() -> engine::Vector_2D<T> {
if (event.key.shift) {
return click;
}
return engine::centroid(rect);
}();
for (auto & v : rect.vertex) {
auto origin = engine::translate(v, -axis.x, -axis.y);
v = engine::translate(origin * transform, axis.x, axis.y);
}
update_pixels();
} else if (event.type == sf::Event::MouseButtonPressed) {
if (event.mouseButton.button == sf::Mouse::Left) {
auto [x, y] = sf::Mouse::getPosition(window);
click = {static_cast<T>(x), static_cast<T>(y)};
}
}
}
template <class W>
auto render(W & window) -> void {
window.render(pixels_sprite);
}
private:
auto update_pixels() -> void {
std::fill(std::begin(pixels), std::end(pixels), 255u);
engine::draw_rect(pixels, rect, { 0, 255, 0, 255 });
pixels_texture.update(std::data(pixels));
}
};
#endif //CPP_ENGINE_RECTANGLE_HPP
| 30.259259 | 85 | 0.517136 | [
"geometry",
"render",
"transform"
] |
20d0703b06029feae3d9a9cb8d89a57216ca4c68 | 296 | cpp | C++ | examples/cpp/hello_world/main.cpp | hartb/vision | f2f085bf099c4c31bc6f09c21844b2d57dabcb87 | [
"BSD-3-Clause"
] | 3 | 2020-11-04T03:18:12.000Z | 2022-03-09T09:38:54.000Z | examples/cpp/hello_world/main.cpp | hartb/vision | f2f085bf099c4c31bc6f09c21844b2d57dabcb87 | [
"BSD-3-Clause"
] | null | null | null | examples/cpp/hello_world/main.cpp | hartb/vision | f2f085bf099c4c31bc6f09c21844b2d57dabcb87 | [
"BSD-3-Clause"
] | 1 | 2021-06-01T11:15:53.000Z | 2021-06-01T11:15:53.000Z | #include <iostream>
#include <torchvision/models/resnet.h>
int main()
{
auto model = vision::models::ResNet18();
model->eval();
// Create a random input tensor and run it through the model.
auto in = torch::rand({1, 3, 10, 10});
auto out = model->forward(in);
std::cout << out;
}
| 18.5 | 63 | 0.641892 | [
"model"
] |
20d07062f93fc0a3f778dc08243b976f4940cacf | 3,660 | cpp | C++ | libbrufs/test/PathParser.cpp | cmpsb/brufs | 83a9cc296653f99042190e968a1499b3191dc8d2 | [
"MIT"
] | null | null | null | libbrufs/test/PathParser.cpp | cmpsb/brufs | 83a9cc296653f99042190e968a1499b3191dc8d2 | [
"MIT"
] | null | null | null | libbrufs/test/PathParser.cpp | cmpsb/brufs | 83a9cc296653f99042190e968a1499b3191dc8d2 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "PathParser.hpp"
TEST_CASE("Parsing paths", "[util]") {
Brufs::PathParser parser;
SECTION("Can parse bare slash") {
const auto path = parser.parse("/");
CHECK_FALSE(path.has_partition());
CHECK(path.get_partition().empty());
CHECK_FALSE(path.has_root());
CHECK(path.get_root().empty());
CHECK(path.get_components().empty());
}
SECTION("Can parse longer path without partition and root") {
const auto path = parser.parse("/three/dirs/deep/");
CHECK_FALSE(path.has_partition());
CHECK_FALSE(path.has_root());
const auto components = path.get_components();
CHECK(components.get_size() == 3);
CHECK(components[0] == "three");
CHECK(components[1] == "dirs");
CHECK(components[2] == "deep");
}
SECTION("Can parse longer path with root, without partition") {
const auto path = parser.parse("www:/sites/example.com/htdocs");
CHECK_FALSE(path.has_partition());
CHECK(path.has_root());
CHECK(path.get_root() == "www");
const auto components = path.get_components();
CHECK(components.get_size() == 3);
CHECK(components[0] == "sites");
CHECK(components[1] == "example.com");
CHECK(components[2] == "htdocs");
}
SECTION("Can parse longer path with all bells and whistles") {
const auto path = parser.parse("disk.img:system:/data/music.7z");
CHECK(path.has_partition());
CHECK(path.get_partition() == "disk.img");
CHECK(path.has_root());
CHECK(path.get_root() == "system");
const auto components = path.get_components();
CHECK(components.get_size() == 2);
CHECK(components[0] == "data");
CHECK(components[1] == "music.7z");
}
SECTION("Can parse with missing root") {
const auto path = parser.parse("disk.img::/what/is/this/I/don't/even");
CHECK(path.has_partition());
CHECK(path.get_partition() == "disk.img");
CHECK_FALSE(path.has_root());
const auto components = path.get_components();
CHECK(components.get_size() == 6);
CHECK(components[0] == "what");
CHECK(components[1] == "is");
CHECK(components[2] == "this");
CHECK(components[3] == "I");
CHECK(components[4] == "don't");
CHECK(components[5] == "even");
}
}
TEST_CASE("Stringifying paths", "[util]") {
Brufs::PathParser parser;
SECTION("Can write simplest path") {
const Brufs::Path path;
const auto str = parser.unparse(path);
CHECK(str == "/");
}
SECTION("Can write simple, multi-component path") {
const Brufs::Path path{Brufs::Vector<Brufs::String>::of("hello", "there")};
const auto str = parser.unparse(path);
CHECK(str == "/hello/there");
}
SECTION("Can write path with root") {
const Brufs::Path path("data", Brufs::Vector<Brufs::String>::of("dust", "test.py"));
const auto str = parser.unparse(path);
CHECK(str == "data:/dust/test.py");
}
SECTION("Can write path with partition and root") {
const Brufs::Path path("vdisk0", "sys", Brufs::Vector<Brufs::String>::of("config", "boot"));
const auto str = parser.unparse(path);
CHECK(str == "vdisk0:sys:/config/boot");
}
SECTION("Can write weird path with partition but no root") {
const Brufs::Path path("mem", "", Brufs::Vector<Brufs::String>::of("a", "b", "abcd"));
const auto str = parser.unparse(path);
CHECK(str == "/a/b/abcd");
}
}
| 30 | 100 | 0.581694 | [
"vector"
] |
20d0967859edf6400ec982edcf5a541ab0df40c1 | 39,362 | cxx | C++ | StRoot/StEvent/StEvent.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StEvent/StEvent.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StEvent/StEvent.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /***************************************************************************
*
* $Id: StEvent.cxx,v 2.57 2018/02/08 17:36:26 ullrich Exp $
*
* Author: Thomas Ullrich, Sep 1999
***************************************************************************
*
* Description:
*
* Do not touch anything here unless you REALLY know what you are doing.
*
***************************************************************************
*
* $Log: StEvent.cxx,v $
* Revision 2.57 2018/02/08 17:36:26 ullrich
* Changed for new EPD classes.
*
* Revision 2.56 2015/10/09 17:46:15 ullrich
* Changed type of mIdTruth from ushort to int.
*
* Revision 2.55 2015/05/13 17:06:13 ullrich
* Added hooks and interfaces to Sst detector (part of HFT).
*
* Revision 2.54 2014/04/10 16:00:12 jeromel
* Changes to inlcude Ist structure (Thomas OK-ed / may revisit some comments)
*
* Revision 2.53 2013/03/05 14:49:44 ullrich
* Added PxlHits to statistics().
*
* Revision 2.52 2013/03/05 14:42:45 ullrich
* Added StPxl hits and Containers.
*
* Revision 2.51 2012/04/16 20:22:16 ullrich
* Changes necessary to add Fgt package.
*
* Revision 2.50 2012/01/24 03:01:38 perev
* Etr detector added
*
* Revision 2.49 2011/10/17 00:13:49 fisyak
* Add handles for IdTruth info
*
* Revision 2.48 2011/10/13 17:52:22 perev
* Comment++
*
* Revision 2.47 2011/04/25 21:25:09 ullrich
* Modifications to hold MTD data.
*
* Revision 2.46 2011/04/01 19:43:19 perev
* Allow zero pointer for TBrowser. debug
*
* Revision 2.45 2011/02/01 19:47:36 ullrich
* Added HLT branch and hooks.
*
* Revision 2.44 2010/08/31 19:53:37 fisyak
* Remove SoftwareMonitors
*
* Revision 2.43 2010/01/08 22:43:44 ullrich
* Updates needed to add StFmsCollection and related classes.
*
* Revision 2.42 2009/11/23 22:22:25 ullrich
* Minor cleanup performed and hooks for RPS added.
*
* Revision 2.41 2009/11/23 16:34:06 fisyak
* Cleanup, remove dependence on dst tables, clean up software monitors
*
* Revision 2.40 2008/12/22 20:36:53 ullrich
* Added hooks for new ToF (BTof)
*
* Revision 2.39 2006/04/25 23:21:25 ullrich
* Modified addPrimaryVertex(). New 2nd arg: StPrimaryVertexOrder.
*
* Revision 2.38 2006/01/19 21:48:21 ullrich
* Add RnD collection.
*
* Revision 2.37 2005/06/15 21:58:16 ullrich
* Change sorting of primary tracks for PPV.
*
* Revision 2.36 2003/04/16 17:48:32 ullrich
* Added StTriggerData and inherited classe(s).
*
* Revision 2.35 2003/01/30 18:36:31 ullrich
* Added hooks for StTriggerIdCollection.
*
* Revision 2.34 2002/12/20 22:41:30 ullrich
* Added PMD.
*
* Revision 2.33 2002/01/17 01:34:07 ullrich
* Fixed the fix in psd() methods.
*
* Revision 2.32 2002/01/17 01:29:10 ullrich
* Fixed bug in psd() methods.
*
* Revision 2.31 2002/01/03 20:59:33 ullrich
* Added BBC and FPD.
*
* Revision 2.30 2001/12/01 15:40:47 ullrich
* Added StDetectorState access function.
*
* Revision 2.29 2001/11/10 23:53:23 ullrich
* Added calibration vertices.
*
* Revision 2.28 2001/11/07 21:19:42 ullrich
* Added L1 trigger.
*
* Revision 2.27 2001/09/18 00:15:25 ullrich
* Added StRunInfo and access functions.
*
* Revision 2.26 2001/06/05 21:59:56 perev
* Split in Streamer added
*
* Revision 2.25 2001/05/30 17:45:53 perev
* StEvent branching
*
* Revision 2.24 2001/05/17 22:56:18 ullrich
* Removed all usage of dst_summary_param.
*
* Revision 2.23 2001/04/25 17:42:28 perev
* HPcorrs
*
* Revision 2.22 2001/04/23 19:28:13 ullrich
* Added StClusteringHints and methods to access it.
*
* Revision 2.21 2001/04/05 04:00:49 ullrich
* Replaced all (U)Long_t by (U)Int_t and all redundant ROOT typedefs.
*
* Revision 2.20 2001/03/14 02:35:43 ullrich
* Added container and methods to handle PSDs.
*
* Revision 2.19 2001/03/09 05:23:53 ullrich
* Added new method statistics().
*
* Revision 2.18 2000/12/08 03:53:40 ullrich
* Prepared hooks for ToF.
*
* Revision 2.17 2000/09/25 14:47:25 ullrich
* Fixed problem in _lookup() and _lookupOrCreate().
*
* Revision 2.16 2000/09/25 14:21:27 ullrich
* Removed enums for content vector. Replaced by lookup function.
*
* Revision 2.15 2000/09/06 22:34:12 ullrich
* Changed mBunchCrossingNumber from scalar to array to hold all 64 bits.
*
* Revision 2.14 2000/06/19 01:32:15 perev
* Thomas StEvent branches added
*
* Revision 2.13 2000/05/24 15:46:05 ullrich
* Added setSummary() method.
*
* Revision 2.12 2000/05/22 21:47:12 ullrich
* Added RICH collection and related methods.
*
* Revision 2.11 2000/05/15 18:35:38 ullrich
* All data member related to collections and containers are now
* kept by pointer. The interface (public methods) stays the same.
* Those methods which returns references were modified to create
* an empty collection in case the pointer is null.
*
* Revision 2.10 2000/04/26 20:33:24 ullrich
* Removed redundant virtual keywords.
*
* Revision 2.9 2000/04/20 14:27:29 perev
* Add Dataset browser to StEvent browser
*
* Revision 2.8 2000/04/18 17:31:28 perev
* StEvent::Browse overload of TDataSet:;One
*
* Revision 2.7 2000/03/29 16:54:11 ullrich
* Added L3 trigger.
*
* Revision 2.6 2000/02/23 17:35:59 ullrich
* Changes due to the addition of the EMC to StEvent
*
* Revision 2.5 2000/02/11 16:14:00 ullrich
* Primary vertices automatically sorted in addPrimaryVertex().
*
* Revision 2.4 2000/01/13 21:06:22 lasiuk
* add rich pixel info/containers
*
* Revision 2.3 2000/01/05 16:02:25 ullrich
* SSD hits added to StEvent.
*
* Revision 2.2 1999/11/04 13:30:40 ullrich
* Added constructor without summary table
*
* Revision 2.1 1999/10/28 22:25:07 ullrich
* Adapted new StArray version. First version to compile on Linux and Sun.
*
* Revision 2.0 1999/10/12 18:41:53 ullrich
* Completely Revised for New Version
*
**************************************************************************/
#include <typeinfo>
#include <algorithm>
#include "TClass.h"
#include "TDataSetIter.h"
#include "TObjectSet.h"
#include "TBrowser.h"
#include "StCalibrationVertex.h"
#include "StDetectorState.h"
#include "StEvent.h"
#include "StEventClusteringHints.h"
#include "StEventInfo.h"
#include "StEventSummary.h"
#include "StTpcHitCollection.h"
#include "StRnDHitCollection.h"
#include "StEtrHitCollection.h"
#include "StSvtHitCollection.h"
#include "StSsdHitCollection.h"
#include "StSstHitCollection.h"
#include "StFtpcHitCollection.h"
#include "StEmcCollection.h"
#include "StEpdCollection.h"
#include "StFmsCollection.h"
#include "StRichCollection.h"
#include "StRpsCollection.h"
#include "StRunInfo.h"
#include "StTofCollection.h"
#include "StBTofCollection.h"
#include "StMtdCollection.h"
#include "StFpdCollection.h"
#include "StPhmdCollection.h"
#include "StTrackDetectorInfo.h"
#include "StTriggerData.h"
#include "StTriggerDetectorCollection.h"
#include "StTriggerIdCollection.h"
#include "StPrimaryVertex.h"
#include "StL0Trigger.h"
#include "StL1Trigger.h"
#include "StL3Trigger.h"
#include "StPsd.h"
#include "event_header.h"
#include "StAutoBrowse.h"
#include "StEventBranch.h"
#include "StHltEvent.h"
#include "StFgtCollection.h"
#include "StPxlHitCollection.h"
#include "StIstHitCollection.h"
#include "StTrackNode.h"
#include "StTrack.h"
#ifndef ST_NO_NAMESPACES
using std::swap;
#endif
TString StEvent::mCvsTag = "$Id: StEvent.cxx,v 2.57 2018/02/08 17:36:26 ullrich Exp $";
static const char rcsid[] = "$Id: StEvent.cxx,v 2.57 2018/02/08 17:36:26 ullrich Exp $";
ClassImp(StEvent)
//______________________________________________________________________________
template<class T> void _lookup(T*& val, StSPtrVecObject &vec)
{
val = 0;
for (unsigned int i=0; i<vec.size(); i++)
if (vec[i] && typeid(*vec[i]) == typeid(T)) {
val = static_cast<T*>(vec[i]);
break;
}
}
//______________________________________________________________________________
template<class T> void _lookupOrCreate(T*& val, StSPtrVecObject &vec)
{
T* t = 0;
_lookup(t, vec);
if (!t) {
t = new T;
vec.push_back(t);
}
val = t;
}
//______________________________________________________________________________
template<class T> void _lookupAndSet(T* val, StSPtrVecObject &vec)
{
for (unsigned int i=0; i<vec.size(); i++)
if (vec[i] && typeid(*vec[i]) == typeid(T)) {
delete vec[i];
vec[i] = val;
return;
}
if (!val) return;
vec.push_back(val);
}
//______________________________________________________________________________
template<class T> void _lookupDynamic(T*& val, StSPtrVecObject &vec)
{
val = 0;
for (unsigned int i=0; i<vec.size(); i++)
if (vec[i]) {
val = dynamic_cast<T*>(vec[i]);
if (val) break;
}
}
//______________________________________________________________________________
template<class T> void _lookupDynamicAndSet(T* val, StSPtrVecObject &vec)
{
T *test;
for (unsigned int i=0; i<vec.size(); i++) {
if (vec[i]) {
test = dynamic_cast<T*>(vec[i]);
if (test) {
delete vec[i];
vec[i] = val;
return;
}
}
}
if (!val) return;
vec.push_back(val);
}
//______________________________________________________________________________
void StEvent::initToZero() { /* noop */ }
//______________________________________________________________________________
StEvent::StEvent() : StXRefMain("StEvent")
{
GenUUId(); //Generate Universally Unique IDentifier
initToZero();
}
//______________________________________________________________________________
StEvent::~StEvent()
{ /* noop */ }
TString
StEvent::type() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->type() : TString();
}
int
StEvent::id() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->id() : 0;
}
int
StEvent::runId() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->runId() : 0;
}
int
StEvent::time() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->time() : 0;
}
unsigned int
StEvent::triggerMask() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->triggerMask() : 0;
}
unsigned int
StEvent::bunchCrossingNumber(unsigned int i) const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info ? info->bunchCrossingNumber(i) : 0;
}
StEventInfo*
StEvent::info()
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info;
}
const StEventInfo*
StEvent::info() const
{
StEventInfo* info = 0;
_lookup(info, mContent);
return info;
}
StRunInfo*
StEvent::runInfo()
{
StRunInfo* info = 0;
_lookup(info, mContent);
return info;
}
const StRunInfo*
StEvent::runInfo() const
{
StRunInfo* info = 0;
_lookup(info, mContent);
return info;
}
StEventSummary*
StEvent::summary()
{
StEventSummary* summary = 0;
_lookup(summary, mContent);
return summary;
}
const StEventSummary*
StEvent::summary() const
{
StEventSummary* summary = 0;
_lookup(summary, mContent);
return summary;
}
const TString&
StEvent::cvsTag() { return mCvsTag; }
//______________________________________________________________________________
StTpcHitCollection* StEvent::tpcHitCollection()
{
StTpcHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
const StTpcHitCollection*
StEvent::tpcHitCollection() const
{
StTpcHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
StRnDHitCollection* StEvent::rndHitCollection()
{
StRnDHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
const StRnDHitCollection* StEvent::rndHitCollection() const
{
StRnDHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
const StEtrHitCollection* StEvent::etrHitCollection() const
{
StEtrHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
StEtrHitCollection* StEvent::etrHitCollection()
{
StEtrHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
//______________________________________________________________________________
StFtpcHitCollection* StEvent::ftpcHitCollection()
{
StFtpcHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
const StFtpcHitCollection*
StEvent::ftpcHitCollection() const
{
StFtpcHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
StSvtHitCollection*
StEvent::svtHitCollection()
{
StSvtHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
const StSvtHitCollection*
StEvent::svtHitCollection() const
{
StSvtHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
StSsdHitCollection*
StEvent::ssdHitCollection()
{
StSsdHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
const StSsdHitCollection*
StEvent::ssdHitCollection() const
{
StSsdHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
StSstHitCollection*
StEvent::sstHitCollection()
{
StSstHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
const StSstHitCollection*
StEvent::sstHitCollection() const
{
StSstHitCollection *hits = 0;
_lookup(hits, mContent);
return hits;
}
StEmcCollection*
StEvent::emcCollection()
{
StEmcCollection *emc = 0;
_lookup(emc, mContent);
return emc;
}
const StEmcCollection*
StEvent::emcCollection() const
{
StEmcCollection *emc = 0;
_lookup(emc, mContent);
return emc;
}
StFmsCollection*
StEvent::fmsCollection()
{
StFmsCollection *fms = 0;
_lookup(fms, mContent);
return fms;
}
const StFmsCollection*
StEvent::fmsCollection() const
{
StFmsCollection *fms = 0;
_lookup(fms, mContent);
return fms;
}
StRichCollection*
StEvent::richCollection()
{
StRichCollection *rich = 0;
_lookup(rich, mContent);
return rich;
}
const StRichCollection*
StEvent::richCollection() const
{
StRichCollection *rich = 0;
_lookup(rich, mContent);
return rich;
}
StRpsCollection*
StEvent::rpsCollection()
{
StRpsCollection *rps = 0;
_lookup(rps, mContent);
return rps;
}
const StRpsCollection*
StEvent::rpsCollection() const
{
StRpsCollection *rps = 0;
_lookup(rps, mContent);
return rps;
}
StTofCollection*
StEvent::tofCollection()
{
StTofCollection *tof = 0;
_lookup(tof, mContent);
return tof;
}
const StTofCollection*
StEvent::tofCollection() const
{
StTofCollection *tof = 0;
_lookup(tof, mContent);
return tof;
}
StBTofCollection*
StEvent::btofCollection()
{
StBTofCollection *btof = 0;
_lookup(btof, mContent);
return btof;
}
const StBTofCollection*
StEvent::btofCollection() const
{
StBTofCollection *btof = 0;
_lookup(btof, mContent);
return btof;
}
StEpdCollection*
StEvent::epdCollection()
{
StEpdCollection *epd = 0;
_lookup(epd, mContent);
return epd;
}
const StEpdCollection*
StEvent::epdCollection() const
{
StEpdCollection *epd = 0;
_lookup(epd, mContent);
return epd;
}
StMtdCollection*
StEvent::mtdCollection()
{
StMtdCollection *mtd = 0;
_lookup(mtd, mContent);
return mtd;
}
const StMtdCollection*
StEvent::mtdCollection() const
{
StMtdCollection *mtd = 0;
_lookup(mtd, mContent);
return mtd;
}
StFpdCollection*
StEvent::fpdCollection()
{
StFpdCollection *fpd = 0;
_lookup(fpd, mContent);
return fpd;
}
const StFpdCollection*
StEvent::fpdCollection() const
{
StFpdCollection *fpd = 0;
_lookup(fpd, mContent);
return fpd;
}
StPhmdCollection*
StEvent::phmdCollection()
{
StPhmdCollection *phmd = 0;
_lookup(phmd, mContent);
return phmd;
}
const StPhmdCollection*
StEvent::phmdCollection() const
{
StPhmdCollection *phmd = 0;
_lookup(phmd, mContent);
return phmd;
}
StTriggerDetectorCollection*
StEvent::triggerDetectorCollection()
{
StTriggerDetectorCollection *trg = 0;
_lookup(trg, mContent);
return trg;
}
const StTriggerDetectorCollection*
StEvent::triggerDetectorCollection() const
{
StTriggerDetectorCollection *trg = 0;
_lookup(trg, mContent);
return trg;
}
StTriggerIdCollection*
StEvent::triggerIdCollection()
{
StTriggerIdCollection *trg = 0;
_lookup(trg, mContent);
return trg;
}
const StTriggerIdCollection*
StEvent::triggerIdCollection() const
{
StTriggerIdCollection *trg = 0;
_lookup(trg, mContent);
return trg;
}
StTriggerData*
StEvent::triggerData()
{
StTriggerData *trg = 0;
_lookupDynamic(trg, mContent);
return trg;
}
const StTriggerData*
StEvent::triggerData() const
{
StTriggerData *trg = 0;
_lookupDynamic(trg, mContent);
return trg;
}
StL0Trigger*
StEvent::l0Trigger()
{
StL0Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
const StL0Trigger*
StEvent::l0Trigger() const
{
StL0Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
StL1Trigger*
StEvent::l1Trigger()
{
StL1Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
const StL1Trigger*
StEvent::l1Trigger() const
{
StL1Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
StL3Trigger*
StEvent::l3Trigger()
{
StL3Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
const StL3Trigger*
StEvent::l3Trigger() const
{
StL3Trigger *trg = 0;
_lookup(trg, mContent);
return trg;
}
StHltEvent*
StEvent::hltEvent()
{
StHltEvent *hlt = 0;
_lookup(hlt, mContent);
return hlt;
}
const StHltEvent*
StEvent::hltEvent() const
{
StHltEvent *hlt = 0;
_lookup(hlt, mContent);
return hlt;
}
StFgtCollection*
StEvent::fgtCollection()
{
StFgtCollection *fgtCollection = 0;
_lookup(fgtCollection, mContent);
return fgtCollection;
}
const StFgtCollection*
StEvent::fgtCollection() const
{
StFgtCollection *fgtCollection = 0;
_lookup(fgtCollection, mContent);
return fgtCollection;
}
StIstHitCollection*
StEvent::istHitCollection()
{
StIstHitCollection *istHitCollection = 0;
_lookup(istHitCollection, mContent);
return istHitCollection;
}
const StIstHitCollection*
StEvent::istHitCollection() const
{
StIstHitCollection *istHitCollection = 0;
_lookup(istHitCollection, mContent);
return istHitCollection;
}
StPxlHitCollection*
StEvent::pxlHitCollection()
{
StPxlHitCollection *pxlHitCollection = 0;
_lookup(pxlHitCollection, mContent);
return pxlHitCollection;
}
const StPxlHitCollection*
StEvent::pxlHitCollection() const
{
StPxlHitCollection *pxlHitCollection = 0;
_lookup(pxlHitCollection, mContent);
return pxlHitCollection;
}
StSPtrVecTrackDetectorInfo&
StEvent::trackDetectorInfo()
{
StSPtrVecTrackDetectorInfo *info = 0;
_lookupOrCreate(info, mContent);
return *info;
}
const StSPtrVecTrackDetectorInfo&
StEvent::trackDetectorInfo() const
{
StSPtrVecTrackDetectorInfo *info = 0;
_lookupOrCreate(info, mContent);
return *info;
}
StSPtrVecTrackNode&
StEvent::trackNodes()
{
StSPtrVecTrackNode *nodes = 0;
_lookupOrCreate(nodes, mContent);
return *nodes;
}
const StSPtrVecTrackNode&
StEvent::trackNodes() const
{
StSPtrVecTrackNode *nodes = 0;
_lookupOrCreate(nodes, mContent);
return *nodes;
}
unsigned int
StEvent::numberOfPrimaryVertices() const
{
StSPtrVecPrimaryVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return vertices ? vertices->size() : 0;
}
StPrimaryVertex*
StEvent::primaryVertex(unsigned int i)
{
StSPtrVecPrimaryVertex *vertices = 0;
_lookup(vertices, mContent);
if (vertices && i < vertices->size())
return (*vertices)[i];
else
return 0;
}
const StPrimaryVertex*
StEvent::primaryVertex(unsigned int i) const
{
StSPtrVecPrimaryVertex *vertices = 0;
_lookup(vertices, mContent);
if (vertices && i < vertices->size())
return (*vertices)[i];
else
return 0;
}
unsigned int
StEvent::numberOfCalibrationVertices() const
{
StSPtrVecCalibrationVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return vertices ? vertices->size() : 0;
}
StCalibrationVertex*
StEvent::calibrationVertex(unsigned int i)
{
StSPtrVecCalibrationVertex *vertices = 0;
_lookup(vertices, mContent);
if (vertices && i < vertices->size())
return (*vertices)[i];
else
return 0;
}
const StCalibrationVertex*
StEvent::calibrationVertex(unsigned int i) const
{
StSPtrVecCalibrationVertex *vertices = 0;
_lookup(vertices, mContent);
if (vertices && i < vertices->size())
return (*vertices)[i];
else
return 0;
}
StSPtrVecV0Vertex&
StEvent::v0Vertices()
{
StSPtrVecV0Vertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
const StSPtrVecV0Vertex&
StEvent::v0Vertices() const
{
StSPtrVecV0Vertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
StSPtrVecXiVertex&
StEvent::xiVertices()
{
StSPtrVecXiVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
const StSPtrVecXiVertex&
StEvent::xiVertices() const
{
StSPtrVecXiVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
StSPtrVecKinkVertex&
StEvent::kinkVertices()
{
StSPtrVecKinkVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
const StSPtrVecKinkVertex&
StEvent::kinkVertices() const
{
StSPtrVecKinkVertex *vertices = 0;
_lookupOrCreate(vertices, mContent);
return *vertices;
}
StDetectorState*
StEvent::detectorState(StDetectorId det)
{
StSPtrVecDetectorState *states = 0;
_lookup(states, mContent);
if (states)
for (unsigned int i=0; i<states->size(); i++)
if ((*states)[i]->detector() == det) return (*states)[i];
return 0;
}
const StDetectorState*
StEvent::detectorState(StDetectorId det) const
{
StSPtrVecDetectorState *states = 0;
_lookup(states, mContent);
if (states)
for (unsigned int i=0; i<states->size(); i++)
if ((*states)[i]->detector() == det) return (*states)[i];
return 0;
}
StPsd*
StEvent::psd(StPwg p, int i)
{
StPsd *thePsd = 0;
for (unsigned int k=0; k<mContent.size(); k++) {
thePsd = dynamic_cast<StPsd*>(mContent[k]);
if (thePsd && thePsd->pwg() == p && thePsd->id() == i)
return thePsd;
}
return 0;
}
const StPsd*
StEvent::psd(StPwg p, int i) const
{
const StPsd *thePsd = 0;
for (unsigned int k=0; k<mContent.size(); k++) {
thePsd = dynamic_cast<StPsd*>(mContent[k]);
if (thePsd && thePsd->pwg() == p && thePsd->id() == i)
return thePsd;
}
return 0;
}
unsigned int
StEvent::numberOfPsds() const
{
int nPsds = 0;
for (unsigned int i=0; i<mContent.size(); i++)
if (dynamic_cast<StPsd*>(mContent[i])) nPsds++;
return nPsds;
}
unsigned int
StEvent::numberOfPsds(StPwg p) const
{
StPsd* thePsd;
int nPsds = 0;
for (unsigned int i=0; i<mContent.size(); i++) {
thePsd = dynamic_cast<StPsd*>(mContent[i]);
if (thePsd && thePsd->pwg() == p) nPsds++;
}
return nPsds;
}
StSPtrVecObject&
StEvent::content() { return mContent; }
const StEventClusteringHints*
StEvent::clusteringHints() const
{
StEventClusteringHints *hints = 0;
_lookupOrCreate(hints, mContent);
return hints;
}
StEventClusteringHints*
StEvent::clusteringHints()
{
StEventClusteringHints *hints = 0;
_lookupOrCreate(hints, mContent);
hints->SetParent(this);
return hints;
}
void
StEvent::setType(const char* val)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setType(val);
}
void
StEvent::setRunId(int val)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setRunId(val);
}
void
StEvent::setId(int val)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setId(val);
}
void
StEvent::setTime(int val)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setTime(val);
}
void
StEvent::setTriggerMask(unsigned int val)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setTriggerMask(val);
}
void
StEvent::setBunchCrossingNumber(unsigned int val, unsigned int i)
{
StEventInfo* info = 0;
_lookupOrCreate(info, mContent);
info->setBunchCrossingNumber(val, i);
}
void
StEvent::setInfo(StEventInfo* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setRunInfo(StRunInfo* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setSummary(StEventSummary* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setTpcHitCollection(StTpcHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setRnDHitCollection(StRnDHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setFtpcHitCollection(StFtpcHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setSvtHitCollection(StSvtHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setSsdHitCollection(StSsdHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setSstHitCollection(StSstHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setEmcCollection(StEmcCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setFmsCollection(StFmsCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setRichCollection(StRichCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setRpsCollection(StRpsCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setTofCollection(StTofCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setBTofCollection(StBTofCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setEpdCollection(StEpdCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setMtdCollection(StMtdCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setFpdCollection(StFpdCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setPhmdCollection(StPhmdCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setTriggerDetectorCollection(StTriggerDetectorCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setTriggerIdCollection(StTriggerIdCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setTriggerData(StTriggerData* val)
{
_lookupDynamicAndSet(val, mContent);
}
void
StEvent::setL0Trigger(StL0Trigger* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setL1Trigger(StL1Trigger* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setL3Trigger(StL3Trigger* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setEtrHitCollection(StEtrHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setHltEvent(StHltEvent* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setFgtCollection(StFgtCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setIstHitCollection(StIstHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::setPxlHitCollection(StPxlHitCollection* val)
{
_lookupAndSet(val, mContent);
}
void
StEvent::addPrimaryVertex(StPrimaryVertex* vertex, StPrimaryVertexOrder order)
{
if (!vertex) return; // not a valid vertex, do nothing
//
// Add the vertex
//
StSPtrVecPrimaryVertex* vertexVector = 0;
_lookupOrCreate(vertexVector, mContent);
vertexVector->push_back(vertex);
//
// Sort vertices.
// New vertex is last entry. We simply toggle through
// the container starting at the back until the new entry
// sits in place. Sorting strategy is given by
// enumeration StPrimaryVertexOrder.
//
int i;
switch (order) {
case(orderByNumberOfDaughters):
for (i=vertexVector->size()-1; i>0; i--) {
if ((*vertexVector)[i]->numberOfDaughters() > (*vertexVector)[i-1]->numberOfDaughters())
swap((*vertexVector)[i], (*vertexVector)[i-1]);
else
break;
}
break;
case(orderByRanking):
default:
for (i=vertexVector->size()-1; i>0; i--) {
if ((*vertexVector)[i]->ranking() > (*vertexVector)[i-1]->ranking())
swap((*vertexVector)[i], (*vertexVector)[i-1]);
else
break;
}
break;
}
}
void
StEvent::addCalibrationVertex(StCalibrationVertex* vertex)
{
if (vertex) {
StSPtrVecCalibrationVertex* vertexVector = 0;
_lookupOrCreate(vertexVector, mContent);
vertexVector->push_back(vertex);
}
}
void
StEvent::addDetectorState(StDetectorState *state)
{
if (state) {
StSPtrVecDetectorState* stateVector = 0;
_lookupOrCreate(stateVector, mContent);
stateVector->push_back(state);
}
}
void
StEvent::addPsd(StPsd* p)
{
if (p) {
if (psd(p->pwg(), p->id()))
cerr << "StEvent::addPsd(): Error, PSD with same identifiers already exist. Nothing added." << endl;
else
mContent.push_back(p);
}
}
void StEvent::removePsd(StPsd* p)
{
StSPtrVecObjectIterator iter;
if (p) {
for (iter = mContent.begin(); iter != mContent.end(); iter++)
if (*iter == p)
mContent.erase(iter);
}
}
void StEvent::Browse(TBrowser* b)
{
if (!b) b = new TBrowser("StEvent",(TObject*)0);
StAutoBrowse::Browse(this,b);
TDataSet::Browse(b);
}
void StEvent::statistics()
{
cout << "Statistics and information for event " << id() << endl;
cout << "\tthis: " << static_cast<void*>(this) << endl;
// cout << "\tcvsTag: " << cvsTag() << endl;
cout << "\ttype: " << type() << endl;
cout << "\tid: " << id() << endl;
cout << "\trunId: " << runId() << endl;
cout << "\ttime: " << time() << endl;
cout << "\ttriggerMask: " << triggerMask() << endl;
cout << "\tbunchCrossingNumber(0): " << bunchCrossingNumber(0) << endl;
cout << "\tbunchCrossingNumber(1): " << bunchCrossingNumber(1) << endl;
cout << "\tStEventSummary: " << static_cast<void*>(summary());
cout << "\tStTpcHitCollection: " << static_cast<void*>(tpcHitCollection());
cout << "\tStRnDHitCollection: " << static_cast<void*>(rndHitCollection());
cout << "\tStFtpcHitCollection: " << static_cast<void*>(ftpcHitCollection());
cout << "\tStSvtHitCollection: " << static_cast<void*>(svtHitCollection());
cout << "\tStSsdHitCollection: " << static_cast<void*>(ssdHitCollection());
cout << "\tStSstHitCollection: " << static_cast<void*>(sstHitCollection());
cout << "\tStIstHitCollection: " << static_cast<void*>(istHitCollection());
cout << "\tStPxlHitCollection: " << static_cast<void*>(pxlHitCollection());
cout << "\tStEmcCollection: " << static_cast<void*>(emcCollection());
cout << "\tStFmsCollection: " << static_cast<void*>(fmsCollection());
cout << "\tStRichCollection: " << static_cast<void*>(richCollection());
cout << "\tStRpsCollection: " << static_cast<void*>(rpsCollection());
cout << "\tStTofCollection: " << static_cast<void*>(tofCollection());
cout << "\tStBTofCollection: " << static_cast<void*>(btofCollection());
cout << "\tStEpdCollection: " << static_cast<void*>(epdCollection());
cout << "\tStMtdCollection: " << static_cast<void*>(mtdCollection());
cout << "\tStFpdCollection: " << static_cast<void*>(fpdCollection());
cout << "\tStPhmdCollection: " << static_cast<void*>(phmdCollection());
cout << "\tStL0Trigger: " << static_cast<void*>(l0Trigger());
cout << "\tStL1Trigger: " << static_cast<void*>(l0Trigger());
cout << "\tStL3Trigger: " << static_cast<void*>(l3Trigger());
cout << "\tStHltEvent: " << static_cast<void*>(hltEvent());
cout << "\tStTriggerDetectorCollection: " << static_cast<void*>(triggerDetectorCollection());
cout << "\tStTriggerIdCollection: " << static_cast<void*>(triggerIdCollection());
cout << "\tStTriggerData: " << static_cast<void*>(triggerData());
cout << "\tStPrimaryVertex: " << static_cast<void*>(primaryVertex(0));
cout << "\tnumberOfPrimaryVertices: " << numberOfPrimaryVertices() << endl;
cout << "\tStCalibrationVertex: " << static_cast<void*>(calibrationVertex(0));
cout << "\tnumberOfCalibrationVertices: " << numberOfCalibrationVertices() << endl;
cout << "\t# of TPC hits: " << (tpcHitCollection() ? tpcHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of FTPC hits: " << (ftpcHitCollection() ? ftpcHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of SVT hits: " << (svtHitCollection() ? svtHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of SSD hits: " << (ssdHitCollection() ? ssdHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of IST hits: " << (istHitCollection() ? istHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of PXL hits: " << (pxlHitCollection() ? pxlHitCollection()->numberOfHits() : 0) << endl;
cout << "\t# of track nodes: " << trackNodes().size() << endl;
cout << "\t# of primary tracks: " << (primaryVertex(0) ? primaryVertex(0)->numberOfDaughters() : 0) << endl;
cout << "\t# of V0s: " << v0Vertices().size() << endl;
cout << "\t# of Xis: " << xiVertices().size() << endl;
cout << "\t# of Kinks: " << kinkVertices().size() << endl;
cout << "\t# of hits in EMC: " << (emcCollection() ? emcCollection()->barrelPoints().size() : 0) << endl;
cout << "\t# of hits in EEMC: " << (emcCollection() ? emcCollection()->endcapPoints().size() : 0) << endl;
cout << "\t# of hits in FGT: " << (fgtCollection() ? fgtCollection()->getNumHits() : 0) << endl;
cout << "\t# of hits in RICH: " << (richCollection() ? richCollection()->getRichHits().size() : 0) << endl;
cout << "\t# of PSDs: " << numberOfPsds() << endl;
}
void StEvent::Split()
{
StEventClusteringHints *clu = clusteringHints();
assert(clu);
TDataSetIter next(this);
TDataSet *ds;
// Delete all the old EventBranches
while ((ds=next())) {
if (ds->IsA()!=StEventBranch::Class()) continue;
Remove(ds); delete ds;
}
vector<string> brs = clu->listOfBranches(); // list of all branches for given mode (miniDST or DST)
int nbrs = brs.size();
for (int ibr =0; ibr < nbrs; ibr++) { //loop over branches
string sbr = brs[ibr];
if(sbr.size()==0) continue;
const char *brName = sbr.c_str();
assert(strncmp(brName,"evt_",4)==0 || strcmp(brName,"event")==0);
UInt_t tally = ((clu->branchId(brName)) << 22) | 1 ;
StEventBranch *obr = new StEventBranch(brName,this,tally);
vector<string> cls = clu->listOfClasses(sbr.c_str());
int ncls = cls.size();
for (int icl =0; icl < ncls; icl++) { //loop over clases
string scl = cls[icl];
if(scl.size()==0) continue;
obr->AddKlass(scl.c_str());
} //end clases
} //end branches
}
Bool_t StEvent::Notify() {Split();return 0;}
void StEvent::Streamer(TBuffer &R__b)
{
// Stream an object of class StEvent.
UInt_t R__s, R__c;
if (R__b.IsReading()) {
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v == 1) {
TDataSet::Streamer(R__b);
mContent.Streamer(R__b);
R__b.CheckByteCount(R__s, R__c, Class());
Split();
return;
}
else { // version >=2
StXRefMain::Streamer(R__b);
R__b.CheckByteCount(R__s, R__c, Class());
}
}
else /*writing*/ {
TDataSetIter next(this);
TDataSet *ds;
while ((ds=next())) {
if (ds->IsA()==StEventBranch::Class()) break;
}
if (!ds) {//Not splited yet
Split();}
R__c = R__b.WriteVersion(Class(), kTRUE);
StXRefMain::Streamer(R__b);
R__b.SetByteCount(R__c, kTRUE);
}
}
//________________________________________________________________________________
StSPtrVecHit* StEvent::hitCollection(const Char_t *name) {
StSPtrVecHit *theHitCollection = 0;
TObjectSet *set = (TObjectSet *) FindByName(name);
if (set) theHitCollection = (StSPtrVecHit *) set->GetObject();
return theHitCollection;
}
//________________________________________________________________________________
void StEvent::addHitCollection(StSPtrVecHit* p, const Char_t *name) {
if (p) {
TObjectSet *set = (TObjectSet *) FindByName(name);
if (set)
cerr << "StEvent::addHitCollection(): Error, HitCollection with "
<< name << " already exist. Nothing added." << endl;
else {
set = new TObjectSet(name,p,kTRUE);
Add(set);
}
}
}
//________________________________________________________________________________
void StEvent::removeHitCollection(const Char_t *name) {
TObjectSet *set = (TObjectSet *) FindByName(name);
if (set) set->Delete();
}
//________________________________________________________________________________
void StEvent::setIdTruth() {
StSPtrVecTrackNode& trackNode = trackNodes();
UInt_t nTracks = trackNode.size();
StTrackNode *node=0;
for (UInt_t i = 0; i < nTracks; i++) {
node = trackNode[i];
if (!node) continue;
UInt_t notr = node->entries();
for (UInt_t t = 0; t < notr; t++) {
StTrack *track = node->track(t);
track->setIdTruth();
}
}
// loop over all type of vertices
Int_t noOfPrimaryVertices = numberOfPrimaryVertices();
for (Int_t i = 0; i < noOfPrimaryVertices; i++) primaryVertex(i)->setIdTruth();
Int_t noOfCalibrationVertices = numberOfCalibrationVertices();
for (Int_t i = 0; i < noOfCalibrationVertices; i++) calibrationVertex(i)->setIdTruth();
Int_t noOfv0Vertices = v0Vertices().size();
for (Int_t i = 0; i < noOfv0Vertices; i++) ((StVertex *) v0Vertices()[i])->setIdTruth();
Int_t noOfxiVertices = xiVertices().size();
for (Int_t i = 0; i < noOfxiVertices; i++) ((StVertex *) xiVertices()[i])->setIdTruth();
Int_t noOfkinkVertices = kinkVertices().size();
for (Int_t i = 0; i < noOfkinkVertices; i++) ((StVertex *) kinkVertices()[i])->setIdTruth();
}
| 24.787154 | 121 | 0.65863 | [
"object",
"vector"
] |
20d16f1d3fd08547bdadd2edd55428346caf0b74 | 6,271 | cpp | C++ | snippets/cpp/VS_Snippets_Winforms/MyDataGridClass_FlatMode_ReadOnly/CPP/mydatagridclass_flatmode_readonly.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 834 | 2017-06-24T10:40:36.000Z | 2022-03-31T19:48:51.000Z | snippets/cpp/VS_Snippets_Winforms/MyDataGridClass_FlatMode_ReadOnly/CPP/mydatagridclass_flatmode_readonly.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 7,042 | 2017-06-23T22:34:47.000Z | 2022-03-31T23:05:23.000Z | snippets/cpp/VS_Snippets_Winforms/MyDataGridClass_FlatMode_ReadOnly/CPP/mydatagridclass_flatmode_readonly.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 1,640 | 2017-06-23T22:31:39.000Z | 2022-03-31T02:45:37.000Z | // System::Windows::Forms::DataGrid::ReadOnlyChanged
// System::Windows::Forms::DataGrid::FlatModeChanged
/* The following program demonstrates the methods 'ReadOnlyChanged' and
'FlatModeChanged' of the 'DataGrid' class. It creates a
'GridControl' and checks the properties 'ReadOnly' and 'FlatMode'
of data grid, depending on the selection of buttons.
*/
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
public ref class MyDataGridClass_FlatMode_ReadOnly: public Form
{
private:
DataGrid^ myDataGrid;
Button^ button1;
Button^ button2;
DataSet^ myDataSet;
System::ComponentModel::Container^ components;
public:
MyDataGridClass_FlatMode_ReadOnly()
{
components = nullptr;
InitializeComponent();
SetUp();
}
public:
~MyDataGridClass_FlatMode_ReadOnly()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->FormBorderStyle = ::FormBorderStyle::FixedDialog;
this->myDataGrid = gcnew DataGrid;
this->button1 = gcnew Button;
this->button2 = gcnew Button;
(dynamic_cast<ISupportInitialize^>(this->myDataGrid))->BeginInit();
this->SuspendLayout();
//
// myDataGrid
//
this->myDataGrid->CaptionText = "My Grid Control";
this->myDataGrid->DataMember = "";
this->myDataGrid->Location = Point(16,16);
this->myDataGrid->Name = "myDataGrid";
this->myDataGrid->Size = System::Drawing::Size( 168, 112 );
this->myDataGrid->TabIndex = 0;
AttachFlatModeChanged();
AttachReadOnlyChanged();
//
// button1
//
this->button1->Location = Point(24,160);
this->button1->Name = "button1";
this->button1->Size = System::Drawing::Size( 72, 40 );
this->button1->TabIndex = 1;
this->button1->Text = "Toggle Flat Mode";
this->button1->Click += gcnew EventHandler( this, &MyDataGridClass_FlatMode_ReadOnly::button1_Click );
//
// button2
//
this->button2->Location = Point(96,160);
this->button2->Name = "button2";
this->button2->Size = System::Drawing::Size( 72, 40 );
this->button2->TabIndex = 1;
this->button2->Text = "Toggle Read Only";
this->button2->Click += gcnew EventHandler( this, &MyDataGridClass_FlatMode_ReadOnly::button2_Click );
//
// MyDataGridClass_FlatMode_ReadOnly
//
this->ClientSize = System::Drawing::Size( 208, 205 );
array<Control^>^temp0 = {this->button1,this->myDataGrid,this->button2};
this->Controls->AddRange( temp0 );
this->MaximizeBox = false;
this->Name = "MyDataGridClass_FlatMode_ReadOnly";
this->Text = "Grid Control";
(dynamic_cast<ISupportInitialize^>(this->myDataGrid))->EndInit();
this->ResumeLayout( false );
}
void SetUp()
{
MakeDataSet();
myDataGrid->SetDataBinding( myDataSet, "Customers" );
}
void MakeDataSet()
{
// Create a DataSet.
myDataSet = gcnew DataSet( "myDataSet" );
// Create a DataTable.
DataTable^ myTable = gcnew DataTable( "Customers" );
// Create two columns, and add them to the table.
DataColumn^ myColumn1 = gcnew DataColumn( "CustID",int::typeid );
DataColumn^ myColumn2 = gcnew DataColumn( "CustName" );
myTable->Columns->Add( myColumn1 );
myTable->Columns->Add( myColumn2 );
// Add the table to the DataSet.
myDataSet->Tables->Add( myTable );
// For the customer, create a 'DataRow' variable.
DataRow^ newRow;
// Create one customer in the customers table.
for ( int i = 1; i < 2; i++ )
{
newRow = myTable->NewRow();
newRow[ "custID" ] = i;
// Add the row to the 'Customers' table.
myTable->Rows->Add( newRow );
}
myTable->Rows[ 0 ][ "custName" ] = "Customer";
}
// <Snippet1>
// Attach to event handler.
private:
void AttachFlatModeChanged()
{
this->myDataGrid->FlatModeChanged +=
gcnew EventHandler( this, &MyDataGridClass_FlatMode_ReadOnly::myDataGrid_FlatModeChanged );
}
// Check if the 'FlatMode' property is changed.
void myDataGrid_FlatModeChanged( Object^ /*sender*/, EventArgs^ /*e*/ )
{
String^ strMessage = "false";
if ( myDataGrid->FlatMode == true )
strMessage = "true";
MessageBox::Show( "Flat mode changed to " + strMessage, "Message", MessageBoxButtons::OK, MessageBoxIcon::Exclamation );
}
// Toggle the 'FlatMode'.
void button1_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
if ( myDataGrid->FlatMode == true )
myDataGrid->FlatMode = false;
else
myDataGrid->FlatMode = true;
}
// </Snippet1>
// <Snippet2>
// Attach to event handler.
private:
void AttachReadOnlyChanged()
{
this->myDataGrid->ReadOnlyChanged += gcnew EventHandler( this, &MyDataGridClass_FlatMode_ReadOnly::myDataGrid_ReadOnlyChanged );
}
// Check if the 'ReadOnly' property is changed.
void myDataGrid_ReadOnlyChanged( Object^ /*sender*/, EventArgs^ /*e*/ )
{
String^ strMessage = "false";
if ( myDataGrid->ReadOnly == true )
strMessage = "true";
MessageBox::Show( "Read only changed to " + strMessage, "Message", MessageBoxButtons::OK, MessageBoxIcon::Exclamation );
}
// Toggle the 'ReadOnly' property.
void button2_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
if ( myDataGrid->ReadOnly == true )
myDataGrid->ReadOnly = false;
else
myDataGrid->ReadOnly = true;
}
// </Snippet2>
};
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
int main()
{
Application::Run( gcnew MyDataGridClass_FlatMode_ReadOnly );
}
| 29.303738 | 134 | 0.634668 | [
"object"
] |
20dca2c64c7473753d737b0763126c43d9e9c483 | 39,647 | hpp | C++ | blog_code/ctcheckmm.hpp | pkeir/ctcheckmm | 92351688f0c6d94c398f27e3efa7b9313ff85bd2 | [
"CC0-1.0"
] | 2 | 2020-12-01T16:47:15.000Z | 2021-08-10T02:18:14.000Z | blog_code/ctcheckmm.hpp | pkeir/ctcheckmm | 92351688f0c6d94c398f27e3efa7b9313ff85bd2 | [
"CC0-1.0"
] | null | null | null | blog_code/ctcheckmm.hpp | pkeir/ctcheckmm | 92351688f0c6d94c398f27e3efa7b9313ff85bd2 | [
"CC0-1.0"
] | null | null | null | // Compile-time Metamath database verifier
// Paul Keir, University of the West of Scotland
//
// This code is released to the public domain under the
// Creative Commons "CC0 1.0 Universal" Public Domain Dedication:
//
// http://creativecommons.org/publicdomain/zero/1.0/
//
// This is a C++20 standalone verifier for Metamath database files based on
// Eric Schmidt's original version (available at
// http://us.metamath.org/downloads/checkmm.cpp).
// To verify a database at runtime, the program may be run with a single file
// path as the parameter. In addition, to verify a database at compile-time,
// compile the program with MMFILEPATH defined as the path to a file containing
// a Metamath database encoded as a C++11 style raw string literal. The
// trivial delimit.sh bash script is provided to help convert database files to
// this format.
#include "cest/algorithm.hpp"
#include "cest/cctype.hpp"
#include "cest/cstdlib.hpp"
#include "cest/deque.hpp"
#include "cest/fstream.hpp"
#include "cest/sstream.hpp"
#include "cest/iostream.hpp"
#include "cest/iterator.hpp"
#include "cest/limits.hpp"
#include "cest/map.hpp"
#include "cest/queue.hpp"
#include "cest/set.hpp"
#include "cest/string.hpp"
#include "cest/vector.hpp"
#include "cest/utility.hpp"
namespace ns = cest;
struct checkmm
{
ns::queue<ns::string> tokens;
ns::set<ns::string> constants;
typedef ns::vector<ns::string> Expression;
// The first parameter is the statement of the hypothesis, the second is
// true iff the hypothesis is floating.
typedef ns::pair<Expression, bool> Hypothesis;
ns::map<ns::string, Hypothesis> hypotheses;
ns::set<ns::string> variables;
// An axiom or a theorem.
struct Assertion
{
// Hypotheses of this axiom or theorem.
ns::deque<ns::string> hypotheses;
ns::set<ns::pair<ns::string, ns::string> > disjvars;
// Statement of axiom or theorem.
Expression expression;
};
ns::map<ns::string, Assertion> assertions;
struct Scope
{
ns::set<ns::string> activevariables;
// Labels of active hypotheses
ns::vector<ns::string> activehyp;
ns::vector<ns::set<ns::string> > disjvars;
// Map from variable to label of active floating hypothesis
ns::map<ns::string, ns::string> floatinghyp;
};
ns::vector<Scope> scopes;
// Determine if a string is used as a label
inline constexpr bool labelused(ns::string const label)
{
return hypotheses.find(label) != hypotheses.end()
|| assertions.find(label) != assertions.end();
}
// Find active floating hypothesis corresponding to variable, or empty string
// if there isn't one.
constexpr ns::string getfloatinghyp(ns::string const var)
{
for (ns::vector<Scope>::const_iterator iter(scopes.begin());
iter != scopes.end(); ++iter)
{
ns::map<ns::string, ns::string>::const_iterator const loc
(iter->floatinghyp.find(var));
if (loc != iter->floatinghyp.end())
return loc->second;
}
return ns::string();
}
// Determine if a string is an active variable.
constexpr bool isactivevariable(ns::string const str)
{
for (ns::vector<Scope>::const_iterator iter(scopes.begin());
iter != scopes.end(); ++iter)
{
if (iter->activevariables.find(str) != iter->activevariables.end())
return true;
}
return false;
}
// Determine if a string is the label of an active hypothesis.
constexpr bool isactivehyp(ns::string const str)
{
for (ns::vector<Scope>::const_iterator iter(scopes.begin());
iter != scopes.end(); ++iter)
{
if (ns::find(iter->activehyp.begin(), iter->activehyp.end(), str)
!= iter->activehyp.end())
return true;
}
return false;
}
// Determine if there is an active disjoint variable restriction on
// two different variables.
constexpr bool isdvr(ns::string var1, ns::string var2)
{
if (var1 == var2)
return false;
for (ns::vector<Scope>::const_iterator iter(scopes.begin());
iter != scopes.end(); ++iter)
{
for (ns::vector<ns::set<ns::string> >::const_iterator iter2
(iter->disjvars.begin()); iter2 != iter->disjvars.end(); ++iter2)
{
if ( iter2->find(var1) != iter2->end()
&& iter2->find(var2) != iter2->end())
return true;
}
}
return false;
}
// Determine if a character is white space in Metamath.
inline constexpr bool ismmws(char const ch)
{
// This doesn't include \v ("vertical tab"), as the spec omits it.
return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f' || ch == '\r';
}
// Determine if a token is a label token.
constexpr bool islabeltoken(ns::string const token)
{
for (ns::string::const_iterator iter(token.begin()); iter != token.end();
++iter)
{
unsigned char const ch(*iter);
if (!(ns::isalnum(ch) || ch == '.' || ch == '-' || ch == '_'))
return false;
}
return true;
}
// Determine if a token is a math symbol token.
inline constexpr bool ismathsymboltoken(ns::string const token)
{
return token.find('$') == ns::string::npos;
}
// Determine if a token consists solely of upper-case letters or question marks
constexpr bool containsonlyupperorq(ns::string token)
{
for (ns::string::const_iterator iter(token.begin()); iter != token.end();
++iter)
{
if (!ns::isupper(*iter) && *iter != '?')
return false;
}
return true;
}
constexpr ns::string nexttoken(ns::istream & input)
{
char ch;
ns::string token;
// Skip whitespace
while (input.get(ch) && ismmws(ch)) { }
if (input.good())
input.unget();
// Get token
while (input.get(ch) && !ismmws(ch))
{
if (ch < '!' || ch > '~')
{
ns::cerr << "Invalid character read with code 0x";
ns::cerr << ns::hex << (unsigned int)(unsigned char)ch
<< ns::endl;
return ns::string();
}
token += ch;
}
if (!input.eof() && input.fail())
return ns::string();
return token;
}
// http://eel.is/c++draft/dcl.constexpr#3.5
// The definition of a constexpr function shall satisfy the following
// requirements:
// - its function-body shall not enclose ([stmt.pre])
// ...
// - a definition of a variable of non-literal type or of static or
// thread storage duration.
ns::set<ns::string> names;
constexpr bool readtokens(ns::string filename, ns::string const &text = "")
{
//static ns::set<ns::string> names;
bool const alreadyencountered(!names.insert(filename).second);
if (alreadyencountered)
return true;
ns::istringstream in;
if (!text.empty())
{
in.str(text);
}
else
{
bool okay = [&]() // lambda: non-literal values in dead constexpr paths
{
ns::ifstream file(filename.c_str());
if (!file)
return false;
ns::string str((ns::istreambuf_iterator(file)), {});
in.str(str);
return true;
}();
if (!okay)
{
ns::cerr << "Could not open " << filename << ns::endl;
return false;
}
}
bool incomment(false);
bool infileinclusion(false);
ns::string newfilename;
ns::string token;
while (!(token = nexttoken(in)).empty())
{
if (incomment)
{
if (token == "$)")
{
incomment = false;
continue;
}
if (token.find("$(") != ns::string::npos)
{
ns::cerr << "Characters $( found in a comment" << ns::endl;
return false;
}
if (token.find("$)") != ns::string::npos)
{
ns::cerr << "Characters $) found in a comment" << ns::endl;
return false;
}
continue;
}
// Not in comment
if (token == "$(")
{
incomment = true;
continue;
}
if (infileinclusion)
{
if (newfilename.empty())
{
if (token.find('$') != ns::string::npos)
{
ns::cerr << "Filename " << token << " contains a $"
<< ns::endl;
return false;
}
newfilename = token;
continue;
}
else
{
if (token != "$]")
{
ns::cerr << "Didn't find closing file inclusion delimiter"
<< ns::endl;
return false;
}
bool const okay(readtokens(newfilename));
if (!okay)
return false;
infileinclusion = false;
newfilename.clear();
continue;
}
}
if (token == "$[")
{
if (std::is_constant_evaluated()) {
throw std::runtime_error("File inclusion unsupported within constexpr evaluation.");
}
infileinclusion = true;
continue;
}
tokens.push(token);
}
if (!in.eof())
{
if (in.fail())
ns::cerr << "Error reading from " << filename << ns::endl;
return false;
}
if (incomment)
{
ns::cerr << "Unclosed comment" << ns::endl;
return false;
}
if (infileinclusion)
{
ns::cerr << "Unfinished file inclusion command" << ns::endl;
return false;
}
return true;
}
// Construct an Assertion from an Expression. That is, determine the
// mandatory hypotheses and disjoint variable restrictions.
// The Assertion is inserted into the assertions collection,
// and is returned by reference.
constexpr Assertion & constructassertion
(ns::string const label, Expression const & exp)
{
Assertion & assertion
(assertions.insert(ns::make_pair(label, Assertion())).first->second);
assertion.expression = exp;
ns::set<ns::string> varsused;
// Determine variables used and find mandatory hypotheses
for (Expression::const_iterator iter(exp.begin()); iter != exp.end();
++iter)
{
if (variables.find(*iter) != variables.end())
varsused.insert(*iter);
}
for (ns::vector<Scope>::const_reverse_iterator iter(scopes.rbegin());
iter != scopes.rend(); ++iter)
{
ns::vector<ns::string> const & hypvec(iter->activehyp);
for (ns::vector<ns::string>::const_reverse_iterator iter2
(hypvec.rbegin()); iter2 != hypvec.rend(); ++iter2)
{
Hypothesis const & hyp(hypotheses.find(*iter2)->second);
if (hyp.second && varsused.find(hyp.first[1]) != varsused.end())
{
// Mandatory floating hypothesis
assertion.hypotheses.push_front(*iter2);
}
else if (!hyp.second)
{
// Essential hypothesis
assertion.hypotheses.push_front(*iter2);
for (Expression::const_iterator iter3(hyp.first.begin());
iter3 != hyp.first.end(); ++iter3)
{
if (variables.find(*iter3) != variables.end())
varsused.insert(*iter3);
}
}
}
}
// Determine mandatory disjoint variable restrictions
for (ns::vector<Scope>::const_iterator iter(scopes.begin());
iter != scopes.end(); ++iter)
{
ns::vector<ns::set<ns::string> > const & disjvars(iter->disjvars);
for (ns::vector<ns::set<ns::string> >::const_iterator iter2
(disjvars.begin()); iter2 != disjvars.end(); ++iter2)
{
ns::set<ns::string> dset;
ns::set_intersection
(iter2->begin(), iter2->end(),
varsused.begin(), varsused.end(),
ns::inserter(dset, dset.end()));
for (ns::set<ns::string>::const_iterator diter(dset.begin());
diter != dset.end(); ++diter)
{
ns::set<ns::string>::const_iterator diter2(diter);
++diter2;
for (; diter2 != dset.end(); ++diter2)
assertion.disjvars.insert(ns::make_pair(*diter, *diter2));
}
}
}
return assertion;
}
// Read an expression from the token stream. Returns true iff okay.
constexpr bool readexpression
( char stattype, ns::string label, ns::string terminator,
Expression * exp)
{
if (tokens.empty())
{
ns::cerr << "Unfinished $" << stattype << " statement " << label
<< ns::endl;
return false;
}
ns::string type(tokens.front());
if (constants.find(type) == constants.end())
{
ns::cerr << "First symbol in $" << stattype << " statement " << label
<< " is " << type << " which is not a constant" << ns::endl;
return false;
}
tokens.pop();
exp->push_back(type);
ns::string token;
while (!tokens.empty() && (token = tokens.front()) != terminator)
{
tokens.pop();
if (constants.find(token) == constants.end()
&& getfloatinghyp(token).empty())
{
ns::cerr << "In $" << stattype << " statement " << label
<< " token " << token
<< " found which is not a constant or variable in an"
" active $f statement" << ns::endl;
return false;
}
exp->push_back(token);
}
if (tokens.empty())
{
ns::cerr << "Unfinished $" << stattype << " statement " << label
<< ns::endl;
return false;
}
tokens.pop(); // Discard terminator token
return true;
}
// Make a substitution of variables. The result is put in "destination",
// which should be empty.
constexpr void makesubstitution
(Expression const & original, ns::map<ns::string, Expression> substmap,
Expression * destination
)
{
for (Expression::const_iterator iter(original.begin());
iter != original.end(); ++iter)
{
ns::map<ns::string, Expression>::const_iterator const iter2
(substmap.find(*iter));
if (iter2 == substmap.end())
{
// Constant
destination->push_back(*iter);
}
else
{
// Variable
ns::copy(iter2->second.begin(), iter2->second.end(),
ns::back_inserter(*destination));
}
}
}
// Get the raw numbers from compressed proof format.
// The letter Z is translated as 0.
constexpr bool getproofnumbers(ns::string label, ns::string proof,
ns::vector<ns::size_t> * proofnumbers)
{
ns::size_t const size_max(ns::numeric_limits<ns::size_t>::max());
ns::size_t num(0u);
bool justgotnum(false);
for (ns::string::const_iterator iter(proof.begin()); iter != proof.end();
++iter)
{
if (*iter <= 'T')
{
ns::size_t const addval(*iter - ('A' - 1));
if (num > size_max / 20 || 20 * num > size_max - addval)
{
ns::cerr << "Overflow computing numbers in compressed proof "
"of " << label << ns::endl;
return false;
}
proofnumbers->push_back(20 * num + addval);
num = 0;
justgotnum = true;
}
else if (*iter <= 'Y')
{
ns::size_t const addval(*iter - 'T');
if (num > size_max / 5 || 5 * num > size_max - addval)
{
ns::cerr << "Overflow computing numbers in compressed proof "
"of " << label << ns::endl;
return false;
}
num = 5 * num + addval;
justgotnum = false;
}
else // It must be Z
{
if (!justgotnum)
{
ns::cerr << "Stray Z found in compressed proof of "
<< label << ns::endl;
return false;
}
proofnumbers->push_back(0);
justgotnum = false;
}
}
if (num != 0)
{
ns::cerr << "Compressed proof of theorem " << label
<< " ends in unfinished number" << ns::endl;
return false;
}
return true;
}
// Subroutine for proof verification. Verify a proof step referencing an
// assertion (i.e., not a hypothesis).
constexpr bool verifyassertionref
(ns::string thlabel, ns::string reflabel, ns::vector<Expression> * stack)
{
Assertion const & assertion(assertions.find(reflabel)->second);
if (stack->size() < assertion.hypotheses.size())
{
ns::cerr << "In proof of theorem " << thlabel
<< " not enough items found on stack" << ns::endl;
return false;
}
ns::vector<Expression>::size_type const base
(stack->size() - assertion.hypotheses.size());
ns::map<ns::string, Expression> substitutions;
// Determine substitutions and check that we can unify
for (ns::deque<ns::string>::size_type i(0);
i < assertion.hypotheses.size(); ++i)
{
Hypothesis const & hypothesis
(hypotheses.find(assertion.hypotheses[i])->second);
if (hypothesis.second)
{
// Floating hypothesis of the referenced assertion
if (hypothesis.first[0] != (*stack)[base + i][0])
{
ns::cout << "In proof of theorem " << thlabel
<< " unification failed" << ns::endl;
return false;
}
Expression & subst(substitutions.insert
(ns::make_pair(hypothesis.first[1],
Expression())).first->second);
ns::copy((*stack)[base + i].begin() + 1, (*stack)[base + i].end(),
ns::back_inserter(subst));
}
else
{
// Essential hypothesis
Expression dest;
makesubstitution(hypothesis.first, substitutions, &dest);
if (dest != (*stack)[base + i])
{
ns::cerr << "In proof of theorem " << thlabel
<< " unification failed" << ns::endl;
return false;
}
}
}
// Remove hypotheses from stack
stack->erase(stack->begin() + base, stack->end());
// Verify disjoint variable conditions
for (ns::set<ns::pair<ns::string, ns::string> >::const_iterator
iter(assertion.disjvars.begin());
iter != assertion.disjvars.end(); ++iter)
{
Expression const & exp1(substitutions.find(iter->first)->second);
Expression const & exp2(substitutions.find(iter->second)->second);
ns::set<ns::string> exp1vars;
for (Expression::const_iterator exp1iter(exp1.begin());
exp1iter != exp1.end(); ++exp1iter)
{
if (variables.find(*exp1iter) != variables.end())
exp1vars.insert(*exp1iter);
}
ns::set<ns::string> exp2vars;
for (Expression::const_iterator exp2iter(exp2.begin());
exp2iter != exp2.end(); ++exp2iter)
{
if (variables.find(*exp2iter) != variables.end())
exp2vars.insert(*exp2iter);
}
for (ns::set<ns::string>::const_iterator exp1iter
(exp1vars.begin()); exp1iter != exp1vars.end(); ++exp1iter)
{
for (ns::set<ns::string>::const_iterator exp2iter
(exp2vars.begin()); exp2iter != exp2vars.end(); ++exp2iter)
{
if (!isdvr(*exp1iter, *exp2iter))
{
ns::cerr << "In proof of theorem " << thlabel
<< " disjoint variable restriction violated"
<< ns::endl;
return false;
}
}
}
}
// Done verification of this step. Insert new statement onto stack.
Expression dest;
makesubstitution(assertion.expression, substitutions, &dest);
stack->push_back(dest);
return true;
}
// Verify a regular proof. The "proof" argument should be a non-empty sequence
// of valid labels. Return true iff the proof is correct.
constexpr bool verifyregularproof
(ns::string label, Assertion const & theorem,
ns::vector<ns::string> const & proof
)
{
ns::vector<Expression> stack;
for (ns::vector<ns::string>::const_iterator proofstep(proof.begin());
proofstep != proof.end(); ++proofstep)
{
// If step is a hypothesis, just push it onto the stack.
ns::map<ns::string, Hypothesis>::const_iterator hyp
(hypotheses.find(*proofstep));
if (hyp != hypotheses.end())
{
stack.push_back(hyp->second.first);
continue;
}
// It must be an axiom or theorem
bool const okay(verifyassertionref(label, *proofstep, &stack));
if (!okay)
return false;
}
if (stack.size() != 1)
{
ns::cerr << "Proof of theorem " << label
<< " does not end with only one item on the stack"
<< ns::endl;
return false;
}
if (stack[0] != theorem.expression)
{
ns::cerr << "Proof of theorem " << label << " proves wrong statement"
<< ns::endl;
}
return true;
}
// Verify a compressed proof
constexpr bool verifycompressedproof
(ns::string label, Assertion const & theorem,
ns::vector<ns::string> const & labels,
ns::vector<ns::size_t> const & proofnumbers)
{
ns::vector<Expression> stack;
ns::size_t const mandhypt(theorem.hypotheses.size());
ns::size_t const labelt(mandhypt + labels.size());
ns::vector<Expression> savedsteps;
for (ns::vector<ns::size_t>::const_iterator iter(proofnumbers.begin());
iter != proofnumbers.end(); ++iter)
{
// Save the last proof step if 0
if (*iter == 0)
{
savedsteps.push_back(stack.back());
continue;
}
// If step is a mandatory hypothesis, just push it onto the stack.
if (*iter <= mandhypt)
{
stack.push_back
(hypotheses.find(theorem.hypotheses[*iter - 1])->second.first);
}
else if (*iter <= labelt)
{
ns::string const proofstep(labels[*iter - mandhypt - 1]);
// If step is a (non-mandatory) hypothesis,
// just push it onto the stack.
ns::map<ns::string, Hypothesis>::const_iterator hyp
(hypotheses.find(proofstep));
if (hyp != hypotheses.end())
{
stack.push_back(hyp->second.first);
continue;
}
// It must be an axiom or theorem
bool const okay(verifyassertionref(label, proofstep, &stack));
if (!okay)
return false;
}
else // Must refer to saved step
{
if (*iter > labelt + savedsteps.size())
{
ns::cerr << "Number in compressed proof of " << label
<< " is too high" << ns::endl;
return false;
}
stack.push_back(savedsteps[*iter - labelt - 1]);
}
}
if (stack.size() != 1)
{
ns::cerr << "Proof of theorem " << label
<< " does not end with only one item on the stack"
<< ns::endl;
return false;
}
if (stack[0] != theorem.expression)
{
ns::cerr << "Proof of theorem " << label << " proves wrong statement"
<< ns::endl;
}
return true;
}
// Parse $p statement. Return true iff okay.
constexpr bool parsep(ns::string label)
{
Expression newtheorem;
bool const okay(readexpression('p', label, "$=", &newtheorem));
if (!okay)
{
return false;
}
Assertion const & assertion(constructassertion(label, newtheorem));
// Now for the proof
if (tokens.empty())
{
ns::cerr << "Unfinished $p statement " << label << ns::endl;
return false;
}
if (tokens.front() == "(")
{
// Compressed proof
tokens.pop();
// Get labels
ns::vector<ns::string> labels;
ns::string token;
while (!tokens.empty() && (token = tokens.front()) != ")")
{
tokens.pop();
labels.push_back(token);
if (token == label)
{
ns::cerr << "Proof of theorem " << label
<< " refers to itself" << ns::endl;
return false;
}
else if (ns::find
(assertion.hypotheses.begin(), assertion.hypotheses.end(),
token) != assertion.hypotheses.end())
{
ns::cerr << "Compressed proof of theorem " << label
<< " has mandatory hypothesis " << token
<< " in label list" << ns::endl;
return false;
}
else if (assertions.find(token) == assertions.end()
&& !isactivehyp(token))
{
ns::cerr << "Proof of theorem " << label << " refers to "
<< token << " which is not an active statement"
<< ns::endl;
return false;
}
}
if (tokens.empty())
{
ns::cerr << "Unfinished $p statement " << label << ns::endl;
return false;
}
tokens.pop(); // Discard ) token
// Get proof steps
ns::string proof;
while (!tokens.empty() && (token = tokens.front()) != "$.")
{
tokens.pop();
proof += token;
if (!containsonlyupperorq(token))
{
ns::cerr << "Bogus character found in compressed proof of "
<< label << ns::endl;
return false;
}
}
if (tokens.empty())
{
ns::cerr << "Unfinished $p statement " << label << ns::endl;
return false;
}
if (proof.empty())
{
ns::cerr << "Theorem " << label << " has no proof" << ns::endl;
return false;
}
tokens.pop(); // Discard $. token
if (proof.find('?') != ns::string::npos)
{
ns::cerr << "Warning: Proof of theorem " << label
<< " is incomplete" << ns::endl;
return true; // Continue processing file
}
ns::vector<ns::size_t> proofnumbers;
proofnumbers.reserve(proof.size()); // Preallocate for efficiency
bool okay(getproofnumbers(label, proof, &proofnumbers));
if (!okay)
return false;
okay = verifycompressedproof(label, assertion, labels, proofnumbers);
if (!okay)
return false;
}
else
{
// Regular (uncompressed proof)
ns::vector<ns::string> proof;
bool incomplete(false);
ns::string token;
while (!tokens.empty() && (token = tokens.front()) != "$.")
{
tokens.pop();
proof.push_back(token);
if (token == "?")
incomplete = true;
else if (token == label)
{
ns::cerr << "Proof of theorem " << label
<< " refers to itself" << ns::endl;
return false;
}
else if (assertions.find(token) == assertions.end()
&& !isactivehyp(token))
{
ns::cerr << "Proof of theorem " << label << " refers to "
<< token << " which is not an active statement"
<< ns::endl;
return false;
}
}
if (tokens.empty())
{
ns::cerr << "Unfinished $p statement " << label << ns::endl;
return false;
}
if (proof.empty())
{
ns::cerr << "Theorem " << label << " has no proof" << ns::endl;
return false;
}
tokens.pop(); // Discard $. token
if (incomplete)
{
ns::cerr << "Warning: Proof of theorem " << label
<< " is incomplete" << ns::endl;
return true; // Continue processing file
}
bool okay(verifyregularproof(label, assertion, proof));
if (!okay)
return false;
}
return true;
}
// Parse $e statement. Return true iff okay.
constexpr bool parsee(ns::string label)
{
Expression newhyp;
bool const okay(readexpression('e', label, "$.", &newhyp));
if (!okay)
{
return false;
}
// Create new essential hypothesis
hypotheses.insert(ns::make_pair(label, ns::make_pair(newhyp, false)));
scopes.back().activehyp.push_back(label);
return true;
}
// Parse $a statement. Return true iff okay.
constexpr bool parsea(ns::string label)
{
Expression newaxiom;
bool const okay(readexpression('a', label, "$.", &newaxiom));
if (!okay)
{
return false;
}
constructassertion(label, newaxiom);
return true;
}
// Parse $f statement. Return true iff okay.
constexpr bool parsef(ns::string label)
{
if (tokens.empty())
{
ns::cerr << "Unfinished $f statement" << label << ns::endl;
return false;
}
ns::string type(tokens.front());
if (constants.find(type) == constants.end())
{
ns::cerr << "First symbol in $f statement " << label << " is "
<< type << " which is not a constant" << ns::endl;
return false;
}
tokens.pop();
if (tokens.empty())
{
ns::cerr << "Unfinished $f statement " << label << ns::endl;
return false;
}
ns::string variable(tokens.front());
if (!isactivevariable(variable))
{
ns::cerr << "Second symbol in $f statement " << label << " is "
<< variable << " which is not an active variable"
<< ns::endl;
return false;
}
if (!getfloatinghyp(variable).empty())
{
ns::cerr << "The variable " << variable
<< " appears in a second $f statement "
<< label << ns::endl;
return false;
}
tokens.pop();
if (tokens.empty())
{
ns::cerr << "Unfinished $f statement" << label << ns::endl;
return false;
}
if (tokens.front() != "$.")
{
ns::cerr << "Expected end of $f statement " << label
<< " but found " << tokens.front() << ns::endl;
return false;
}
tokens.pop(); // Discard $. token
// Create new floating hypothesis
Expression newhyp;
newhyp.push_back(type);
newhyp.push_back(variable);
hypotheses.insert(ns::make_pair(label, ns::make_pair(newhyp, true)));
scopes.back().activehyp.push_back(label);
scopes.back().floatinghyp.insert(ns::make_pair(variable, label));
return true;
}
// Parse labeled statement. Return true iff okay.
constexpr bool parselabel(ns::string label)
{
if (constants.find(label) != constants.end())
{
ns::cerr << "Attempt to reuse constant " << label << " as a label"
<< ns::endl;
return false;
}
if (variables.find(label) != variables.end())
{
ns::cerr << "Attempt to reuse variable " << label << " as a label"
<< ns::endl;
return false;
}
if (labelused(label))
{
ns::cerr << "Attempt to reuse label " << label << ns::endl;
return false;
}
if (tokens.empty())
{
ns::cerr << "Unfinished labeled statement" << ns::endl;
return false;
}
ns::string const type(tokens.front());
tokens.pop();
bool okay(true);
if (type == "$p")
{
okay = parsep(label);
}
else if (type == "$e")
{
okay = parsee(label);
}
else if (type == "$a")
{
okay = parsea(label);
}
else if (type == "$f")
{
okay = parsef(label);
}
else
{
ns::cerr << "Unexpected token " << type << " encountered"
<< ns::endl;
return false;
}
return okay;
}
// Parse $d statement. Return true iff okay.
constexpr bool parsed()
{
ns::set<ns::string> dvars;
ns::string token;
while (!tokens.empty() && (token = tokens.front()) != "$.")
{
tokens.pop();
if (!isactivevariable(token))
{
ns::cerr << "Token " << token << " is not an active variable, "
<< "but was found in a $d statement" << ns::endl;
return false;
}
bool const duplicate(!dvars.insert(token).second);
if (duplicate)
{
ns::cerr << "$d statement mentions " << token << " twice"
<< ns::endl;
return false;
}
}
if (tokens.empty())
{
ns::cerr << "Unterminated $d statement" << ns::endl;
return false;
}
if (dvars.size() < 2)
{
ns::cerr << "Not enough items in $d statement" << ns::endl;
return false;
}
// Record it
scopes.back().disjvars.push_back(dvars);
tokens.pop(); // Discard $. token
return true;
}
// Parse $c statement. Return true iff okay.
constexpr bool parsec()
{
if (scopes.size() > 1)
{
ns::cerr << "$c statement occurs in inner block"
<< ns::endl;
return false;
}
ns::string token;
bool listempty(true);
while (!tokens.empty() && (token = tokens.front()) != "$.")
{
tokens.pop();
listempty = false;
if (!ismathsymboltoken(token))
{
ns::cerr << "Attempt to declare " << token
<< " as a constant" << ns::endl;
return false;
}
if (variables.find(token) != variables.end())
{
ns::cerr << "Attempt to redeclare variable " << token
<< " as a constant" << ns::endl;
return false;
}
if (labelused(token))
{
ns::cerr << "Attempt to reuse label " << token
<< " as a constant" << ns::endl;
return false;
}
bool const alreadydeclared(!constants.insert(token).second);
if (alreadydeclared)
{
ns::cerr << "Attempt to redeclare constant " << token
<< ns::endl;
return false;
}
}
if (tokens.empty())
{
ns::cerr << "Unterminated $c statement" << ns::endl;
return false;
}
if (listempty)
{
ns::cerr << "Empty $c statement" << ns::endl;
return false;
}
tokens.pop(); // Discard $. token
return true;
}
// Parse $v statement. Return true iff okay.
constexpr bool parsev()
{
ns::string token;
bool listempty(true);
while (!tokens.empty() && (token = tokens.front()) != "$.")
{
tokens.pop();
listempty = false;
if (!ismathsymboltoken(token))
{
ns::cerr << "Attempt to declare " << token
<< " as a variable" << ns::endl;
return false;
}
if (constants.find(token) != constants.end())
{
ns::cerr << "Attempt to redeclare constant " << token
<< " as a variable" << ns::endl;
return false;
}
if (labelused(token))
{
ns::cerr << "Attempt to reuse label " << token
<< " as a variable" << ns::endl;
return false;
}
bool const alreadyactive(isactivevariable(token));
if (alreadyactive)
{
ns::cerr << "Attempt to redeclare active variable " << token
<< ns::endl;
return false;
}
variables.insert(token);
scopes.back().activevariables.insert(token);
}
if (tokens.empty())
{
ns::cerr << "Unterminated $v statement" << ns::endl;
return false;
}
if (listempty)
{
ns::cerr << "Empty $v statement" << ns::endl;
return false;
}
tokens.pop(); // Discard $. token
return true;
}
constexpr int run(ns::string const filename, ns::string const &text = "")
{
bool const okay(readtokens(filename, text));
if (!okay)
return EXIT_FAILURE;
scopes.push_back(Scope());
while (!tokens.empty())
{
ns::string const token(tokens.front());
tokens.pop();
bool okay(true);
if (islabeltoken(token))
{
okay = parselabel(token);
}
else if (token == "$d")
{
okay = parsed();
}
else if (token == "${")
{
scopes.push_back(Scope());
}
else if (token == "$}")
{
scopes.pop_back();
if (scopes.empty())
{
ns::cerr << "$} without corresponding ${" << ns::endl;
return EXIT_FAILURE;
}
}
else if (token == "$c")
{
okay = parsec();
}
else if (token == "$v")
{
okay = parsev();
}
else
{
ns::cerr << "Unexpected token " << token << " encountered"
<< ns::endl;
return EXIT_FAILURE;
}
if (!okay)
return EXIT_FAILURE;
}
if (scopes.size() > 1)
{
ns::cerr << "${ without corresponding $}" << ns::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}; // struct checkmm
| 29.066716 | 99 | 0.495422 | [
"vector"
] |
221bb2c9910ba310f35542d7f2e5ce7fb67cc27d | 31,237 | cpp | C++ | my_computer/11/src/lib/vmwriter/vmwriter.cpp | kippesp/Nand2Tetris | b43d60f9267286eae5570244aaa76c34bda28c0e | [
"MIT"
] | null | null | null | my_computer/11/src/lib/vmwriter/vmwriter.cpp | kippesp/Nand2Tetris | b43d60f9267286eae5570244aaa76c34bda28c0e | [
"MIT"
] | null | null | null | my_computer/11/src/lib/vmwriter/vmwriter.cpp | kippesp/Nand2Tetris | b43d60f9267286eae5570244aaa76c34bda28c0e | [
"MIT"
] | null | null | null | #include "vmwriter/vmwriter.h"
#include <signal.h>
#include <algorithm>
#include <cassert>
#include <queue>
#include "parser/parse_tree.h"
#include "semantic_exception.h"
using namespace std;
// seven
// dec-to-bin
// square dance
// average
// pong
// complex arrays
static string get_term_node_str(const ParseTreeNode* pN)
{
auto pTN = dynamic_cast<const ParseTreeTerminal*>(pN);
assert(pTN && "Non-term node");
return pTN->token.value_str;
}
const ParseTreeNode* VmWriter::visit()
{
if (unvisited_nodes.size() == 0) return nullptr;
auto node = unvisited_nodes.back();
unvisited_nodes.pop_back();
if (auto nonterm_node = dynamic_cast<const ParseTreeNonTerminal*>(node))
{
std::vector<std::shared_ptr<ParseTreeNode>> ncopy;
for (auto child_node : nonterm_node->get_child_nodes())
ncopy.push_back(child_node);
reverse(ncopy.begin(), ncopy.end());
for (auto child_node : ncopy) unvisited_nodes.push_back(&(*child_node));
}
return node;
}
// TODO:
// https://stackoverflow.com/questions/15911890/overriding-return-type-in-function-template-specialization
const ParseTreeTerminal* VmWriter::find_first_term_node(
ParseTreeNodeType_t type, const ParseTreeNonTerminal* nt_node) const
{
auto child_nodes = nt_node->get_child_nodes();
for (auto node : child_nodes)
{
if ((*node).type == type)
{
auto rvalue = dynamic_cast<const ParseTreeTerminal*>(&(*node));
assert(rvalue && "Not a terminal node");
return rvalue;
}
}
return nullptr;
}
const ParseTreeNonTerminal* VmWriter::find_first_nonterm_node(
ParseTreeNodeType_t type, const ParseTreeNonTerminal* nt_node) const
{
auto child_nodes = nt_node->get_child_nodes();
for (auto node : child_nodes)
{
if ((*node).type == type)
{
auto rvalue = dynamic_cast<const ParseTreeNonTerminal*>(&(*node));
assert(rvalue && "Not a non-terminal node");
return rvalue;
}
}
return nullptr;
}
const string VmWriter::get_class_name(const ParseTreeNonTerminal* nt_node) const
{
assert(nt_node->type == ParseTreeNodeType_t::P_CLASS_DECL_BLOCK);
auto class_name_node =
find_first_term_node(ParseTreeNodeType_t::P_CLASS_NAME, nt_node);
const string name = get_term_node_str(class_name_node);
return name;
}
void VmWriter::create_classvar_symtable(const ParseTreeNonTerminal* nt_node)
{
assert(nt_node->type == ParseTreeNodeType_t::P_CLASS_DECL_BLOCK);
auto pClassVarDeclBlock = find_first_nonterm_node(
ParseTreeNodeType_t::P_CLASSVAR_DECL_BLOCK, nt_node);
if (!pClassVarDeclBlock) return;
for (auto node : pClassVarDeclBlock->get_child_nodes())
{
if ((*node).type == ParseTreeNodeType_t::P_CLASSVAR_DECL_STATEMENT)
{
auto classvar_decl_statement =
dynamic_cast<const ParseTreeNonTerminal*>(&(*node));
assert(classvar_decl_statement && "Not a non-terminal node");
auto classvar_scope_node = find_first_term_node(
ParseTreeNodeType_t::P_CLASSVAR_SCOPE, classvar_decl_statement);
auto vardecl_node = find_first_nonterm_node(
ParseTreeNodeType_t::P_VARIABLE_DECL, classvar_decl_statement);
auto vartype_node = find_first_term_node(
ParseTreeNodeType_t::P_VARIABLE_TYPE, vardecl_node);
Symbol::StorageClass_t storage_class;
if (classvar_scope_node->token.value_enum == TokenValue_t::J_STATIC)
storage_class = Symbol::ClassStorageClass_t::S_STATIC;
else if (classvar_scope_node->token.value_enum == TokenValue_t::J_FIELD)
storage_class = Symbol::ClassStorageClass_t::S_FIELD;
else
assert(0 && "Invalid storage class in token");
Symbol::VariableType_t variable_type =
Symbol::variable_type_from_token(vartype_node->token);
if (const auto pBT = get_if<Symbol::BasicType_t>(&variable_type))
if (*pBT == Symbol::BasicType_t::T_VOID)
throw SemanticException("void type not allowed here");
auto variable_list = find_first_nonterm_node(
ParseTreeNodeType_t::P_VARIABLE_LIST, vardecl_node);
for (auto variable_list_cnodes : variable_list->get_child_nodes())
{
if ((*variable_list_cnodes).type ==
ParseTreeNodeType_t::P_VARIABLE_NAME)
{
const string varname = get_term_node_str(&(*variable_list_cnodes));
symbol_table.add_symbol(Symbol::ScopeLevel_t::CLASS, varname,
variable_type, storage_class);
}
}
}
}
}
void VmWriter::create_subroutine_symtable(const ParseTreeNonTerminal* sub_node)
{
assert(sub_node->type == ParseTreeNodeType_t::P_SUBROUTINE_DECL_BLOCK);
if (auto sub_type_node = find_first_term_node(
ParseTreeNodeType_t::P_SUBROUTINE_TYPE, sub_node);
sub_type_node->token.value_enum == TokenValue_t::J_METHOD)
{
symbol_table.add_symbol(Symbol::ScopeLevel_t::SUBROUTINE, "this",
Symbol::ClassType_t{class_name},
Symbol::SubroutineStorageClass_t::S_ARGUMENT);
}
// Add any argument variables to the symbol table
{
auto parmlist_node = find_first_nonterm_node(
ParseTreeNodeType_t::P_PARAMETER_LIST, sub_node);
auto nodes = parmlist_node->get_child_nodes();
for (decltype(nodes)::iterator it = nodes.begin(); it != nodes.end(); ++it)
{
// All child nodes are terminals
auto pTermNode = dynamic_cast<const ParseTreeTerminal*>(&(*(*it)));
assert(pTermNode);
if (pTermNode->type == ParseTreeNodeType_t::P_VARIABLE_TYPE)
{
const decltype(pTermNode) vartype_node = pTermNode;
Symbol::VariableType_t variable_type =
Symbol::variable_type_from_token(vartype_node->token);
if (const auto pBT = get_if<Symbol::BasicType_t>(&variable_type))
if (*pBT == Symbol::BasicType_t::T_VOID)
throw SemanticException("void type not allowed here");
++it;
auto pVarnameNode = dynamic_cast<const ParseTreeTerminal*>(&(*(*it)));
assert(pVarnameNode);
assert(pVarnameNode->type == ParseTreeNodeType_t::P_VARIABLE_NAME);
string varname = pVarnameNode->token.value_str;
symbol_table.add_symbol(Symbol::ScopeLevel_t::SUBROUTINE, varname,
variable_type,
Symbol::SubroutineStorageClass_t::S_ARGUMENT);
}
}
}
// Add any subroutine local variables to the symbol table
{
auto pSubroutineBody = find_first_nonterm_node(
ParseTreeNodeType_t::P_SUBROUTINE_BODY, sub_node);
auto pVarDeclBlock = find_first_nonterm_node(
ParseTreeNodeType_t::P_VAR_DECL_BLOCK, pSubroutineBody);
if (!pVarDeclBlock) return;
auto pVarDeclBlockNodes = pVarDeclBlock->get_child_nodes();
// Process all P_VAR_DECL_BLOCK children nodes
for (decltype(pVarDeclBlockNodes)::iterator it = pVarDeclBlockNodes.begin();
it != pVarDeclBlockNodes.end(); ++it)
{
auto pVarDeclStatement =
dynamic_cast<const ParseTreeNonTerminal*>(&(*(*it)));
if (!pVarDeclStatement) continue;
assert(pVarDeclStatement->type ==
ParseTreeNodeType_t::P_VAR_DECL_STATEMENT);
auto pVarDecl = find_first_nonterm_node(
ParseTreeNodeType_t::P_VARIABLE_DECL, pVarDeclStatement);
auto pVarType =
find_first_term_node(ParseTreeNodeType_t::P_VARIABLE_TYPE, pVarDecl);
assert(pVarType);
Symbol::VariableType_t variable_type =
Symbol::variable_type_from_token(pVarType->token);
if (const auto pBT = get_if<Symbol::BasicType_t>(&variable_type))
if (*pBT == Symbol::BasicType_t::T_VOID)
throw SemanticException("void type not allowed here");
auto pVarList = find_first_nonterm_node(
ParseTreeNodeType_t::P_VARIABLE_LIST, pVarDecl);
auto var_list_children_nodes = pVarList->get_child_nodes();
// Process all P_VARIABLE_LIST children nodes
for (decltype(var_list_children_nodes)::iterator it2 =
var_list_children_nodes.begin();
it2 != var_list_children_nodes.end(); ++it2)
{
// All child nodes are terminals
auto pTermNode = dynamic_cast<const ParseTreeTerminal*>(&(*(*it2)));
assert(pTermNode);
if (pTermNode->type == ParseTreeNodeType_t::P_VARIABLE_NAME)
{
string varname = pTermNode->token.value_str;
symbol_table.add_symbol(Symbol::ScopeLevel_t::SUBROUTINE, varname,
variable_type,
Symbol::SubroutineStorageClass_t::S_LOCAL);
}
}
}
}
}
SubroutineDescr::SubroutineDescr(const VmWriter& VM,
const ParseTreeNonTerminal* pSubDecl)
{
auto sub_type_node =
VM.find_first_term_node(ParseTreeNodeType_t::P_SUBROUTINE_TYPE, pSubDecl);
auto sub_return_type_node =
VM.find_first_term_node(ParseTreeNodeType_t::P_RETURN_TYPE, pSubDecl);
auto sub_name_node =
VM.find_first_term_node(ParseTreeNodeType_t::P_SUBROUTINE_NAME, pSubDecl);
pBody = VM.find_first_nonterm_node(ParseTreeNodeType_t::P_SUBROUTINE_BODY,
pSubDecl);
type = sub_type_node->token.value_enum;
return_type = Symbol::variable_type_from_token(sub_return_type_node->token);
name = sub_name_node->token.value_str;
structured_control_id = 0;
}
void VmWriter::lower_class()
{
symbol_table.reset(Symbol::ScopeLevel_t::CLASS);
symbol_table.reset(Symbol::ScopeLevel_t::SUBROUTINE);
class_name = get_class_name(pClassRootNode);
create_classvar_symtable(pClassRootNode);
auto child_nodes = pClassRootNode->get_child_nodes();
for (auto node : child_nodes)
{
if ((*node).type == ParseTreeNodeType_t::P_SUBROUTINE_DECL_BLOCK)
{
auto pN = dynamic_cast<const ParseTreeNonTerminal*>(&(*node));
lower_subroutine(pN);
}
}
}
void VmWriter::lower_return_statement(const ParseTreeNonTerminal* pStatement)
{
auto pExpression =
find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION, pStatement);
if ((pSubDescr->type == TokenValue_t::J_FUNCTION) &&
get_if<Symbol::BasicType_t>(&pSubDescr->return_type) &&
(get<Symbol::BasicType_t>(pSubDescr->return_type) ==
Symbol::BasicType_t::T_VOID))
{
if (pExpression)
throw SemanticException("Function declared void but returning non-void");
lowered_vm << "push constant 0" << endl;
lowered_vm << "return" << endl;
}
else
{
if (pExpression)
{
if ((pSubDescr->type == TokenValue_t::J_METHOD) &&
get_if<Symbol::BasicType_t>(&pSubDescr->return_type) &&
(get<Symbol::BasicType_t>(pSubDescr->return_type) ==
Symbol::BasicType_t::T_VOID))
{
throw SemanticException("Method declared void but returning non-void");
}
lower_expression(pExpression);
}
else
{
// Only Methods can return nothing
assert(pSubDescr->type == TokenValue_t::J_METHOD);
lowered_vm << "push constant 0" << endl;
}
lowered_vm << "return" << endl;
}
}
void VmWriter::lower_statement_list(
const ParseTreeNonTerminal* pStatementListNode)
{
assert(pStatementListNode->type == ParseTreeNodeType_t::P_STATEMENT_LIST);
auto childNodes = pStatementListNode->get_child_nodes();
for (auto child : childNodes)
{
auto pS = dynamic_cast<const ParseTreeNonTerminal*>(&(*child));
switch ((*child).type)
{
case ParseTreeNodeType_t::P_DO_STATEMENT:
lower_do_statement(pS);
break;
case ParseTreeNodeType_t::P_IF_STATEMENT:
lower_if_statement(pS);
break;
case ParseTreeNodeType_t::P_LET_STATEMENT:
lower_let_statement(pS);
break;
case ParseTreeNodeType_t::P_RETURN_STATEMENT:
lower_return_statement(pS);
break;
case ParseTreeNodeType_t::P_WHILE_STATEMENT:
lower_while_statement(pS);
break;
default:
assert(0 && "fallthrough");
throw SemanticException("Unexpected node type");
}
}
}
void VmWriter::lower_subroutine(const ParseTreeNonTerminal* pSubDeclBlockNode)
{
pSubDescr = make_unique<SubroutineDescr>(*this, pSubDeclBlockNode);
symbol_table.reset(Symbol::ScopeLevel_t::SUBROUTINE);
symbol_table.pSubroutineDescr = &(*pSubDescr);
create_subroutine_symtable(pSubDeclBlockNode);
if ((pSubDescr->type == TokenValue_t::J_CONSTRUCTOR) &&
(!get_if<Symbol::ClassType_t>(&pSubDescr->return_type)))
{
throw SemanticException("constructor not returning a class type");
}
lowered_vm << "function " << class_name << "." << pSubDescr->name;
lowered_vm << " " << get_symbol_table().num_locals() << endl;
// For class constructors, allocate class object and save to pointer 0
if (pSubDescr->type == TokenValue_t::J_CONSTRUCTOR)
{
int num_fields = get_symbol_table().num_fields();
lowered_vm << "push constant " << num_fields << endl;
lowered_vm << "call Memory.alloc 1" << endl;
lowered_vm << "pop pointer 0" << endl;
}
// For class methods, get the THIS pointer passed in as argument 0
// and set up POINTER 0
if (const Symbol* this_var = symbol_table.find_symbol("this"))
{
lowered_vm << "push argument " << this_var->var_index << endl;
lowered_vm << "pop pointer 0" << endl;
}
auto pStatementListNode = find_first_nonterm_node(
ParseTreeNodeType_t::P_STATEMENT_LIST, pSubDescr->pBody);
auto childNodes = pStatementListNode->get_child_nodes();
if (childNodes.size() == 0) throw SemanticException("empty subroutine body");
lower_statement_list(pStatementListNode);
}
void VmWriter::lower_op(const ParseTreeTerminal* pOp)
{
string vm_op;
// raise(SIGTRAP);
switch (pOp->token.value_enum)
{
case TokenValue_t::J_PLUS:
vm_op = "add";
break;
case TokenValue_t::J_MINUS:
vm_op = "sub";
break;
case TokenValue_t::J_ASTERISK:
vm_op = "call Math.multiply 2";
break;
case TokenValue_t::J_DIVIDE:
vm_op = "call Math.divide 2";
break;
case TokenValue_t::J_AMPERSAND:
vm_op = "and";
break;
case TokenValue_t::J_VBAR:
vm_op = "or";
break;
case TokenValue_t::J_LESS_THAN:
vm_op = "lt";
break;
case TokenValue_t::J_GREATER_THAN:
vm_op = "gt";
break;
case TokenValue_t::J_EQUAL:
vm_op = "eq";
break;
default:
throw SemanticException("Unexpected op fallthrough");
}
lowered_vm << vm_op << endl;
}
void VmWriter::lower_term(const ParseTreeNonTerminal* pTerm)
{
vector<const ParseTreeNode*> child_nodes;
for (auto node : pTerm->get_child_nodes()) child_nodes.push_back(&(*node));
if (child_nodes.size() == 1)
{
if (auto pT = dynamic_cast<const ParseTreeTerminal*>(child_nodes[0]))
{
if (pT->type == ParseTreeNodeType_t::P_INTEGER_CONSTANT)
{
string int_string = pT->token.value_str;
int int_value = -1;
try
{
int_value = stoi(int_string);
} catch (...)
{
throw SemanticException("Expecting integer value 0..32767");
}
if (int_value > 0x7fff)
throw SemanticException("Integer constant out of range. **" +
int_string + "** > 32767");
if (int_value < 0)
throw SemanticException("Unexpected encountered negative number");
lowered_vm << "push constant " << int_value << endl;
}
else if (pT->type == ParseTreeNodeType_t::P_KEYWORD_CONSTANT)
{
switch (pT->token.value_enum)
{
case TokenValue_t::J_TRUE:
// TRUE is defined as 0xFFFF (i.e. -1) in the VM
lowered_vm << "push constant 0" << endl;
lowered_vm << "not" << endl;
break;
case TokenValue_t::J_FALSE:
case TokenValue_t::J_NULL:
lowered_vm << "push constant 0" << endl;
break;
case TokenValue_t::J_THIS:
if (pSubDescr->type == TokenValue_t::J_FUNCTION)
throw SemanticException(
"Reference to 'this' not permitted in a function");
lowered_vm << "push pointer 0" << endl;
break;
// TODO: okay in constructor and method
// TODO: need test for this
default:
throw SemanticException("Unexpected term fallthrough");
}
}
else if (pT->type == ParseTreeNodeType_t::P_SCALAR_VAR)
{
string varname = get_term_node_str(pT);
const Symbol* rhs = symbol_table.find_symbol(varname);
if (!rhs) throw SemanticException("Variable not found: " + varname);
if (auto pClassSC =
get_if<Symbol::ClassStorageClass_t>(&rhs->storage_class))
{
switch (*pClassSC)
{
case Symbol::ClassStorageClass_t::S_STATIC:
lowered_vm << "push static ";
break;
case Symbol::ClassStorageClass_t::S_FIELD:
lowered_vm << "push this ";
break;
}
}
else if (auto pSubroutineSC = get_if<Symbol::SubroutineStorageClass_t>(
&rhs->storage_class))
{
switch (*pSubroutineSC)
{
case Symbol::SubroutineStorageClass_t::S_ARGUMENT:
lowered_vm << "push argument ";
break;
case Symbol::SubroutineStorageClass_t::S_LOCAL:
lowered_vm << "push local ";
break;
}
}
lowered_vm << rhs->var_index << endl;
}
else if (pT->type == ParseTreeNodeType_t::P_STRING_CONSTANT)
{
const string& s(get_term_node_str(pT));
lowered_vm << "push constant " << s.length() << endl;
lowered_vm << "call String.new 1" << endl;
for (auto ch : s)
{
lowered_vm << "push constant " << (int)ch << endl;
lowered_vm << "call String.appendChar 2" << endl;
}
}
else
{
throw SemanticException("TODO/TERM: unhandled terminal case");
}
}
else if (auto pN =
dynamic_cast<const ParseTreeNonTerminal*>(child_nodes[0]))
{
if (pN->type == ParseTreeNodeType_t::P_SUBROUTINE_CALL)
{
lower_subroutine_call(pN);
}
else if (pN->type == ParseTreeNodeType_t::P_ARRAY_BINDING)
{
string varname = get_term_node_str(
find_first_term_node(ParseTreeNodeType_t::P_ARRAY_VAR, pN));
const Symbol* lhs = symbol_table.find_symbol(varname);
if (!lhs) throw SemanticException("Variable not found: " + varname);
auto pArrayExpr =
find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION, pN);
assert(pArrayExpr);
lower_expression(pArrayExpr);
// Calculate array address + offset
if (auto pClassSC =
get_if<Symbol::ClassStorageClass_t>(&lhs->storage_class))
{
switch (*pClassSC)
{
case Symbol::ClassStorageClass_t::S_STATIC:
lowered_vm << "push static ";
break;
case Symbol::ClassStorageClass_t::S_FIELD:
lowered_vm << "push this ";
break;
}
}
else if (auto pSubroutineSC = get_if<Symbol::SubroutineStorageClass_t>(
&lhs->storage_class))
{
switch (*pSubroutineSC)
{
case Symbol::SubroutineStorageClass_t::S_ARGUMENT:
lowered_vm << "push argument ";
break;
case Symbol::SubroutineStorageClass_t::S_LOCAL:
lowered_vm << "push local ";
break;
}
}
lowered_vm << lhs->var_index << endl;
lowered_vm << "add" << endl;
lowered_vm << "pop pointer 1" << endl;
lowered_vm << "push that 0" << endl;
}
else
{
throw SemanticException("TODO/TERM: unhandled non-terminals");
}
}
}
else if (child_nodes.size() == 2)
{
if (child_nodes[0]->type == ParseTreeNodeType_t::P_UNARY_OP &&
child_nodes[1]->type == ParseTreeNodeType_t::P_TERM)
{
auto pO = dynamic_cast<const ParseTreeTerminal*>(child_nodes[0]);
auto pT = dynamic_cast<const ParseTreeNonTerminal*>(child_nodes[1]);
lower_term(pT);
switch (pO->token.value_enum)
{
case (TokenValue_t::J_MINUS):
lowered_vm << "neg" << endl;
break;
case (TokenValue_t::J_TILDE):
lowered_vm << "not" << endl;
break;
default:
throw SemanticException("fallthrough unary op");
}
}
}
else if (child_nodes.size() == 3)
{
if (child_nodes[0]->type == ParseTreeNodeType_t::P_DELIMITER &&
child_nodes[1]->type == ParseTreeNodeType_t::P_EXPRESSION)
{
auto pE = dynamic_cast<const ParseTreeNonTerminal*>(child_nodes[1]);
lower_expression(pE);
}
else
{
throw SemanticException("TODO/TERM: fallthrough 3-term");
}
}
else
{
throw SemanticException("TODO/TERM: fallthrough N-term");
}
}
void VmWriter::lower_expression(const ParseTreeNonTerminal* pExpression)
{
std::queue<const ParseTreeNode*> worklist;
// raise(SIGTRAP);
auto N = pExpression->get_child_nodes();
// <expression> ::= <term> {<op> <term>}*
if (decltype(N)::iterator it = N.begin(); it != N.end())
{
const ParseTreeNode* pN = &(*(*it));
assert(pN->type == ParseTreeNodeType_t::P_TERM);
// enqueue <term> #1
worklist.push(pN);
while (++it != N.end())
{
const ParseTreeNode* pON = &(*(*it));
assert(pON->type == ParseTreeNodeType_t::P_OP);
++it;
assert(it != N.end());
pN = &(*(*it));
assert(pN->type == ParseTreeNodeType_t::P_TERM);
// enqueue <term> #2
worklist.push(pN);
// enqueue <op>
worklist.push(pON);
}
}
while (!worklist.empty())
{
auto pN = worklist.front();
worklist.pop();
if (auto pT = dynamic_cast<const ParseTreeNonTerminal*>(pN))
{
lower_term(pT);
}
else if (auto pO = dynamic_cast<const ParseTreeTerminal*>(pN))
{
lower_op(pO);
}
}
}
void VmWriter::lower_subroutine_call(
const ParseTreeNonTerminal* pSubroutineCall)
{
stringstream call_site_name;
// Determine call-site name first. If this is in the symbol table, it must
// be a class variable. If it has a '.' in the name, it is a function or
// constructor call. Otherwise, it is a method call.
auto pCallSite = find_first_nonterm_node(
ParseTreeNodeType_t::P_SUBROUTINE_CALL_SITE_BINDING, pSubroutineCall);
assert(pCallSite);
auto pCallVar =
find_first_term_node(ParseTreeNodeType_t::P_CLASS_OR_VAR_NAME, pCallSite);
size_t num_arguments = 0;
if (pCallVar)
{
if (const Symbol* this_var =
symbol_table.find_symbol(pCallVar->token.value_str))
{
if (auto pClassSC =
get_if<Symbol::ClassStorageClass_t>(&this_var->storage_class))
{
switch (*pClassSC)
{
case Symbol::ClassStorageClass_t::S_STATIC:
lowered_vm << "push static ";
break;
case Symbol::ClassStorageClass_t::S_FIELD:
lowered_vm << "push this ";
break;
}
auto pTypeName = get_if<Symbol::ClassType_t>(&this_var->type);
assert(pTypeName);
call_site_name << *pTypeName << ".";
}
else if (auto pSubroutineSC = get_if<Symbol::SubroutineStorageClass_t>(
&this_var->storage_class))
{
switch (*pSubroutineSC)
{
case Symbol::SubroutineStorageClass_t::S_ARGUMENT:
lowered_vm << "push argument ";
break;
case Symbol::SubroutineStorageClass_t::S_LOCAL:
lowered_vm << "push local ";
break;
}
auto pTypeName = get_if<Symbol::ClassType_t>(&this_var->type);
assert(pTypeName);
call_site_name << *pTypeName << ".";
}
lowered_vm << this_var->var_index << endl;
num_arguments++;
}
else
{
call_site_name << get_term_node_str(pCallVar) << ".";
}
}
else if (const Symbol* this_var = symbol_table.find_symbol("this"))
{
lowered_vm << "push pointer 0" << endl;
num_arguments++;
auto pThisVarTypeName = get_if<Symbol::ClassType_t>(&this_var->type);
assert(pThisVarTypeName);
call_site_name << *pThisVarTypeName << ".";
}
else
{
// Class method call from constructor
assert(pSubDescr->type == TokenValue_t::J_CONSTRUCTOR);
// provide 'this' pointer to internal method call
lowered_vm << "push pointer 0" << endl;
num_arguments++;
call_site_name << class_name << ".";
}
auto pSubName =
find_first_term_node(ParseTreeNodeType_t::P_SUBROUTINE_NAME, pCallSite);
call_site_name << pSubName->token.value_str;
auto pExpressionList = find_first_nonterm_node(
ParseTreeNodeType_t::P_EXPRESSION_LIST, pSubroutineCall);
for (auto pN : pExpressionList->get_child_nodes())
{
if (auto pE = dynamic_cast<const ParseTreeNonTerminal*>(&(*pN)))
{
num_arguments++;
assert(pE->type == ParseTreeNodeType_t::P_EXPRESSION);
if (pE) lower_expression(pE);
}
}
lowered_vm << "call " << call_site_name.str() << " ";
lowered_vm << num_arguments << endl;
}
void VmWriter::lower_if_statement(const ParseTreeNonTerminal* pS)
{
// IF not EXPR GOTO FALSE-PART
// TRUE_STATEMENTS
// GOTO IF-END
// FALSE-PART
// FALSE_STATEMENTS
// IF-END
auto pE = find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION, pS);
lower_expression(pE);
std::vector<std::shared_ptr<ParseTreeNode>> if_nodes;
for (auto child_node : pS->get_child_nodes()) if_nodes.push_back(child_node);
bool has_else = false;
// raise(SIGTRAP);
if (if_nodes.size() >= 11) has_else = true;
stringstream control_label;
// CLASS-NAME.FUNCTION-NAME
const auto ID = pSubDescr->structured_control_id++;
assert(if_nodes[5]->type == ParseTreeNodeType_t::P_STATEMENT_LIST);
auto pTrueStatementBlock =
dynamic_cast<const ParseTreeNonTerminal*>(&(*if_nodes[5]));
if (has_else)
{
assert(if_nodes[9]->type == ParseTreeNodeType_t::P_STATEMENT_LIST);
auto pFalseStatementBlock =
dynamic_cast<const ParseTreeNonTerminal*>(&(*if_nodes[9]));
lowered_vm << "if-goto IF_TRUE_" << ID << endl;
lowered_vm << "label IF_FALSE_" << ID << endl;
lower_statement_list(pFalseStatementBlock);
lowered_vm << "goto IF_END_" << ID << endl;
lowered_vm << "label IF_TRUE_" << ID << endl;
lower_statement_list(pTrueStatementBlock);
lowered_vm << "label IF_END_" << ID << endl;
}
else
{
lowered_vm << "if-goto IF_TRUE_" << ID << endl;
lowered_vm << "goto IF_END_" << ID << endl;
lowered_vm << "label IF_TRUE_" << ID << endl;
lower_statement_list(pTrueStatementBlock);
lowered_vm << "label IF_END_" << ID << endl;
}
}
void VmWriter::lower_while_statement(const ParseTreeNonTerminal* pS)
{
// WHILE-BEGIN
// IF-GOTO not EXPR GOTO WHILE-END
// WHILE_STATEMENT
// GOTO WHILE_BEGIN
// WHILE-END
auto pE = find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION, pS);
std::vector<std::shared_ptr<ParseTreeNode>> while_nodes;
for (auto child_node : pS->get_child_nodes())
while_nodes.push_back(child_node);
stringstream control_label;
// CLASS-NAME.FUNCTION-NAME
const auto ID = pSubDescr->structured_control_id++;
auto pStatementBlock =
dynamic_cast<const ParseTreeNonTerminal*>(&(*while_nodes[5]));
lowered_vm << "label WHILE_BEGIN_" << ID << endl;
lower_expression(pE);
lowered_vm << "if-goto WHILE_TRUE_" << ID << endl;
lowered_vm << "goto WHILE_END_" << ID << endl;
lowered_vm << "label WHILE_TRUE_" << ID << endl;
lower_statement_list(pStatementBlock);
lowered_vm << "goto WHILE_BEGIN_" << ID << endl;
lowered_vm << "label WHILE_END_" << ID << endl;
}
void VmWriter::lower_let_statement(const ParseTreeNonTerminal* pS)
{
auto pE = find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION, pS);
assert(pE);
lower_expression(pE);
auto pScalarVar = find_first_term_node(ParseTreeNodeType_t::P_SCALAR_VAR, pS);
auto pArrayBinding =
find_first_nonterm_node(ParseTreeNodeType_t::P_ARRAY_BINDING, pS);
string varname;
if (pScalarVar)
varname = get_term_node_str(pScalarVar);
else if (pArrayBinding)
varname = get_term_node_str(
find_first_term_node(ParseTreeNodeType_t::P_ARRAY_VAR, pArrayBinding));
else
assert(0 && "Fall through");
const Symbol* lhs = symbol_table.find_symbol(varname);
if (!lhs) throw SemanticException("Variable not found: " + varname);
if (pScalarVar)
{
if (auto pClassSC =
get_if<Symbol::ClassStorageClass_t>(&lhs->storage_class))
{
switch (*pClassSC)
{
case Symbol::ClassStorageClass_t::S_STATIC:
lowered_vm << "pop static ";
break;
case Symbol::ClassStorageClass_t::S_FIELD:
lowered_vm << "pop this ";
break;
}
}
else if (auto pSubroutineSC =
get_if<Symbol::SubroutineStorageClass_t>(&lhs->storage_class))
{
switch (*pSubroutineSC)
{
case Symbol::SubroutineStorageClass_t::S_ARGUMENT:
lowered_vm << "pop argument ";
break;
case Symbol::SubroutineStorageClass_t::S_LOCAL:
lowered_vm << "pop local ";
break;
}
}
lowered_vm << lhs->var_index << endl;
}
else
{
auto pArrayExpr = find_first_nonterm_node(ParseTreeNodeType_t::P_EXPRESSION,
pArrayBinding);
assert(pArrayExpr);
lower_expression(pArrayExpr);
// Calculate array address + offset
if (auto pClassSC =
get_if<Symbol::ClassStorageClass_t>(&lhs->storage_class))
{
switch (*pClassSC)
{
case Symbol::ClassStorageClass_t::S_STATIC:
lowered_vm << "push static ";
break;
case Symbol::ClassStorageClass_t::S_FIELD:
lowered_vm << "push this ";
break;
}
}
else if (auto pSubroutineSC =
get_if<Symbol::SubroutineStorageClass_t>(&lhs->storage_class))
{
switch (*pSubroutineSC)
{
case Symbol::SubroutineStorageClass_t::S_ARGUMENT:
lowered_vm << "push argument ";
break;
case Symbol::SubroutineStorageClass_t::S_LOCAL:
lowered_vm << "push local ";
break;
}
}
lowered_vm << lhs->var_index << endl;
lowered_vm << "add" << endl;
lowered_vm << "pop pointer 1" << endl;
lowered_vm << "pop that 0" << endl;
}
}
void VmWriter::lower_do_statement(const ParseTreeNonTerminal* pDoStatement)
{
auto pSubroutineCall = find_first_nonterm_node(
ParseTreeNodeType_t::P_SUBROUTINE_CALL, pDoStatement);
lower_subroutine_call(pSubroutineCall);
// discare call-ed subroutine's return
lowered_vm << "pop temp 0" << endl;
}
| 30.534702 | 106 | 0.641099 | [
"object",
"vector"
] |
2222d75c2d5164d138ad017d1869037f5ad2a963 | 3,855 | hpp | C++ | include/wiztk/base/memory/shared-ptr.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | include/wiztk/base/memory/shared-ptr.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | include/wiztk/base/memory/shared-ptr.hpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 - 2018 The WizTK Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WIZTK_BASE_MEMORY_SHARED_PTR_HPP_
#define WIZTK_BASE_MEMORY_SHARED_PTR_HPP_
#include "wiztk/base/macros.hpp"
#include "wiztk/base/memory/ref-count.hpp"
#include "wiztk/base/memory/ref-counted-base.hpp"
namespace wiztk {
namespace base {
namespace memory {
/**
* @ingroup base_memory
* @brief Shared pointer
* @tparam T
*/
template<typename T>
class SharedPtr {
template<typename R> friend
class WeakPtr;
public:
/**
* @brief Default constructor.
*/
constexpr SharedPtr() noexcept = default;
explicit SharedPtr(T *obj) noexcept {
Reset(obj);
}
SharedPtr(const SharedPtr &other) {
Reset(other.ptr_);
}
SharedPtr(SharedPtr &&other) noexcept
: ptr_(other.ptr_), ref_count_(other.ref_count_) {
other.ptr_ = nullptr;
other.ref_count_ = nullptr;
}
~SharedPtr() {
Reset();
}
SharedPtr &operator=(const SharedPtr &other) noexcept {
Reset(other.ptr_);
return *this;
}
SharedPtr &operator=(SharedPtr &&other) noexcept {
ptr_ = other.ptr_;
ref_count_ = other.ref_count_;
other.ptr_ = nullptr;
other.ref_count_ = nullptr;
return *this;
}
SharedPtr &operator=(T *obj) noexcept {
Reset(obj);
return *this;
}
void Reset(T *obj = nullptr) noexcept {
T *old_ptr = ptr_;
RefCount *old_ref_count = ref_count_;
ptr_ = obj;
ref_count_ = nullptr;
if (nullptr != ptr_) {
if (nullptr == ptr_->ref_count_) {
ptr_->ref_count_ = new RefCount();
_ASSERT(0 == ptr_->ref_count_->use_count_ && 0 == ptr_->ref_count_->weak_count_);
}
ref_count_ = ptr_->ref_count_;
ptr_->Reference();
}
if (nullptr != old_ptr) {
_ASSERT(old_ptr->ref_count_ == old_ref_count);
old_ptr->Unreference();
if (0 == old_ref_count->use_count() && 0 == old_ref_count->weak_count()) {
delete old_ref_count;
}
}
}
void Swap(SharedPtr &other) {
T *old_ptr = ptr_;
RefCount *old_ref_count = ref_count_;
ptr_ = other.ptr_;
ref_count_ = other.ref_count_;
other.ptr_ = old_ptr;
other.ref_count_ = old_ref_count;
}
T *Get() const noexcept { return ptr_; }
T &operator*() const noexcept { return *ptr_; }
T *operator->() const noexcept { return ptr_; }
size_t use_count() const noexcept {
return nullptr == ref_count_ ? 0 : ref_count_->use_count();
}
size_t weak_count() const noexcept {
return nullptr == ref_count_ ? 0 : ref_count_->weak_count();
}
bool IsUnique() const noexcept {
return 1 == use_count();
}
explicit operator bool() const noexcept {
if (nullptr == ptr_) {
_ASSERT(nullptr == ref_count_);
return false;
}
_ASSERT(ptr_->ref_count_ == ref_count_);
return true;
}
private:
T *ptr_ = nullptr;
RefCount *ref_count_ = nullptr;
};
/**
* @ingroup base_memory
* @brief Constructs an object of tyep T and wraps it in a SharedPtr
* @tparam T
* @tparam Args
* @param args
* @return
*/
template<typename T, typename ... Args>
inline SharedPtr<T> MakeShared(Args &&... args) {
return SharedPtr<T>(new T(std::forward<Args>(args)...));
};
} // namespace memory
} // namespace base
} // namespace wiztk
#endif // WIZTK_BASE_MEMORY_SHARED_PTR_HPP_
| 22.283237 | 89 | 0.658366 | [
"object"
] |
222cf5f3418df598786022397f2c817c459e6442 | 6,447 | cpp | C++ | test/octree.cpp | proyan/hpp-fcl | d63ea45eeb60f39822dc258ea29f8b837da7c044 | [
"BSD-3-Clause"
] | null | null | null | test/octree.cpp | proyan/hpp-fcl | d63ea45eeb60f39822dc258ea29f8b837da7c044 | [
"BSD-3-Clause"
] | null | null | null | test/octree.cpp | proyan/hpp-fcl | d63ea45eeb60f39822dc258ea29f8b837da7c044 | [
"BSD-3-Clause"
] | null | null | null | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, CNRS-LAAS.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** \author Florent Lamiraux <florent@laas.fr> */
#define BOOST_TEST_MODULE FCL_OCTREE
#include <fstream>
#include <boost/test/included/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <hpp/fcl/BVH/BVH_model.h>
#include <hpp/fcl/collision.h>
#include <hpp/fcl/distance.h>
#include <hpp/fcl/shape/geometric_shapes.h>
#include <hpp/fcl/internal/BV_splitter.h>
#include "utility.h"
#include "fcl_resources/config.h"
namespace utf = boost::unit_test::framework;
using hpp::fcl::BVHModel;
using hpp::fcl::BVSplitter;
using hpp::fcl::CollisionRequest;
using hpp::fcl::CollisionResult;
using hpp::fcl::FCL_REAL;
using hpp::fcl::OBBRSS;
using hpp::fcl::OcTree;
using hpp::fcl::Transform3f;
using hpp::fcl::Triangle;
using hpp::fcl::Vec3f;
void makeMesh(const std::vector<Vec3f>& vertices,
const std::vector<Triangle>& triangles, BVHModel<OBBRSS>& model) {
hpp::fcl::SplitMethodType split_method(hpp::fcl::SPLIT_METHOD_MEAN);
model.bv_splitter.reset(new BVSplitter<OBBRSS>(split_method));
model.bv_splitter.reset(new BVSplitter<OBBRSS>(split_method));
model.beginModel();
model.addSubModel(vertices, triangles);
model.endModel();
}
hpp::fcl::OcTree makeOctree(const BVHModel<OBBRSS>& mesh,
const FCL_REAL& resolution) {
Vec3f m(mesh.aabb_local.min_);
Vec3f M(mesh.aabb_local.max_);
hpp::fcl::Box box(resolution, resolution, resolution);
CollisionRequest request(hpp::fcl::CONTACT | hpp::fcl::DISTANCE_LOWER_BOUND,
1);
CollisionResult result;
Transform3f tfBox;
octomap::OcTreePtr_t octree(new octomap::OcTree(resolution));
for (FCL_REAL x = resolution * floor(m[0] / resolution); x <= M[0];
x += resolution) {
for (FCL_REAL y = resolution * floor(m[1] / resolution); y <= M[1];
y += resolution) {
for (FCL_REAL z = resolution * floor(m[2] / resolution); z <= M[2];
z += resolution) {
Vec3f center(x + .5 * resolution, y + .5 * resolution,
z + .5 * resolution);
tfBox.setTranslation(center);
hpp::fcl::collide(&box, tfBox, &mesh, Transform3f(), request, result);
if (result.isCollision()) {
octomap::point3d p((float)center[0], (float)center[1],
(float)center[2]);
octree->updateNode(p, true);
result.clear();
}
}
}
}
octree->updateInnerOccupancy();
octree->writeBinary("./env.octree");
return OcTree(octree);
}
BOOST_AUTO_TEST_CASE(OCTREE) {
Eigen::IOFormat tuple(Eigen::FullPrecision, Eigen::DontAlignCols, "", ", ",
"", "", "(", ")");
FCL_REAL resolution(10.);
std::vector<Vec3f> pRob, pEnv;
std::vector<Triangle> tRob, tEnv;
boost::filesystem::path path(TEST_RESOURCES_DIR);
loadOBJFile((path / "rob.obj").string().c_str(), pRob, tRob);
loadOBJFile((path / "env.obj").string().c_str(), pEnv, tEnv);
BVHModel<OBBRSS> robMesh, envMesh;
// Build meshes with robot and environment
makeMesh(pRob, tRob, robMesh);
makeMesh(pEnv, tEnv, envMesh);
// Build octomap with environment
envMesh.computeLocalAABB();
// Load octree built from envMesh by makeOctree(envMesh, resolution)
OcTree envOctree(
hpp::fcl::loadOctreeFile((path / "env.octree").string(), resolution));
std::cout << "Finished loading octree." << std::endl;
std::vector<Transform3f> transforms;
FCL_REAL extents[] = {-2000, -2000, 0, 2000, 2000, 2000};
#ifndef NDEBUG // if debug mode
std::size_t N = 100;
#else
std::size_t N = 10000;
#endif
N = hpp::fcl::getNbRun(utf::master_test_suite().argc,
utf::master_test_suite().argv, N);
generateRandomTransforms(extents, transforms, 2 * N);
CollisionRequest request(hpp::fcl::CONTACT | hpp::fcl::DISTANCE_LOWER_BOUND,
1);
for (std::size_t i = 0; i < N; ++i) {
CollisionResult resultMesh;
CollisionResult resultOctree;
Transform3f tf1(transforms[2 * i]);
Transform3f tf2(transforms[2 * i + 1]);
;
// Test collision between meshes with random transform for robot.
hpp::fcl::collide(&robMesh, tf1, &envMesh, tf2, request, resultMesh);
// Test collision between mesh and octree for the same transform.
hpp::fcl::collide(&robMesh, tf1, &envOctree, tf2, request, resultOctree);
bool resMesh(resultMesh.isCollision());
bool resOctree(resultOctree.isCollision());
BOOST_CHECK(!resMesh || resOctree);
if (!resMesh && resOctree) {
hpp::fcl::DistanceRequest dreq;
hpp::fcl::DistanceResult dres;
hpp::fcl::distance(&robMesh, tf1, &envMesh, tf2, dreq, dres);
std::cout << "distance mesh mesh: " << dres.min_distance << std::endl;
BOOST_CHECK(dres.min_distance < sqrt(2.) * resolution);
}
}
}
| 38.147929 | 80 | 0.677214 | [
"mesh",
"shape",
"vector",
"model",
"transform"
] |
222df8ed5d09d8bf698d28babab86d6ad4c86e03 | 10,811 | cpp | C++ | dev/Gems/NvCloth/Code/Tests/NvClothTest.cpp | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/NvCloth/Code/Tests/NvClothTest.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/NvCloth/Code/Tests/NvClothTest.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzTest/AzTest.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Math/Transform.h>
#include <AzCore/Component/TickBus.h>
#include <NvCloth/IClothSystem.h>
#include <NvCloth/ICloth.h>
#include <NvCloth/IClothConfigurator.h>
#include <NvCloth/IFabricCooker.h>
#include <TriangleInputHelper.h>
namespace UnitTest
{
//! Sets up a cloth and colliders for each test case.
class NvClothTestFixture
: public ::testing::Test
{
protected:
// ::testing::Test overrides ...
void SetUp() override;
void TearDown() override;
//! Sends tick events to make cloth simulation happen.
//! Returns the position of cloth particles at tickBefore, continues ticking till tickAfter.
void TickClothSimulation(const AZ::u32 tickBefore,
const AZ::u32 tickAfter,
AZStd::vector<NvCloth::SimParticleFormat>& particlesBefore);
NvCloth::ICloth* m_cloth = nullptr;
NvCloth::ICloth::PreSimulationEvent::Handler m_preSimulationEventHandler;
NvCloth::ICloth::PostSimulationEvent::Handler m_postSimulationEventHandler;
bool m_postSimulationEventInvoked = false;
private:
bool CreateCloth();
void DestroyCloth();
// ICloth notifications
void OnPreSimulation(NvCloth::ClothId clothId, float deltaTime);
void OnPostSimulation(NvCloth::ClothId clothId,
float deltaTime,
const AZStd::vector<NvCloth::SimParticleFormat>& updatedParticles);
AZ::Transform m_clothTransform = AZ::Transform::CreateIdentity();
AZStd::vector<AZ::Vector4> m_sphereColliders;
};
void NvClothTestFixture::SetUp()
{
m_preSimulationEventHandler = NvCloth::ICloth::PreSimulationEvent::Handler(
[this](NvCloth::ClothId clothId, float deltaTime)
{
this->OnPreSimulation(clothId, deltaTime);
});
m_postSimulationEventHandler = NvCloth::ICloth::PostSimulationEvent::Handler(
[this](NvCloth::ClothId clothId, float deltaTime, const AZStd::vector<NvCloth::SimParticleFormat>& updatedParticles)
{
this->OnPostSimulation(clothId, deltaTime, updatedParticles);
});
bool clothCreated = CreateCloth();
ASSERT_TRUE(clothCreated);
}
void NvClothTestFixture::TearDown()
{
DestroyCloth();
}
void NvClothTestFixture::TickClothSimulation(const AZ::u32 tickBefore,
const AZ::u32 tickAfter,
AZStd::vector<NvCloth::SimParticleFormat>& particlesBefore)
{
const float timeOneFrameSeconds = 0.016f; //approx 60 fps
for (AZ::u32 tickCount = 0; tickCount < tickAfter; ++tickCount)
{
AZ::TickBus::Broadcast(&AZ::TickEvents::OnTick,
timeOneFrameSeconds,
AZ::ScriptTimePoint(AZStd::chrono::system_clock::now()));
if (tickCount == tickBefore)
{
particlesBefore = m_cloth->GetParticles();
}
}
}
bool NvClothTestFixture::CreateCloth()
{
const float width = 2.0f;
const float height = 2.0f;
const AZ::u32 segmentsX = 10;
const AZ::u32 segmentsY = 10;
const TriangleInput planeXY = CreatePlane(width, height, segmentsX, segmentsY);
// Cook Fabric
AZStd::optional<NvCloth::FabricCookedData> cookedData = AZ::Interface<NvCloth::IFabricCooker>::Get()->CookFabric(planeXY.m_vertices, planeXY.m_indices);
if (!cookedData)
{
return false;
}
// Create cloth instance
m_cloth = AZ::Interface<NvCloth::IClothSystem>::Get()->CreateCloth(planeXY.m_vertices, *cookedData);
if (!m_cloth)
{
return false;
}
m_sphereColliders.emplace_back(512.0f, 512.0f, 35.0f, 1.0f);
m_clothTransform.SetTranslation(AZ::Vector3(512.0f, 519.0f, 35.0f));
m_cloth->GetClothConfigurator()->SetTransform(m_clothTransform);
m_cloth->GetClothConfigurator()->ClearInertia();
// Add cloth to default solver to be simulated
AZ::Interface<NvCloth::IClothSystem>::Get()->AddCloth(m_cloth);
return true;
}
void NvClothTestFixture::DestroyCloth()
{
if (m_cloth)
{
AZ::Interface<NvCloth::IClothSystem>::Get()->RemoveCloth(m_cloth);
AZ::Interface<NvCloth::IClothSystem>::Get()->DestroyCloth(m_cloth);
}
}
void NvClothTestFixture::OnPreSimulation([[maybe_unused]] NvCloth::ClothId clothId, float deltaTime)
{
m_cloth->GetClothConfigurator()->SetTransform(m_clothTransform);
static float time = 0.0f;
static float velocity = 1.0f;
time += deltaTime;
for (auto& sphere : m_sphereColliders)
{
sphere.SetY(sphere.GetY() + velocity * deltaTime);
}
auto clothInverseTransform = m_clothTransform.GetInverseFast();
auto sphereColliders = m_sphereColliders;
for (auto& sphere : sphereColliders)
{
sphere.Set(clothInverseTransform * sphere.GetAsVector3(), sphere.GetW());
}
m_cloth->GetClothConfigurator()->SetSphereColliders(sphereColliders);
}
void NvClothTestFixture::OnPostSimulation(
NvCloth::ClothId clothId, float deltaTime,
const AZStd::vector<NvCloth::SimParticleFormat>& updatedParticles)
{
AZ_UNUSED(clothId);
AZ_UNUSED(deltaTime);
AZ_UNUSED(updatedParticles);
m_postSimulationEventInvoked = true;
}
//! Smallest Z and largest Y coordinates for a list of particles before, and a list of particles after simulation for some time.
struct ParticleBounds
{
float m_beforeSmallestZ = std::numeric_limits<float>::max();
float m_beforeLargestY = -std::numeric_limits<float>::max();
float m_afterSmallestZ = std::numeric_limits<float>::max();
float m_afterLargestY = -std::numeric_limits<float>::max();
};
static ParticleBounds GetBeforeAndAfterParticleBounds(const AZStd::vector<NvCloth::SimParticleFormat>& particlesBefore,
const AZStd::vector<NvCloth::SimParticleFormat>& particlesAfter)
{
assert(particlesBefore.size() == particlesAfter.size());
ParticleBounds beforeAndAfterParticleBounds;
for (size_t particleIndex = 0; particleIndex < particlesBefore.size(); ++particleIndex)
{
if (particlesBefore[particleIndex].GetZ() < beforeAndAfterParticleBounds.m_beforeSmallestZ)
{
beforeAndAfterParticleBounds.m_beforeSmallestZ = particlesBefore[particleIndex].GetZ();
}
if (particlesBefore[particleIndex].GetY() > beforeAndAfterParticleBounds.m_beforeLargestY)
{
beforeAndAfterParticleBounds.m_beforeLargestY = particlesBefore[particleIndex].GetY();
}
if (particlesAfter[particleIndex].GetZ() < beforeAndAfterParticleBounds.m_afterSmallestZ)
{
beforeAndAfterParticleBounds.m_afterSmallestZ = particlesAfter[particleIndex].GetZ();
}
if (particlesAfter[particleIndex].GetY() > beforeAndAfterParticleBounds.m_afterLargestY)
{
beforeAndAfterParticleBounds.m_afterLargestY = particlesAfter[particleIndex].GetY();
}
}
return beforeAndAfterParticleBounds;
}
//! Tests that basic cloth simulation works.
TEST_F(NvClothTestFixture, Cloth_NoCollision_FallWithGravity)
{
const AZ::u32 tickBefore = 150;
const AZ::u32 tickAfter = 300;
AZStd::vector<NvCloth::SimParticleFormat> particlesBefore;
TickClothSimulation(tickBefore, tickAfter, particlesBefore);
ParticleBounds particleBounds = GetBeforeAndAfterParticleBounds(particlesBefore,
m_cloth->GetParticles());
// Cloth was extended horizontally in the y-direction earlier.
// If cloth fell with gravity, its y-extent should be smaller later,
// and its z-extent should go lower to a smaller Z value later.
ASSERT_TRUE((particleBounds.m_afterLargestY < particleBounds.m_beforeLargestY) &&
(particleBounds.m_afterSmallestZ < particleBounds.m_beforeSmallestZ));
}
//! Tests that collision works and pre/post simulation events work.
TEST_F(NvClothTestFixture, Cloth_Collision_CollidedWithPrePostSimEvents)
{
m_cloth->ConnectPreSimulationEventHandler(m_preSimulationEventHandler); // The pre-simulation callback moves the sphere collider towards the cloth every tick.
m_cloth->ConnectPostSimulationEventHandler(m_postSimulationEventHandler);
const AZ::u32 tickBefore = 150;
const AZ::u32 tickAfter = 320;
AZStd::vector<NvCloth::SimParticleFormat> particlesBefore;
TickClothSimulation(tickBefore, tickAfter, particlesBefore);
ParticleBounds particleBounds = GetBeforeAndAfterParticleBounds(particlesBefore,
m_cloth->GetParticles());
// Cloth starts extended horizontally (along Y-axis). Simulation makes it swing down with gravity (as tested with the other unit test).
// Then the sphere collider collides with the cloth and pushes it back up. So it is again extended in the Y-direction and
// at about the same vertical height (Z-coord) as before.
const float threshold = 0.25f;
EXPECT_TRUE(AZ::IsClose(particleBounds.m_beforeSmallestZ , -0.97f, threshold));
EXPECT_TRUE(AZ::IsClose(particleBounds.m_beforeLargestY, 0.76f, threshold));
EXPECT_TRUE(AZ::IsClose(particleBounds.m_afterSmallestZ, -1.1f, threshold));
EXPECT_TRUE(AZ::IsClose(particleBounds.m_afterLargestY, 0.72f, threshold));
ASSERT_TRUE((fabsf(particleBounds.m_afterLargestY - particleBounds.m_beforeLargestY) < threshold) &&
(fabsf(particleBounds.m_afterSmallestZ - particleBounds.m_beforeSmallestZ) < threshold));
// Check that post simulation event was invoked.
ASSERT_TRUE(m_postSimulationEventInvoked);
m_preSimulationEventHandler.Disconnect();
m_postSimulationEventHandler.Disconnect();
}
} // namespace UnitTest
| 39.892989 | 166 | 0.672648 | [
"vector",
"transform"
] |
2237ae6764c3a4ab04d467f35e758cde04d306c4 | 5,888 | hpp | C++ | source/include/coffee/app/Application.hpp | ciscoruiz/wepa | e6d922157543c91b6804f11073424a0a9c6e8f51 | [
"MIT"
] | 2 | 2018-02-03T06:56:29.000Z | 2021-04-20T10:28:32.000Z | source/include/coffee/app/Application.hpp | ciscoruiz/wepa | e6d922157543c91b6804f11073424a0a9c6e8f51 | [
"MIT"
] | 8 | 2018-02-18T21:00:07.000Z | 2018-02-20T15:31:24.000Z | source/include/coffee/app/Application.hpp | ciscoruiz/wepa | e6d922157543c91b6804f11073424a0a9c6e8f51 | [
"MIT"
] | 1 | 2018-02-09T07:09:26.000Z | 2018-02-09T07:09:26.000Z | // MIT License
//
// Copyright (c) 2018 Francisco Ruiz (francisco.ruiz.rayo@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef _coffee_app_Application_hpp_
#define _coffee_app_Application_hpp_
#include <vector>
#include <memory>
#include <map>
#include <boost/filesystem.hpp>
#include <coffee/basis/RuntimeException.hpp>
#include <coffee/app/Runnable.hpp>
#include <coffee/app/Feature.hpp>
namespace coffee {
namespace xml {
class Node;
}
namespace app {
class Service;
/**
* This abstraction manage all resources needed to run our application.
*
* It maintains the list of services needed to run our application.
*
* \include Application_test.cc
*/
class Application : public Runnable {
public:
/**
Constructor.
@param shortName Logical name.
@param title Title of this application. It will be shown during run up.
@param version version of this application.
*/
Application(const char* shortName, const char* title, const char* version);
/**
Destructor.
*/
virtual ~Application();
/**
* \return the logical name of this application.
*/
const std::string& getShortName() const noexcept { return getName(); }
/**
* \return The version of this application.
*/
const std::string& getVersion() const noexcept { return a_version; }
/**
* \return the title of this application.
*/
const std::string& getTitle() const noexcept { return a_title; }
/**
* \return the pid assigned by the operating system to the proccess running this application.
*/
pid_t getPid() const noexcept { return a_pid; }
/**
* The the path where it would write the context.
*/
void setOutputContextFilename(const boost::filesystem::path& outputContextFilename) noexcept { this->a_outputContextFilename = outputContextFilename; }
/**
* \return The context path where it would write the context.
*/
const boost::filesystem::path& getOutputContextFilename() const noexcept { return a_outputContextFilename; }
/**
* Initialize all resources related to this application, and then it will call virtual method #initialize and #run.
*/
void start() throw(basis::RuntimeException);
/**
* Attach the service to this application. It will be started before this application start to run.
*/
bool attach(std::shared_ptr<Service> service) throw(basis::RuntimeException);
/**
* @param feature Feature required for the caller
* @param implementation Implementation required for the caller. It could be Service::WhateverImplementation to not apply.
* @return One service instance that matches the requirements.
*/
std::shared_ptr<Service> select(const Feature::_v feature, const std::string& implementation) throw(basis::RuntimeException);
/**
* Write the context as a coffee::xml::Node into the path indicated by file.
*/
void writeContext(const boost::filesystem::path& file) throw(basis::RuntimeException);
/**
* This virtual method will give us the opportunity to initialize custom resources of
* our inherit application.
*/
virtual void initialize() throw(basis::RuntimeException) {;}
/**
* \return Summarize information of this instance in a coffee::basis::StreamString.
*/
virtual basis::StreamString asString() const noexcept;
/**
* \return Summarize information of this instance in a coffee::xml::Node.
*/
virtual std::shared_ptr<xml::Node> asXML(std::shared_ptr<xml::Node>& parent) const throw(basis::RuntimeException);
protected:
/**
* Virtual method to implement for running our application.
*/
virtual void run() throw(basis::RuntimeException) = 0;
/**
* Virtual method to capture the request stop.
*/
virtual void do_stop() throw(basis::RuntimeException);
/**
* Handler for signal USR1, it will write the context into file #getOutputContextFilename.
*/
virtual void signalUSR1() throw(basis::RuntimeException);
/**
* Handler for signal USR2
* By default it will change the trace level, adding 1 to the current level. Once it reach
* the level logger::Level::Debug it will return to the logger::Level::Error.
*/
virtual void signalUSR2() throw(basis::RuntimeException);
private:
typedef std::multimap<Feature::_v, std::shared_ptr<Service> > Services;
static Application* m_this;
const std::string a_version;
const std::string a_title;
const pid_t a_pid;
boost::filesystem::path a_outputContextFilename;
Services m_services;
void startServices() throw(basis::RuntimeException);
void sendSignalToChilds(const int signal) noexcept;
static void handlerUserSignal(int) noexcept;
static void handlerSignalTerminate(int) noexcept;
static void handlerChildTerminate(int sig) noexcept;
};
}
}
#endif
| 31.655914 | 154 | 0.715693 | [
"vector"
] |
223d8f06351d4399fd3055d468243992c67541a3 | 9,312 | cpp | C++ | src/dev/dhustigschultz/TC_MixedLearning/FlemonsSpineModelMixed.cpp | wangsd01/NTRT-Sim | a9f01ffb7aab411a1f14320f47dd2b599643b1ed | [
"Apache-2.0"
] | null | null | null | src/dev/dhustigschultz/TC_MixedLearning/FlemonsSpineModelMixed.cpp | wangsd01/NTRT-Sim | a9f01ffb7aab411a1f14320f47dd2b599643b1ed | [
"Apache-2.0"
] | null | null | null | src/dev/dhustigschultz/TC_MixedLearning/FlemonsSpineModelMixed.cpp | wangsd01/NTRT-Sim | a9f01ffb7aab411a1f14320f47dd2b599643b1ed | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/
/**
* @file FlemonsSpineModelContact.cpp
* @brief Implementing the tetrahedral complex spine inspired by Tom Flemons
* @author Brian Mirletz, Dawn Hustig-Schultz
* @date August 2015
* @version 1.0.0
* $Id$
*/
// This module
#include "FlemonsSpineModelMixed.h"
// This library
#include "core/tgCast.h"
#include "core/tgSpringCableActuator.h"
#include "core/tgString.h"
#include "tgcreator/tgBasicContactCableInfo.h"
#include "tgcreator/tgKinematicContactCableInfo.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgBasicActuatorInfo.h"
#include "tgcreator/tgKinematicActuatorInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
#include "tgcreator/tgUtil.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <algorithm> // std::fill
#include <iostream>
#include <map>
#include <set>
FlemonsSpineModelMixed::FlemonsSpineModelMixed(int segments) :
BaseSpineModelLearning(segments)
{
}
FlemonsSpineModelMixed::~FlemonsSpineModelMixed()
{
}
void FlemonsSpineModelMixed::setup(tgWorld& world)
{
// This is basically a manual setup of a model.
// There are things that do this for us
/// @todo: reference the things that do this for us
// Rod and Muscle configuration
// Note: This needs to be high enough or things fly apart...
const double density = 4.2/300.0;
const double radius = 0.5;
const double friction = 0.5;
const double rollFriction = 0.0;
const double restitution = 0.0;
const tgRod::Config rodConfig(radius, density, friction, rollFriction, restitution);
const double elasticity = 1000.0;
const double damping = 10.0;
const double pretension = 0.0;
const bool history = false;
const double maxTens = 7000.0;
const double maxSpeed = 12.0;
const double mRad = 1.0;
const double motorFriction = 10.0;
const double motorInertia = 1.0;
const bool backDrivable = false;
tgKinematicActuator::Config motorConfig(elasticity, damping, pretension,
mRad, motorFriction, motorInertia, backDrivable,
history, maxTens, maxSpeed);
// Calculations for the flemons spine model
double v_size = 10.0;
// Create the tetrahedra
tgStructure tetra;
tetra.addNode(0.0, 0.0, 0.0); // center
tetra.addNode( v_size, v_size, v_size); // front
tetra.addNode( v_size, -v_size, -v_size); // right
tetra.addNode(-v_size, v_size, -v_size); // back
tetra.addNode(-v_size, -v_size, v_size); // left
tetra.addPair(0, 1, "front rod");
tetra.addPair(0, 2, "right rod");
tetra.addPair(0, 3, "back rod");
tetra.addPair(0, 4, "left rod");
// Move the first one so we can create a longer snake.
// Or you could move the snake at the end, up to you.
tetra.move(btVector3(0.0,15.0,100.0));
// Create our snake segments
tgStructure snake;
/// @todo: there seems to be an issue with Muscle2P connections if the front
/// of a tetra is inside the next one.
btVector3 offset(0.0, 0.0, -v_size * 1.15);
for (std::size_t i = 0; i < m_segments; i++)
{
/// @todo: the snake is a temporary variable --
/// will its destructor be called?
/// If not, where do we delete its children?
tgStructure* const p = new tgStructure(tetra);
p->addTags(tgString("segment num", i + 1));
p->move((i + 1.0) * offset);
snake.addChild(p); // Add a child to the snake
}
//conditionally compile for debugging
#if (1)
// Add muscles that connect the segments
// Tag the muscles with their segment numbers so CPGs can find
// them.
std::vector<tgStructure*> children = snake.getChildren();
for (std::size_t i = 1; i < children.size(); i++)
{
tgNodes n0 = children[i - 1]->getNodes();
tgNodes n1 = children[i]->getNodes();
if (i == 1)
{
snake.addPair(n0[1], n1[1],
tgString("starting outer front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[2],
tgString("starting outer right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[3],
tgString("starting outer back muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[4], n1[4],
tgString("starting outer top muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[1],
tgString("starting inner front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[4],
tgString("starting inner right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[1],
tgString("starting inner left muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[4],
tgString("starting inner back muscle seg", i - 1) + tgString(" seg", i));
}
/*else if(i == children.size() - 1)
{
snake.addPair(n0[1], n1[1],
tgString("ending outer front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[2],
tgString("ending outer right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[3],
tgString("ending outer back muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[4], n1[4],
tgString("ending outer top muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[1],
tgString("ending inner front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[4],
tgString("ending inner right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[1],
tgString("ending inner left muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[4],
tgString("ending inner back muscle seg", i - 1) + tgString(" seg", i));
}*/
else
{
snake.addPair(n0[1], n1[1],
tgString("middle outer front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[2],
tgString("middle outer right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[3],
tgString("middle outer back muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[4], n1[4],
tgString("middle outer top muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[1],
tgString("middle inner front muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[2], n1[4],
tgString("middle inner right muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[1],
tgString("middle inner left muscle seg", i - 1) + tgString(" seg", i));
snake.addPair(n0[3], n1[4],
tgString("middle inner back muscle seg", i - 1) + tgString(" seg", i));
}
}
#endif
// Create the build spec that uses tags to turn the structure into a real model
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(rodConfig));
#if (1)
spec.addBuilder("muscle", new tgKinematicContactCableInfo(motorConfig));
#else
spec.addBuilder("muscle", new tgBasicContactCableInfo(motorConfig));
#endif
// Create your structureInfo
tgStructureInfo structureInfo(snake, spec);
// Use the structureInfo to build ourselves
structureInfo.buildInto(*this, world);
// Setup vectors for control
m_allMuscles = tgCast::filter<tgModel, tgSpringCableActuator> (getDescendants());
m_allSegments = this->find<tgModel> ("segment");
#if (0)
// Debug printing
std::cout << "StructureInfo:" << std::endl;
std::cout << structureInfo << std::endl;
std::cout << "Model: " << std::endl;
std::cout << *this << std::endl;
#endif
children.clear();
// Actually setup the children, notify controller
BaseSpineModelLearning::setup(world);
}
void FlemonsSpineModelMixed::teardown()
{
BaseSpineModelLearning::teardown();
}
void FlemonsSpineModelMixed::step(double dt)
{
/* CPG update occurs in the controller so that we can decouple it
* from the physics update
*/
BaseSpineModelLearning::step(dt); // Step any children
}
| 37.099602 | 93 | 0.61555 | [
"vector",
"model"
] |
223dac6b106d694cf276a07196c11efdd2c272a2 | 7,112 | cpp | C++ | tke/src/v20180525/model/PrometheusAgentOverview.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tke/src/v20180525/model/PrometheusAgentOverview.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tke/src/v20180525/model/PrometheusAgentOverview.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tke/v20180525/model/PrometheusAgentOverview.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tke::V20180525::Model;
using namespace std;
PrometheusAgentOverview::PrometheusAgentOverview() :
m_clusterTypeHasBeenSet(false),
m_clusterIdHasBeenSet(false),
m_statusHasBeenSet(false),
m_clusterNameHasBeenSet(false),
m_externalLabelsHasBeenSet(false)
{
}
CoreInternalOutcome PrometheusAgentOverview::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ClusterType") && !value["ClusterType"].IsNull())
{
if (!value["ClusterType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PrometheusAgentOverview.ClusterType` IsString=false incorrectly").SetRequestId(requestId));
}
m_clusterType = string(value["ClusterType"].GetString());
m_clusterTypeHasBeenSet = true;
}
if (value.HasMember("ClusterId") && !value["ClusterId"].IsNull())
{
if (!value["ClusterId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PrometheusAgentOverview.ClusterId` IsString=false incorrectly").SetRequestId(requestId));
}
m_clusterId = string(value["ClusterId"].GetString());
m_clusterIdHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PrometheusAgentOverview.Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(value["Status"].GetString());
m_statusHasBeenSet = true;
}
if (value.HasMember("ClusterName") && !value["ClusterName"].IsNull())
{
if (!value["ClusterName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PrometheusAgentOverview.ClusterName` IsString=false incorrectly").SetRequestId(requestId));
}
m_clusterName = string(value["ClusterName"].GetString());
m_clusterNameHasBeenSet = true;
}
if (value.HasMember("ExternalLabels") && !value["ExternalLabels"].IsNull())
{
if (!value["ExternalLabels"].IsArray())
return CoreInternalOutcome(Core::Error("response `PrometheusAgentOverview.ExternalLabels` is not array type"));
const rapidjson::Value &tmpValue = value["ExternalLabels"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Label item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_externalLabels.push_back(item);
}
m_externalLabelsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void PrometheusAgentOverview::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_clusterTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ClusterType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_clusterType.c_str(), allocator).Move(), allocator);
}
if (m_clusterIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ClusterId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_clusterId.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator);
}
if (m_clusterNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ClusterName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_clusterName.c_str(), allocator).Move(), allocator);
}
if (m_externalLabelsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExternalLabels";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_externalLabels.begin(); itr != m_externalLabels.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
string PrometheusAgentOverview::GetClusterType() const
{
return m_clusterType;
}
void PrometheusAgentOverview::SetClusterType(const string& _clusterType)
{
m_clusterType = _clusterType;
m_clusterTypeHasBeenSet = true;
}
bool PrometheusAgentOverview::ClusterTypeHasBeenSet() const
{
return m_clusterTypeHasBeenSet;
}
string PrometheusAgentOverview::GetClusterId() const
{
return m_clusterId;
}
void PrometheusAgentOverview::SetClusterId(const string& _clusterId)
{
m_clusterId = _clusterId;
m_clusterIdHasBeenSet = true;
}
bool PrometheusAgentOverview::ClusterIdHasBeenSet() const
{
return m_clusterIdHasBeenSet;
}
string PrometheusAgentOverview::GetStatus() const
{
return m_status;
}
void PrometheusAgentOverview::SetStatus(const string& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool PrometheusAgentOverview::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string PrometheusAgentOverview::GetClusterName() const
{
return m_clusterName;
}
void PrometheusAgentOverview::SetClusterName(const string& _clusterName)
{
m_clusterName = _clusterName;
m_clusterNameHasBeenSet = true;
}
bool PrometheusAgentOverview::ClusterNameHasBeenSet() const
{
return m_clusterNameHasBeenSet;
}
vector<Label> PrometheusAgentOverview::GetExternalLabels() const
{
return m_externalLabels;
}
void PrometheusAgentOverview::SetExternalLabels(const vector<Label>& _externalLabels)
{
m_externalLabels = _externalLabels;
m_externalLabelsHasBeenSet = true;
}
bool PrometheusAgentOverview::ExternalLabelsHasBeenSet() const
{
return m_externalLabelsHasBeenSet;
}
| 30.393162 | 153 | 0.688555 | [
"vector",
"model"
] |
22442860d6cc5b6615a11ee16cb1968dbbc5b86f | 13,514 | cpp | C++ | ogles_gpgpu/common/proc/flow.cpp | sniperkit/ogles_gpgpu | 2acf6d576bbf013674bdee3f35a6bc0f5a193c2a | [
"Apache-2.0"
] | 10 | 2016-04-17T16:35:47.000Z | 2021-08-15T11:12:49.000Z | ogles_gpgpu/common/proc/flow.cpp | sniperkit/ogles_gpgpu | 2acf6d576bbf013674bdee3f35a6bc0f5a193c2a | [
"Apache-2.0"
] | 20 | 2017-07-09T21:03:37.000Z | 2018-04-27T02:02:35.000Z | ogles_gpgpu/common/proc/flow.cpp | sniperkit/ogles_gpgpu | 2acf6d576bbf013674bdee3f35a6bc0f5a193c2a | [
"Apache-2.0"
] | 6 | 2016-07-09T13:06:38.000Z | 2021-07-01T07:43:48.000Z | //
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// See LICENSE file in project repository root for the license.
//
// Copyright (c) 2016-2017, David Hirvonen (this file)
#include "flow.h"
#include "../common_includes.h"
// For the full pipeline
#include "box_opt.h"
#include "diff.h"
#include "fifo.h"
#include "gauss_opt.h"
#include "grayscale.h"
#include "ixyt.h"
#include "median.h"
#include "nms.h"
#include "tensor.h"
#include <limits>
BEGIN_OGLES_GPGPU
FlowProc::FlowProc(float tau, float strength)
: tau(tau)
, strength(strength) {
}
void FlowProc::filterShaderSetup(const char* vShaderSrc, const char* fShaderSrc, GLenum target) {
// create shader object and get attributes:
ProcBase::createShader(vShaderSrc, fShaderSrc, target);
shParamAPos = shader->getParam(ATTR, "position");
shParamATexCoord = shader->getParam(ATTR, "inputTextureCoordinate");
}
void FlowProc::getUniforms() {
FilterProcBase::getUniforms();
texelWidthUniform = shader->getParam(UNIF, "texelWidth");
texelHeightUniform = shader->getParam(UNIF, "texelHeight");
shParamUInputTex = shader->getParam(UNIF, "inputImageTexture");
shParamUStrength = shader->getParam(UNIF, "strength");
shParamUTau = shader->getParam(UNIF, "tau");
}
void FlowProc::setUniforms() {
FilterProcBase::setUniforms();
const float offset = 1.0f;
glUniform1f(texelWidthUniform, (offset / float(outFrameW)));
glUniform1f(texelHeightUniform, (offset / float(outFrameH)));
glUniform1f(shParamUStrength, strength);
glUniform1f(shParamUTau, tau);
}
// Solve 2x2 matrix inverse via Cramer's rule:
// [ IxX Ixy; Iyx Iyy ] [u v]' = [ Ix*It Iy*It ]
// "Let it be..."
// [ A C; C B ] * [ u v ]' = [ X Y ]
// |A C|
// |Y B|
// D = det([A C; C B])
// |X C|
// |Y B|
// Dx = det([X C; Y B])
// |A X|
// |C Y|
// Dy = det([A X; C Y])
// x = Dx/D
// y = Dy/D
// See, for example:
// http://www.mathworks.com/help/vision/ref/opticalflowlk-class.html?refresh=true
// Cornerness:
// T1 = (A+B)/2.0
// T2 = sqrt(4*C^2 + (A-B)^2)/2.0
// lambda_1 = T1 + T2
// lambda+2 = T1 - T2
// case 1: lambda_1 >= tau && lambda_2 >= tau | non singular
// case 2: lambda_1 >= tau && lambda_2 < tau | singular (can be normalized to calculate u and v)
// case 3: lambda_1 < tau && lambda_2 < tau | flow is 0
// TODO: slow, avoid dependent texture lookups!!!!
// -------------
// | |*| + |*| |
// -------------
// | |*| + |*| |
// -------------
// | |*| + |*| |
// -------------
// clang-format off
const char *FlowProc::fshaderFlowSrc =
#if defined(OGLES_GPGPU_OPENGLES)
OG_TO_STR(precision highp float;)
#endif
OG_TO_STR(
varying vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform float texelWidth;
uniform float texelHeight;
uniform float strength;
uniform float tau; // noise threshold (0.004)
const int wSize = 5;
void main()
{
float X = 0.0;
float Y = 0.0;
float A = 0.0;
float B = 0.0;
float C = 0.0;
// Build the 2x2 matrix and the Intensity vector:
for(int y=-wSize; y<=wSize; y++)
{
for(int x=-wSize; x<=wSize; x++)
{
vec2 delta = vec2( float(x)*texelWidth, float(y)*texelHeight );
vec2 pos = textureCoordinate + delta;
vec4 pix = texture2D(inputImageTexture, pos) * 2.0 - 1.0;
float w = 1.0; // cos(dot(delta,delta)*40.0);
A = A + w * pix.x * pix.x;
B = B + w * pix.y * pix.y;
C = C + w * pix.x * pix.y;
X = X + w * pix.x * pix.z * 2.0;
Y = Y + w * pix.y * pix.z * 2.0;
}
}
// T1 = (A+B)/2.0
// T2 = sqrt(4*C^2 + (A-B)^2)/2.0
// lambda_1 = T1 + T2
// lambda_2 = T1 - T2
float TMP = (A-B);
float T1 = (A+B)/2.0;
float T2 = sqrt(4.0 * C*C + TMP*TMP)/2.0;
float L1 = T1 + T2;
float L2 = T1 - T2;
float D = 1.0/(A*B-C*C);
if(L1 <= tau || L2 <= tau)
{
D = 0.0;
}
vec4 center = texture2D(inputImageTexture, textureCoordinate);
vec2 uv = strength * (vec2(X*B - C*Y, A*Y - X*C) * D);
vec4 flow = vec4(((-uv + 1.0) / 2.0), (center.xy + 1.0) / 2.0);
gl_FragColor = flow;
});
// clang-format on
// ============== convenience =========================
struct FlowPipeline::Impl {
Impl(float tau, float strength, bool doGray)
: doGray(doGray)
, gaussProc(1.0f)
, flowProc(tau, strength) {
if (!doGray) {
grayProc.setGrayscaleConvType(GRAYSCALE_INPUT_CONVERSION_NONE);
}
{
// flow processing
grayProc.add(&diffProc, 0);
grayProc.add(&fifoProc);
fifoProc.add(&diffProc, 1);
diffProc.add(&gaussProc);
gaussProc.add(&flowProc);
}
}
bool doGray = true;
GrayscaleProc grayProc;
FifoProc fifoProc;
IxytProc diffProc;
GaussOptProc gaussProc;
FlowProc flowProc;
};
FlowPipeline::FlowPipeline(float tau, float strength, bool doGray) {
m_pImpl = std::unique_ptr<Impl>(new Impl(tau, strength, doGray));
procPasses.push_back(&m_pImpl->grayProc);
procPasses.push_back(&m_pImpl->fifoProc);
procPasses.push_back(&m_pImpl->gaussProc);
procPasses.push_back(&m_pImpl->flowProc);
};
FlowPipeline::~FlowPipeline() {}
float FlowPipeline::getStrength() const {
return m_pImpl->flowProc.getStrength();
}
ProcInterface* FlowPipeline::getInputFilter() const {
return &m_pImpl->grayProc;
}
ProcInterface* FlowPipeline::getOutputFilter() const {
return &m_pImpl->flowProc;
}
int FlowPipeline::render(int position) {
getInputFilter()->process(position);
return 0;
}
int FlowPipeline::init(int inW, int inH, unsigned int order, bool prepareForExternalInput) {
getInputFilter()->prepare(inW, inH, 0, std::numeric_limits<int>::max(), 0);
return 0;
}
int FlowPipeline::reinit(int inW, int inH, bool prepareForExternalInput) {
getInputFilter()->prepare(inW, inH, 0, std::numeric_limits<int>::max(), 0);
return 0;
}
// ====================================================
// ======= Test two input smoothed tensor output ======
// ====================================================
FlowImplProc::FlowImplProc(bool isX, float strength)
: isX(isX)
, strength(strength) {
}
void FlowImplProc::filterShaderSetup(const char* vShaderSrc, const char* fShaderSrc, GLenum target) {
ProcBase::createShader(vShaderSrc, fShaderSrc, target);
shParamAPos = shader->getParam(ATTR, "position");
shParamATexCoord = shader->getParam(ATTR, "inputTextureCoordinate");
}
void FlowImplProc::getUniforms() {
FilterProcBase::getUniforms();
shParamUInputTex = shader->getParam(UNIF, "inputImageTexture");
shParamUStrength = shader->getParam(UNIF, "strength");
}
void FlowImplProc::setUniforms() {
FilterProcBase::setUniforms();
glUniform1f(shParamUStrength, strength);
}
// clang-format off
const char * FlowImplProc::fshaderFlowXSrc =
#if defined(OGLES_GPGPU_OPENGLES)
OG_TO_STR(precision highp float;)
#endif
OG_TO_STR(
varying vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform float strength;
void main()
{
vec4 val = texture2D(inputImageTexture, textureCoordinate);
vec4 pix = (val * 2.0) - 1.0;
vec3 t = vec3(pix.x*pix.x, pix.y*pix.y, (pix.x*pix.y+1.0)/2.0);
vec4 x = vec4(t, (pix.x*pix.z+1.0)/2.0);
gl_FragColor = x * strength;
});
// clang-format on
// clang-format off
const char *FlowImplProc::fshaderFlowYSrc =
#if defined(OGLES_GPGPU_OPENGLES)
OG_TO_STR(precision highp float;)
#endif
OG_TO_STR(
varying vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform float strength;
void main()
{
vec4 val = texture2D(inputImageTexture, textureCoordinate);
vec4 pix = (val * 2.0) - 1.0;
vec3 t = vec3(pix.x*pix.x, pix.y*pix.y, (pix.x*pix.y+1.0)/2.0);
vec4 y = vec4(t, (pix.y*pix.z+1.0)/2.0);
gl_FragColor = y * strength;
});
// clang-format on
//##########################################################################
// +=> [Ix^2; Ix*Iy; Iy^2; Ix*It] => SMOOTH ===+
// [Ix; Iy; It; .] | | => FLOW
// +=> [Ix^2; Ix*Iy; Iy^2; Iy*It] => SMOOTH ===+
//##########################################################################
Flow2Proc::Flow2Proc(float tau, float strength)
: tau(tau)
, strength(strength) {
}
void Flow2Proc::filterShaderSetup(const char* vShaderSrc, const char* fShaderSrc, GLenum target) {
ProcBase::createShader(vShaderSrc, fShaderSrc, target);
shParamAPos = shader->getParam(ATTR, "position");
shParamATexCoord = shader->getParam(ATTR, "inputTextureCoordinate");
}
void Flow2Proc::getUniforms() {
TwoInputProc::getUniforms();
shParamUStrength = shader->getParam(UNIF, "strength");
shParamUTau = shader->getParam(UNIF, "tau");
}
void Flow2Proc::setUniforms() {
TwoInputProc::setUniforms();
glUniform1f(shParamUStrength, strength);
glUniform1f(shParamUTau, tau);
}
// clang-format off
const char *Flow2Proc::fshaderFlowSrc =
#if defined(OGLES_GPGPU_OPENGLES)
OG_TO_STR(precision highp float;)
#endif
OG_TO_STR(
varying vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2;
uniform float strength;
uniform float tau; // noise threshold (0.004)
void main()
{
vec4 pix1 = texture2D(inputImageTexture, textureCoordinate);
vec4 pix2 = texture2D(inputImageTexture2, textureCoordinate);
float A = pix1.x; // Ix^2
float B = pix1.y; // Iy^2
float C = pix1.z * 2.0 - 1.0; // Ix*Iy
float X = pix1.w * 2.0 - 1.0; // Ix * It
float Y = pix2.w * 2.0 - 1.0; // Iy * It
// T1 = (A+B)/2.0
// T2 = sqrt(4*C^2 + (A-B)^2)/2.0
// lambda_1 = T1 + T2
// lambda_2 = T1 - T2
float TMP = (A-B);
float T1 = (A+B)/2.0;
float T2 = sqrt(4.0 * C*C + TMP*TMP)/2.0;
float L1 = T1 + T2;
float L2 = T1 - T2;
float D = 1.0/(A*B-C*C);
// Sort such that L1 < L2
if(L1 > L2)
{
float L = L1;
L1 = L2;
L2 = L;
}
if(L1 <= tau)
{
D = 0.0;
}
vec2 uv = strength * (vec2(X*B - C*Y, A*Y - X*C) * D);
vec4 flow = vec4(((-uv + 1.0) / 2.0), L1, L2); // TODO: L1,L2 need scaling
gl_FragColor = flow;
});
// clang-format on
// =========================================
#define USE_MEDIAN 0
struct Flow2Pipeline::Impl {
typedef GaussOptProc SmoothProc;
Impl(float tau, float strength, bool doGray)
: diffProc(40.0)
, flowXProc(true, 1.f)
, flowXSmoothProc(5.0)
, flowYProc(false, 1.f)
, flowYSmoothProc(5.0)
, flowProc(tau, strength) {
if (!doGray) {
grayProc.setGrayscaleConvType(GRAYSCALE_INPUT_CONVERSION_NONE);
}
{
// flow processing
grayProc.add(&fifoProc);
fifoProc.add(&diffProc, 1);
grayProc.add(&diffProc, 0);
diffProc.add(&flowXProc);
flowXProc.add(&flowXSmoothProc);
flowXSmoothProc.add(&flowProc, 0);
diffProc.add(&flowYProc);
flowYProc.add(&flowYSmoothProc);
flowYSmoothProc.add(&flowProc, 1);
nmsProc.swizzle(2); // b channel
nmsProc.setThreshold(0.1f);
flowProc.add(&nmsProc);
#if USE_MEDIAN
flowProc.add(&medianProc);
#endif
}
}
GrayscaleProc grayProc;
FIFOPRoc fifoProc;
IxytProc diffProc;
FlowImplProc flowXProc;
SmoothProc flowXSmoothProc;
FlowImplProc flowYProc;
SmoothProc flowYSmoothProc;
Flow2Proc flowProc;
NmsProc nmsProc; // corners!
#if USE_MEDIAN
MedianProc medianProc;
#endif
};
Flow2Pipeline::Flow2Pipeline(float tau, float strength, bool doGray) {
m_pImpl = std::unique_ptr<Impl>(new Impl(tau, strength, doGray));
procPasses.push_back(&m_pImpl->grayProc);
procPasses.push_back(&m_pImpl->fifoProc);
procPasses.push_back(&m_pImpl->diffProc);
procPasses.push_back(&m_pImpl->flowXProc);
procPasses.push_back(&m_pImpl->flowXSmoothProc);
procPasses.push_back(&m_pImpl->flowYProc);
procPasses.push_back(&m_pImpl->flowYSmoothProc);
procPasses.push_back(&m_pImpl->flowProc);
procPasses.push_back(&m_pImpl->nmsProc);
};
Flow2Pipeline::~Flow2Pipeline() {
procPasses.clear();
}
ProcInterface* Flow2Pipeline::getInputFilter() const {
return &m_pImpl->grayProc;
}
#if USE_MEDIAN
ProcInterface* Flow2Pipeline::getOutputFilter() const {
return &m_pImpl->medianProc;
}
#else
ProcInterface* Flow2Pipeline::getOutputFilter() const {
return &m_pImpl->nmsProc;
}
#endif
float Flow2Pipeline::getStrength() const {
return m_pImpl->flowProc.getStrength();
}
ProcInterface* Flow2Pipeline::corners() {
return &m_pImpl->nmsProc;
}
int Flow2Pipeline::render(int position) {
// Execute internal filter chain
getInputFilter()->process(position);
return 0;
}
int Flow2Pipeline::init(int inW, int inH, unsigned int order, bool prepareForExternalInput) {
getInputFilter()->prepare(inW, inH, 0, std::numeric_limits<int>::max(), 0);
return 0;
}
int Flow2Pipeline::reinit(int inW, int inH, bool prepareForExternalInput) {
getInputFilter()->prepare(inW, inH, 0, std::numeric_limits<int>::max(), 0);
return 0;
}
END_OGLES_GPGPU
| 27.191147 | 101 | 0.607296 | [
"render",
"object",
"vector"
] |
2254800056c8cb334ce692020c964fdeb8f2209f | 644 | cpp | C++ | ch09/0909ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch09/0909ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch09/0909ex.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | 1 | 2022-01-25T15:51:34.000Z | 2022-01-25T15:51:34.000Z | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <deque>
using std::string;
using std::vector;
using std::list;
using std::deque;
int main(void)
{
const char *words[] = {"This", "Is", "A", "Word"};
list<string> slist(words, words+(sizeof(words)/sizeof(words[0])));
for(list<string>::iterator iter = slist.begin(); iter != slist.end(); iter++)
{
std::cout << *iter << std::endl;
}
std::cout << "----" << std::endl;
list<string>::iterator riter = slist.end();
--riter;
for(; riter != slist.begin(); --riter)
{
std::cout << *riter << std::endl;
}
std::cout << *riter << std::endl;
return 0;
}
| 20.125 | 78 | 0.602484 | [
"vector"
] |
2259769df779732572aada83b1919636fc293167 | 801 | cpp | C++ | code/leetcode/src/0059.Spiral-Matrix-II.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | 1 | 2021-09-01T14:39:12.000Z | 2021-09-01T14:39:12.000Z | code/leetcode/src/0059.Spiral-Matrix-II.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | code/leetcode/src/0059.Spiral-Matrix-II.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | /**
* @date 2020-08-21 16:11:38
* @authors Lewis Tian (taseikyo@gmail.com)
* @link github.com/taseikyo
*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n < 1) {
return {}
}
if (n == 1) {
return {1};
}
vector<vector<int>> ans(n, vector<int>(n));
help(ans, 1, 0, 0, n - 1, n - 1);
return ans;
}
void help(vector<vector<int>> &ans, int cur, int x1, int y1,
int x2, int y2) {
if (x1 > x2 || y1 > y2) {
return;
}
for (int i = y1; i <= y2; ++i) {
ans[x1][i] = cur++;
}
for (int i = x1 + 1; i <= x2; ++i) {
ans[i][y2] = cur++;
}
for (int i = y2 - 1; i >= y1; --i) {
ans[x2][i] = cur++;
}
for (int i = x2 - 1; i > x1; --i) {
ans[i][y1] = cur++;
}
help(ans, cur, x1 + 1, y1 + 1, x2 - 1, y2 - 1);
}
}; | 20.538462 | 61 | 0.470662 | [
"vector"
] |
226c7aca902ba2605897f47cc19902cbd066db4c | 14,157 | cpp | C++ | gui/src/gui_fontstring.cpp | unnamed-mmo/lxgui | 5c4b9d0c164d2d35cfe5c59888b10020184f717d | [
"MIT"
] | null | null | null | gui/src/gui_fontstring.cpp | unnamed-mmo/lxgui | 5c4b9d0c164d2d35cfe5c59888b10020184f717d | [
"MIT"
] | null | null | null | gui/src/gui_fontstring.cpp | unnamed-mmo/lxgui | 5c4b9d0c164d2d35cfe5c59888b10020184f717d | [
"MIT"
] | null | null | null | #include "lxgui/gui_fontstring.hpp"
#include "lxgui/gui_layeredregion.hpp"
#include "lxgui/gui_manager.hpp"
#include "lxgui/gui_renderer.hpp"
#include "lxgui/gui_out.hpp"
#include "lxgui/gui_uiobject_tpl.hpp"
#include <sstream>
namespace lxgui {
namespace gui
{
const uint OUTLINE_QUALITY = 10;
const float OUTLINE_THICKNESS = 2.0f;
font_string::font_string(manager* pManager) : layered_region(pManager)
{
lType_.push_back(CLASS_NAME);
}
void font_string::render()
{
if (pText_ && is_visible())
{
float fX = 0.0f, fY = 0.0f;
if (std::isinf(pText_->get_box_width()))
{
switch (mJustifyH_)
{
case text::alignment::LEFT : fX = lBorderList_.left; break;
case text::alignment::CENTER : fX = (lBorderList_.left + lBorderList_.right)/2; break;
case text::alignment::RIGHT : fX = lBorderList_.right; break;
}
}
else
fX = lBorderList_.left;
if (std::isinf(pText_->get_box_height()))
{
switch (mJustifyV_)
{
case text::vertical_alignment::TOP : fY = lBorderList_.top; break;
case text::vertical_alignment::MIDDLE : fY = (lBorderList_.top + lBorderList_.bottom)/2; break;
case text::vertical_alignment::BOTTOM : fY = lBorderList_.bottom; break;
}
}
else
fY = lBorderList_.top;
fX += iXOffset_;
fY += iYOffset_;
if (bHasShadow_)
{
pText_->set_color(mShadowColor_, true);
pText_->render(fX + iShadowXOffset_, fY + iShadowYOffset_);
}
if (bIsOutlined_)
{
pText_->set_color(color(0, 0, 0, mTextColor_.a), true);
for (uint i = 0; i < OUTLINE_QUALITY; ++i)
{
static const float PI2 = 2.0f*acos(-1.0f);
pText_->render(
fX + OUTLINE_THICKNESS*cos(PI2*float(i)/OUTLINE_QUALITY),
fY + OUTLINE_THICKNESS*sin(PI2*float(i)/OUTLINE_QUALITY)
);
}
}
pText_->set_color(mTextColor_);
pText_->render(fX, fY);
}
}
std::string font_string::serialize(const std::string& sTab) const
{
std::ostringstream sStr;
sStr << layered_region::serialize(sTab);
sStr << sTab << " # Font name : " << sFontName_ << "\n";
sStr << sTab << " # Font height : " << uiHeight_ << "\n";
sStr << sTab << " # Text ready : " << (pText_ != nullptr) << "\n";
sStr << sTab << " # Text : \"" << utils::unicode_to_utf8(sText_) << "\"\n";
sStr << sTab << " # Outlined : " << bIsOutlined_ << "\n";
sStr << sTab << " # Text color : " << mTextColor_ << "\n";
sStr << sTab << " # Spacing : " << fSpacing_ << "\n";
sStr << sTab << " # Justify :\n";
sStr << sTab << " #-###\n";
sStr << sTab << " | # horizontal : ";
switch (mJustifyH_)
{
case text::alignment::LEFT : sStr << "LEFT\n"; break;
case text::alignment::CENTER : sStr << "CENTER\n"; break;
case text::alignment::RIGHT : sStr << "RIGHT\n"; break;
default : sStr << "<error>\n"; break;
}
sStr << sTab << " | # vertical : ";
switch (mJustifyV_)
{
case text::vertical_alignment::TOP : sStr << "TOP\n"; break;
case text::vertical_alignment::MIDDLE : sStr << "MIDDLE\n"; break;
case text::vertical_alignment::BOTTOM : sStr << "BOTTOM\n"; break;
default : sStr << "<error>\n"; break;
}
sStr << sTab << " #-###\n";
sStr << sTab << " # NonSpaceW. : " << bCanNonSpaceWrap_ << "\n";
if (bHasShadow_)
{
sStr << sTab << " # Shadow off. : (" << iShadowXOffset_ << ", " << iShadowYOffset_ << ")\n";
sStr << sTab << " # Shadow col. : " << mShadowColor_ << "\n";
}
return sStr.str();
}
void font_string::create_glue()
{
create_glue_<lua_font_string>();
}
void font_string::copy_from(uiobject* pObj)
{
uiobject::copy_from(pObj);
font_string* pFontString = down_cast<font_string>(pObj);
if (!pFontString)
return;
std::string sFontName = pFontString->get_font_name();
uint uiHeight = pFontString->get_font_height();
if (!sFontName.empty() && uiHeight != 0)
this->set_font(sFontName, uiHeight);
this->set_justify_h(pFontString->get_justify_h());
this->set_justify_v(pFontString->get_justify_v());
this->set_spacing(pFontString->get_spacing());
this->set_text(pFontString->get_text());
this->set_outlined(pFontString->is_outlined());
if (pFontString->has_shadow())
{
this->set_shadow(true);
this->set_shadow_color(pFontString->get_shadow_color());
this->set_shadow_offsets(pFontString->get_shadow_offsets());
}
this->set_text_color(pFontString->get_text_color());
this->set_non_space_wrap(pFontString->can_non_space_wrap());
}
const std::string& font_string::get_font_name() const
{
return sFontName_;
}
uint font_string::get_font_height() const
{
return uiHeight_;
}
void font_string::set_outlined(bool bIsOutlined)
{
if (bIsOutlined_ != bIsOutlined)
{
bIsOutlined_ = bIsOutlined;
notify_renderer_need_redraw();
}
}
bool font_string::is_outlined() const
{
return bIsOutlined_;
}
text::alignment font_string::get_justify_h() const
{
return mJustifyH_;
}
text::vertical_alignment font_string::get_justify_v() const
{
return mJustifyV_;
}
const color& font_string::get_shadow_color() const
{
return mShadowColor_;
}
vector2i font_string::get_shadow_offsets() const
{
return vector2i(iShadowXOffset_, iShadowYOffset_);
}
vector2i font_string::get_offsets() const
{
return vector2i(iXOffset_, iYOffset_);
}
int font_string::get_shadow_x_offset() const
{
return iShadowXOffset_;
}
int font_string::get_shadow_y_offset() const
{
return iShadowYOffset_;
}
float font_string::get_spacing() const
{
return fSpacing_;
}
const color& font_string::get_text_color() const
{
return mTextColor_;
}
void font_string::notify_scaling_factor_updated()
{
uiobject::notify_scaling_factor_updated();
if (pText_)
set_font(sFontName_, uiHeight_);
}
void font_string::set_font(const std::string& sFontName, uint uiHeight)
{
sFontName_ = sFontName;
uiHeight_ = uiHeight;
uint uiPixelHeight = std::round(pManager_->get_interface_scaling_factor()*uiHeight);
renderer* pRenderer = pManager_->get_renderer();
pText_ = std::unique_ptr<text>(new text(pRenderer, pRenderer->create_font(sFontName, uiPixelHeight)));
pText_->set_scaling_factor(1.0f/pManager_->get_interface_scaling_factor());
pText_->set_remove_starting_spaces(true);
pText_->set_text(sText_);
pText_->set_alignment(mJustifyH_);
pText_->set_vertical_alignment(mJustifyV_);
pText_->set_tracking(fSpacing_);
pText_->enable_word_wrap(bCanWordWrap_, bAddEllipsis_);
pText_->enable_formatting(bFormattingEnabled_);
notify_borders_need_update();
notify_renderer_need_redraw();
}
void font_string::set_justify_h(text::alignment mJustifyH)
{
if (mJustifyH_ != mJustifyH)
{
mJustifyH_ = mJustifyH;
if (pText_)
{
pText_->set_alignment(mJustifyH_);
notify_renderer_need_redraw();
}
}
}
void font_string::set_justify_v(text::vertical_alignment mJustifyV)
{
if (mJustifyV_ != mJustifyV)
{
mJustifyV_ = mJustifyV;
if (pText_)
{
pText_->set_vertical_alignment(mJustifyV_);
notify_renderer_need_redraw();
}
}
}
void font_string::set_shadow_color(const color& mShadowColor)
{
if (mShadowColor_ != mShadowColor)
{
mShadowColor_ = mShadowColor;
if (bHasShadow_)
notify_renderer_need_redraw();
}
}
void font_string::set_shadow_offsets(int iShadowXOffset, int iShadowYOffset)
{
if (iShadowXOffset_ != iShadowXOffset || iShadowYOffset_ != iShadowYOffset)
{
iShadowXOffset_ = iShadowXOffset;
iShadowYOffset_ = iShadowYOffset;
if (bHasShadow_)
notify_renderer_need_redraw();
}
}
void font_string::set_shadow_offsets(const vector2i& mShadowOffsets)
{
if (iShadowXOffset_ != mShadowOffsets.x || iShadowYOffset_ != mShadowOffsets.y)
{
iShadowXOffset_ = mShadowOffsets.x;
iShadowYOffset_ = mShadowOffsets.y;
if (bHasShadow_)
notify_renderer_need_redraw();
}
}
void font_string::set_offsets(int iXOffset, int iYOffset)
{
if (iXOffset_ != iXOffset || iYOffset_ != iYOffset)
{
iXOffset_ = iXOffset;
iYOffset_ = iYOffset;
notify_renderer_need_redraw();
}
}
void font_string::set_offsets(const vector2i& mOffsets)
{
if (iXOffset_ != mOffsets.x || iYOffset_ != mOffsets.y)
{
iXOffset_ = mOffsets.x;
iYOffset_ = mOffsets.y;
notify_renderer_need_redraw();
}
}
void font_string::set_spacing(float fSpacing)
{
if (fSpacing_ != fSpacing)
{
fSpacing_ = fSpacing;
if (pText_)
{
pText_->set_tracking(fSpacing_);
notify_renderer_need_redraw();
}
}
}
void font_string::set_text_color(const color& mTextColor)
{
if (mTextColor_ != mTextColor)
{
mTextColor_ = mTextColor;
notify_renderer_need_redraw();
}
}
bool font_string::can_non_space_wrap() const
{
return bCanNonSpaceWrap_;
}
float font_string::get_string_height() const
{
if (pText_)
return pText_->get_text_height();
else
return 0.0f;
}
float font_string::get_string_width() const
{
if (pText_)
return pText_->get_text_width();
else
return 0.0f;
}
const utils::ustring& font_string::get_text() const
{
return sText_;
}
void font_string::set_non_space_wrap(bool bCanNonSpaceWrap)
{
if (bCanNonSpaceWrap_ != bCanNonSpaceWrap)
{
bCanNonSpaceWrap_ = bCanNonSpaceWrap;
notify_renderer_need_redraw();
}
}
bool font_string::has_shadow() const
{
return bHasShadow_;
}
void font_string::set_shadow(bool bHasShadow)
{
if (bHasShadow_ != bHasShadow)
{
bHasShadow_ = bHasShadow;
notify_renderer_need_redraw();
}
}
void font_string::set_word_wrap(bool bCanWordWrap, bool bAddEllipsis)
{
bCanWordWrap_ = bCanWordWrap;
bAddEllipsis_ = bAddEllipsis;
if (pText_)
pText_->enable_word_wrap(bCanWordWrap_, bAddEllipsis_);
}
bool font_string::can_word_wrap() const
{
return bCanWordWrap_;
}
void font_string::enable_formatting(bool bFormatting)
{
bFormattingEnabled_ = bFormatting;
if (pText_)
pText_->enable_formatting(bFormattingEnabled_);
}
bool font_string::is_formatting_enabled() const
{
return bFormattingEnabled_;
}
void font_string::set_text(const utils::ustring& sText)
{
if (sText_ != sText)
{
sText_ = sText;
if (pText_)
{
pText_->set_text(sText_);
notify_borders_need_update();
}
}
}
text* font_string::get_text_object()
{
return pText_.get();
}
const text* font_string::get_text_object() const
{
return pText_.get();
}
void font_string::update_borders_() const
{
if (!pText_)
return uiobject::update_borders_();
if (!bUpdateBorders_)
return;
//#define DEBUG_LOG(msg) gui::out << (msg) << std::endl
#define DEBUG_LOG(msg)
bool bOldReady = bReady_;
bReady_ = true;
if (!lAnchorList_.empty())
{
float fLeft = 0.0f, fRight = 0.0f, fTop = 0.0f, fBottom = 0.0f;
float fXCenter = 0.0f, fYCenter = 0.0f;
DEBUG_LOG(" Read anchors");
read_anchors_(fLeft, fRight, fTop, fBottom, fXCenter, fYCenter);
if (uiAbsWidth_ == 0u)
{
if (lDefinedBorderList_.left && lDefinedBorderList_.right)
pText_->set_box_width(fRight - fLeft);
else
pText_->set_box_width(std::numeric_limits<float>::infinity());
}
else
pText_->set_box_width(uiAbsWidth_);
if (uiAbsHeight_ == 0u)
{
if (lDefinedBorderList_.top && lDefinedBorderList_.bottom)
pText_->set_box_height(fBottom - fTop);
else
pText_->set_box_height(std::numeric_limits<float>::infinity());
}
else
pText_->set_box_height(uiAbsHeight_);
DEBUG_LOG(" Make borders");
if (uiAbsHeight_ != 0u)
make_borders_(fTop, fBottom, fYCenter, uiAbsHeight_);
else
make_borders_(fTop, fBottom, fYCenter, pText_->get_height());
if (uiAbsWidth_ != 0u)
make_borders_(fLeft, fRight, fXCenter, uiAbsWidth_);
else
make_borders_(fLeft, fRight, fXCenter, pText_->get_width());
if (bReady_)
{
int iLeft = fLeft, iRight = fRight, iTop = fTop, iBottom = fBottom;
if (iRight < iLeft)
iRight = iLeft+1;
if (iBottom < iTop)
iBottom = iTop+1;
lBorderList_.left = iLeft;
lBorderList_.right = iRight;
lBorderList_.top = iTop;
lBorderList_.bottom = iBottom;
}
else
lBorderList_ = quad2i::ZERO;
bUpdateBorders_ = false;
}
else
bReady_ = false;
if (bReady_ || (!bReady_ && bOldReady))
{
DEBUG_LOG(" Fire redraw");
notify_renderer_need_redraw();
}
DEBUG_LOG(" @");
}
}
}
| 26.461682 | 112 | 0.591368 | [
"render"
] |
229041d2aeebe14509a8fc7881bfa3ef7d3e99fc | 16,819 | cpp | C++ | sssh.cpp | brian-sigurdson/CS5080-Operating-Systems-Project | be83fd3fb27c69b196d96bb101fc5df6115e2af9 | [
"Apache-2.0"
] | null | null | null | sssh.cpp | brian-sigurdson/CS5080-Operating-Systems-Project | be83fd3fb27c69b196d96bb101fc5df6115e2af9 | [
"Apache-2.0"
] | null | null | null | sssh.cpp | brian-sigurdson/CS5080-Operating-Systems-Project | be83fd3fb27c69b196d96bb101fc5df6115e2af9 | [
"Apache-2.0"
] | null | null | null | /*
* File Name : sssh.cpp
* Descripton : Develope a Super Simple SHell (sssh), per project specs.
* Author : Brian K. Sigurson
* Course : CS5080
* Assignment : Project 01
* Due Date : 2017-03-27
*
* Extra Credit : 1) Command History !!
* : 2) Environment variables
* : 3) Multiple Foreground Commands
*/
//=================================
// included dependencies
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h> // execlp
#include <stdlib.h> // system
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <list>
#include "sssh.h"
#include "process.h"
#include "job.h"
//=================================
// forward declared dependencies
//=================================
// initalize static member variables
int SSSH::currentSsshId = 0;
//=============================================================================
// begin main()
//=============================================================================
int main(int argc, char* argv[])
{
// the shell
SSSH the_shell;
bool stop = false;
while(stop == false){
// background jobs?
the_shell.printBGJobs();
// parse the input
the_shell.parseInput();
// check a few items before proceeding
if(the_shell.isExit()){
// exit
std::cout << std::endl <<
"** Info: Exiting Super Simple SHell."
<< std::endl << std::endl;
the_shell.clearCmdLineArgs();
// use this, it works.
// odd behavior with exit(EXIT_SUCCESS) and return
// low priority bug
stop = true;
continue;
}
if(the_shell.isEmptyString()){
// empty string command
std::cout << std::endl <<
"** WARNING: Empty string command found. Please try again."
<< std::endl << std::endl;
// clear the command line argurments
the_shell.clearCmdLineArgs();
// start loop over and get input again
continue;
}
if(the_shell.isWaitNum()){
// wait num
if(the_shell.runWaitNum()){
std::cout << std::endl <<
"** Info: wait num command processed."
<< std::endl << std::endl;
} else{
std::cout << std::endl <<
"** Info: wait num cannot be processed."
<< std::endl << std::endl;
}
// clear the command line argurments
the_shell.clearCmdLineArgs();
// start loop over and get input again
continue;
}
if(the_shell.isChangeDirectory()){
// cd dir
the_shell.runChangeDirectory();
std::cout << std::endl <<
"** Info: cd dir command processes."
<< std::endl << std::endl;
// clear the command line argurments
the_shell.clearCmdLineArgs();
// start loop over and get input again
continue;
}
if(the_shell.isPriorCommandRequest()){
// user requested !!
// over-ride the current "!!" command with whatever was the prior
the_shell.setCurrentCommand( the_shell.getLastCommand() );
// now initiate a normal process
if( the_shell.runInput() ){
//
std::cout << std::endl <<
"** Info: !! command processes."
<< std::endl << std::endl;
}
// clear the command line argurments
the_shell.clearCmdLineArgs();
// start loop over and get input again
continue;
}
// proceed to running some jobs
if(the_shell.runInput()){
// success
// now what?
// clear the vector of the current commands
the_shell.clearCmdLineArgs();
// I don't think there is anything else to do at this point, but loop
} else{
// not success
// anything todo here?
// clear the vector of the current commands
the_shell.clearCmdLineArgs();
// i don't think so.
}
}
return EXIT_SUCCESS;
}
//=============================================================================
// end main()
//=============================================================================
// =============================================================================
/*
* Description
* add a new process to the vector of processess
*
* Parameters
* new process
*
* Return Value
* void
*/
void SSSH::addProcess(Process* theProcess)
{
// add a new process
SSSH::myprocs.push_back(theProcess);
// SSSH::theProcess = theProcess;
}
// =============================================================================
/*
* Description
* parse the input and store it in the cmd_line_args vector
*
* Parameters
* void
*
* Return Value
* void
*/
void SSSH::parseInput()
{
// reading the cmd line
std::string word;
std::string line;
// prompt
std::cout << "sssh: ";
// process input
std::getline(std::cin, line);
std::istringstream iss(line);
while ( iss >> word) {
cmd_line_args.push_back(word);
}
}
// =============================================================================
/*
* Description
* run the input
*
* Parameters
* void
*
* Return Value
* void
*/
bool SSSH::runInput()
{
// create new process
Process *p = new Process();
// pass the args to process
if( p->processInput(cmd_line_args) ){
// success
// if this is a background job
if(p->isBGProcess()){
// add it
addProcess(p);
}
return true;
} else{
return false;
}
}
// =============================================================================
/*
* Description
* get the last command
*
* Parameters
* void
*
* Return Value
* prior command
*/
std::vector<std::string> SSSH::getLastCommand()
{
return SSSH::prior_cmd_line_args;
}
// =============================================================================
/*
* Description
* set the current command
*
* Parameters
* void
*
* Return Value
* void
*/
void SSSH::setCurrentCommand(std::vector<std::string> new_cmd)
{
SSSH::cmd_line_args = new_cmd;
}
// =============================================================================
/*
* Description
* constructor
*
* Parameters
* void
*
* Return Value
* void
*/
SSSH::SSSH()
{
}
// =============================================================================
/*
* Description
* destructor
*
* Parameters
* void
*
* Return Value
* void
*/
SSSH::~SSSH()
{
// delete pointers to processes
// for(std::vector<Process*>::iterator iter = myprocs.begin();
// iter != myprocs.end();
// iter++){
// delete *iter;
// }
// myprocs.clear();
}
// =============================================================================
/*
* Description
* did user enter wait num?
*
* Parameters
* dir
*
* Return Value
* void
*/
bool SSSH::isWaitNum()
{
if(cmd_line_args.size() == 0){
return false;
}else {
// get the command and compare
return SSSH::toLower(cmd_line_args.at(0)) == "wait";
}
}
// =============================================================================
/*
* Description
* handle built in wait num
*
* Parameters
* time to wait
*
* Return Value
* void
*/
bool SSSH::runWaitNum()
{
// the number should be the second value in the arguments list
int num = -1;
std::string test = cmd_line_args.at(1);
if( isdigit( test[0]) ){
num = atoi(test.c_str());
// iterate through all of the processes checking if the indicated
// sssh number exists and is running
bool matchFound = false;
Job *theJob;
// check that the sssh # exists and is running
for(size_t i = 0; i < myprocs.size(); i++){
theJob = myprocs.at( i)->getJob();
if(theJob != NULL){
// test if we have a match
while( (theJob->getSSSHID() == num) && (theJob->isRunning()) ){
// if we're here, then the sssh# matches and job running
matchFound = true;
std::cout << "Job# " << num << " is running." << std::endl;
sleep(1);
}
if(matchFound){
std::cout << "Job# " << num << " is finished." << std::endl;
break;
}
}
}
if( !matchFound ){
std::cout << "Job# " << num << " is not found or job already finised." << std::endl;
}
}else{
return false;
}
return true;
}
// =============================================================================
/*
* Description
* user enter empty string?
*
* Parameters
* void
*
* Return Value
* void
*/
bool SSSH::isEmptyString()
{
return cmd_line_args.size() == 0;
}
// =============================================================================
/*
* Description
* user enter exit?
*
* Parameters
* void
*
* Return Value
* void
*/
bool SSSH::isExit()
{
if(cmd_line_args.size() == 0){
return false;
}else {
// get the command and compare
return SSSH::toLower(cmd_line_args.at(0)) == "exit";
}
}
// =============================================================================
/*
* Description
* user enter cd dir?
*
* Parameters
* void
*
* Return Value
* bool
*/
bool SSSH::isChangeDirectory()
{
// i thought cd dir might be implemented as a fg process, but didn't seem
// to work
if(cmd_line_args.size() == 0){
return false;
}else {
// get the command and compare
return SSSH::toLower(cmd_line_args.at(0)) == "cd";
}
}
// =============================================================================
/*
* Description
* handle built in cd dir
*
* Parameters
*
*
* Return Value
* success failure
*/
void SSSH::runChangeDirectory()
{
// user entered cd dir
std::string dir = SSSH::cmd_line_args.at(1);
std::string result;
int test = chdir(dir.c_str());
if( test < 0 ){
//error
result = "unsuccessful";
}else{
// success
result = "successful";
}
std::cout << "Changing to " << dir << " was " << result << "." << std::endl;
}
// =============================================================================
/*
* Description
* helper function to make strings lowercase
*
* Parameters
* string to transform
*
* Return Value
* lower case string
*/
std::string SSSH::toLower(std::string tmp)
{
// get the command
tmp = cmd_line_args.at(0);
// to lower
std::transform( tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
return tmp;
}
// =============================================================================
/*
* Description
* keep a copy of the last command
*
* Parameters
*
*
* Return Value
* void
*/
void SSSH::clearCmdLineArgs()
{
// test if the current command was "!!" which is to run the prior command
// if so, then don't save it to prior command, just discard it
if( SSSH::isPriorCommandRequest()){
// then just discard it and keep prior command
// this allows the multiple use of !!,albeit the same command
cmd_line_args.clear();
}else{
SSSH::prior_cmd_line_args.clear();
SSSH::prior_cmd_line_args = cmd_line_args;
SSSH::cmd_line_args.clear();
}
}
// =============================================================================
/*
* Description
* get the next sssh id#
*
* Parameters
*
*
* Return Value
* the next value
*/
int SSSH::getNextSsshId()
{
// increment and return
currentSsshId += 1;
return currentSsshId;
}
// =============================================================================
/*
* Description
* decrement sssh #
*
* Parameters
*
*
* Return Value
* void
*/
void SSSH::decSsshId()
{
// decrement the current sssh id #
if(currentSsshId > 0){
currentSsshId--;
}
}
// =============================================================================
/*
* Description
* print the background jobs
*
* Parameters
*
*
* Return Value
* void
*/
void SSSH::printBGJobs()
{
// print fg
std::cout << std::endl;
printBGRunningJobs();
std::cout << std::endl;
// print bg
printBGFinishedJobs();
std::cout << std::endl;
// remove finised processes
removeFinishedProcesses();
}
// =============================================================================
/*
* Description
* print the background jobs still running
*
* Parameters
*
*
* Return Value
* void
*/
void SSSH::printBGRunningJobs()
{
// are there any jobs?
if( myprocs.empty() ){
std::cout << "No background jobs running." << std::endl;
} else{
// header
std::cout << "Running BG Jobs" << std::endl;
std::cout << "---------------" << std::endl;
Process* theProc;
std::vector<Process*>::iterator itr;
for(itr = myprocs.begin(); itr != myprocs.end(); itr++){
theProc = (*itr);
// if not null and not empty
if( (theProc != NULL) && !(theProc->isEmpty() ) ){
// okay to print
theProc->printBGRunningJobs();
}
theProc = NULL;
}
}
}
// =============================================================================
/*
* Description
* print the background jobs that have finised running
*
* Parameters
*
*
* Return Value
* void
*/
void SSSH::printBGFinishedJobs()
{
// are there any jobs?
if( myprocs.empty() ){
// std::cout << "No background jobs running." << std::endl;
} else{
// header
std::cout << "Finished BG Jobs" << std::endl;
std::cout << "---------------" << std::endl;
Process *theProc;
std::vector<Process*>::iterator itr;
for(itr = myprocs.begin(); itr != myprocs.end(); itr++){
//copy const shouldmake thrProc a ref not a pointer
theProc = (*itr);
// if not null and not empty
if( (theProc != NULL) && !(theProc->isEmpty() ) ){
// okay to print
theProc->printBGFinishedJobs();
}
theProc = NULL;
}
}
}
// =============================================================================
/*
* Description
* remove finished processes
*
* Parameters
*
*
* Return Value
* bool
*/
void SSSH::removeFinishedProcesses()
{
// a process should remove finished jobs, so any process with size
// of zero should also be removed
// vectors causing problems bc i'm removing random positions and i think
// the iterator pointer is being invalidated.
// move to linked list data structure
// won't rewrite everthing, due to time constraints, but
// this should do as this is the only place causing problems
std::vector<Process*> myCopy;
Process *theProc;
// copy desirable processes to the list
for(size_t i = 0; i < myprocs.size(); i++){
theProc = myprocs.at(i);
// if the process is not null and not empty, keep it
if( theProc != NULL && !(theProc->isEmpty()) ){
// store a reference in the list
myCopy.push_back( theProc );
theProc = NULL;
}
}
// clear the vector s/b okay b/c it should call the destructor on each
// process which does nothing
myprocs.clear();
// if not empty
if( !myCopy.empty() ){
// put the kept process back in vector
std::vector<Process*>::iterator itr;
for(size_t i = 0; i < myCopy.size(); i++){
myprocs.push_back(myCopy.at(i));
}
}
// clear the copy
// myCopy.clear();
}
/*
* Description
* test for command !!
*
* Parameters
* command line input
*
* Return Value
* bool
*/
bool SSSH::isPriorCommandRequest() const
{
if( !cmd_line_args.empty() ){
std::string tmp =cmd_line_args.at(0);
if( tmp == "!!"){
return true;
} else{
return false;
}
} else{
return false;
}
}
| 22.606183 | 96 | 0.470242 | [
"vector",
"transform"
] |
229064d7b69277e9b41514981ea9144d708e30cd | 4,551 | cc | C++ | media/cast/logging/logging_raw.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | media/cast/logging/logging_raw.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | media/cast/logging/logging_raw.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/cast/logging/logging_raw.h"
#include <algorithm>
#include "base/logging.h"
#include "base/time/time.h"
namespace media {
namespace cast {
LoggingRaw::LoggingRaw() {}
LoggingRaw::~LoggingRaw() {}
void LoggingRaw::InsertFrameEvent(const base::TimeTicks& time_of_event,
CastLoggingEvent event,
EventMediaType event_media_type,
uint32 rtp_timestamp,
uint32 frame_id) {
InsertBaseFrameEvent(time_of_event, event, event_media_type, frame_id,
rtp_timestamp, base::TimeDelta(), 0, false, 0);
}
void LoggingRaw::InsertEncodedFrameEvent(const base::TimeTicks& time_of_event,
CastLoggingEvent event,
EventMediaType event_media_type,
uint32 rtp_timestamp, uint32 frame_id,
int size, bool key_frame,
int target_bitrate) {
InsertBaseFrameEvent(time_of_event, event, event_media_type,
frame_id, rtp_timestamp, base::TimeDelta(), size,
key_frame, target_bitrate);
}
void LoggingRaw::InsertFrameEventWithDelay(const base::TimeTicks& time_of_event,
CastLoggingEvent event,
EventMediaType event_media_type,
uint32 rtp_timestamp,
uint32 frame_id,
base::TimeDelta delay) {
InsertBaseFrameEvent(time_of_event, event, event_media_type, frame_id,
rtp_timestamp, delay, 0, false, 0);
}
void LoggingRaw::InsertBaseFrameEvent(const base::TimeTicks& time_of_event,
CastLoggingEvent event,
EventMediaType event_media_type,
uint32 frame_id,
uint32 rtp_timestamp,
base::TimeDelta delay, int size,
bool key_frame, int target_bitrate) {
FrameEvent frame_event;
frame_event.rtp_timestamp = rtp_timestamp;
frame_event.frame_id = frame_id;
frame_event.size = size;
frame_event.timestamp = time_of_event;
frame_event.type = event;
frame_event.media_type = event_media_type;
frame_event.delay_delta = delay;
frame_event.key_frame = key_frame;
frame_event.target_bitrate = target_bitrate;
for (std::vector<RawEventSubscriber*>::const_iterator it =
subscribers_.begin();
it != subscribers_.end(); ++it) {
(*it)->OnReceiveFrameEvent(frame_event);
}
}
void LoggingRaw::InsertPacketEvent(const base::TimeTicks& time_of_event,
CastLoggingEvent event,
EventMediaType event_media_type,
uint32 rtp_timestamp,
uint32 frame_id, uint16 packet_id,
uint16 max_packet_id, size_t size) {
PacketEvent packet_event;
packet_event.rtp_timestamp = rtp_timestamp;
packet_event.frame_id = frame_id;
packet_event.max_packet_id = max_packet_id;
packet_event.packet_id = packet_id;
packet_event.size = size;
packet_event.timestamp = time_of_event;
packet_event.type = event;
packet_event.media_type = event_media_type;
for (std::vector<RawEventSubscriber*>::const_iterator it =
subscribers_.begin();
it != subscribers_.end(); ++it) {
(*it)->OnReceivePacketEvent(packet_event);
}
}
void LoggingRaw::AddSubscriber(RawEventSubscriber* subscriber) {
DCHECK(subscriber);
DCHECK(std::find(subscribers_.begin(), subscribers_.end(), subscriber) ==
subscribers_.end());
subscribers_.push_back(subscriber);
}
void LoggingRaw::RemoveSubscriber(RawEventSubscriber* subscriber) {
DCHECK(subscriber);
DCHECK(std::find(subscribers_.begin(), subscribers_.end(), subscriber) !=
subscribers_.end());
subscribers_.erase(
std::remove(subscribers_.begin(), subscribers_.end(), subscriber),
subscribers_.end());
}
} // namespace cast
} // namespace media
| 39.573913 | 80 | 0.591958 | [
"vector"
] |
22a3be06fbc81624e1afbe5d285ad4d281ac5d40 | 1,193 | cpp | C++ | data/train/cpp/a64d0b1561c04b096563466ea9d7af42b006e7beModelManager.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/cpp/a64d0b1561c04b096563466ea9d7af42b006e7beModelManager.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/cpp/a64d0b1561c04b096563466ea9d7af42b006e7beModelManager.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #include "ModelManager.h"
#include "Global.h"
using namespace std;
using namespace DirectX;
using namespace DirectX::SimpleMath;
//*********************************************************************
// コンストラクタ
//*********************************************************************
ModelManager::ModelManager()
{
}
//*********************************************************************
// デストラクタ
//*********************************************************************
ModelManager::~ModelManager()
{
}
//*********************************************************************
// モデルの登録
//*********************************************************************
Model* ModelManager::EntryModel(eModels modelNumber, const wchar_t* modelName)
{
// モデルの読み込み
Model* model;
model = Model::CreateFromCMO(g_pd3dDevice, L"Cube.cmo", *g_FXFactory).get();
// マップ登録
_models.insert( map<eModels, Model*>::value_type( modelNumber, model ));
return nullptr;
}
//*********************************************************************
// モデルのポインタ取得
//*********************************************************************
Model* ModelManager::GetModel(eModels modelNumber)
{
return nullptr;
}
| 23.86 | 78 | 0.376362 | [
"model"
] |
22a6a5c640aa2ad3a51dfa7495eea54e0685b051 | 16,791 | hpp | C++ | include/src/Core/Eigen/BlockBindings.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | 1 | 2021-11-03T11:30:05.000Z | 2021-11-03T11:30:05.000Z | include/src/Core/Eigen/BlockBindings.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | include/src/Core/Eigen/BlockBindings.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | /*
* This file is part of bogus, a C++ sparse block matrix library.
*
* Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
*
* 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/.
*/
/*! \file
Necessary bindings to use Eigen matrices as block types, and
\c operator* specialization for matrix/vector products
*/
#ifndef BLOCK_EIGENBINDINGS_HPP
#define BLOCK_EIGENBINDINGS_HPP
#include <Eigen/Core>
#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE
#include "SparseHeader.hpp"
#endif
#include "../Block/BlockMatrixBase.hpp"
#include "../Block/Expressions.hpp"
#ifndef BOGUS_BLOCK_WITHOUT_LINEAR_SOLVERS
#include "EigenLinearSolvers.hpp"
#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE
#include "EigenSparseLinearSolvers.hpp"
#endif
#endif
#include "../Utils/CppTools.hpp"
#define BOGUS_EIGEN_NEW_EXPRESSIONS EIGEN_VERSION_AT_LEAST(3,2,90)
namespace bogus
{
// transpose_block, is_zero, resize, set_identity
template< typename EigenDerived >
inline bool is_zero ( const Eigen::MatrixBase< EigenDerived >& block,
typename EigenDerived::Scalar precision )
{
return block.isZero( precision ) ;
}
template< typename EigenDerived >
inline void set_zero ( Eigen::MatrixBase< EigenDerived >& block )
{
block.derived().setZero( ) ;
}
template< typename EigenDerived >
inline void set_identity ( Eigen::MatrixBase< EigenDerived >& block )
{
block.derived().setIdentity( ) ;
}
template< typename EigenDerived >
inline void resize ( Eigen::MatrixBase< EigenDerived >& block, int rows, int cols )
{
block.derived().resize( rows, cols ) ;
}
template< typename EigenDerived >
inline const typename EigenDerived::Scalar* data_pointer ( const Eigen::MatrixBase< EigenDerived >& block )
{
return block.derived().data() ;
}
#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE
#if !BOGUS_EIGEN_NEW_EXPRESSIONS
template < typename BlockT >
struct BlockTransposeTraits< Eigen::SparseMatrixBase < BlockT > > {
typedef const Eigen::Transpose< const BlockT > ReturnType ;
} ;
template<typename _Scalar, int _Flags, typename _Index>
struct BlockTransposeTraits< Eigen::SparseMatrix < _Scalar, _Flags, _Index > >
: public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::SparseMatrix < _Scalar, _Flags, _Index > > >
{} ;
template<typename _Scalar, int _Flags, typename _Index>
struct BlockTransposeTraits< Eigen::SparseVector < _Scalar, _Flags, _Index > >
: public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::SparseVector < _Scalar, _Flags, _Index > > >
{} ;
template<typename _Scalar, int _Flags, typename _Index>
struct BlockTransposeTraits< Eigen::MappedSparseMatrix < _Scalar, _Flags, _Index > >
: public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::MappedSparseMatrix < _Scalar, _Flags, _Index > > >
{} ;
template< typename EigenDerived >
inline const Eigen::Transpose< const EigenDerived >
transpose_block( const Eigen::SparseMatrixBase< EigenDerived >& block )
{
return block.transpose() ;
}
#endif
template< typename EigenDerived >
inline bool is_zero ( const Eigen::SparseMatrixBase< EigenDerived >& block,
typename EigenDerived::Scalar precision )
{
return block.isZero( precision ) ;
}
template < typename Scalar, int Options, typename Index >
inline void set_identity ( Eigen::SparseMatrix< Scalar, Options, Index >& block )
{
return block.setIdentity( ) ;
}
template < typename Scalar, int Options, typename Index >
inline void resize ( Eigen::SparseMatrix< Scalar, Options, Index >& block, Index rows, Index cols )
{
block.resize( rows, cols ) ;
}
#endif
// Block traits for Eigen::Matrix
template< typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols >
struct BlockTraits < Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
{
typedef _Scalar Scalar ;
enum {
RowsAtCompileTime = _Rows,
ColsAtCompileTime = _Cols,
uses_plain_array_storage = 1,
is_row_major = !!( _Options & Eigen::RowMajor ),
is_self_transpose = ( _Rows == _Cols ) && ( _Rows == 1 )
} ;
// Manipulates _Options so that row and column vectorz have the correct RowMajor value
// Should we default to _Options ^ Eigen::RowMajor ?
typedef Eigen::Matrix< _Scalar, _Cols, _Rows,
( _Options | ((_Cols==1&&_Rows!=1)?Eigen::RowMajor:0)) & ~((_Rows==1&&_Cols!=1)?Eigen::RowMajor:0),
_MaxCols, _MaxRows >
TransposeStorageType ;
} ;
// Block/block product return type
template<
typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols,
typename _Scalar2, int _Rows2, int _Cols2, int _Options2, int _MaxRows2, int _MaxCols2,
bool TransposeLhs, bool TransposeRhs >
struct BlockBlockProductTraits <
Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>,
Eigen::Matrix<_Scalar2, _Rows2, _Cols2, _Options2, _MaxRows2, _MaxCols2>,
TransposeLhs, TransposeRhs >
{
typedef Eigen::Matrix< _Scalar,
SwapIf< TransposeLhs, _Rows, _Cols >::First,
SwapIf< TransposeRhs, _Rows2, _Cols2 >::Second,
_Options,
SwapIf< TransposeLhs, _MaxRows, _MaxCols >::First,
SwapIf< TransposeRhs, _MaxRows2, _MaxCols2 >::Second >
ReturnType ;
} ;
template< typename Derived >
inline typename Eigen::internal::plain_matrix_type<Derived>::type
get_mutable_vector( const Eigen::MatrixBase< Derived > & )
{
return typename Eigen::internal::plain_matrix_type<Derived>::type() ;
}
} //ns bogus
// Matrix vector product return types and operator*
namespace bogus {
namespace mv_impl {
//! Wrapper so our SparseBlockMatrix can be used inside Eigen expressions
template< typename Derived >
struct EigenBlockWrapper : public Eigen::EigenBase< EigenBlockWrapper< Derived > >
{
typedef EigenBlockWrapper Nested ;
typedef EigenBlockWrapper NestedExpression ;
typedef EigenBlockWrapper PlainObject ;
typedef Eigen::internal::traits< EigenBlockWrapper< Derived > > Traits ;
typedef typename Traits::Scalar Scalar ;
typedef typename Traits::Index Index ;
enum { Flags = Traits::Flags, IsVectorAtCompileTime = 0,
MaxRowsAtCompileTime = Traits::MaxRowsAtCompileTime,
MaxColsAtCompileTime = Traits::MaxColsAtCompileTime
} ;
EigenBlockWrapper ( const Derived &obj_, Scalar s = 1 )
: obj( obj_ ), scaling(s)
{}
Index rows() const { return obj.rows() ; }
Index cols() const { return obj.cols() ; }
// Mult by scalar
inline EigenBlockWrapper
operator*(const Scalar& scalar) const
{ return EigenBlockWrapper( obj, scaling * scalar ) ; }
inline friend EigenBlockWrapper
operator*(const Scalar& scalar, const EigenBlockWrapper& matrix)
{ return EigenBlockWrapper( matrix.obj, matrix.scaling * scalar ) ; }
// Product with other Eigen expr
#if BOGUS_EIGEN_NEW_EXPRESSIONS
template < typename EigenDerived >
inline Eigen::Product< EigenBlockWrapper, EigenDerived > operator* (
const EigenDerived &rhs ) const
{
return Eigen::Product< EigenBlockWrapper, EigenDerived > (*this, rhs) ;
}
template < typename EigenDerived >
friend inline Eigen::Product< EigenDerived, EigenBlockWrapper > operator* (
const EigenDerived &lhs, const EigenBlockWrapper &matrix )
{
return Eigen::Product< EigenDerived, EigenBlockWrapper > (lhs, matrix) ;
}
#endif
const Derived &obj ;
const Scalar scaling ;
};
//! SparseBlockMatrix / Dense producty expression
template< typename Lhs, typename Rhs >
struct block_product_impl;
#if BOGUS_EIGEN_NEW_EXPRESSIONS
template < typename Lhs, typename Rhs >
struct BlockEigenProduct
: public Eigen::Product< Lhs, Rhs >
{
typedef Eigen::Product< Lhs, Rhs > Base ;
BlockEigenProduct( const Lhs& lhs, const Rhs& rhs )
: Base( lhs, rhs)
{}
} ;
#else
template < typename Lhs, typename Rhs >
struct BlockEigenProduct
: public Eigen::ProductBase< BlockEigenProduct< Lhs, Rhs>, Lhs, Rhs >
{
typedef Eigen::ProductBase< BlockEigenProduct, Lhs, Rhs > Base ;
BlockEigenProduct( const Lhs& lhs, const Rhs& rhs )
: Base( lhs, rhs)
{}
EIGEN_DENSE_PUBLIC_INTERFACE( BlockEigenProduct )
using Base::m_lhs;
using Base::m_rhs;
typedef block_product_impl< typename Base::LhsNested, typename Base::RhsNested > product_impl ;
template<typename Dest> inline void evalTo(Dest& dst) const
{
product_impl::evalTo( dst, m_lhs, this->m_rhs ) ;
}
template<typename Dest> inline void scaleAndAddTo(Dest& dst, Scalar alpha) const
{
product_impl::scaleAndAddTo( dst, m_lhs, m_rhs, alpha ) ;
}
};
#endif
template< typename Derived, typename EigenDerived >
BlockEigenProduct< EigenBlockWrapper< Derived >, EigenDerived > block_eigen_product(
const Derived &matrix, const EigenDerived &vector, typename Derived::Scalar scaling = 1 )
{
return BlockEigenProduct< EigenBlockWrapper< Derived >, EigenDerived > ( EigenBlockWrapper< Derived >(matrix, scaling), vector ) ;
}
template< typename Derived, typename EigenDerived >
BlockEigenProduct< EigenDerived, EigenBlockWrapper< Derived > > eigen_block_product(
const EigenDerived &vector, const Derived &matrix, typename Derived::Scalar scaling = 1 )
{
return BlockEigenProduct< EigenDerived, EigenBlockWrapper< Derived > > ( vector, EigenBlockWrapper< Derived >(matrix, scaling) ) ;
}
template<typename Derived, typename EigenDerived >
struct block_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived >
{
typedef bogus::mv_impl::EigenBlockWrapper<Derived> Lhs ;
typedef EigenDerived Rhs ;
typedef typename Derived::Scalar Scalar;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
lhs.obj.template multiply< false >( rhs.derived(), dst, lhs.scaling, 0 ) ;
}
template<typename Dst>
static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
lhs.obj.template multiply< false >( rhs.derived(), dst, alpha*lhs.scaling, 1 ) ;
}
};
template<typename Derived, typename EigenDerived >
struct block_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived> >
{
typedef EigenDerived Lhs ;
typedef bogus::mv_impl::EigenBlockWrapper<Derived> Rhs ;
typedef typename Derived::Scalar Scalar;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
Eigen::Transpose< Dst > transposed( dst.transpose() ) ;
rhs.obj.template multiply< true >( lhs.transpose(), transposed, rhs.scaling, 0 ) ;
}
template<typename Dst>
static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
Eigen::Transpose< Dst > transposed( dst.transpose() ) ;
rhs.obj.template multiply< true >( lhs.transpose(), transposed, alpha * rhs.scaling, 1 ) ;
}
};
} //namespace mv_impl
} //namespace bogus
#if BOGUS_EIGEN_NEW_EXPRESSIONS
namespace Eigen {
namespace internal {
template<typename Derived, typename EigenDerived, int ProductType >
struct generic_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived, SparseShape, DenseShape, ProductType>
: public generic_product_impl_base <
bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived,
generic_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived, SparseShape, DenseShape, ProductType > >
{
typedef bogus::mv_impl::EigenBlockWrapper<Derived> Lhs ;
typedef EigenDerived Rhs ;
typedef typename Derived::Scalar Scalar;
typedef typename nested_eval<Rhs,Dynamic>::type RhsNested;
typedef bogus::mv_impl::block_product_impl< Lhs, RhsNested > product_impl ;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
RhsNested rhsNested( rhs ) ;
product_impl::evalTo( dst, lhs, rhsNested ) ;
}
template<typename Dst>
static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, Scalar alpha)
{
RhsNested rhsNested( rhs ) ;
product_impl::scaleAndAddTo( dst, lhs, rhsNested, alpha ) ;
}
};
template<typename Derived, typename EigenDerived, int ProductType >
struct generic_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>, DenseShape, SparseShape, ProductType >
: public generic_product_impl_base <
EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>,
generic_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>, DenseShape, SparseShape, ProductType > >
{
typedef EigenDerived Lhs ;
typedef bogus::mv_impl::EigenBlockWrapper<Derived> Rhs ;
typedef typename Derived::Scalar Scalar;
typedef typename nested_eval<Lhs,Dynamic>::type LhsNested;
typedef bogus::mv_impl::block_product_impl< LhsNested, Rhs > product_impl ;
template<typename Dst>
static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)
{
LhsNested lhsNested(lhs);
product_impl::evalTo( dst, lhsNested, rhs) ;
}
template<typename Dst>
static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)
{
LhsNested lhsNested(lhs);
product_impl::scaleAndAddTo( dst, lhsNested, rhs, alpha ) ;
}
};
// s * (A * V) -> ( (s*A) * V )
// (A already includes a scaling parameter)
// TODO adapt to other orderings
template<typename Derived, typename Rhs, typename Scalar1, typename Scalar2, typename Plain1>
struct evaluator<CwiseBinaryOp<internal::scalar_product_op<Scalar1,Scalar2>,
const CwiseNullaryOp<internal::scalar_constant_op<Scalar1>, Plain1>,
const Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > >
: public evaluator<Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> >
{
typedef CwiseBinaryOp<internal::scalar_product_op<Scalar1,Scalar2>,
const CwiseNullaryOp<internal::scalar_constant_op<Scalar1>, Plain1>,
const Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > XprType;
typedef evaluator<Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > Base;
explicit evaluator(const XprType& xpr)
: Base( bogus::mv_impl::EigenBlockWrapper<Derived>(
xpr.rhs().lhs().obj, xpr.lhs().functor().m_other * xpr.rhs().lhs().scaling)
* xpr.rhs().rhs() )
{}
};
} //internal
} //Eigen
#endif
// Eigen traits for our new structs
namespace Eigen{
namespace internal {
template < typename Lhs, typename Rhs >
struct traits< bogus::mv_impl::BlockEigenProduct< Lhs, Rhs > >
#if BOGUS_EIGEN_NEW_EXPRESSIONS
: public traits< typename bogus::mv_impl::BlockEigenProduct< Lhs, Rhs >::Base >
#else
: public traits< ProductBase< bogus::mv_impl::BlockEigenProduct< Lhs, Rhs >, Lhs, Rhs > >
#endif
{
typedef Dense StorageKind;
} ;
template<typename Derived>
struct traits<bogus::mv_impl::EigenBlockWrapper<Derived> >
{
typedef typename Derived::Scalar Scalar;
typedef typename Derived::Index Index;
typedef typename Derived::Index StorageIndex;
#if BOGUS_EIGEN_NEW_EXPRESSIONS
typedef Sparse StorageKind;
#else
typedef Dense StorageKind;
#endif
typedef MatrixXpr XprKind;
enum {
RowsAtCompileTime = Dynamic,
ColsAtCompileTime = Dynamic,
MaxRowsAtCompileTime = Dynamic,
MaxColsAtCompileTime = Dynamic,
Flags = 0
};
};
}
} //namespace Eigen
// Matrix-Vector operators
namespace bogus{
template < typename Derived, typename EigenDerived >
mv_impl::BlockEigenProduct< mv_impl::EigenBlockWrapper<Derived>, EigenDerived > operator* (
const BlockObjectBase< Derived >& lhs,
const Eigen::MatrixBase< EigenDerived > &rhs )
{
assert( rhs.rows() == lhs.cols() ) ;
return mv_impl::block_eigen_product ( lhs.derived(), rhs.derived() ) ;
}
template < typename Derived, typename EigenDerived >
mv_impl::BlockEigenProduct< mv_impl::EigenBlockWrapper<Derived>, EigenDerived > operator* (
const Scaling< Derived >& lhs,
const Eigen::MatrixBase< EigenDerived > &rhs )
{
assert( rhs.rows() == lhs.cols() ) ;
return mv_impl::block_eigen_product ( lhs.operand.object, rhs.derived(), lhs.operand.scaling ) ;
}
template < typename Derived, typename EigenDerived >
mv_impl::BlockEigenProduct< EigenDerived, mv_impl::EigenBlockWrapper<Derived> > operator* (
const Eigen::MatrixBase< EigenDerived > &lhs,
const BlockObjectBase< Derived >& rhs )
{
assert( lhs.cols() == rhs.rows() ) ;
return mv_impl::eigen_block_product ( lhs.derived(), rhs.derived() ) ;
}
template < typename Derived, typename EigenDerived >
mv_impl::BlockEigenProduct< EigenDerived, mv_impl::EigenBlockWrapper<Derived> > operator* (
const Eigen::MatrixBase< EigenDerived > &lhs,
const Scaling< Derived >& rhs )
{
assert( lhs.cols() == rhs.rows() ) ;
return mv_impl::eigen_block_product ( lhs.derived(), rhs.operand.object, rhs.operand.scaling ) ;
}
} //namespace bogus
#endif // EIGENBINDINGS_HPP
| 32.923529 | 132 | 0.731999 | [
"object",
"vector"
] |
22aa4ae3ab39c71948f8f19e98bc8ddea416c290 | 1,907 | cc | C++ | services/device/public/cpp/hid/hid_device_filter.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 | services/device/public/cpp/hid/hid_device_filter.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/device/public/cpp/hid/hid_device_filter.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/device/public/cpp/hid/hid_device_filter.h"
namespace device {
HidDeviceFilter::HidDeviceFilter()
: vendor_id_set_(false),
product_id_set_(false),
usage_page_set_(false),
usage_set_(false) {}
HidDeviceFilter::~HidDeviceFilter() {}
void HidDeviceFilter::SetVendorId(uint16_t vendor_id) {
vendor_id_set_ = true;
vendor_id_ = vendor_id;
}
void HidDeviceFilter::SetProductId(uint16_t product_id) {
product_id_set_ = true;
product_id_ = product_id;
}
void HidDeviceFilter::SetUsagePage(uint16_t usage_page) {
usage_page_set_ = true;
usage_page_ = usage_page;
}
void HidDeviceFilter::SetUsage(uint16_t usage) {
usage_set_ = true;
usage_ = usage;
}
bool HidDeviceFilter::Matches(const mojom::HidDeviceInfo& device_info) const {
if (vendor_id_set_) {
if (device_info.vendor_id != vendor_id_) {
return false;
}
if (product_id_set_ && device_info.product_id != product_id_) {
return false;
}
}
if (usage_page_set_) {
bool found_matching_collection = false;
for (const auto& collection : device_info.collections) {
if (collection->usage->usage_page != usage_page_) {
continue;
}
if (usage_set_ && collection->usage->usage != usage_) {
continue;
}
found_matching_collection = true;
}
if (!found_matching_collection) {
return false;
}
}
return true;
}
// static
bool HidDeviceFilter::MatchesAny(const mojom::HidDeviceInfo& device_info,
const std::vector<HidDeviceFilter>& filters) {
for (const HidDeviceFilter& filter : filters) {
if (filter.Matches(device_info)) {
return true;
}
}
return false;
}
} // namespace device
| 24.139241 | 79 | 0.683272 | [
"vector"
] |
22aa6afbca1c110837266763e9ee84929b6a7462 | 761 | cpp | C++ | 1197. Lonesome Knight.cpp | satvik007/Timus | b1ed1d693b67fdbb17891e8612f596eabedfff67 | [
"MIT"
] | null | null | null | 1197. Lonesome Knight.cpp | satvik007/Timus | b1ed1d693b67fdbb17891e8612f596eabedfff67 | [
"MIT"
] | null | null | null | 1197. Lonesome Knight.cpp | satvik007/Timus | b1ed1d693b67fdbb17891e8612f596eabedfff67 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <int> vi;
typedef pair<int, int> ii;
#define inf (int)1e9
int dr[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dc[] = {1, 2, 2, 1, -1, -2, -2, -1};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int tc;
cin >> tc;
while(tc--) {
string a;
cin >> a;
int u = a[0] - 'a';
int v = a[1] - '1';
int cnt = 0;
for(int k = 0; k < 8; k++) {
int tx = u + dr[k];
int ty = v + dc[k];
if(tx >= 0 && ty >= 0 && tx < 8 && ty < 8) cnt++;
}
cout << cnt << "\n";
}
return 0;
}
| 18.119048 | 61 | 0.425756 | [
"vector"
] |
22ac27786b2204cf58a057605ac781efd7dbedb2 | 5,150 | cpp | C++ | src/image/test_image_class/test_image.cpp | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | null | null | null | src/image/test_image_class/test_image.cpp | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | null | null | null | src/image/test_image_class/test_image.cpp | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | null | null | null | //
// Created by Vrushank on 11/20/2021.
//
#include "../image.cpp"
#include "../blurs.cpp"
#include "../collage/collage.cpp"
#include <string>
#include <unistd.h>
#include <algorithm>
using img::Image;
using img::Collage;
std::string get_curr_dir() {
char add[256];
getcwd(add, 256);
// convert char to string
std::string address;
for (int i =0; i< strlen(add); i++)
address += add[i];
return address;
}
int main() {
std::string add = get_curr_dir();
// change path for macOS
add += "\\..\\lena.jpg";
std::string image_path = cv::samples::findFile(add, cv::IMREAD_COLOR);
Image img1 = Image(image_path);
std::string file = img1.getFilename();
Mat matrix = img1.getMat();
// ------------------------BASIC FUNCTIONS---------------------------
// img1.imgPreview("testing");
// cout<<file<<endl;
// img1.resizeImg(500, 600);
// img1.imgModifiedPreview("testing_img_resize");
// img1.rotateImg(25);
// img1.imgModifiedPreview("testing_img_rotate");
// test image dimension equalizing functions
// img1.equalizeImgDim(1920, 1080);
// img1.imgModifiedPreview("test image dimension equalizing");
// img1.bilateralFilter(51 );
// img1.imgModifiedPreview("testing_bilateral_filter");
// img1.addWeighted(0.3, 0.9);
// img1.imgModifiedPreview("testing_fade_function");
// ---------------------------BLUR PREVIEW----------------------------
// testing dynamic image blur functions
// equalize image first
// img1.equalizeImgDim(1920, 1080);
// img1.blurPreview(30 ,30 );
// img1.imgBlurPreview("testing_blur_0");
// img1.bilateralFilterPreview(31 );
// img1.imgBilateralFilterPreview("testing_blur_0");
// img1.boxBlurPreview(30 ,29 );
// img1.imgBoxBlurPreview("testing_blur_0");
// img1.gaussianBlurPreview(30 ,27 );
// img1.imgGaussianBlurPreview("testing_blur_0");
// img1.medianBlurPreview(31 );
// img1.imgMedianBlurPreview("testing_blur_0");
// img1.imgModifiedPreview("testing_blur_0");
// int i = cv::waitKey(0);
// img1.blurPreview(1 ,1 );
// img1.imgBlurPreview("testing_blur_1");
// img1.bilateralFilterPreview(1 );
// img1.imgBilateralFilterPreview("testing_blur_1");
// img1.boxBlurPreview(1 ,1 );
// img1.imgBoxBlurPreview("testing_blur_1");
// img1.gaussianBlurPreview(1 ,1 );
// img1.imgGaussianBlurPreview("testing_blur_1");
// img1.medianBlurPreview(1 );
// img1.imgMedianBlurPreview("testing_blur_1");
// img1.imgModifiedPreview("testing_blur_1");
// int a = cv::waitKey(0);
// img1.blurPreview(50 ,50 );
// img1.imgBlurPreview("testing_blur_2");
// img1.bilateralFilterPreview(51 );
// img1.imgBilateralFilterPreview("testing_blur_2");
// img1.boxBlurPreview(50 ,49 );
// img1.imgBoxBlurPreview("testing_blur_2");
// img1.gaussianBlurPreview(50 ,47 );
// img1.imgGaussianBlurPreview("testing_blur_2");
// img1.medianBlurPreview(51 );
// img1.imgMedianBlurPreview("testing_blur_2");
// img1.imgModifiedPreview("testing_blur_2");
// int b = cv::waitKey(0);
// img1.blurPreview(1 ,1 );
// img1.imgBlurPreview("testing_blur_3");
// img1.bilateralFilterPreview(1 );
// img1.imgBilateralFilterPreview("testing_blur_3");
// img1.boxBlurPreview(1 ,1 );
// img1.imgBoxBlurPreview("testing_blur_3");
// img1.gaussianBlurPreview(1 ,1 );
// img1.imgGaussianBlurPreview("testing_blur_3");
// img1.medianBlurPreview(1 );
// img1.imgMedianBlurPreview("testing_blur_3");
// img1.imgModifiedPreview("testing_blur_3");
// -----------------------------BLURS-------------------------------
// img1.blur(30 ,30 );
// img1.imgModifiedPreview("testing_blur");
// img1.gaussianBlur(4, 6);
// img1.imgModifiedPreview("testing_gaussian_blur");
// img1.medianBlur(5);
// img1.imgModifiedPreview("testing_median_blur");
// img1.boxBlur(5, 6);
// img1.imgModifiedPreview("testing_box_filter");
// ----------------------------STITCHING------------------------------
//define images and vectors
Image img2 = Image(image_path);
Image img3 = Image(image_path);
Image img4 = Image(image_path);
std::vector<Image> imageArr2 = {img1, img2};
std::vector<Image> imageArr3 = {img1, img2, img3};
std::vector<Image> imageArr4 = {img1, img2, img3, img4};
//define collages
// Collage collage2 = Collage(imageArr2);
// Collage collage3 = Collage(imageArr3);
Collage collage4 = Collage(imageArr4);
//run collage functions
// collage2.twoStitch();
// collage3.threeStitch();
// collage4.fourStitch();
collage4.fourStitchRec(3);
// display collage
// Image collage_img2 = Image(collage2.getModifiedImage());
// Image collage_img3 = Image(collage3.getModifiedImage());
Image collage_img4 = Image(collage4.getModifiedImage());
// collage_img2.imgPreview("test_lena_collage2");
// collage_img3.imgPreview("test_lena_collage3");
collage_img4.imgPreview("test_lena_collage4");
// --------------------------------EXIT--------------------------------
int j = cv::waitKey(0);
exit(0);
} | 30.473373 | 74 | 0.634951 | [
"vector"
] |
22b0029939c54a1b31541a7a7c843ca236602096 | 6,289 | cpp | C++ | src/other/ext/openscenegraph/src/osgViewer/HelpHandler.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osgViewer/HelpHandler.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osgViewer/HelpHandler.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/Renderer>
#include <osg/PolygonMode>
#include <osgText/Text>
using namespace osgViewer;
HelpHandler::HelpHandler(osg::ApplicationUsage* au):
_applicationUsage(au),
_keyEventTogglesOnScreenHelp('h'),
_helpEnabled(false),
_initialized(false)
{
_camera = new osg::Camera;
_camera->setRenderer(new Renderer(_camera.get()));
_camera->setRenderOrder(osg::Camera::POST_RENDER, 11);
}
void HelpHandler::reset()
{
_initialized = false;
_camera->setGraphicsContext(0);
}
bool HelpHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
if (!view) return false;
osgViewer::ViewerBase* viewer = view->getViewerBase();
if (!viewer) return false;
if (ea.getHandled()) return false;
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()==_keyEventTogglesOnScreenHelp)
{
if (!_initialized)
{
setUpHUDCamera(viewer);
setUpScene(viewer);
}
_helpEnabled = !_helpEnabled;
if (_helpEnabled)
{
_camera->setNodeMask(0xffffffff);
}
else
{
_camera->setNodeMask(0);
}
return true;
}
}
default: break;
}
return false;
}
void HelpHandler::setUpHUDCamera(osgViewer::ViewerBase* viewer)
{
osgViewer::GraphicsWindow* window = dynamic_cast<osgViewer::GraphicsWindow*>(_camera->getGraphicsContext());
if (!window)
{
osgViewer::Viewer::Windows windows;
viewer->getWindows(windows);
if (windows.empty()) return;
window = windows.front();
_camera->setGraphicsContext(window);
}
_camera->setGraphicsContext(window);
_camera->setViewport(0, 0, window->getTraits()->width, window->getTraits()->height);
_camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
_camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_camera->setViewMatrix(osg::Matrix::identity());
// only clear the depth buffer
_camera->setClearMask(0);
_initialized = true;
}
void HelpHandler::setUpScene(osgViewer::ViewerBase* viewer)
{
_switch = new osg::Switch;
_camera->addChild(_switch.get());
osg::StateSet* stateset = _switch->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
stateset->setAttribute(new osg::PolygonMode(), osg::StateAttribute::PROTECTED);
std::string font("fonts/arial.ttf");
if (!_applicationUsage) setApplicationUsage(new osg::ApplicationUsage());
viewer->getUsage(*_applicationUsage);
float leftPos = 10.0f;
float startDescription = 200.0f;
float characterSize = 20.0f;
osg::Vec3 pos(leftPos,1000.0f,0.0f);
osg::Vec4 color(1.0f,1.0f,1.0f,1.0f);
osg::Geode* geode = new osg::Geode();
_switch->addChild(geode, true);
// application description
if (!_applicationUsage->getDescription().empty())
{
osg::ref_ptr<osgText::Text> label = new osgText::Text;
geode->addDrawable( label.get() );
label->setColor(color);
label->setBackdropType(osgText::Text::OUTLINE);
label->setFont(font);
label->setCharacterSize(characterSize);
label->setPosition(pos);
label->setText(_applicationUsage->getDescription());
pos.x() = label->getBoundingBox().xMax();
pos.y() -= characterSize*2.5f;
}
const osg::ApplicationUsage::UsageMap& keyboardBinding = _applicationUsage->getKeyboardMouseBindings();
for(osg::ApplicationUsage::UsageMap::const_iterator itr = keyboardBinding.begin();
itr != keyboardBinding.end();
++itr)
{
pos.x() = leftPos;
osg::ref_ptr<osgText::Text> key = new osgText::Text;
geode->addDrawable( key.get() );
key->setColor(color);
key->setBackdropType(osgText::Text::OUTLINE);
key->setFont(font);
key->setCharacterSize(characterSize);
key->setPosition(pos);
key->setText(itr->first);
pos.x() = startDescription;
osg::ref_ptr<osgText::Text> description = new osgText::Text;
geode->addDrawable( description.get() );
description->setColor(color);
description->setBackdropType(osgText::Text::OUTLINE);
description->setFont(font);
description->setCharacterSize(characterSize);
description->setPosition(pos);
description->setText(itr->second);
pos.y() -= characterSize*1.5f;
}
osg::BoundingBox bb = geode->getBoundingBox();
if (bb.valid())
{
float width = bb.xMax() - bb.xMin();
float height = bb.yMax() - bb.yMin();
float ratio = 1.0;
if (width > 1024.0f) ratio = 1024.0f/width;
if (height*ratio > 800.0f) ratio = 800.0f/height;
_camera->setViewMatrix(osg::Matrix::translate(-bb.center()) *
osg::Matrix::scale(ratio,ratio,ratio) *
osg::Matrix::translate(osg::Vec3(640.0f, 520.0f, 0.0f)));
}
}
void HelpHandler::getUsage(osg::ApplicationUsage& usage) const
{
if (_keyEventTogglesOnScreenHelp) usage.addKeyboardMouseBinding(_keyEventTogglesOnScreenHelp,"Onscreen help.");
}
| 29.805687 | 115 | 0.633964 | [
"transform"
] |
22b0aa3c76308253c3f3ffe5a5890fbc53b1b88c | 14,068 | cpp | C++ | sd/sd_dx8/Dx8SoundBuffer.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 3 | 2019-04-20T10:16:36.000Z | 2021-03-21T19:51:38.000Z | sd/sd_dx8/Dx8SoundBuffer.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | null | null | null | sd/sd_dx8/Dx8SoundBuffer.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 2 | 2020-04-18T20:04:24.000Z | 2021-09-19T05:07:41.000Z | #include "StdAfx.h"
#include "Dx8SoundDevice.h"
#include "Dx8SoundBuffer.h"
#include "error.h"
#include "toDx8.h"
#include "toString.h"
#include <sd/Errors.h>
#include <float.h>
#include <assert.h>
#include "config.h"
//-----------------------------------------------------------------------------
using namespace sd;
using namespace math;
//-----------------------------------------------------------------------------
Dx8SoundBuffer::Dx8SoundBuffer() :
m_refs(0)
{
defaults();
}
Dx8SoundBuffer::~Dx8SoundBuffer()
{
destroy();
}
void Dx8SoundBuffer::addReference()
{
InterlockedIncrement( &m_refs );
}
void Dx8SoundBuffer::release()
{
if ( 0 == InterlockedDecrement( &m_refs ) )
delete this;
}
int Dx8SoundBuffer::create( SoundDevice* device,
int bytes, int samplesPerSec, int bitsPerSample, int channels, int usageFlags )
{
assert( device );
assert( bytes > 0 );
assert( samplesPerSec > 0 );
assert( bitsPerSample == 8 || bitsPerSample == 16 );
assert( channels == 1 || channels == 2 );
destroy();
m_buffer = 0;
m_buffer3D = 0;
m_samples = bytes / (bitsPerSample/8) / channels;
m_samplesPerSec = samplesPerSec;
m_bitsPerSample = bitsPerSample;
m_channels = channels;
m_usageFlags = usageFlags;
m_dataSize = bytes;
m_data = 0;
m_dataRefs = 0;
m_dirty = false;
m_tm = Matrix4x4(1.f);
m_vel = Vector3(0.f,0.f,0.f);
m_minDistance = 1.f;
m_maxDistance = FLT_MAX;
if ( usageFlags & USAGE_STATIC )
{
m_data = new uint8_t[ m_dataSize ];
m_dataRefs = new long(1);
memset( m_data, 0, m_dataSize );
}
Dx8SoundDevice* dev = static_cast<Dx8SoundDevice*>( device );
IDirectSound8* ds = dev->ds();
IDirectSoundBuffer* buffer = 0;
assert( ds );
// buffer wave format
WAVEFORMATEX fmt;
memset( &fmt, 0, sizeof(fmt) );
fmt.cbSize = 0;
fmt.nAvgBytesPerSec = samplesPerSec * channels * (bitsPerSample/8);
fmt.nBlockAlign = (WORD)(bitsPerSample * channels / 8);
fmt.nChannels = (WORD)channels;
fmt.nSamplesPerSec = samplesPerSec;
fmt.wBitsPerSample = (WORD)bitsPerSample;
fmt.wFormatTag = WAVE_FORMAT_PCM;
// creation flags
int creationFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY; // DSBCAPS_CTRLPAN
if ( creationFlags & USAGE_STATIC )
creationFlags |= DSBCAPS_STATIC;
if ( usageFlags & USAGE_CONTROL3D )
creationFlags |= DSBCAPS_CTRL3D | DSBCAPS_MUTE3DATMAXDISTANCE;
// create the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC desc;
memset( &desc, 0, sizeof(desc) );
desc.dwSize = sizeof(DSBUFFERDESC);
desc.dwFlags = creationFlags;
desc.dwBufferBytes = bytes;
desc.lpwfxFormat = &fmt;
desc.guid3DAlgorithm = DS3DALG_DEFAULT;
//desc.guid3DAlgorithm = DS3DALG_HRTF_FULL;
HRESULT hr = ds->CreateSoundBuffer( &desc, &buffer, 0 );
if ( hr != DS_OK )
{
error( "CreateSoundBuffer failed: %s", toString(hr) );
return ERROR_GENERIC;
}
// get new interfaces
int err = getInterfaces( buffer );
buffer->Release();
buffer = 0;
if ( err )
{
destroy();
return err;
}
return ERROR_NONE;
}
int Dx8SoundBuffer::getInterfaces( IDirectSoundBuffer* buffer )
{
assert( buffer );
// NOTE: Cloned sound buffer do not seem to have IDirectSoundBuffer8 interface
// get DirectX8 interface
/*HRESULT hr = buffer->QueryInterface( IID_IDirectSoundBuffer8, (void**)&m_buffer );
if ( hr != DS_OK )
{
error( "QueryInterface IID_IDirectSoundBuffer8 failed: %s", toString(hr) );
return ERROR_GENERIC;
}*/
m_buffer = buffer;
m_buffer->AddRef();
// get 3D interface
if ( m_usageFlags & USAGE_CONTROL3D )
{
HRESULT hr = m_buffer->QueryInterface( IID_IDirectSound3DBuffer8, (void**)&m_buffer3D );
if ( hr != DS_OK )
{
error( "QueryInterface IID_IDirectSound3DBuffer8 failed: %s", toString(hr) );
return ERROR_GENERIC;
}
}
return ERROR_NONE;
}
int Dx8SoundBuffer::duplicate( sd::SoundDevice* device, sd::SoundBuffer* source )
{
destroy();
Dx8SoundBuffer* src = static_cast<Dx8SoundBuffer*>( source );
Dx8SoundDevice* dev = static_cast<Dx8SoundDevice*>( device );
IDirectSound8* ds = dev->ds();
IDirectSoundBuffer* buffer = 0;
assert( ds );
m_buffer = 0;
m_buffer3D = 0;
m_samples = src->m_samples;
m_samplesPerSec = src->m_samplesPerSec;
m_bitsPerSample = src->m_bitsPerSample;
m_channels = src->m_channels;
m_usageFlags = src->m_usageFlags;
m_dataSize = src->m_dataSize;
m_data = src->m_data;
m_dataRefs = src->m_dataRefs; if (m_dataRefs) *m_dataRefs += 1;
m_dirty = src->m_dirty;
m_tm = src->m_tm;
m_vel = src->m_vel;
m_minDistance = src->m_minDistance;
m_maxDistance = src->m_maxDistance;
// duplicate DirectSound buffer
HRESULT hr = ds->DuplicateSoundBuffer( src->m_buffer, &buffer );
if ( hr != DS_OK )
{
error( "IDirectSound8 DuplicateSoundBuffer failed: %s", toString(hr) );
return ERROR_GENERIC;
}
// get new interfaces
int err = getInterfaces( buffer );
buffer->Release();
buffer = 0;
if ( err )
{
destroy();
return err;
}
return ERROR_NONE;
}
void Dx8SoundBuffer::destroy()
{
destroyDeviceObject();
if ( m_data )
{
if ( 0 == InterlockedDecrement(m_dataRefs) )
{
delete[] m_data;
m_data = 0;
delete m_dataRefs;
m_dataRefs = 0;
m_dataSize = 0;
}
}
defaults();
}
void Dx8SoundBuffer::defaults()
{
m_buffer = 0;
m_buffer3D = 0;
m_samples = 0;
m_samplesPerSec = 0;
m_bitsPerSample = 0;
m_channels = 0;
m_usageFlags = 0;
m_dataSize = 0;
m_data = 0;
m_dataRefs = 0;
m_dirty = false;
m_tm = Matrix4x4(1.f);
m_vel = Vector3(0,0,0);
m_minDistance = 1.f;
m_maxDistance = FLT_MAX;
}
void Dx8SoundBuffer::destroyDeviceObject()
{
if ( m_buffer3D )
{
m_buffer3D->Release();
m_buffer3D = 0;
}
if ( m_buffer )
{
m_buffer->Release();
m_buffer = 0;
}
}
void Dx8SoundBuffer::setCurrentPosition( int offset )
{
HRESULT hr = m_buffer->SetCurrentPosition( offset );
if ( hr != DS_OK )
error( "IDirectSoundBuffer8 SetCurrentPosition failed: %s", toString(hr) );
}
void Dx8SoundBuffer::play( int flags )
{
if ( m_dirty )
if ( load() )
return;
DWORD playFlags = 0;
if ( flags & PLAY_LOOPING )
playFlags |= DSBPLAY_LOOPING;
HRESULT hr = m_buffer->Play( 0, 0, playFlags );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 Play failed: %s", toString(hr) );
if ( hr == DSERR_BUFFERLOST )
handleLostBuffer();
}
}
void Dx8SoundBuffer::stop()
{
HRESULT hr = m_buffer->Stop();
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 Stop failed: %s", toString(hr) );
return;
}
}
int Dx8SoundBuffer::lock( int offset, int bytes,
void** data1, int* bytes1,
void** data2, int* bytes2,
int flags )
{
assert( !locked() );
assert( offset >= 0 && offset < m_dataSize );
assert( offset+bytes > 0 && offset+bytes <= m_dataSize );
assert( data1 && bytes1 );
if ( m_usageFlags & USAGE_STATIC )
{
*data1 = m_data + offset;
*bytes1 = bytes;
if ( data2 )
*data2 = 0;
if ( bytes2 )
*bytes2 = 0;
m_dirty = true;
m_usageFlags |= USAGE_LOCKED;
return ERROR_NONE;
}
else
{
assert( m_usageFlags & USAGE_DYNAMIC );
return lockDevice( offset, bytes, data1, bytes1, data2, bytes2, flags );
}
}
void Dx8SoundBuffer::unlock( void* data1, int bytes1,
void* data2, int bytes2 )
{
assert( locked() );
if ( m_usageFlags & USAGE_DYNAMIC )
unlockDevice( data1, bytes1, data2, bytes2 );
m_usageFlags &= ~USAGE_LOCKED;
if ( m_buffer )
load();
}
void Dx8SoundBuffer::setFrequency( int samplesPerSec )
{
assert( samplesPerSec > 0 );
HRESULT hr = m_buffer->SetFrequency( samplesPerSec );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 SetFrequency failed: %s", toString(hr) );
return;
}
}
void Dx8SoundBuffer::setPan( int pan )
{
assert( pan >= -10000 && pan <= 10000 );
HRESULT hr = m_buffer->SetPan( pan );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 SetPan failed: %s", toString(hr) );
return;
}
}
void Dx8SoundBuffer::setVolume( int vol )
{
assert( vol >= -10000 && vol <= 0 );
HRESULT hr = m_buffer->SetVolume( vol );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 SetVolume failed: %s", toString(hr) );
return;
}
}
void Dx8SoundBuffer::commit()
{
if ( m_buffer3D )
{
Matrix3x3 rot = m_tm.rotation();
DS3DBUFFER param;
memset( ¶m, 0, sizeof(param) );
param.dwSize = sizeof(param);
toDx8( m_tm.translation(), param.vPosition );
toDx8( m_vel, param.vVelocity );
param.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
param.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
toDx8( rot.getColumn(2), param.vConeOrientation );
param.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
param.flMinDistance = m_minDistance;
param.flMaxDistance = m_maxDistance;
param.dwMode = DS3DMODE_NORMAL;
/*m_buffer3D->SetMinDistance( param.flMinDistance, DS3D_DEFERRED );
m_buffer3D->SetMaxDistance( param.flMaxDistance, DS3D_DEFERRED );
m_buffer3D->SetPosition( param.vPosition.x, param.vPosition.y, param.vPosition.z, DS3D_DEFERRED );
//m_buffer3D->SetVelocity( param.vVelocity.x, param.vVelocity.y, param.vVelocity.z, DS3D_DEFERRED );*/
HRESULT hr = m_buffer3D->SetAllParameters( ¶m, DS3D_DEFERRED );
if ( hr != DS_OK )
error( "IDirectSound3DBuffer8 SetAllParemeters failed: %s", toString(hr) );
}
}
void Dx8SoundBuffer::setMaxDistance( float dist )
{
assert( m_usageFlags & USAGE_CONTROL3D );
assert( m_buffer3D );
m_maxDistance = dist;
}
void Dx8SoundBuffer::setMinDistance( float dist )
{
assert( m_usageFlags & USAGE_CONTROL3D );
assert( m_buffer3D );
m_minDistance = dist;
}
void Dx8SoundBuffer::setTransform( const math::Matrix4x4& tm )
{
assert( m_usageFlags & USAGE_CONTROL3D );
assert( m_buffer3D );
m_tm = tm;
}
void Dx8SoundBuffer::setVelocity( const math::Vector3& v )
{
assert( m_usageFlags & USAGE_CONTROL3D );
assert( m_buffer3D );
m_vel = v;
}
int Dx8SoundBuffer::frequency() const
{
DWORD v = 0;
HRESULT hr = m_buffer->GetFrequency( &v );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 GetFrequency failed: %s", toString(hr) );
return 0;
}
return (int)v;
}
int Dx8SoundBuffer::pan() const
{
long v = 0;
HRESULT hr = m_buffer->GetPan( &v );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 GetPan failed: %s", toString(hr) );
return 0;
}
return (int)v;
}
int Dx8SoundBuffer::volume() const
{
long v = 0;
HRESULT hr = m_buffer->GetVolume( &v );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 GetVolume failed: %s", toString(hr) );
return 0;
}
return (int)v;
}
float Dx8SoundBuffer::maxDistance() const
{
return m_maxDistance;
}
float Dx8SoundBuffer::minDistance() const
{
return m_minDistance;
}
const math::Matrix4x4& Dx8SoundBuffer::transform() const
{
return m_tm;
}
const math::Vector3& Dx8SoundBuffer::velocity() const
{
return m_vel;
}
void Dx8SoundBuffer::getCurrentPosition( int* play, int* write ) const
{
assert( sizeof(DWORD) == sizeof(int) && (play || write) );
HRESULT hr = m_buffer->GetCurrentPosition( reinterpret_cast<DWORD*>(play), reinterpret_cast<DWORD*>(write) );
if ( hr != DS_OK )
error( "IDirectSoundBuffer8 GetCurrentPosition failed: %s", toString(hr) );
}
bool Dx8SoundBuffer::locked() const
{
return 0 != (m_usageFlags & USAGE_LOCKED);
}
bool Dx8SoundBuffer::playing() const
{
return getStatus( DSBSTATUS_PLAYING );
}
int Dx8SoundBuffer::bytes() const
{
return m_dataSize;
}
int Dx8SoundBuffer::samples() const
{
return m_samples;
}
int Dx8SoundBuffer::channels() const
{
return m_channels;
}
int Dx8SoundBuffer::bitsPerSample() const
{
return m_bitsPerSample;
}
int Dx8SoundBuffer::lockDevice( int offset, int bytes,
void** data1, int* bytes1,
void** data2, int* bytes2,
int flags )
{
assert( data1 && bytes1 );
assert( sizeof(int) == sizeof(DWORD) );
DWORD lockFlags = 0;
if ( flags & LOCK_FROMWRITECURSOR )
lockFlags |= DSBLOCK_FROMWRITECURSOR;
HRESULT hr = m_buffer->Lock( offset, bytes, data1, (DWORD*)bytes1, data2, (DWORD*)bytes2, lockFlags );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 Lock failed: %s", toString(hr) );
if ( hr == DSERR_BUFFERLOST )
{
handleLostBuffer();
return ERROR_BUFFERLOST;
}
return ERROR_GENERIC;
}
m_usageFlags |= USAGE_LOCKED;
return ERROR_NONE;
}
void Dx8SoundBuffer::unlockDevice( void* data1, int bytes1,
void* data2, int bytes2 )
{
assert( locked() );
HRESULT hr = m_buffer->Unlock( data1, bytes1, data2, bytes2 );
if ( hr != DS_OK )
{
error( "IDirectSoundBuffer8 Unlock failed: %s", toString(hr) );
return;
}
m_usageFlags &= ~USAGE_LOCKED;
}
void Dx8SoundBuffer::handleLostBuffer()
{
assert( m_buffer );
HRESULT hr = m_buffer->Restore();
if ( hr != DS_OK )
error( "Sound buffer Restore() failed: %s", toString(hr) );
m_dirty = true;
}
bool Dx8SoundBuffer::getStatus( DWORD statusFlags ) const
{
DWORD stat = 0;
HRESULT hr = m_buffer->GetStatus( &stat );
if ( hr != DS_OK )
error( "IDirectSoundBuffer8 GetStatus failed: %s", toString(hr) );
return 0 != (stat & statusFlags);
}
int Dx8SoundBuffer::load()
{
if ( m_usageFlags & USAGE_STATIC )
{
void* data = 0;
int bytes = 0;
int err = lockDevice( 0, m_dataSize, &data, &bytes, 0, 0, 0 );
if ( err )
return err;
assert( bytes == m_dataSize );
memcpy( data, m_data, bytes );
unlockDevice( data, bytes, 0, 0 );
m_dirty = false;
}
return ERROR_NONE;
}
int Dx8SoundBuffer::usageFlags() const
{
return m_usageFlags;
}
| 22.617363 | 111 | 0.646716 | [
"transform",
"3d"
] |
22b206562318a543f8c3ac4385c14bdaeef5ab6b | 67,863 | hpp | C++ | RX600/glcdc_mgr.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 56 | 2015-06-04T14:15:38.000Z | 2022-03-01T22:58:49.000Z | RX600/glcdc_mgr.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 30 | 2019-07-27T11:03:14.000Z | 2021-12-14T09:59:57.000Z | RX600/glcdc_mgr.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 15 | 2017-06-24T11:33:39.000Z | 2021-12-07T07:26:58.000Z | #pragma once
//=====================================================================//
/*! @file
@brief RX600 グループ GLCDC 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "graphics/pixel.hpp"
#include "RX600/glcdc.hpp"
#include "RX600/glcdc_def.hpp"
#include "common/delay.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief GLCDC 制御 class
@param[in] GLC glcdc クラス
@param[in] XSIZE X 方向ピクセルサイズ
@param[in] YSIZE Y 方向ピクセルサイズ
@param[in] PXT_ ピクセル・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class GLC, int16_t XSIZE, int16_t YSIZE, graphics::pixel::TYPE PXT_>
class glcdc_mgr {
public:
static const int16_t width = XSIZE;
static const int16_t height = YSIZE;
static const graphics::pixel::TYPE PXT = PXT_;
static const int16_t line_width =
(((width * static_cast<int16_t>(PXT) / 8) + 63) & 0x7fc0) / (static_cast<int16_t>(PXT) / 8);
static const uint32_t frame_size =
line_width * (static_cast<uint32_t>(PXT) / 8) * height;
private:
static const uint32_t FRAME_LAYER_NUM = 2; ///< Number of graphics layers
static const uint32_t CLUT_PLANE_NUM = 2; ///< Number of color palletes
static const uint32_t PANEL_CLKDIV_NUM = 13; ///< Number of clock division ratio
/** Serial RGB data output delay cycles select (this function is not supported) */
enum class SERIAL_OUTPUT_DELAY
{
CYCLE_0 = 0, // 0 cycles delay.
CYCLE_1 = 1, // 1 cycle delay.
CYCLE_2 = 2, // 2 cycles delay.
CYCLE_3 = 3, // 3 cycles delay.
};
/** Serial RGB scan direction select (this function is not supported) */
enum class SERIAL_SCAN_DIRECTION
{
FORWARD = 0, // Forward scan.
REVERSE = 1, // Reverse scan.
};
struct gamma_correction_t
{
static const uint32_t GAMMA_CURVE_GAIN_ELEMENT_NUM = 16;
static const uint32_t GAMMA_CURVE_THRESHOLD_ELEMENT_NUM = 15;
struct correction_t
{
uint16_t gain[GAMMA_CURVE_GAIN_ELEMENT_NUM]; // Gain adjustment.
uint16_t threshold[GAMMA_CURVE_THRESHOLD_ELEMENT_NUM]; // Start threshold.
correction_t() : gain{ 0 }, threshold{ 0 } { }
};
bool enable; // Gamma Correction On/Off.
correction_t* p_r; // Gamma correction for R channel.
correction_t* p_g; // Gamma correction for G channel.
correction_t* p_b; // Gamma correction for B channel.
gamma_correction_t() : enable(false), p_r(nullptr), p_g(nullptr), p_b(nullptr)
{ }
};
struct contrast_t
{
bool enable; // Contrast Correction On/Off.
uint8_t r; // Contrast (gain) adjustment for R channel.
uint8_t g; // Contrast (gain) adjustment for G channel.
uint8_t b; // Contrast (gain) adjustment for B channel.
contrast_t() : enable(false), r(0), g(0), b(0) { }
};
/** Brightness (DC) correction setting */
struct brightness_t
{
bool enable; // Brightness Correction On/Off.
uint16_t r; // Brightness (DC) adjustment for R channel.
uint16_t g; // Brightness (DC) adjustment for G channel.
uint16_t b; // Brightness (DC) adjustment for B channel.
brightness_t() : enable(false), r(0), g(0), b(0) { }
};
/** Chroma key setting */
struct chromakey_t
{
bool enable; // Chroma key On/Off.
glcdc_def::color_t before; // Compare Color for -RGB.
glcdc_def::color_t after; // Replace Color for ARGB.
chromakey_t() : enable(false), before(), after() { }
};
/** Color correction setting */
struct correction_t
{
brightness_t brightness; // Brightness setting.
contrast_t contrast; // Contrast setting.
gamma_correction_t gamma; // Gamma setting.
correction_t() : brightness(), contrast(), gamma() { }
};
/** Dithering setup parameter */
struct dithering_t
{
bool dithering_on; // Dithering on/off.
glcdc_def::DITHERING_MODE dithering_mode; // Dithering mode.
glcdc_def::DITHERING_PATTERN dithering_pattern_a; // Dithering pattern A.
glcdc_def::DITHERING_PATTERN dithering_pattern_b; // Dithering pattern B.
glcdc_def::DITHERING_PATTERN dithering_pattern_c; // Dithering pattern C.
glcdc_def::DITHERING_PATTERN dithering_pattern_d; // Dithering pattern D.
};
/** Graphics plane input configuration */
struct input_cfg_t
{
void* base; ///< Base address to the frame buffer.(can not set null)
uint16_t hsize; ///< Horizontal pixel size in a line.
uint16_t vsize; ///< Vertical pixel size in a frame.
int32_t offset; ///< offset value to next line.
glcdc_def::IN_FORMAT format; ///< Input format setting.
bool frame_edge; ///< Show/hide setting of the frame of the graphics area.
glcdc_def::coordinate_t coordinate; ///< Starting point of image.
glcdc_def::color_t bg_color; ///< Color outside region.
input_cfg_t() : base(nullptr), hsize(0), vsize(0), offset(0),
format(glcdc_def::IN_FORMAT::RGB565), frame_edge(false), coordinate(), bg_color()
{ }
};
/** Display output configuration */
struct output_cfg_t
{
glcdc_def::timing_t htiming; // Horizontal display cycle setting.
glcdc_def::timing_t vtiming; // Vertical display cycle setting.
glcdc_def::OUT_FORMAT format; // Output format setting.
glcdc_def::ENDIAN endian; // Bit order of output data.
glcdc_def::COLOR_ORDER color_order; // Color order in pixel.
glcdc_def::SIGNAL_SYNC_EDGE sync_edge; // Signal sync edge selection.
glcdc_def::color_t bg_color; // Background color.
brightness_t brightness; // Brightness setting.
contrast_t contrast; // Contrast setting.
gamma_correction_t gamma; // Gamma correction setting.
glcdc_def::CORRECTION_PROC_ORDER correction_proc_order; // Correction control route select.
dithering_t dithering; // Dithering setting.
glcdc_def::TCON_PIN tcon_hsync; // GLCD TCON output pin select.
glcdc_def::TCON_PIN tcon_vsync; // GLCD TCON output pin select.
glcdc_def::TCON_PIN tcon_de; // GLCD TCON output pin select.
glcdc_def::SIGNAL_POLARITY data_enable_polarity; // Data Enable signal polarity.
glcdc_def::SIGNAL_POLARITY hsync_polarity; // Horizontal sync signal polarity.
glcdc_def::SIGNAL_POLARITY vsync_polarity; // Vertical sync signal polarity.
glcdc_def::CLK_SRC clksrc; // Clock Source selection.
glcdc_def::PANEL_CLK_DIVISOR clock_div_ratio; // Clock divide ratio for dot clock.
SERIAL_OUTPUT_DELAY serial_output_delay; // Serial RGB Data output delay cycle select (this function is not supported).
SERIAL_SCAN_DIRECTION serial_scan_direction; // Serial RGB Scan direction select (this function is not supported).
};
/** Graphics layer blend setup parameter */
struct blend_t
{
glcdc_def::BLEND_CONTROL blend_control; // Layer fade-in/out , blending on/off.
bool visible; // Visible or hide graphics.
bool frame_edge; // Show/hide setting of the frame of rectangular alpha blending area.
uint8_t fixed_blend_value; // Blend value. Valid only when blend_control is _FIXED.
uint8_t fade_speed; // Layer fade-in/out frame rate.
glcdc_def::coordinate_t start_coordinate; // Start coordinate of rectangle blending.
glcdc_def::coordinate_t end_coordinate; // End coordinate of rectangle blending.
};
/** CLUT configuration */
struct clut_cfg_t
{
bool enable; // CLUT update enable/disable.
uint32_t* p_base; // Pointer to CLUT source data.
uint16_t start; // Beginning of CLUT entry to be updated.
uint16_t size; // Size of CLUT entry to be updated.
clut_cfg_t() : enable(false), p_base(nullptr), start(0), size(0) { }
};
/** Detect enable setting */
struct detect_cfg_t
{
bool vpos_detect; // Line detection enable.
bool gr1uf_detect; // Graphics plane1 underflow detection enable.
bool gr2uf_detect; // Graphics plane2 underflow detection enable.
detect_cfg_t() : vpos_detect(false), gr1uf_detect(false), gr2uf_detect(false) { }
};
/** Display callback parameter definition */
struct callback_args_t
{
enum class EVENT {
GR1_UNDERFLOW = 1, // Graphics plane1 underflow occurs
GR2_UNDERFLOW = 2, // Graphics plane2 underflow occurs
LINE_DETECTION = 3, // Designated line is processed.
};
EVENT event; // Event code.
};
public:
static const uint32_t FRAME_LAYER_1 = 0; ///< Frame layer 1.
static const uint32_t FRAME_LAYER_2 = 1; ///< Frame layer 2.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Control Command
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class CONTROL_CMD {
START_DISPLAY, ///< Start display command.
STOP_DISPLAY, ///< Stop display command.
SET_INTERRUPT, ///< Interrupt setting command.
CLR_DETECTED_STATUS, ///< Detected status clear command.
CHANGE_BG_COLOR, ///< Change background color in background screen.
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ERROR {
SUCCESS = 0, ///< Success.
INVALID_PTR, ///< Pointer points to invalid memory location.
LOCK_FUNC, ///< GLCDC resource is in use by another process.
INVALID_ARG, ///< Invalid input parameter.
INVALID_MODE, ///< Unsupported or incorrect mode.
NOT_OPEN, ///< Requested channel is not configured or API not open.
INVALID_TIMING_SETTING, // Invalid timing parameter.
INVALID_LAYER_SETTING, // Invalid layer parameter.
INVALID_ALIGNMENT, // Invalid memory alignment found.
INVALID_GAMMA_SETTING, // Invalid gamma correction parameter.
INVALID_UPDATE_TIMING, // Invalid timing for register update.
INVALID_CLUT_ACCESS, // Invalid access to CLUT entry.
INVALID_BLEND_SETTING, // Invalid blending setting.
};
struct cfg_t
{
/** Generic configuration for display devices */
input_cfg_t input[FRAME_LAYER_NUM]; // Graphics input frame setting.
output_cfg_t output; // Graphics output frame setting.
blend_t blend[FRAME_LAYER_NUM]; // Graphics layer blend setting.
chromakey_t chromakey[FRAME_LAYER_NUM]; // Graphics chroma key setting.
clut_cfg_t clut[FRAME_LAYER_NUM]; // Graphics CLUT setting.
/** Interrupt setting*/
detect_cfg_t detection; // Detection enable/disable setting.
glcdc_def::interrupt_cfg_t interrupt; // Interrupt enable/disable setting.
/** Configuration for display event processing */
void (*callback)(void *); // Pointer to callback function.
};
/** Runtime configuration */
struct runtime_cfg_t
{
/** Generic configuration for display devices */
input_cfg_t input; // Graphics input frame setting
blend_t blend; // Graphics layer blend setting.
chromakey_t chromakey; // Graphics chroma key setting.
};
/** status */
struct status_t
{
glcdc_def::OPERATING_STATUS state; // Status of GLCD module
bool state_vpos; // Status of line detection.
bool state_gr1uf; // Status of graphics plane1 underflow.
bool state_gr2uf; // Status of graphics plane2 underflow.
glcdc_def::FADE_STATUS fade_status[FRAME_LAYER_NUM]; // Status of fade-in/fade-out status
};
private:
static const uint32_t PIX_WIDTH = static_cast<uint32_t>(PXT_);
static const uint32_t BYTES_PER_LINE = ((PIX_WIDTH * XSIZE) / 8);
static const uint32_t LINE_OFFSET = (((BYTES_PER_LINE + 63) / 64) * 64);
static const uint32_t VXSIZE_PHYS = ((LINE_OFFSET * 8) / PIX_WIDTH);
static const uint32_t BYTES_PER_BUFFER = (LINE_OFFSET * YSIZE);
static const uint32_t BRIGHTNESS_ = 0x200;
static const uint32_t CONTRAST_ = 0x80;
static const uint32_t ADDRESS_ALIGNMENT_64B = 0x0000003F;
static const uint32_t GAMMA_CURVE_GAIN_ELEMENT_NUM = 16;
static const uint32_t GAMMA_CURVE_THRESHOLD_ELEMENT_NUM = 15;
/* Fixed margin by Hardware operation */
static const uint32_t BG_PLANE_H_CYC_MARGIN_MIN = 2; /* Hsync signal margin is 2 */
static const uint32_t BG_PLANE_V_CYC_MARGIN_MIN = 1; /* Vsync signal margin is 1 */
/* Color correction setting threshold */
// OUT_BRIGHT1.BRTG, OUT_BRIGHT2.BRTR and .BRTB (Mid=512)
static const uint32_t BRIGHTNESS_DEFAULT = 512;
// OUT_BRIGHT1.BRTG, OUT_BRIGHT2.BRTR and .BRTB (Max=1023)
static const uint32_t BRIGHTNESS_MAX = 1023;
// OUT_CONTRAST.CONTG and .CONTB and .CONTR (Mid=128)
static const uint32_t CONTRAST_DEFAULT = 128;
// OUT_CONTRAST.CONTG and .CONTB and .CONTR (Max=255)
static const uint32_t CONTRAST_MAX = 255;
// GAMx_LUTn.GAIN15 - GAIN0 (Max=2047)
static const uint32_t GAMMA_GAIN_MAX = 2047;
// GAMx_AREAn.TH15 - TH0 (Max=1023)
static const uint32_t GAMMA_THRESHOLD_MAX = 1023;
static const uint32_t OUT_SET_FRQSEL_NO_DIVISION = 0;
static const uint32_t OUT_SET_FRQSEL_QUATER_DIVISION = 1;
/* Panel timing, Minimum threshold */
static const int32_t BG_PLANE_H_CYC_MIN = 24; // BG_PERI.FH (Min=24)
static const int32_t BG_PLANE_V_CYC_MIN = 20; // BG_PERI.FV (Min=20)
static const int32_t BG_PLANE_HSYNC_POS_MIN = 1; // BG_HSYNC.HP (Min=1)
static const int32_t BG_PLANE_VSYNC_POS_MIN = 1; // BG_HSYNC.VP (Min=1)
static const int32_t BG_PLANE_H_CYC_ACTIVE_SIZE_MIN = 16; // BG_HSIZE.HW (Min=16)
static const int32_t BG_PLANE_V_CYC_ACTIVE_SIZE_MIN = 16; // BG_VSIZE.VW (Min=16)
static const int32_t BG_PLANE_H_ACTIVE_POS_MIN = 6; // BG_HSIZE.HP (Min=6)
static const int32_t BG_PLANE_V_ACTIVE_POS_MIN = 3; // BG_VSIZE.VP (Min=3)
// GRn_FLM3_LNOFF(positive num min=-32768)
static const int32_t GR_PLANE_LNOFF_POS_MIN = -32768;
static const int32_t GR_PLANE_H_CYC_ACTIVE_SIZE_MIN = 16; // GRn_AB3.GRCHW (Min=16)
static const int32_t GR_PLANE_V_CYC_ACTIVE_SIZE_MIN = 16; // GRn_AB2.GRCVW (Min=16)
static const int32_t GR_PLANE_H_ACTIVE_POS_MIN = 5; // GRn_AB2.GRCHS (Min=5)
static const int32_t GR_PLANE_V_ACTIVE_POS_MIN = 2; // GRn_AB2.GRCVS (Min=2)
// Horizontal front porch parameter (MIN=3)
static const int32_t BG_PLANE_H_FRONT_PORCH_MIN = 3;
// Vertical front porch parameter (MIN=2)
static const int32_t BG_PLANE_V_FRONT_PORCH_MIN = 2;
// Horizontal back porch parameter (MIN=1)
static const int32_t BG_PLANE_H_BACK_PORCH_MIN = 1;
// Vertical back porch parameter (MIN=1)
static const int32_t BG_PLANE_V_BACK_PORCH_MIN = 1;
// Horizontal sync signal width parameter (MIN=4)
static const int32_t BG_PLANE_H_SYNC_WIDTH_MIN = 4;
// Vertical sync signal width parameter (MIN=1)
static const int32_t BG_PLANE_V_SYNC_WIDTH_MIN = 1;
static const int32_t GR_BLEND_H_ACTIVE_POS_MIN = 5; // GRn_AB5_GRCHS (Min=5)
static const int32_t GR_BLEND_V_ACTIVE_POS_MIN = 2; // GRn_AB4_GRCVS (Min=2)
static const int32_t GR_BLEND_H_CYC_ACTIVE_SIZE_MIN = 1; // GRn_AB5_GRCHW (Min=1)
static const int32_t GR_BLEND_V_CYC_ACTIVE_SIZE_MIN = 1; // GRn_AB4_GRCVW (Min=1)
struct TCON_SIGNAL_SELECT {
static const uint32_t STVA_VS = 0; // STVA/VS
static const uint32_t STVB_VE = 1; // STVB/VE
static const uint32_t STHA_HS = 2; // STH/SP/HS
static const uint32_t STHB_HE = 3; // STB/LP/HE
static const uint32_t DE = 7; // DE
};
struct FADING_CONTROL_INITIAL_ALPHA {
// Initial alpha value setting for a graphics plane is zero.
static const uint32_t MIN = 0x00;
// Initial alpha value setting for a graphics plane is maximum.
static const uint32_t MAX = 0xff;
};
enum class PLANE_BLEND {
TRANSPARENT = 1, // Current graphics layer is transparent
// and the lower layer is displayed.
NON_TRANSPARENT = 2, // Current graphics layer is displayed.
ON_LOWER_LAYER = 3 // Current graphics layer is blended with
// the lower layer.
};
static const uint32_t CLUT_PLANE_0 = 0; // GLCD CLUT plane 0.
static const uint32_t CLUT_PLANE_1 = 1; // GLCD CLUT plane 1.
struct DITHERING_OUTPUT_FORMAT {
static const uint32_t RGB888 = 0; // Dithering output format RGB888.
static const uint32_t RGB666 = 1; // Dithering output format RGB666.
static const uint32_t RGB565 = 2; // Dithering output format RGB565.
};
static glcdc_def::ctrl_t ctrl_blk_;
void* layer1_org_;
void* layer2_org_;
uint32_t flip_count_;
bool enable_double_;
uint8_t intr_lvl_;
ERROR last_error_;
void release_software_reset_()
{
GLC::BGEN.SWRST = 1;
}
void clock_set_(const cfg_t& cfg)
{
// Selects input source for panel clock
GLC::PANELCLK.CLKSEL = static_cast<uint32_t>(cfg.output.clksrc);
// Sets division ratio
GLC::PANELCLK.DCDR = static_cast<uint32_t>(cfg.output.clock_div_ratio);
// Selects pixel clock output
if(glcdc_def::OUT_FORMAT::SERIAL != cfg.output.format) {
GLC::PANELCLK.PIXSEL = 0; /* ParallelRGBSelect */
} else {
GLC::PANELCLK.PIXSEL = 1; /* SerialRGBSelect */
}
GLC::PANELCLK.CLKEN = 1; /* Panel Clock(LCD_CLK) Output Enable */
/* Waiting for supply of panel clock(LCD_CLK) and pixel clock(PXCLK)
* The BGMON.SWRST bit is sampled with PXCLK. Therefore, if the CLKEN bit is set,
* the BGEN.SWRST bit is reflected on the BGMON.SWRST bit. */
while(0 == GLC::BGMON.SWRST()) {
asm("nop");
}
}
void hsync_set_(glcdc_def::TCON_PIN tcon, const glcdc_def::timing_t& timing,
glcdc_def::SIGNAL_POLARITY polarity)
{
switch(tcon) {
case glcdc_def::TCON_PIN::_1:
/* Hsync(STHA) -> TCON1 */
GLC::TCONSTVB2.SEL = TCON_SIGNAL_SELECT::STHA_HS;
break;
case glcdc_def::TCON_PIN::_2:
/* Hsync(STHA) -> TCON2 */
GLC::TCONSTHA2.SEL = TCON_SIGNAL_SELECT::STHA_HS;
break;
case glcdc_def::TCON_PIN::_3:
/* Hsync(STHA) -> TCON3 */
GLC::TCONSTHB2.SEL = TCON_SIGNAL_SELECT::STHA_HS;
break;
case glcdc_def::TCON_PIN::_0: /* Intentionally go though to the default case */
default:
/* Hsync(STHA) -> TCON0 */
GLC::TCONSTVA2.SEL = TCON_SIGNAL_SELECT::STHA_HS;
break;
}
// Hsync(STHA) -> Invert or Not Invert
GLC::TCONSTHA2.INV = static_cast<uint32_t>(polarity);
// Hsync beginning position
GLC::TCONSTHA1.HS = 0; /* No delay */
GLC::TCONSTHA2.HSSEL = 0; /* Select input Hsync as reference */
// HSync Width Setting
GLC::TCONSTHA1.HW = timing.sync_width;
}
void vsync_set_(glcdc_def::TCON_PIN tcon, const glcdc_def::timing_t& timing,
glcdc_def::SIGNAL_POLARITY polarity)
{
switch(tcon) {
case glcdc_def::TCON_PIN::_0:
/* Vsync(STVA) -> TCON0 */
GLC::TCONSTVA2.SEL = TCON_SIGNAL_SELECT::STVA_VS;
break;
case glcdc_def::TCON_PIN::_2:
/* Vsync(STVA) -> TCON2 */
GLC::TCONSTHA2.SEL = TCON_SIGNAL_SELECT::STVA_VS;
break;
case glcdc_def::TCON_PIN::_3:
/* Vsync(STVA) -> TCON3 */
GLC::TCONSTHB2.SEL = TCON_SIGNAL_SELECT::STVA_VS;
break;
case glcdc_def::TCON_PIN::_1: /* Intentionally go though to the default case */
default:
/* Vsync(STVA) -> TCON1 */
GLC::TCONSTVB2.SEL = TCON_SIGNAL_SELECT::STVA_VS;
break;
}
/* Vsync(STVA) -> Invert or Vsync(STVA) -> Not Invert */
GLC::TCONSTVA2.INV = static_cast<uint32_t>(polarity);
/* Vsync beginning position */
GLC::TCONSTVA1.VS = 0; /* No delay. */
/* VSync Width Setting */
GLC::TCONSTVA1.VW = timing.sync_width;
}
void data_enable_set_(glcdc_def::TCON_PIN tcon, const glcdc_def::timing_t& vtiming,
const glcdc_def::timing_t& htiming,
glcdc_def::SIGNAL_POLARITY polarity)
{
switch(tcon) {
case glcdc_def::TCON_PIN::_0:
/* DE -> TCON0 */
GLC::TCONSTVA2.SEL = TCON_SIGNAL_SELECT::DE;
break;
case glcdc_def::TCON_PIN::_1:
// DE -> TCON1
GLC::TCONSTVB2.SEL = TCON_SIGNAL_SELECT::DE;
break;
case glcdc_def::TCON_PIN::_3:
// DE -> TCON3
GLC::TCONSTHB2.SEL = TCON_SIGNAL_SELECT::DE;
break;
case glcdc_def::TCON_PIN::_2: /* Intentionally go though to the default case */
default:
// DE -> TCON2
GLC::TCONSTHA2.SEL = TCON_SIGNAL_SELECT::DE;
break;
}
GLC::TCONDE.INV = static_cast<uint32_t>(polarity); /* DE -> Invert or Not Invert */
/* Set data enable timing */
GLC::TCONSTHB1.HS = htiming.back_porch + htiming.sync_width;
GLC::TCONSTHB1.HW = htiming.display_cyc;
GLC::TCONSTHB2.HSSEL = 0; /* Select input Hsync as reference */
GLC::TCONSTVB1.VS = vtiming.back_porch + vtiming.sync_width;
GLC::TCONSTVB1.VW = vtiming.display_cyc;
}
void sync_signal_set_(const cfg_t& cfg)
{
GLC::CLKPHASE.LCDEDG = static_cast<uint32_t>(cfg.output.sync_edge);
GLC::CLKPHASE.TCON0EDG = static_cast<uint32_t>(cfg.output.sync_edge);
GLC::CLKPHASE.TCON1EDG = static_cast<uint32_t>(cfg.output.sync_edge);
GLC::CLKPHASE.TCON2EDG = static_cast<uint32_t>(cfg.output.sync_edge);
GLC::CLKPHASE.TCON3EDG = static_cast<uint32_t>(cfg.output.sync_edge);
GLC::TCONTIM.OFFSET = 0; // 1 pixel
GLC::TCONTIM.HALF = 0; // 1 pixel (No delay)
hsync_set_(cfg.output.tcon_hsync, cfg.output.htiming, cfg.output.hsync_polarity);
vsync_set_(cfg.output.tcon_vsync, cfg.output.vtiming, cfg.output.vsync_polarity);
data_enable_set_(cfg.output.tcon_de, cfg.output.vtiming, cfg.output.htiming,
cfg.output.data_enable_polarity);
}
void background_screen_set_(const cfg_t& cfg)
{
uint32_t hsync_total_cyc;
uint32_t vsync_total_cyc;
hsync_total_cyc = (((cfg.output.htiming.front_porch + cfg.output.htiming.sync_width)
+ cfg.output.htiming.display_cyc) + cfg.output.htiming.back_porch);
vsync_total_cyc = (((cfg.output.vtiming.front_porch + cfg.output.vtiming.sync_width)
+ cfg.output.vtiming.display_cyc) + cfg.output.vtiming.back_porch);
// utils::format("Total LCD count: %d, %d\n") % hsync_total_cyc % vsync_total_cyc;
GLC::BGPERI.FH = hsync_total_cyc - 1;
GLC::BGPERI.FV = vsync_total_cyc - 1;
GLC::BGSYNC.HP = cfg.output.htiming.front_porch - BG_PLANE_H_CYC_MARGIN_MIN;
GLC::BGSYNC.VP = cfg.output.vtiming.front_porch - BG_PLANE_V_CYC_MARGIN_MIN;
GLC::BGHSIZE.HP = cfg.output.htiming.front_porch - BG_PLANE_H_CYC_MARGIN_MIN
+ cfg.output.htiming.sync_width + cfg.output.htiming.back_porch;
GLC::BGVSIZE.VP = cfg.output.vtiming.front_porch - BG_PLANE_V_CYC_MARGIN_MIN
+ cfg.output.vtiming.sync_width + cfg.output.vtiming.back_porch;
/* ---- Set the width of Background screen ---- */
GLC::BGHSIZE.HW = cfg.output.htiming.display_cyc;
GLC::BGVSIZE.VW = cfg.output.vtiming.display_cyc;
/* ---- Set the Background color ---- */
GLC::BGCOLOR.R = cfg.output.bg_color.r;
GLC::BGCOLOR.G = cfg.output.bg_color.g;
GLC::BGCOLOR.B = cfg.output.bg_color.b;
}
static uint16_t get_bit_size_(glcdc_def::IN_FORMAT format)
{
uint16_t bit_size = 0;
/* ---- Get bit size and set color format ---- */
switch (format) {
case glcdc_def::IN_FORMAT::ARGB8888: ///< ARGB8888, 32bits
case glcdc_def::IN_FORMAT::RGB888: ///< RGB888, 32bits
bit_size = 32;
break;
case glcdc_def::IN_FORMAT::RGB565: ///< RGB565, 16bits
case glcdc_def::IN_FORMAT::ARGB1555: ///< ARGB1555, 16bits
case glcdc_def::IN_FORMAT::ARGB4444: ///< ARGB4444, 16bits
bit_size = 16;
break;
case glcdc_def::IN_FORMAT::CLUT8: ///< CLUT8
bit_size = 8;
break;
case glcdc_def::IN_FORMAT::CLUT4: ///< CLUT4
bit_size = 4;
break;
case glcdc_def::IN_FORMAT::CLUT1: ///< CLUT1
default:
bit_size = 1;
break;
}
return bit_size;
}
void gr_plane_format_set_(glcdc_def::IN_FORMAT format, uint32_t frame)
{
if(frame == 0) {
GLC::GR1FLM6.FORMAT = static_cast<uint32_t>(format);
} else {
GLC::GR2FLM6.FORMAT = static_cast<uint32_t>(format);
}
}
void graphics_layer_set_(const input_cfg_t& input, uint32_t frame)
{
uint32_t bit_size = get_bit_size_(input.format);
// If enable graphics data read from memory
if(false == ctrl_blk_.graphics_read_enable[frame]) {
return;
}
gr_plane_format_set_(input.format, frame);
/* ---- Set the base address of graphics plane ---- */
if(frame == 0) {
GLC::GR1FLM2 = reinterpret_cast<uint32_t>(input.base);
} else {
GLC::GR2FLM2 = reinterpret_cast<uint32_t>(input.base);
}
/* ---- Set the background color on graphics plane ---- */
if(frame == 0) {
GLC::GR1BASE.R = input.bg_color.r;
GLC::GR1BASE.G = input.bg_color.g;
GLC::GR1BASE.B = input.bg_color.b;
} else {
GLC::GR2BASE.R = input.bg_color.r;
GLC::GR2BASE.G = input.bg_color.g;
GLC::GR2BASE.B = input.bg_color.b;
}
// --- Set the number of data transfer times per line, 64 bytes are transferred
// in each transfer ----
// Convert to byte size of Single line data transfer, round up fractions below
// the decimal point
uint32_t line_byte_num = ((bit_size * input.hsize) / 8);
if(0 != ((bit_size * input.hsize) % 8)) {
line_byte_num += 1;
}
// Convert to Single line data transfer count, round up fractions below the
// decimal point
uint32_t line_trans_num = (line_byte_num >> 6);
if(0 != (line_byte_num & ADDRESS_ALIGNMENT_64B)) {
line_trans_num += 1;
}
if(frame == 0) {
GLC::GR1FLM5.DATANUM = line_trans_num - 1;
} else {
GLC::GR2FLM5.DATANUM = line_trans_num - 1;
}
/* ---- Set the line offset address for accessing the graphics data ---- */
if(frame == 0) {
GLC::GR1FLM5.LNNUM = input.vsize - 1;
} else {
GLC::GR2FLM5.LNNUM = input.vsize - 1;
}
// ---- Set the line offset address for accessing the graphics data on graphics
// plane ----
if(frame == 0) {
GLC::GR1FLM3.LNOFF = input.offset;
} else {
GLC::GR2FLM3.LNOFF = input.offset;
}
if(frame == 0) {
GLC::GR1AB2.GRCVW = input.vsize;
} else {
GLC::GR2AB2.GRCVW = input.vsize;
}
if(frame == 0) {
GLC::GR1AB2.GRCVS = ctrl_blk_.active_start_pos.y + input.coordinate.y;
} else {
GLC::GR2AB2.GRCVS = ctrl_blk_.active_start_pos.y + input.coordinate.y;
}
/* ---- Set the width of the graphics layers ---- */
if(frame == 0) {
GLC::GR1AB3.GRCHW = input.hsize;
} else {
GLC::GR2AB3.GRCHW = input.hsize;
}
/* ---- Set the start position of the graphics layers ---- */
if(frame == 0) {
GLC::GR1AB3.GRCHS = ctrl_blk_.active_start_pos.x + input.coordinate.x;
} else {
GLC::GR2AB3.GRCHS = ctrl_blk_.active_start_pos.x + input.coordinate.x;
}
if(frame == 0) {
GLC::GR1AB1.GRCDISPON = input.frame_edge ? 1 : 0;
} else {
GLC::GR2AB1.GRCDISPON = input.frame_edge ? 1 : 0;
}
}
void blend_condition_set_(const blend_t& blend, uint32_t frame)
{
/* if enable graphics data read from memory */
if(false == ctrl_blk_.graphics_read_enable[frame]) {
/* Set layer transparent */
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
}
return;
}
switch(blend.blend_control)
{
case glcdc_def::BLEND_CONTROL::NONE:
if(frame == 0) {
GLC::GR1AB1.ARCON = 0;
} else {
GLC::GR2AB1.ARCON = 0;
}
if(true == blend.visible) {
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::NON_TRANSPARENT);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::NON_TRANSPARENT);
}
} else {
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
}
}
break;
case glcdc_def::BLEND_CONTROL::FADEIN:
case glcdc_def::BLEND_CONTROL::FADEOUT:
case glcdc_def::BLEND_CONTROL::FIXED:
// gp_gr[frame]->grxab5.bit.archs =
//
if(frame == 0) {
GLC::GR1AB5.ARCHS = ctrl_blk_.active_start_pos.x + blend.start_coordinate.x;
} else {
GLC::GR2AB5.ARCHS = ctrl_blk_.active_start_pos.x + blend.start_coordinate.x;
}
if(frame == 0) {
GLC::GR1AB4.ARCVS = ctrl_blk_.active_start_pos.y + blend.start_coordinate.y;
} else {
GLC::GR2AB4.ARCVS = ctrl_blk_.active_start_pos.y + blend.start_coordinate.y;
}
/* ---- Set the width of the graphics layers ---- */
if(frame == 0) {
GLC::GR1AB5.ARCHW = blend.end_coordinate.x - blend.start_coordinate.x;
} else {
GLC::GR2AB5.ARCHW = blend.end_coordinate.x - blend.start_coordinate.x;
}
if(frame == 0) {
GLC::GR1AB4.ARCVW = blend.end_coordinate.y - blend.start_coordinate.y;
} else {
GLC::GR2AB4.ARCVW = blend.end_coordinate.y - blend.start_coordinate.y;
}
/*---- Enable rectangular alpha blending ---- */
if(frame == 0) {
GLC::GR1AB1.ARCON = 1;
} else {
GLC::GR2AB1.ARCON = 1;
}
// gp_gr[frame]->grxab6.bit.arcrate = 0x00;
if(frame == 0) {
GLC::GR1AB6.ARCRATE = 0x00;
} else {
GLC::GR2AB6.ARCRATE = 0x00;
}
if(glcdc_def::BLEND_CONTROL::FADEIN == blend.blend_control) {
if(frame == 0) {
GLC::GR1AB7.ARCDEF = FADING_CONTROL_INITIAL_ALPHA::MIN;
} else {
GLC::GR2AB7.ARCDEF = FADING_CONTROL_INITIAL_ALPHA::MIN;
}
if(frame == 0) {
GLC::GR1AB6.ARCCOEF = blend.fade_speed;
} else {
GLC::GR2AB6.ARCCOEF = blend.fade_speed;
}
} else if (glcdc_def::BLEND_CONTROL::FADEOUT == blend.blend_control) {
if(frame == 0) {
GLC::GR1AB7.ARCDEF = FADING_CONTROL_INITIAL_ALPHA::MAX;
} else {
GLC::GR2AB7.ARCDEF = FADING_CONTROL_INITIAL_ALPHA::MAX;
}
if(frame == 0) {
GLC::GR1AB6.ARCCOEF = blend.fade_speed | (1 << 8);
} else {
GLC::GR2AB6.ARCCOEF = blend.fade_speed | (1 << 8);
}
} else { /* ---- GLCDC_FADE_CONTROL_FIXED ---- */
/* GRnAB7 - Graphic n Alpha Blending Control Register 7
b23:b16 ARCDEF[7:0] - Initial Alpha Value Setting. - Set is 0. */
if(frame == 0) {
GLC::GR1AB7.ARCDEF = blend.fixed_blend_value;
} else {
GLC::GR2AB7.ARCDEF = blend.fixed_blend_value;
}
if(frame == 0) {
GLC::GR1AB6.ARCCOEF = 0x000;
} else {
GLC::GR2AB6.ARCCOEF = 0x000;
}
}
// gp_gr[frame]->grxab1.bit.arcdispon = 1;
if(frame == 0) {
GLC::GR1AB1.ARCDISPON = blend.frame_edge == true ? 1 : 0;
} else {
GLC::GR2AB1.ARCDISPON = blend.frame_edge == true ? 1 : 0;
}
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::ON_LOWER_LAYER);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::ON_LOWER_LAYER);
}
break;
case glcdc_def::BLEND_CONTROL::PIXEL:
default:
if(frame == 0) {
GLC::GR1AB1.ARCON = 0;
} else {
GLC::GR2AB1.ARCON = 0;
}
if(true == blend.visible) {
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::ON_LOWER_LAYER);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::ON_LOWER_LAYER);
}
} else {
/* Set layer transparent */
if(frame == 0) {
GLC::GR1AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
} else {
GLC::GR2AB1.DISPSEL = static_cast<uint32_t>(PLANE_BLEND::TRANSPARENT);
}
}
break;
}
}
void graphics_chromakey_set_(const chromakey_t& chromakey, uint32_t frame)
{
/* if enable graphics data read from memory */
if(false == ctrl_blk_.graphics_read_enable[frame]) {
return;
}
if(true == chromakey.enable) {
/* ---- Chroma key enable ---- */
if(frame == 0) {
GLC::GR1AB7.CKON = 1;
} else {
GLC::GR2AB7.CKON = 1;
}
/* ---- Before ---- */
if(frame == 0) {
GLC::GR1AB8.CKKR = chromakey.before.r;
GLC::GR1AB8.CKKG = chromakey.before.g;
GLC::GR1AB8.CKKB = chromakey.before.b;
} else {
GLC::GR2AB8.CKKR = chromakey.before.r;
GLC::GR2AB8.CKKG = chromakey.before.g;
GLC::GR2AB8.CKKB = chromakey.before.b;
}
/* ---- After ---- */
if(frame == 0) {
GLC::GR1AB9.CKA = chromakey.after.a;
GLC::GR1AB9.CKR = chromakey.after.r;
GLC::GR1AB9.CKG = chromakey.after.g;
GLC::GR1AB9.CKB = chromakey.after.b;
} else {
GLC::GR2AB9.CKA = chromakey.after.a;
GLC::GR2AB9.CKR = chromakey.after.r;
GLC::GR2AB9.CKG = chromakey.after.g;
GLC::GR2AB9.CKB = chromakey.after.b;
}
} else {
/* ---- Chroma key disable ---- */
if(frame == 0) {
GLC::GR1AB7.CKON = 0;
} else {
GLC::GR2AB7.CKON = 0;
}
}
}
uint32_t is_clutplane_selected_(uint32_t frame)
{
if(frame == 0) {
return GLC::GR1CLUTINT.SEL();
} else {
return GLC::GR2CLUTINT.SEL();
}
}
void clutplane_select_(uint32_t frame, uint32_t clut_plane)
{
if(frame == 0) {
GLC::GR1CLUTINT.SEL = clut_plane;
} else {
GLC::GR2CLUTINT.SEL = clut_plane;
}
}
void clut_set_(uint32_t frame, uint32_t clut_plane, uint32_t entry, uint32_t data)
{
if(frame == 0) {
if(clut_plane == 0) {
GLC::GR1CLUT0[entry] = data;
} else {
GLC::GR1CLUT1[entry] = data;
}
} else {
if(clut_plane == 0) {
GLC::GR2CLUT0[entry] = data;
} else {
GLC::GR2CLUT1[entry] = data;
}
}
}
void clut_update_(const clut_cfg_t& clut, uint32_t frame)
{
/* If enable graphics data read from memory */
if(!ctrl_blk_.graphics_read_enable[frame]) {
return;
}
if(clut.enable) {
const uint32_t* p_base = clut.p_base;
uint32_t set_clutplane;
if(CLUT_PLANE_1 == is_clutplane_selected_(frame)) {
set_clutplane = CLUT_PLANE_0;
} else {
set_clutplane = CLUT_PLANE_1;
}
/* Copy the new CLUT data on the source memory to the CLUT SRAM in
the GLCD module */
for(uint32_t i = clut.start; i < (clut.start + clut.size); ++i) {
clut_set_(frame, set_clutplane, i, *p_base++);
}
/* Make the GLCD module read the new CLUT table data from the next frame */
clutplane_select_(frame, set_clutplane);
}
}
void output_block_set_(const cfg_t& cfg)
{
// Selects big or little endian for output data
GLC::OUTSET.ENDIANON = (uint32_t)cfg.output.endian;
// Selects the output byte order swapping
GLC::OUTSET.SWAPON = (uint32_t)cfg.output.color_order;
// Selects the output format
switch(cfg.output.format) {
case glcdc_def::OUT_FORMAT::SERIAL: /* In case of serial RGB, set as RGB888 format */
GLC::OUTSET.FORMAT = static_cast<uint32_t>(glcdc_def::OUT_FORMAT::SERIAL);
GLC::OUTSET.PHASE = (uint32_t)cfg.output.serial_output_delay;
GLC::OUTSET.DIRSEL = (uint32_t)cfg.output.serial_scan_direction;
GLC::PANELDTHA.FORM = DITHERING_OUTPUT_FORMAT::RGB888;
break;
case glcdc_def::OUT_FORMAT::RGB565:
GLC::OUTSET.FORMAT = static_cast<uint32_t>(glcdc_def::OUT_FORMAT::RGB565);
GLC::PANELDTHA.FORM = DITHERING_OUTPUT_FORMAT::RGB565;
break;
case glcdc_def::OUT_FORMAT::RGB666:
GLC::OUTSET.FORMAT = static_cast<uint32_t>(glcdc_def::OUT_FORMAT::RGB666);
GLC::PANELDTHA.FORM = DITHERING_OUTPUT_FORMAT::RGB666;
break;
case glcdc_def::OUT_FORMAT::RGB888:
default:
GLC::OUTSET.FORMAT = static_cast<uint32_t>(glcdc_def::OUT_FORMAT::RGB888);
GLC::PANELDTHA.FORM = DITHERING_OUTPUT_FORMAT::RGB888;
break;
}
/* Sets the pixel clock (the GLCD internal signal) frequency in case that
the output format is 8-bit serial RGB */
if(glcdc_def::OUT_FORMAT::SERIAL == cfg.output.format) {
GLC::OUTSET.FRQSEL = OUT_SET_FRQSEL_QUATER_DIVISION;
} else {
GLC::OUTSET.FRQSEL = OUT_SET_FRQSEL_NO_DIVISION;
}
/* Sets the Brightness/contrast and Gamma Correction processing order */
/* CLKPHASE - Output Phase Control Register
b12 FRONTGAM - Correction Sequence Control. */
GLC::CLKPHASE.FRONTGAM = (uint32_t)cfg.output.correction_proc_order;
/* ---- Set the dithering mode ---- */
if(true == cfg.output.dithering.dithering_on) {
if(glcdc_def::DITHERING_MODE::PATTERN2X2 == cfg.output.dithering.dithering_mode) {
GLC::PANELDTHA.PA = (uint32_t)cfg.output.dithering.dithering_pattern_a;
GLC::PANELDTHA.PB = (uint32_t)cfg.output.dithering.dithering_pattern_b;
GLC::PANELDTHA.PC = (uint32_t)cfg.output.dithering.dithering_pattern_c;
GLC::PANELDTHA.PD = (uint32_t)cfg.output.dithering.dithering_pattern_d;
}
GLC::PANELDTHA.SEL = (uint32_t)cfg.output.dithering.dithering_mode;
} else {
GLC::PANELDTHA.SEL = static_cast<uint32_t>(glcdc_def::DITHERING_MODE::TRUNCATE);
}
}
void brightness_correction_(const brightness_t& brightness)
{
if(true == brightness.enable) {
/* ---- Sets brightness correction register for each color in a pixel. ---- */
GLC::BRIGHT1.BRTG = brightness.g;
GLC::BRIGHT2.BRTB = brightness.b;
GLC::BRIGHT2.BRTR = brightness.r;
} else {
/* --- If brightness setting in configuration is 'off', apply default value --- */
GLC::BRIGHT1.BRTG = BRIGHTNESS_DEFAULT;
GLC::BRIGHT2.BRTB = BRIGHTNESS_DEFAULT;
GLC::BRIGHT2.BRTR = BRIGHTNESS_DEFAULT;
}
}
void contrast_correction_(const contrast_t& contrast)
{
if(true == contrast.enable) {
/* ---- Sets the contrast correction register for each color in a pixel. ---- */
GLC::CONTRAST.CONTG = contrast.g;
GLC::CONTRAST.CONTB = contrast.b;
GLC::CONTRAST.CONTR = contrast.r;
} else {
/* ---- If the contrast setting in the configuration is set to 'off',
apply default value ---- */
GLC::CONTRAST.CONTG = CONTRAST_DEFAULT;
GLC::CONTRAST.CONTB = CONTRAST_DEFAULT;
GLC::CONTRAST.CONTR = CONTRAST_DEFAULT;
}
}
void gamma_correction_(const gamma_correction_t& gamma)
{
if(true == gamma.enable) {
/* ---- Gamma correction enable and set gamma setting ---- */
GLC::GAMSW.GAMON = 1;
#if 0
/* Green */
uint32_t* lut_table;
p_lut_table = (uint32_t*)(&GLCDC.GAMGLUT1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_GAIN_ELEMENT_NUM; i += 2) {
/* GAMGLUTx - Gamma Correction G Table Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_g->gain[i] & GAMX_LUTX_GAIN_MASK) << 16)
| ((uint32_t)p_gamma->p_g->gain[i + 1] & GAMX_LUTX_GAIN_MASK));
lut_table++;
}
lut_table = (uint32_t*)(&GLCDC.GAMGAREA1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_THRESHOLD_ELEMENT_NUM; i += 3) {
/* GAMGAREAx - Gamma Correction G Area Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_g->threshold[i] & GAMX_AREAX_MASK) << 20)
| (((uint32_t)p_gamma->p_g->threshold[i + 1] & GAMX_AREAX_MASK) << 10)
| ((uint32_t)p_gamma->p_g->threshold[i + 2] & GAMX_AREAX_MASK));
lut_table++;
}
/* Blue */
lut_table = (uint32_t *)(&GLCDC.GAMBLUT1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_GAIN_ELEMENT_NUM; i += 2) {
/* GAMBLUTx - Gamma Correction B Table Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_b->gain[i] & GAMX_LUTX_GAIN_MASK) << 16)
| ((uint32_t)p_gamma->p_b->gain[i + 1] & GAMX_LUTX_GAIN_MASK));
lut_table++;
}
lut_table = (uint32_t*)(&GLCDC.GAMBAREA1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_THRESHOLD_ELEMENT_NUM; i += 3) {
/* GAMBAREAx - Gamma Correction B Area Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_b->threshold[i] & GAMX_AREAX_MASK) << 20)
| (((uint32_t)p_gamma->p_b->threshold[i + 1] & GAMX_AREAX_MASK) << 10)
| ((uint32_t)p_gamma->p_b->threshold[i + 2] & GAMX_AREAX_MASK));
lut_table++;
}
/* Red */
lut_table = (uint32_t*)(&GLCDC.GAMRLUT1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_GAIN_ELEMENT_NUM; i += 2) {
/* GAMRLUTx - Gamma Correction R Table Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_r->gain[i] & GAMX_LUTX_GAIN_MASK) << 16)
| ((uint32_t)p_gamma->p_r->gain[i + 1] & GAMX_LUTX_GAIN_MASK));
lut_table++;
}
lut_table = (uint32_t*)(&GLCDC.GAMRAREA1);
for(uint32_t i = 0; i < GLCDC_GAMMA_CURVE_THRESHOLD_ELEMENT_NUM; i += 3) {
/* GAMRAREAx - Gamma Correction R Area Setting Register x */
*lut_table = ((((uint32_t)p_gamma->p_r->threshold[i] & GAMX_AREAX_MASK) << 20)
| (((uint32_t)p_gamma->p_r->threshold[i + 1] & GAMX_AREAX_MASK) << 10)
| ((uint32_t)p_gamma->p_r->threshold[i + 2] & GAMX_AREAX_MASK));
lut_table++;
}
#endif
} else {
/* ---- Gamma Correction Disable ---- */
GLC::GAMSW.GAMON = 0;
}
}
void line_detect_number_set_(uint32_t line)
{
GLC::GR2CLUTINT.LINE = line;
}
void detect_setting_(const detect_cfg_t& detection)
{
if(true == detection.vpos_detect) {
// Set Graphic 2 Specified Line Notification Detection to enable
GLC::DTCTEN.VPOSDTC = 1;
} else {
// Set Graphic 2 Specified Line Notification Detection to disable
GLC::DTCTEN.VPOSDTC = 0;
}
if(true == detection.gr1uf_detect) {
// Set Graphic 1 Underflow Detection to enable
GLC::DTCTEN.GR1UFDTC = 1;
} else {
// Set Graphic 1 Underflow Detection to disable
GLC::DTCTEN.GR1UFDTC = 0;
}
if(true == detection.gr2uf_detect) {
// Set Graphic 2 Underflow Detection to enable
GLC::DTCTEN.GR2UFDTC = 1;
} else {
// Set Graphic 2 Underflow Detection to disable
GLC::DTCTEN.GR2UFDTC = 0;
}
}
static void interrupt_setting_(const glcdc_def::interrupt_cfg_t& interrupt)
{
if(interrupt.vpos_enable) {
GLC::INTEN.VPOSINTEN = 1;
} else {
GLC::INTEN.VPOSINTEN = 0;
// 割り込みを止める場合は注意
/// EN(GLCDC,VPOS) = 0;
/// while(0 != IS(GLCDC,VPOS)) {
/// asm("nop");
/// }
}
if(interrupt.gr1uf_enable) {
GLC::INTEN.GR1UFINTEN = 1;
} else {
GLC::INTEN.GR1UFINTEN = 0;
/// EN(GLCDC,GR1UF) = 0;
/// while(0 != IS(GLCDC,GR1UF)) {
/// asm("nop");
/// }
}
if(interrupt.gr2uf_enable) {
GLC::INTEN.GR2UFINTEN = 1;
} else {
GLC::INTEN.GR2UFINTEN = 0;
/// while (0 != IS(GLCDC,GR2UF)) {
/// asm("nop");
/// }
}
/* Set GROUPAL1 interrupt request to enable, if GLCDC interrupt parameter is enabled
Set GROUPAL1 interrupt request to disable, if GLCDC interrupt parameter is disabled */
if(interrupt.vpos_enable || interrupt.gr1uf_enable || interrupt.gr2uf_enable) {
/// R_BSP_InterruptControl(BSP_INT_SRC_AL1_GLCDC_VPOS, BSP_INT_CMD_GROUP_INTERRUPT_ENABLE, (void *) &grpal1.ipl);
} else {
/// R_BSP_InterruptControl(BSP_INT_SRC_AL1_GLCDC_VPOS, BSP_INT_CMD_GROUP_INTERRUPT_DISABLE, NULL);
}
}
void graphics_read_enable_()
{
if(true == ctrl_blk_.graphics_read_enable[FRAME_LAYER_1]) {
GLC::GR1FLMRD.RENB = 1; /* Enable reading. */
} else {
GLC::GR1FLMRD.RENB = 0; /* Disable reading. */
}
if(true == ctrl_blk_.graphics_read_enable[FRAME_LAYER_2]) {
GLC::GR2FLMRD.RENB = 1; /* Enable reading. */
} else {
GLC::GR2FLMRD.RENB = 0; /* Disable reading. */
}
}
static void gr_plane_update_(uint32_t frame)
{
if(frame = 0) {
GLC::GR1VEN.VEN = 1;
} else {
GLC::GR2VEN.VEN = 1;
}
}
static bool is_gr_plane_updating_(uint32_t frame)
{
if(frame == 0) {
return GLC::GR1VEN.VEN();
} else {
return GLC::GR2VEN.VEN();
}
}
static void gamma_update_()
{
GLC::GAMGVEN.VEN = 1;
GLC::GAMBVEN.VEN = 1;
GLC::GAMRVEN.VEN = 1;
}
static bool is_gamma_updating_()
{
return (GLC::GAMGVEN.VEN() | GLC::GAMBVEN.VEN() | GLC::GAMRVEN.VEN());
}
static bool vpos_int_status_check_()
{
return GLC::STMON.VPOS();
}
static bool gr1uf_int_status_check_()
{
return GLC::STMON.GR1UF();
}
static bool gr2uf_int_status_check_()
{
return GLC::STMON.GR2UF();
}
static void vpos_int_status_clear_()
{
GLC::STCLR.VPOSCLR = 1;
}
static void gr1uf_int_status_clear_()
{
GLC::STCLR.GR1UFCLR = 1;
}
static void gr2uf_int_status_clear_()
{
GLC::STCLR.GR2UFCLR = 1;
}
static void output_ctrl_update_()
{
GLC::OUTVEN.VEN = 1;
}
static bool is_output_ctrl_updating_()
{
return GLC::OUTVEN.VEN();
}
static bool is_register_reflecting_()
{
return GLC::BGEN.VEN();
}
static void vsync_task_(void* ptr)
{
#if 0
glcdc_callback_args_t* t = static_cast<glcdc_callback_args_t*>(ptr);
#if (NUM_BUFFERS == 3)
uint32_t Addr;
glcdc_err_t ret;
#endif
// Clears the STMON.VPOS flag (GLCDC FIT module clears STMON.VPOS flag)
#if (NUM_BUFFERS == 3)
//
// Makes the pending buffer visible
//
if (_PendingBuffer >= 0) {
Addr = FRAMEBUFFER_START
+ BYTES_PER_BUFFER * _PendingBuffer; // Calculate address of buffer to be used as visible frame buffer
runtime_cfg.input.p_base = (uint32_t *)Addr; // Specify the start address of the frame buffer
ret = R_GLCDC_LayerChange(FRAME_LAYER_2, &runtime_cfg); // Graphic 2 Register Value Reflection Enable
if (ret != GLCDC_SUCCESS) {
while(1);
}
GUI_MULTIBUF_ConfirmEx(0, _PendingBuffer); // Tell emWin that buffer is used
_PendingBuffer = -1; // Clear pending buffer flag
}
#elif (NUM_BUFFERS == 2)
//
// Sets a flag to be able to notice the interrupt
//
_PendingBuffer = 0;
#endif
#endif
}
// 割り込みグループタスクの場合、割り込み関数として宣言しない事。
static void line_detect_isr_()
{
callback_args_t args;
if(ctrl_blk_.callback != nullptr) {
args.event = callback_args_t::EVENT::LINE_DETECTION;
ctrl_blk_.callback((void *)&args);
}
vpos_int_status_clear_();
if(!ctrl_blk_.first_vpos_interrupt_flag) {
// Clear interrupt flag in the register of the GLCD module
gr1uf_int_status_clear_();
gr2uf_int_status_clear_();
// Set the GLCD interrupts
interrupt_setting_(ctrl_blk_.interrupt);
// Set the first VPOS interrupt flag
ctrl_blk_.first_vpos_interrupt_flag = true;
}
++ctrl_blk_.vpos_count;
}
// 割り込みグループタスクの場合、割り込み関数として宣言しない事。
static void underflow_1_isr_()
{
callback_args_t args;
if(ctrl_blk_.callback != nullptr) {
args.event = callback_args_t::EVENT::GR1_UNDERFLOW;
ctrl_blk_.callback((void *)&args);
}
// Clear interrupt flag in the register of the GLCD module
gr1uf_int_status_clear_();
}
// 割り込みグループタスクの場合、割り込み関数として宣言しない事。
static void underflow_2_isr_()
{
callback_args_t args;
if(ctrl_blk_.callback != nullptr) {
args.event = callback_args_t::EVENT::GR2_UNDERFLOW;
ctrl_blk_.callback ((void *)&args);
}
// Clear interrupt flag in the register of the GLCD module
gr2uf_int_status_clear_();
}
bool open_(const cfg_t& cfg)
{
last_error_ = ERROR::SUCCESS;
// Status check
if(glcdc_def::OPERATING_STATUS::CLOSED != ctrl_blk_.state) {
last_error_ = ERROR::INVALID_MODE;
return false;
}
// Store position information to the control block
// (it is necessary to set the layer and blending section later)
ctrl_blk_.active_start_pos.x = static_cast<int16_t>(cfg.output.htiming.back_porch
+ cfg.output.htiming.sync_width);
ctrl_blk_.active_start_pos.y = static_cast<int16_t>(cfg.output.vtiming.back_porch
+ cfg.output.vtiming.sync_width);
ctrl_blk_.hsize = cfg.output.htiming.display_cyc;
ctrl_blk_.vsize = cfg.output.vtiming.display_cyc;
// Save status of frame buffer read enable
if(cfg.input[FRAME_LAYER_1].offset == 0) {
ctrl_blk_.graphics_read_enable[FRAME_LAYER_1] = false;
} else {
ctrl_blk_.graphics_read_enable[FRAME_LAYER_1] = true;
}
if(cfg.input[FRAME_LAYER_2].offset == 0) {
ctrl_blk_.graphics_read_enable[FRAME_LAYER_2] = false;
} else {
ctrl_blk_.graphics_read_enable[FRAME_LAYER_2] = true;
}
// Save callback function
ctrl_blk_.callback = cfg.callback;
// Save setting of interrupt
ctrl_blk_.interrupt.vpos_enable = cfg.interrupt.vpos_enable;
ctrl_blk_.interrupt.gr1uf_enable = cfg.interrupt.gr1uf_enable;
ctrl_blk_.interrupt.gr2uf_enable = cfg.interrupt.gr2uf_enable;
// If one of the interrupt setting is enable, setting value is
// set after first vpos interrupt
glcdc_def::interrupt_cfg_t initial_interrupt;
if(cfg.interrupt.vpos_enable || cfg.interrupt.gr1uf_enable
|| cfg.interrupt.gr2uf_enable) {
ctrl_blk_.first_vpos_interrupt_flag = false;
initial_interrupt.vpos_enable = true;
initial_interrupt.gr1uf_enable = false;
initial_interrupt.gr2uf_enable = false;
} else {
ctrl_blk_.first_vpos_interrupt_flag = true;
initial_interrupt.vpos_enable = false;
initial_interrupt.gr1uf_enable = false;
initial_interrupt.gr2uf_enable = false;
}
// Check parameters
// err = r_glcdc_open_param_check (p_cfg);
// if(GLCDC_SUCCESS != err) {
// return err;
// }
// この中で行うべきでない処理
#if 0
// Check GLCDC resource is locked by another process
if(false == R_BSP_HardwareLock ((mcu_lock_t) BSP_LOCK_GLCDC)) {
return GLCDC_ERR_LOCK_FUNC;
}
#endif
// Supply the peripheral clock to the GLCD module
power_mgr::turn(GLC::PERIPHERAL);
// LCD_DATA0 to LCD_DATA15, LCD_CLK, LCD_TCON0, LCD_TCON2, LCD_TCON3
if(!port_map::turn(GLC::PERIPHERAL)) {
utils::format("GLCDC: port map fail...\n");
return false;
}
// Release GLCD from a SW reset status.
release_software_reset_();
// Set the dot clock frequency
clock_set_(cfg);
// Set the panel signal timing
sync_signal_set_(cfg);
// Configure the background screen
background_screen_set_(cfg);
// Configure the graphics plane layers
for(uint32_t frame = 0; frame <= FRAME_LAYER_2; ++frame) {
graphics_layer_set_(cfg.input[frame], frame);
blend_condition_set_(cfg.blend[frame], frame);
graphics_chromakey_set_(cfg.chromakey[frame], frame);
clut_update_(cfg.clut[frame], frame);
}
// Configure the output control block
output_block_set_(cfg);
// Configure the color correction setting
// (brightness, brightness and gamma correction)
brightness_correction_(cfg.output.brightness);
contrast_correction_(cfg.output.contrast);
gamma_correction_(cfg.output.gamma);
{ // setup default CLUT
// rrr_ggg_bb
for(uint32_t i = 0; i < 256; ++i) {
uint8_t r = (i & 0b1110'0000) | ((i & 0b1110'0000) >> 3) | ((i & 0b1110'0000) >> 6);
uint8_t g = (i & 0b0001'1100) | ((i & 0b0001'1100) << 3) | ((i & 0b0001'1100) >> 3);
uint8_t b = (i & 0b0000'0011) | ((i & 0b0000'0011) << 2) | ((i & 0b0000'0011) << 4)
| ((i & 0b00000011) << 6);
uint8_t a = 0;
uint32_t rgba = (r << 24) | (g << 16) | (b << 8) | a;
GLC::GR1CLUT0[i] = rgba;
GLC::GR1CLUT1[i] = rgba;
GLC::GR2CLUT0[i] = rgba;
GLC::GR2CLUT1[i] = rgba;
}
}
// Set the line number which is suppose to happen the line detect interrupt
line_detect_number_set_(
(uint16_t) (((cfg.output.vtiming.sync_width + cfg.output.vtiming.back_porch)
+ cfg.output.vtiming.display_cyc) + BG_PLANE_HSYNC_POS_MIN));
// Enable the GLCD detections and interrupts
if(!ctrl_blk_.is_entry) {
icu_mgr::set_level(ICU::VECTOR::GROUPAL1, intr_lvl_);
if(intr_lvl_ > 0) {
icu_mgr::install_group_task(ICU::VECTOR_AL1::VPOS, line_detect_isr_);
icu_mgr::install_group_task(ICU::VECTOR_AL1::GR1UF, underflow_1_isr_);
icu_mgr::install_group_task(ICU::VECTOR_AL1::GR2UF, underflow_2_isr_);
}
ctrl_blk_.is_entry = true;
}
detect_setting_(cfg.detection);
interrupt_setting_(initial_interrupt);
// Allow reading of graphics data
graphics_read_enable_();
// Change GLCDC driver state
ctrl_blk_.state = glcdc_def::OPERATING_STATUS::NOT_DISPLAYING;
return true;
}
void bg_color_setting_(const glcdc_def::color_t& color)
{
GLC::BGCOLOR.R = color.r;
GLC::BGCOLOR.G = color.g;
GLC::BGCOLOR.B = color.b;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
@param[in] ly1 レイヤー1アドレス
@param[in] ly2 レイヤー2アドレス
*/
//-----------------------------------------------------------------//
glcdc_mgr(void* ly1, void* ly2) noexcept :
layer1_org_(ly1), layer2_org_(ly2),
flip_count_(0), enable_double_(false),
intr_lvl_(0), last_error_(ERROR::SUCCESS)
{ }
//-----------------------------------------------------------------//
/*!
@brief フレームバッファポインター取得
@return フレームバッファポインター
*/
//-----------------------------------------------------------------//
void* get_fbp() const noexcept
{
uint32_t ofs = 0;
if(enable_double_) {
ofs = (flip_count_ & 1) != 0 ? 0 : frame_size;
}
if(layer2_org_ != nullptr) {
uint32_t org = reinterpret_cast<uint32_t>(layer2_org_);
return reinterpret_cast<void*>(org + ofs);
} else if(layer1_org_ != nullptr) {
uint32_t org = reinterpret_cast<uint32_t>(layer1_org_);
return reinterpret_cast<void*>(org + ofs);
}
return nullptr;
}
//-----------------------------------------------------------------//
/*!
@brief ダブルバッファを有効にする
@param[in] ena 無効にする場合「false」
@return 有効に出来ない場合「false」を返す
*/
//-----------------------------------------------------------------//
bool enable_double_buffer(bool ena = true) noexcept {
#if defined(SIG_RX72N) || defined(SIG_RX72M)
enable_double_ = ena;
return true;
#else
return false;
#endif
}
//-----------------------------------------------------------------//
/*!
@brief ダブルバッファが有効か検査
@return 有効な場合「true」
*/
//-----------------------------------------------------------------//
bool is_double_buffer() const noexcept { return enable_double_; }
//-----------------------------------------------------------------//
/*!
@brief レイヤー1のアドレス取得
@return レイヤー1のアドレス
*/
//-----------------------------------------------------------------//
void* get_layer1() const noexcept { return layer1_org_; }
//-----------------------------------------------------------------//
/*!
@brief レイヤー2のアドレス取得
@return レイヤー2のアドレス
*/
//-----------------------------------------------------------------//
void* get_layer2() const noexcept { return layer2_org_; }
//-----------------------------------------------------------------//
/*!
@brief BG の許可(不許可)
@param[in] ena 不許可の場合「false」
*/
//-----------------------------------------------------------------//
void bg_operation_enable(bool ena = true) noexcept
{
if(ena) {
GLC::BGEN = 0x00010101;
} else {
GLC::BGEN.EN = 1;
while(GLC::BGMON.EN() != 0) {
asm("nop");
}
}
}
//-----------------------------------------------------------------//
/*!
@brief 開始 480x272専用
@param[in] ilvl 割り込みレベル(0なら割り込み無し)
@return エラーなら「false」
*/
//-----------------------------------------------------------------//
bool start(uint8_t ilvl = 2) noexcept
{
intr_lvl_ = ilvl;
// メインバス2優先順位設定(GLCDC、DRW2D)
device::BUS::EBMAPCR.PR1SEL = 0;
device::BUS::EBMAPCR.PR2SEL = 3;
device::BUS::EBMAPCR.PR3SEL = 1;
device::BUS::EBMAPCR.PR4SEL = 2;
device::BUS::EBMAPCR.PR5SEL = 4;
cfg_t cfg;
cfg.output.clksrc = glcdc_def::CLK_SRC::INTERNAL; // Select PLL clock
// 240 / 24 = 10 MHz
// No frequency division
// Enable LCD_CLK output
cfg.output.clock_div_ratio = glcdc_def::PANEL_CLK_DIVISOR::_24;
//
// Definition of LCD for 480x272 LCD by 60Hz
//
// Horizontal cycle (whole control screen) 529
// Vertical cycle (whole control screen) 315
// Horizontal Synchronization Signal Assertion Position
cfg.output.htiming.front_porch = 8;
// Vertical Synchronization Assertion Position
cfg.output.vtiming.front_porch = 10;
// Horizontal Active Pixel Start Position (min. 6 pixels)
cfg.output.htiming.back_porch = 39;
cfg.output.vtiming.back_porch = 32;
// Horizontal Active Pixel Width
cfg.output.htiming.display_cyc = XSIZE;
// Vertical Active Display Width
cfg.output.vtiming.display_cyc = YSIZE;
// Vertical Active Display Start Position (min. 3 lines)
cfg.output.htiming.sync_width = 2;
cfg.output.vtiming.sync_width = 1;
//
// Graphic 1 configuration
//
if(layer1_org_ != nullptr) {
cfg.input[FRAME_LAYER_1].base = layer1_org_;
cfg.input[FRAME_LAYER_1].offset = LINE_OFFSET;
} else {
cfg.input[FRAME_LAYER_1].offset = 0; // Disable Graphics 1
}
//
// Graphic 2 configuration
//
// Enable reading of the frame buffer
// Specify the start address of the frame buffer
if(layer2_org_ != nullptr) {
cfg.input[FRAME_LAYER_2].base = layer2_org_;
cfg.input[FRAME_LAYER_2].offset = LINE_OFFSET;
} else {
cfg.input[FRAME_LAYER_2].offset = 0;
}
// Single Line Data Transfer Count
// Single Frame Line Count
switch(PXT_) {
case graphics::pixel::TYPE::CLUT1:
cfg.input[FRAME_LAYER_2].format = glcdc_def::IN_FORMAT::CLUT1;
break;
case graphics::pixel::TYPE::CLUT4:
cfg.input[FRAME_LAYER_2].format = glcdc_def::IN_FORMAT::CLUT4;
break;
case graphics::pixel::TYPE::CLUT8:
cfg.input[FRAME_LAYER_2].format = glcdc_def::IN_FORMAT::CLUT8;
break;
case graphics::pixel::TYPE::RGB565:
cfg.input[FRAME_LAYER_2].format = glcdc_def::IN_FORMAT::RGB565;
break;
// (GLCDC_IN_FORMAT_16BITS_ARGB1555)
// (GLCDC_IN_FORMAT_16BITS_ARGB4444)
case graphics::pixel::TYPE::RGB888:
cfg.input[FRAME_LAYER_2].format = glcdc_def::IN_FORMAT::RGB888;
break;
// (GLCDC_IN_FORMAT_32BITS_ARGB8888)
}
cfg.blend[FRAME_LAYER_2].visible = true;
// Display Screen Control (current graphics)
cfg.blend[FRAME_LAYER_2].blend_control = glcdc_def::BLEND_CONTROL::NONE;
// Rectangular Alpha Blending Area Frame Display Control
cfg.blend[FRAME_LAYER_2].frame_edge = false;
// Graphics Area Frame Display Control
cfg.input[FRAME_LAYER_2].frame_edge = false;
// Alpha Blending Control (Per-pixel alpha blending)
// Graphics Area Vertical Start Position
cfg.input[FRAME_LAYER_2].coordinate.y = 0;
// Graphics Area Vertical Width
cfg.input[FRAME_LAYER_2].vsize = YSIZE;
// Graphics Area Horizontal Start Position
cfg.input[FRAME_LAYER_2].coordinate.x = 0;
// Graphics Area Horizontal Width
cfg.input[FRAME_LAYER_2].hsize = XSIZE;
// Rectangular Alpha Blending Area Vertical Start Position
cfg.blend[FRAME_LAYER_2].start_coordinate.x = 0;
// Rectangular Alpha Blending Area Vertical Width
cfg.blend[FRAME_LAYER_2].end_coordinate.x= YSIZE;
// Rectangular Alpha Blending Area Horizontal Start Position
cfg.blend[FRAME_LAYER_2].start_coordinate.y = 0;
// Rectangular Alpha Blending Area Horizontal Width
cfg.blend[FRAME_LAYER_2].end_coordinate.y= XSIZE;
// Graphic 2 Register Value Reflection Enable
//
// Timing configuration
//
// Horizontal Synchronization Signal Reference Timing Offset (not support)
// Signal Reference Timing Select (not support)
// STVB Signal Assertion Timing
// STVB Signal Pulse Width
// STHB Signal Pulse Width
// TCON0 Output Signal Select STVA (VSYNC)
cfg.output.tcon_vsync = glcdc_def::TCON_PIN::_0;
// TCON2 Output Signal Select STHA (HSYNC)
cfg.output.tcon_hsync = glcdc_def::TCON_PIN::_2;
// TCON3 Output Signal Select DE (DEN)
cfg.output.tcon_de = glcdc_def::TCON_PIN::_3;
cfg.output.data_enable_polarity = glcdc_def::SIGNAL_POLARITY::HIACTIVE;
cfg.output.hsync_polarity = glcdc_def::SIGNAL_POLARITY::LOACTIVE;
cfg.output.vsync_polarity = glcdc_def::SIGNAL_POLARITY::LOACTIVE;
cfg.output.sync_edge = glcdc_def::SIGNAL_SYNC_EDGE::RISING;
//
// Output interface
//
// Serial RGB Data Output Delay Control (0 cycles) (not support)
// Serial RGB Scan Direction Select (forward) (not support)
// Pixel Clock Division Control (no division)
// Output Data Format Select (RGB565)
cfg.output.format = glcdc_def::OUT_FORMAT::RGB565;
// Pixel Order Control (B-G-R)
cfg.output.color_order = glcdc_def::COLOR_ORDER::RGB; // GLCDC_COLOR_ORDER_BGR;
// Bit Endian Control (Little endian)
cfg.output.endian = glcdc_def::ENDIAN::LITTLE;
//
// Brightness Adjustment
//
cfg.output.brightness.b = BRIGHTNESS_; // B
cfg.output.brightness.g = BRIGHTNESS_; // G
cfg.output.brightness.r = BRIGHTNESS_; // R
//
// Contrast Adjustment Value
//
cfg.output.contrast.b = CONTRAST_; // B
cfg.output.contrast.g = CONTRAST_; // G
cfg.output.contrast.r = CONTRAST_; // R
//
// Disable Gamma
//
cfg.output.gamma.enable = false;
//
// Disable Chromakey
//
cfg.chromakey[FRAME_LAYER_2].enable = false;
//
// Disable Dithering
//
cfg.output.dithering.dithering_on = false;
//
// CLUT Adjustment Value
//
cfg.clut[FRAME_LAYER_2].enable = false;
//
// Enable VPOS ISR
//
// Detecting Scanline Setting
// Enable detection of specified line notification in graphic 2
cfg.detection.vpos_detect = true;
// Enable VPOS interrupt request
cfg.interrupt.vpos_enable = true;
// Interrupt Priority Level (r_glcdc_rx_config.h)
// Interrupt Request Enable
// Clears the STMON.VPOS flag
// VPOS (line detection)
cfg.detection.gr1uf_detect = false;
cfg.detection.gr2uf_detect = false;
cfg.interrupt.gr1uf_enable = false;
cfg.interrupt.gr2uf_enable = false;
//
// Set function to be called on VSYNC
//
cfg.callback = vsync_task_;
#if 0
runtime_cfg.blend = cfg.blend[FRAME_LAYER_2];
runtime_cfg.input = cfg.input[FRAME_LAYER_2];
runtime_cfg.chromakey = cfg.chromakey[FRAME_LAYER_2];
#endif
//
// Register Reflection
//
auto ret = open_(cfg);
if(!ret) {
return false;
}
if(cfg.input[FRAME_LAYER_1].offset != 0) {
memset(cfg.input[FRAME_LAYER_1].base, 0x00, BYTES_PER_BUFFER);
}
if(cfg.input[FRAME_LAYER_2].offset != 0) {
memset(cfg.input[FRAME_LAYER_2].base, 0x00, BYTES_PER_BUFFER);
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 制御
@param[in] cmd 制御種別
@param[in] args パラメーター
@return エラーなら「false」
*/
//-----------------------------------------------------------------//
bool control(CONTROL_CMD cmd, const void* args = nullptr) noexcept
{
if(glcdc_def::OPERATING_STATUS::CLOSED == ctrl_blk_.state) {
last_error_ = ERROR::NOT_OPEN;
return false;
}
switch(cmd) {
case CONTROL_CMD::START_DISPLAY:
if(glcdc_def::OPERATING_STATUS::DISPLAYING == ctrl_blk_.state) {
last_error_ = ERROR::INVALID_MODE;
return false;
}
/* Change GLCDC driver state */
ctrl_blk_.state = glcdc_def::OPERATING_STATUS::DISPLAYING;
/* Start to output the vertical and horizontal synchronization signals and
screen data. */
bg_operation_enable();
break;
case CONTROL_CMD::STOP_DISPLAY:
if(glcdc_def::OPERATING_STATUS::NOT_DISPLAYING == ctrl_blk_.state) {
last_error_ = ERROR::INVALID_MODE;
return false;
}
/* Return immediately if the register is being updated */
if(is_gr_plane_updating_(FRAME_LAYER_1)) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
if(is_gr_plane_updating_(FRAME_LAYER_2)) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
if(is_output_ctrl_updating_()) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
if(is_gamma_updating_()) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
if(is_register_reflecting_()) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
/* Stop outputting the vertical and horizontal synchronization signals
and screen data. */
bg_operation_enable(false);
/* status update */
ctrl_blk_.state = glcdc_def::OPERATING_STATUS::NOT_DISPLAYING;
break;
case CONTROL_CMD::SET_INTERRUPT:
#if (GLCDC_CFG_PARAM_CHECKING_ENABLE)
if(nullptr == args) {
last_error_ = ERROR::INVALID_PTR;
return false;
}
#endif
if(false == ctrl_blk_.first_vpos_interrupt_flag) {
last_error_ = ERROR::INVALID_UPDATE_TIMING;
return false;
}
/* interrupt setting */
{
const glcdc_def::interrupt_cfg_t* t =
static_cast<const glcdc_def::interrupt_cfg_t*>(args);
interrupt_setting_(*t);
}
break;
case CONTROL_CMD::CLR_DETECTED_STATUS:
#if (GLCDC_CFG_PARAM_CHECKING_ENABLE)
if (nullptr == args) {
return GLCDC_ERR_INVALID_PTR;
}
#endif
{
const detect_cfg_t* p_detection;
p_detection = static_cast<const detect_cfg_t*>(args);
if(true == p_detection->vpos_detect) {
vpos_int_status_clear_();
}
if(true == p_detection->gr1uf_detect) {
gr1uf_int_status_clear_();
}
if(true == p_detection->gr2uf_detect) {
gr2uf_int_status_clear_();
}
}
break;
case CONTROL_CMD::CHANGE_BG_COLOR:
{
const auto* t = static_cast<const glcdc_def::color_t*>(args);
if(t != nullptr) {
bg_color_setting_(*t);
} else {
last_error_ = ERROR::INVALID_PTR;
return false;
}
}
break;
default:
last_error_ = ERROR::INVALID_ARG;
return false;
}
last_error_ = ERROR::SUCCESS;
return true;
}
//-----------------------------------------------------------------//
/*!
@brief VPOS との同期
*/
//-----------------------------------------------------------------//
void sync_vpos() const noexcept
{
if(enable_double_) {
uint32_t ofs = (flip_count_ & 1) != 0 ? 0 : frame_size;
uint32_t org = reinterpret_cast<uint32_t>(layer2_org_);
GLC::GR2VEN = 1;
GLC::GR2FLM2 = org + ofs;
}
volatile auto n = ctrl_blk_.vpos_count;
while(n == ctrl_blk_.vpos_count) {
asm("nop");
}
}
//-----------------------------------------------------------------//
/*!
@brief バッファの FLIP @n
※480x272 の解像度では、RAM は 512K バイト必要
*/
//-----------------------------------------------------------------//
void flip() noexcept
{
++flip_count_;
}
//-----------------------------------------------------------------//
/*!
@brief VPOS カウントの取得
@return VPOS カウント
*/
//-----------------------------------------------------------------//
uint32_t get_vpos_count() const noexcept
{
return ctrl_blk_.vpos_count;
}
//-----------------------------------------------------------------//
/*!
@brief CLUT の直接アクセス
@param[in] rgba カラー
@param[in] index インデックス
@return エラーなら「false」
*/
//-----------------------------------------------------------------//
bool set_clut(glcdc_def::color_t& rgba, uint32_t index) noexcept
{
if(index >= 256) return false;
GLC::GR1CLUT0[index] = rgba;
return true;
}
};
template <class GLC, int16_t XSIZE, int16_t YSIZE, graphics::pixel::TYPE PXT_>
glcdc_def::ctrl_t glcdc_mgr<GLC, XSIZE, YSIZE, PXT_>::ctrl_blk_;
}
| 31.490951 | 124 | 0.635678 | [
"vector"
] |
22c1781bb7e61796c4280c6dc9d0dd9c451797ef | 2,285 | cpp | C++ | TSS.CPP/Samples/TpmConfig.cpp | dkov01/TSS.MSR | 54629f1182c5e6aeaa10e06646e43d4bd1bd28be | [
"MIT"
] | null | null | null | TSS.CPP/Samples/TpmConfig.cpp | dkov01/TSS.MSR | 54629f1182c5e6aeaa10e06646e43d4bd1bd28be | [
"MIT"
] | null | null | null | TSS.CPP/Samples/TpmConfig.cpp | dkov01/TSS.MSR | 54629f1182c5e6aeaa10e06646e43d4bd1bd28be | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "TpmConfig.h"
#include <algorithm>
std::vector<TPM_ALG_ID> TpmConfig::ImplementedAlgs;
// Implemented hash algorithms
std::vector<TPM_ALG_ID> TpmConfig::HashAlgs;
// All commands implemented by the TPM
std::vector<TPM_CC> TpmConfig::ImplementedCommands;
void TpmConfig::Init(Tpm2& tpm)
{
if (ImplementedCommands.size() > 0)
{
_ASSERT(ImplementedAlgs.size() > 0 && HashAlgs.size() > 0);
return;
}
UINT32 startProp = (UINT32)TPM_ALG_ID::FIRST;
GetCapabilityResponse resp;
do {
resp = tpm.GetCapability(TPM_CAP::ALGS, startProp,
(UINT32)TPM_ALG_ID::LAST - startProp + 1);
auto capData = dynamic_cast<TPML_ALG_PROPERTY*>(&*resp.capabilityData);
auto algProps = capData->algProperties;
for (const TPMS_ALG_PROPERTY& p: algProps)
{
ImplementedAlgs.push_back(p.alg);
if (p.algProperties == TPMA_ALGORITHM::hash)
HashAlgs.push_back(p.alg);
}
startProp = (UINT32)algProps.back().alg + 1;
} while (resp.moreData);
startProp = (UINT32)TPM_CC::FIRST;
do {
const UINT32 MaxVendorCmds = 32;
resp = tpm.GetCapability(TPM_CAP::COMMANDS, startProp,
(UINT32)TPM_CC::LAST - startProp + MaxVendorCmds + 1);
auto capData = dynamic_cast<TPML_CCA*>(&*resp.capabilityData);
auto cmdAttrs = capData->commandAttributes;
for (auto iter = cmdAttrs.begin(); iter != cmdAttrs.end(); iter++)
{
UINT32 attrVal = (UINT32)*iter;
TPM_CC cc = (TPM_CC)(attrVal & 0xFFFF);
//TPMA_CC maskedAttr = (TPMA_CC)(attrVal & 0xFFFF0000);
ImplementedCommands.push_back(cc);
}
startProp = ((UINT32)cmdAttrs.back() & 0xFFFF) + 1;
} while (resp.moreData);
} // TpmConfig::Init()
bool TpmConfig::Implements(TPM_CC cmd)
{
return std::find(ImplementedCommands.begin(), ImplementedCommands.end(), cmd)
!= ImplementedCommands.end();
}
bool TpmConfig::Implements(TPM_ALG_ID alg)
{
return std::find(ImplementedAlgs.begin(), ImplementedAlgs.end(), alg) != ImplementedAlgs.end();
}
| 32.183099 | 100 | 0.604814 | [
"vector"
] |
22c1f96603cff0fb0c8335816d8efe1e1e9cbb43 | 28,426 | hpp | C++ | src/inference/include/openvino/runtime/core.hpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | 1 | 2022-02-26T17:33:44.000Z | 2022-02-26T17:33:44.000Z | src/inference/include/openvino/runtime/core.hpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | 17 | 2021-11-25T10:22:17.000Z | 2022-03-28T13:19:31.000Z | src/inference/include/openvino/runtime/core.hpp | pfinashx/openvino | 1d417e888b508415510fb0a92e4a9264cf8bdef7 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @brief This is a header file for the OpenVINO Runtime Core class C++ API
*
* @file openvino/runtime/core.hpp
*/
#pragma once
#include <istream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "ie_plugin_config.hpp"
#include "openvino/core/extension.hpp"
#include "openvino/core/model.hpp"
#include "openvino/core/op_extension.hpp"
#include "openvino/core/version.hpp"
#include "openvino/op/op.hpp"
#include "openvino/runtime/common.hpp"
#include "openvino/runtime/compiled_model.hpp"
#include "openvino/runtime/remote_context.hpp"
#include "openvino/runtime/tensor.hpp"
namespace InferenceEngine {
class IExtension;
} // namespace InferenceEngine
namespace ov {
/**
* @brief This class represents OpenVINO runtime Core entity.
* User applications can create several Core class instances, but in this case the underlying plugins
* are created multiple times and not shared between several Core instances. The recommended way is to have
* a single Core instance per application.
*/
class OPENVINO_RUNTIME_API Core {
class Impl;
std::shared_ptr<Impl> _impl;
void get_property(const std::string& device_name, const std::string& name, ov::Any& to) const;
public:
/** @brief Constructs OpenVINO Core instance using XML configuration file with
* devices and their plugins description.
*
* See Core::register_plugins for more details.
*
* @param xml_config_file A path to .xml file with plugins to load from. If XML configuration file is not specified,
* then default OpenVINO Runtime plugins are loaded from the default `plugin.xml` file located in the same folder
* as OpenVINO runtime shared library.
*/
explicit Core(const std::string& xml_config_file = {});
/**
* @brief Returns device plugins version information
* Device name can be complex and identify multiple devices at once like `HETERO:CPU,GPU`
* and in this case a std::map contains multiple entries each per device.
*
* @param device_name Device name to identify a plugin
* @return A vector of versions
*/
std::map<std::string, Version> get_versions(const std::string& device_name) const;
#ifdef OPENVINO_ENABLE_UNICODE_PATH_SUPPORT
/**
* @brief Reads models from IR / ONNX / PDPD formats
* @param model_path A path to a model
* @param bin_path A path to a data file
* For IR format (*.bin):
* * if path is empty, will try to read bin file with the same name as xml and
* * if bin file with the same name was not found, will load IR without weights.
* For ONNX format (*.onnx):
* * bin_path parameter is not used.
* For PDPD format (*.pdmodel)
* * bin_path parameter is not used.
* @return A model
*/
std::shared_ptr<ov::Model> read_model(const std::wstring& model_path, const std::wstring& bin_path = {}) const;
#endif
/**
* @brief Reads models from IR / ONNX / PDPD formats
* @param model_path A path to a model
* @param bin_path A path to a data file
* For IR format (*.bin):
* * if path is empty, will try to read bin file with the same name as xml and
* * if bin file with the same name was not found, will load IR without weights.
* For ONNX format (*.onnx):
* * bin_path parameter is not used.
* For PDPD format (*.pdmodel)
* * bin_path parameter is not used.
* @return A model
*/
std::shared_ptr<ov::Model> read_model(const std::string& model_path, const std::string& bin_path = {}) const;
/**
* @brief Reads models from IR / ONNX / PDPD formats
* @param model A string with model in IR / ONNX / PDPD format
* @param weights A shared pointer to constant tensor with weights
* Reading ONNX / PDPD models doesn't support loading weights from @p weights tensors.
* @note Created model object shares the weights with @p weights object.
* So, do not create @p weights on temporary data which can be later freed, since the model
* constant data becomes point to an invalid memory.
* @return A model
*/
std::shared_ptr<ov::Model> read_model(const std::string& model, const Tensor& weights) const;
/**
* @brief Creates and loads a compiled model from a source model to the default OpenVINO device selected by AUTO
* plugin.
*
* Users can create as many compiled models as they need and use
* them simultaneously (up to the limitation of the hardware resources)
*
* @param model Model object acquired from Core::read_model
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation
* @return A compiled model
*/
CompiledModel compile_model(const std::shared_ptr<const ov::Model>& model, const AnyMap& properties = {});
/**
* @brief Creates and loads a compiled model from a source model to the default OpenVINO device selected by AUTO
* plugin.
*
* Users can create as many compiled models as they need and use
* them simultaneously (up to the limitation of the hardware resources)
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model Model object acquired from Core::read_model
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
*
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> compile_model(
const std::shared_ptr<const ov::Model>& model,
Properties&&... properties) {
return compile_model(model, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Creates a compiled model from a source model object.
*
* Users can create as many compiled models as they need and use
* them simultaneously (up to the limitation of the hardware resources)
*
* @param model Model object acquired from Core::read_model
* @param device_name Name of device to load model to
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation
* @return A compiled model
*/
CompiledModel compile_model(const std::shared_ptr<const ov::Model>& model,
const std::string& device_name,
const AnyMap& properties = {});
/**
* @brief Creates a compiled model from a source model object.
*
* Users can create as many compiled models as they need and use
* them simultaneously (up to the limitation of the hardware resources)
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model Model object acquired from Core::read_model
* @param device_name Name of device to load model to
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> compile_model(
const std::shared_ptr<const ov::Model>& model,
const std::string& device_name,
Properties&&... properties) {
return compile_model(model, device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Reads and loads a compiled model from IR / ONNX / PDPD file to the default OpenVINI device selected by
* AUTO plugin.
*
* This can be more efficient than using Core::read_model + Core::compile_model(model_in_memory_object) flow
* especially for cases when caching is enabled and cached model is available
*
* @param model_path path to model
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation/
*
* @return A compiled model
*/
CompiledModel compile_model(const std::string& model_path, const AnyMap& properties = {});
/**
* @brief Reads and loads a compiled model from IR / ONNX / PDPD file to the default OpenVINI device selected by
* AUTO plugin.
*
* This can be more efficient than using read_model + compile_model(Model) flow
* especially for cases when caching is enabled and cached model is available
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model_path path to model
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
*
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> compile_model(const std::string& model_path,
Properties&&... properties) {
return compile_model(model_path, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Reads model and creates a compiled model from IR / ONNX / PDPD file
*
* This can be more efficient than using Core::read_model + Core::compile_model(model_in_memory_object) flow
* especially for cases when caching is enabled and cached model is available
*
* @param model_path Path to a model
* @param device_name Name of device to load a model to
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation/
*
* @return A compiled model
*/
CompiledModel compile_model(const std::string& model_path,
const std::string& device_name,
const AnyMap& properties = {});
/**
* @brief Reads model and creates a compiled model from IR / ONNX / PDPD file
*
* This can be more efficient than using read_model + compile_model(Model) flow
* especially for cases when caching is enabled and cached model is available
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model_path path to model
* @param device_name Name of device to load model to
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
*
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> compile_model(const std::string& model_path,
const std::string& device_name,
Properties&&... properties) {
return compile_model(model_path, device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Creates a compiled model from a source model within a specified remote context.
* @param model Model object acquired from Core::read_model
* @param context A reference to a RemoteContext object
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation
* @return A compiled model object
*/
CompiledModel compile_model(const std::shared_ptr<const ov::Model>& model,
const RemoteContext& context,
const AnyMap& properties = {});
/**
* @brief Creates a compiled model from a source model within a specified remote context.
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model Model object acquired from Core::read_model
* @param context Pointer to RemoteContext object
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
* @return A compiled model object
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> compile_model(
const std::shared_ptr<const ov::Model>& model,
const RemoteContext& context,
Properties&&... properties) {
return compile_model(model, context, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @deprecated This method is deprecated. Please use other Core::add_extension methods
* @brief Registers OpenVINO 1.0 extension to a Core object
* @param extension Pointer to already loaded extension
*/
OPENVINO_DEPRECATED("Please use add_extension(ov::Extension) or add_extension(path_to_library) instead.")
void add_extension(const std::shared_ptr<InferenceEngine::IExtension>& extension);
/**
* @brief Registers an extension to a Core object
* @param library_path Path to library with ov::Extension
*/
void add_extension(const std::string& library_path);
#ifdef OPENVINO_ENABLE_UNICODE_PATH_SUPPORT
/**
* @brief Registers an extension to a Core object
* @param library_path Unicode path to library with ov::Extension
*/
void add_extension(const std::wstring& library_path);
#endif
/**
* @brief Registers an extension to a Core object
* @param extension Pointer to extension
*/
void add_extension(const std::shared_ptr<ov::Extension>& extension);
/**
* @brief Registers extensions to a Core object
* @param extensions Vector of loaded extensions
*/
void add_extension(const std::vector<std::shared_ptr<ov::Extension>>& extensions);
/**
* @brief Registers an extension to a Core object
* @param extension Extension class which is inherited from ov::Extension class
*/
template <class T, typename std::enable_if<std::is_base_of<ov::Extension, T>::value, bool>::type = true>
void add_extension(const T& extension) {
std::shared_ptr<ov::Extension> ext = std::make_shared<T>(extension);
add_extension(ext);
}
/**
* @brief Registers extensions to a Core object
* @param extension Extension class which is inherited from ov::Extension class
* @param args A list of extensions
*/
template <class T,
class... Targs,
typename std::enable_if<std::is_base_of<ov::Extension, T>::value, bool>::type = true>
void add_extension(const T& extension, Targs... args) {
std::shared_ptr<ov::Extension> ext = std::make_shared<T>(extension);
add_extension(ext);
add_extension(args...);
}
/**
* @brief Registers a custom operation inherited from ov::op::Op
*/
template <class T, typename std::enable_if<std::is_base_of<ov::op::Op, T>::value, bool>::type = true>
void add_extension() {
std::shared_ptr<ov::Extension> ext = std::make_shared<ov::OpExtension<T>>();
add_extension(ext);
}
/**
* @brief Registers custom operations inherited from ov::op::Op
*/
template <class T,
class... Targs,
typename std::enable_if<std::is_base_of<ov::op::Op, T>::value && sizeof...(Targs), bool>::type = true>
void add_extension() {
std::shared_ptr<ov::Extension> ext = std::make_shared<ov::OpExtension<T>>();
add_extension(ext);
if (sizeof...(Targs) > 0)
add_extension<Targs...>();
}
/**
* @brief Imports a compiled model from a previously exported one
* @param model_stream std::istream input stream containing a model previously exported using
* ov::CompiledModel::export_model method
* @param device_name Name of device to import compiled model for. Note, if @p device_name device was not used to
* compile the original mode, an exception is thrown
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation*
* @return A compiled model
*/
CompiledModel import_model(std::istream& model_stream,
const std::string& device_name,
const AnyMap& properties = {});
/**
* @brief Imports a compiled model from a previously exported one
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model_stream Model stream
* @param device_name Name of device to import compiled model for. Note, if @p device_name device was not used to
* compile the original mode, an exception is thrown
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> import_model(std::istream& model_stream,
const std::string& device_name,
Properties&&... properties) {
return import_model(model_stream, device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Imports a compiled model from a previously exported one with a specified remote context.
* @param model_stream std::istream input stream containing a model previously exported from
* ov::CompiledModel::export_model
* @param context A reference to a RemoteContext object. Note, if the device from @p context was not used to compile
* the original mode, an exception is thrown
* @param properties Optional map of pairs: (property name, property value) relevant only for this load
* operation
* @return A compiled model
*/
CompiledModel import_model(std::istream& model_stream, const RemoteContext& context, const AnyMap& properties = {});
/**
* @brief Imports a compiled model from a previously exported one with a specified remote context.
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param model_stream Model stream
* @param context Pointer to RemoteContext object
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* load operation
* @return A compiled model
*/
template <typename... Properties>
util::EnableIfAllProperties<CompiledModel, Properties...> import_model(std::istream& model_stream,
const RemoteContext& context,
Properties&&... properties) {
return import_model(model_stream, context, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Query device if it supports specified model with specified properties
*
* @param device_name A name of a device to query
* @param model Model object to query
* @param properties Optional map of pairs: (property name, property value)
* @return An object containing a map of pairs a operation name -> a device name supporting this operation.
*/
SupportedOpsMap query_model(const std::shared_ptr<const ov::Model>& model,
const std::string& device_name,
const AnyMap& properties = {}) const;
/**
* @brief Query device if it supports specified model with specified properties
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param device_name A name of a device to query
* @param model Model object to query
* @param properties Optional pack of pairs: (property name, property value) relevant only for this
* query operation
* @return An object containing a map of pairs a operation name -> a device name supporting this operation.
*/
template <typename... Properties>
util::EnableIfAllProperties<SupportedOpsMap, Properties...> query_model(
const std::shared_ptr<const ov::Model>& model,
const std::string& device_name,
Properties&&... properties) const {
return query_model(model, device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Sets properties for all the
* registered devices, acceptable keys can be found in openvino/runtime/properties.hpp
*
* @param properties Map of pairs: (property name, property value)
*/
void set_property(const AnyMap& properties);
/**
* @brief Sets properties for all the
* registered devices, acceptable keys can be found in openvino/runtime/properties.hpp
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param properties Optional pack of pairs: (property name, property value)
* @return nothing
*/
template <typename... Properties>
util::EnableIfAllProperties<void, Properties...> set_property(Properties&&... properties) {
set_property(AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Sets properties for device, acceptable keys can be found in openvino/runtime/properties.hpp
*
* @param device_name An name of a device.
*
* @param properties Map of pairs: (property name, property value)
*/
void set_property(const std::string& device_name, const AnyMap& properties);
/**
* @brief Sets properties for device, acceptable keys can be found in openvino/runtime/properties.hpp
*
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param device_name An name of a device.
* @param properties Optional pack of pairs: (property name, property value)
* @return nothing
*/
template <typename... Properties>
util::EnableIfAllProperties<void, Properties...> set_property(const std::string& device_name,
Properties&&... properties) {
set_property(device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Gets properties dedicated to device behaviour.
*
* The method is targeted to extract information which can be set via set_property method.
*
* @param device_name - A name of a device to get a properties value.
* @param name - property name.
* @return Value of property corresponding to property name.
*/
Any get_property(const std::string& device_name, const std::string& name) const;
/**
* @brief Gets properties dedicated to device behaviour.
*
* The method is needed to request common device or system properties.
* It can be device name, temperature, other devices-specific values.
*
* @tparam T - type of returned value
* @param deviceName - A name of a device to get a properties value.
* @param property - property object.
* @return Property value.
*/
template <typename T, PropertyMutability M>
T get_property(const std::string& deviceName, const ov::Property<T, M>& property) const {
auto to = Any::make<T>();
get_property(deviceName, property.name(), to);
return to.template as<T>();
}
/**
* @brief Returns devices available for inference
* Core objects goes over all registered plugins and asks about available devices.
*
* @return A vector of devices. The devices are returned as { CPU, GPU.0, GPU.1, MYRIAD }
* If there more than one device of specific type, they are enumerated with .# suffix.
* Such enumerated device can later be used as a device name in all Core methods like Core::compile_model,
* Core::query_model, Core::set_property and so on.
*/
std::vector<std::string> get_available_devices() const;
/**
* @brief Register a new device and plugin which enable this device inside OpenVINO Runtime.
*
* @param plugin_name A name of plugin. Depending on platform `plugin_name` is wrapped with shared library suffix
* and prefix to identify library full name
* E.g. on Linux platform plugin name specified as `plugin_name` will be wrapped as `libplugin_name.so`.
* Plugin search algorithm:
* - If plugin is located in the same directory as OpenVINO runtime library, it will be used
* - If no, plugin is tried to be loaded from paths pointed by PATH / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH
* environment variables depending on the platform.
*
* @param device_name A device name to register plugin for.
*/
void register_plugin(const std::string& plugin_name, const std::string& device_name);
/**
* @brief Unloads the previously loaded plugin identified by @p device_name from OpenVINO Runtime
* The method is needed to remove loaded plugin instance and free its resources. If plugin for a
* specified device has not been created before, the method throws an exception.
* @note This method does not remove plugin from the plugins known to OpenVINO Core object.
* @param device_name A device name identifying plugin to remove from OpenVINO Runtime
*/
void unload_plugin(const std::string& device_name);
/** @brief Registers a device plugin to OpenVINO Runtime Core instance using XML configuration file with
* plugins description.
*
* XML file has the following structure:
*
* ```xml
* <ie>
* <plugins>
* <plugin name="" location="">
* <extensions>
* <extension location=""/>
* </extensions>
* <properties>
* <property key="" value=""/>
* </properties>
* </plugin>
* </plugins>
* </ie>
* ```
*
* - `name` identifies name of device enabled by a plugin
* - `location` specifies absolute path to dynamic library with a plugin.
* A path can also be relative to inference engine shared library. It allows to have common config
* for different systems with different configurations.
* - `properties` are set to a plugin via the ov::Core::set_property method.
* - `extensions` are set to a plugin via the ov::Core::add_extension method.
*
* @param xml_config_file A path to .xml file with plugins to register.
*/
void register_plugins(const std::string& xml_config_file);
/**
* @brief Create a new remote shared context object on specified accelerator device
* using specified plugin-specific low level device API parameters (device handle, pointer, context, etc.)
* @param device_name A name of a device to create a new shared context on.
* @param properties Map of device-specific shared context properties.
* @return A reference to a created remote context.
*/
RemoteContext create_context(const std::string& device_name, const AnyMap& properties);
/**
* @brief Create a new shared context object on specified accelerator device
* using specified plugin-specific low level device API properties (device handle, pointer, etc.)
* @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types
* @param device_name Name of a device to create new shared context on.
* @param properties Pack of device-specific shared context properties.
* @return A shared pointer to a created remote context.
*/
template <typename... Properties>
util::EnableIfAllProperties<RemoteContext, Properties...> create_context(const std::string& device_name,
Properties&&... properties) {
return create_context(device_name, AnyMap{std::forward<Properties>(properties)...});
}
/**
* @brief Get a pointer to default (plugin-supplied) shared context object for specified accelerator device.
* @param device_name A name of a device to get a default shared context from.
* @return A reference to a default remote context.
*/
RemoteContext get_default_context(const std::string& device_name);
};
namespace runtime {
using ov::Core;
} // namespace runtime
} // namespace ov
| 45.120635 | 120 | 0.658798 | [
"object",
"vector",
"model"
] |
42f64aeaa841cc7ada042e87db9983cba10e2e26 | 977 | cpp | C++ | src/APU.cpp | scottjcrouch/ScootNES | 402ae3e598ec4ac9b8b61ca2c3d2008bb8a6de1e | [
"MIT"
] | null | null | null | src/APU.cpp | scottjcrouch/ScootNES | 402ae3e598ec4ac9b8b61ca2c3d2008bb8a6de1e | [
"MIT"
] | null | null | null | src/APU.cpp | scottjcrouch/ScootNES | 402ae3e598ec4ac9b8b61ca2c3d2008bb8a6de1e | [
"MIT"
] | null | null | null | #include <cstdint>
#include <vector>
#include <APU.h>
static int null_dmc_reader(void*, unsigned int)
{
return 0x55; // causes dmc sample to be flat
}
APU::APU()
{
time = 0;
frameLength = 29780;
apu.dmc_reader(null_dmc_reader, NULL);
apu.output(&buf);
buf.clock_rate(1789773);
buf.sample_rate(44100);
}
void APU::setDmcCallback(int (*f)(void* user_data, unsigned int), void* p)
{
apu.dmc_reader(f, p);
}
void APU::writeRegister(uint16_t addr, uint8_t data)
{
apu.write_register(clock(), addr, data);
}
int APU::getStatus()
{
return apu.read_status(clock());
}
void APU::endFrame()
{
time = 0;
frameLength ^= 1;
apu.end_frame(frameLength);
buf.end_frame(frameLength);
}
long APU::samplesAvailable() const
{
return buf.samples_avail();
}
std::vector<short> APU::getAvailableSamples()
{
std::vector<short> buffer(samplesAvailable());
buf.read_samples(buffer.data(), buffer.size());
return buffer;
}
| 17.763636 | 74 | 0.664278 | [
"vector"
] |
42f88f40a7f8c8e4240df4400f118f4f53e43446 | 2,591 | cpp | C++ | CSCI-104/hw5/main.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | null | null | null | CSCI-104/hw5/main.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | null | null | null | CSCI-104/hw5/main.cpp | liyang990803/CSCI-103 | 6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a | [
"MIT"
] | 1 | 2018-03-23T04:19:24.000Z | 2018-03-23T04:19:24.000Z | #include <iostream>
#include "Thanksgiving.cpp"
#include "qsort.h"
using namespace std;
template<class Comparator>
void static DoStringCompare(const std::string &s1, const std::string &s2, Comparator comp) {
cout << comp(s1, s2) << endl; // calls comp.operator()(s1,s2);
}
void printNice(std::vector<std::pair<int, int>> &result) {
for (int i = 0; i < result.size(); ++i) {
cout << result[i].first << " " << result[i].second << endl;
}
}
void testProblem1b() {
vector<int> intTest = {3, 4, 2, 4, 1};
const int size = 100;
for (int i = 0; i < size; ++i) {
intTest.push_back(rand() % size);
}
QuickSort(intTest, std::less<int>());
for (int j = 0; j < intTest.size(); ++j) {
cout << intTest[j] << " ";
}
cout << endl;
}
// void InterpolationTest() {
// int arr[] = { 2, 4, 8,16,3200};
// int n = sizeof(arr) / sizeof(arr[0]);
// int x = 16; // Element to be searched
// int index = interpolationSearch(arr, n, x);
// // If element was found
// if (index != -1)
// printf("Element found at index %d", index);
// else
// printf("Element not found.");
// }
void testProblem5() {
vector<int> turkey1 = {};
vector<int> turkey2 = {0};
vector<int> turkey3 = {1};
vector<int> turkey4 = {1, 2};
vector<int> turkey5;
for (int i = 0; i < 50; ++i) {
turkey5.push_back(i);
}
vector<int> potatoes1 = {};
vector<int> potatoes2 = {0};
vector<int> potatoes3 = {5};
vector<int> potatoes4 = {3, 8};
vector<int> potatoes5;
for (int i = 0; i < 50; ++i) {
potatoes5.push_back(100 - i);
}
std::vector<std::pair<int, int>> result0
= assignPlates(turkey1, potatoes1);
std::vector<std::pair<int, int>> result1
= assignPlates(turkey2, potatoes2);
std::vector<std::pair<int, int>> result3
= assignPlates(turkey3, potatoes3);
std::vector<std::pair<int, int>> result4
= assignPlates(turkey4, potatoes4);
std::vector<std::pair<int, int>> result5
= assignPlates(turkey5, potatoes5);
printNice(result0);
printNice(result1);
printNice(result3);
printNice(result4);
printNice(result5);
try {
std::vector<std::pair<int, int>> result2
= assignPlates(turkey1, potatoes2);
} catch (const exception &e) {
cout << e.what() << endl;
}
}
int main() {
srand((0));
if (1) {
// testProblem1a();
// testProblem1b();
// InterpolationTest();
testProblem5();
}
} | 26.989583 | 92 | 0.553068 | [
"vector"
] |
42fc2dcfc56280a1ed97ad5652ff2749e0a150de | 26,919 | cpp | C++ | PhysBAM/Public_Library/PhysBAM_Tools/Parallel_Computation/FLOOD_FILL_MPI.cpp | uwgraphics/PhysicsBasedModeling-Core | dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b | [
"BSD-3-Clause"
] | 1 | 2020-01-31T13:28:41.000Z | 2020-01-31T13:28:41.000Z | PhysBAM/Public_Library/PhysBAM_Tools/Parallel_Computation/FLOOD_FILL_MPI.cpp | uwgraphics/PhysicsBasedModeling-Core | dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b | [
"BSD-3-Clause"
] | null | null | null | PhysBAM/Public_Library/PhysBAM_Tools/Parallel_Computation/FLOOD_FILL_MPI.cpp | uwgraphics/PhysicsBasedModeling-Core | dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b | [
"BSD-3-Clause"
] | null | null | null | //#####################################################################
// Copyright 2005-2006, Eran Guendelman, Geoffrey Irving, Andrew Selle, Tamar Shinar, Jerry Talton.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_2D.h>
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_3D.h>
#endif
#include <PhysBAM_Tools/Grids_Uniform/GRID.h>
#include <PhysBAM_Tools/Log/DEBUG_UTILITIES.h>
#include <PhysBAM_Tools/Parallel_Computation/FLOOD_FILL_MPI.h>
#ifdef USE_MPI
#include <PhysBAM_Tools/Arrays/ARRAY_VIEW.h>
#include <PhysBAM_Tools/Arrays_Computations/SUMMATIONS.h>
#include <PhysBAM_Tools/Data_Structures/UNION_FIND.h>
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_ITERATOR_FACE_HORIZONTAL.h>
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_ITERATOR_FACE_Y.h>
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_SIMPLE_ITERATOR.h>
#include <PhysBAM_Tools/Parallel_Computation/MPI_RLE_GRID.h>
#endif
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h>
#include <PhysBAM_Tools/Grids_Uniform_Arrays/FACE_ARRAYS.h>
#include <PhysBAM_Tools/Parallel_Computation/MPI_PACKAGE.h>
#include <PhysBAM_Tools/Parallel_Computation/MPI_UNIFORM_GRID.h>
#include <PhysBAM_Tools/Parallel_Computation/MPI_UTILITIES.h>
#include <PhysBAM_Tools/Parallel_Computation/PCG_SPARSE_MPI.h>
#endif
using namespace PhysBAM;
//#####################################################################
// Constructor
//#####################################################################
template<class T_GRID> FLOOD_FILL_MPI<T_GRID>::
FLOOD_FILL_MPI(const T_MPI_GRID& mpi_grid_input,const T_GRID& local_grid_input,const T_FACE_ARRAYS_BOOL& psi_N_input,int& number_of_regions_input,T_ARRAYS_INT& colors_input,
ARRAY<ARRAY<int> >& color_ranks_input,ARRAY<bool>* color_touches_uncolorable_input)
:mpi_grid(mpi_grid_input),local_grid(local_grid_input),psi_N(psi_N_input),number_of_regions(number_of_regions_input),colors(colors_input),color_ranks(color_ranks_input),
color_touches_uncolorable(color_touches_uncolorable_input)
{}
//#####################################################################
// Destructor
//#####################################################################
template<class T_GRID> FLOOD_FILL_MPI<T_GRID>::
~FLOOD_FILL_MPI()
{}
//#####################################################################
#ifdef USE_MPI
//#####################################################################
// Function Union_Find_Merge_Op
//#####################################################################
static MPI::Comm* union_find_merge_op_comm; // TODO: This is needed because user-defined operations don't get to know their communicator. A better hack would be nice.
static void Union_Find_Merge_Op(const void* in,void* inout,int len,const MPI::Datatype& datatype)
{
// unpack union finds
UNION_FIND<> union_find_in,union_find_inout;
int m=datatype.Get_size();assert(len==1);
{int position=0;MPI_UTILITIES::Unpack(union_find_in,ARRAY_VIEW<const char>(m,static_cast<const char*>(in)),position,*union_find_merge_op_comm);}
{int position=0;MPI_UTILITIES::Unpack(union_find_inout,ARRAY_VIEW<const char>(m,static_cast<char*>(inout)),position,*union_find_merge_op_comm);}
// merge
union_find_inout.Merge(union_find_in);
// pack output
{int position=0;MPI_UTILITIES::Pack(union_find_inout,ARRAY_VIEW<char>(m,static_cast<char*>(inout)),position,*union_find_merge_op_comm);}
}
//#####################################################################
// Function Synchronize_Colors
//#####################################################################
template<class T_ARRAYS,class T_GRID,class T_BOX> static inline void Resize_Helper(T_ARRAYS& array,const T_GRID& grid,const T_BOX& box)
{
array.Resize(box); // for uniform grids we can allocate exactly the requested region
}
template<class T_GRID,class T_BOX> static inline void Resize_Helper(ARRAY<int>& array,const T_GRID& grid,const T_BOX& box)
{
array.Resize(grid.Cell_Indices()); // for rle grids we have to allocate space for the entire grid due to the unstructuredness
}
template<class T_GRID> int FLOOD_FILL_MPI<T_GRID>::
Synchronize_Colors()
{
if(mpi_grid.threaded_grid) return Synchronize_Colors_Threaded();
ARRAY<RANGE<typename T_PARALLEL_GRID::VECTOR_INT> > boundary_regions;
mpi_grid.Find_Boundary_Regions(boundary_regions,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Zero_Box(),false,RANGE<VECTOR<int,1> >(-1,0),false,true,local_grid);
// figure out which colors are global
int global_color_count=0;
ARRAY<int,VECTOR<int,1> > color_map(-1,number_of_regions);color_map(-1)=-1;color_map(0)=0;
{ARRAY<bool,VECTOR<int,1> > color_is_global(-1,number_of_regions);
Find_Global_Colors(color_is_global,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Centered_Box());
for(int color=1;color<=number_of_regions;color++)if(color_is_global(color)) color_map(color)=++global_color_count;}
// send numbers of global colors to everyone
ARRAY<int> global_color_counts(mpi_grid.number_of_processes);
mpi_grid.comm->Allgather(&global_color_count,1,MPI_UTILITIES::Datatype<int>(),&global_color_counts(1),1,MPI_UTILITIES::Datatype<int>());
int total_global_colors=ARRAYS_COMPUTATIONS::Sum(global_color_counts);
int global_color_offset=ARRAYS_COMPUTATIONS::Sum(global_color_counts.Prefix(mpi_grid.rank));
LOG::cout<<"initial colors: "<<number_of_regions<<" total, "<<global_color_count<<" out of "<<total_global_colors<<" global"<<std::endl;
if(!total_global_colors){color_ranks.Clean_Memory();return 0;}
ARRAY<MPI_PACKAGE> packages;
ARRAY<T_ARRAYS_INT> colors_copy(boundary_regions.m);
// send left (front) colors
ARRAY<MPI::Request> send_requests;
for(int side=1;side<=T_PARALLEL_GRID::number_of_faces_per_cell;side+=2)if(mpi_grid.side_neighbor_ranks(side)!=MPI::PROC_NULL){
Resize_Helper(colors_copy(side),local_grid,boundary_regions(side));
Translate_Local_Colors_To_Global_Colors(color_map,colors_copy(side),boundary_regions(side),global_color_offset);
MPI_PACKAGE package=mpi_grid.Package_Cell_Data(colors_copy(side),boundary_regions(side));
packages.Append(package);
send_requests.Append(package.Isend(*mpi_grid.comm,mpi_grid.side_neighbor_ranks(side),mpi_grid.Get_Send_Tag(mpi_grid.side_neighbor_directions(side))));}
// receive right (back) colors and initialize union find
UNION_FIND<> union_find(total_global_colors);
{ARRAY<MPI::Request> recv_requests;
for(int side=2;side<=T_PARALLEL_GRID::number_of_faces_per_cell;side+=2)if(mpi_grid.side_neighbor_ranks(side)!=MPI::PROC_NULL){
Resize_Helper(colors_copy(side),local_grid,boundary_regions(side));
MPI_PACKAGE package=mpi_grid.Package_Cell_Data(colors_copy(side),boundary_regions(side));
packages.Append(package);
recv_requests.Append(package.Irecv(*mpi_grid.comm,mpi_grid.side_neighbor_ranks(side),mpi_grid.Get_Recv_Tag(mpi_grid.side_neighbor_directions(side))));}
MPI::Status status;
while(MPI_UTILITIES::Wait_Any(recv_requests,status)){
int side;for(side=2;side<=T_PARALLEL_GRID::number_of_faces_per_cell;side+=2)if(mpi_grid.Get_Recv_Tag(mpi_grid.side_neighbor_directions(side))==status.Get_tag()) break;
Find_Color_Matches(color_map,union_find,colors_copy(side),boundary_regions(side),global_color_offset);}}
// synchronize union find
UNION_FIND<> final_union_find;
{ARRAY<char> union_find_buffer(MPI_UTILITIES::Pack_Size(union_find,*mpi_grid.comm)+1);
{int position=0;MPI_UTILITIES::Pack(union_find,union_find_buffer,position,*mpi_grid.comm);}
MPI::Datatype union_find_type=MPI::PACKED.Create_contiguous(union_find_buffer.m);union_find_type.Commit();
MPI::Op union_find_merge_op;union_find_merge_op.Init(Union_Find_Merge_Op,true);
ARRAY<char> final_union_find_buffer(union_find_buffer.m);
union_find_merge_op_comm=mpi_grid.comm;
mpi_grid.comm->Allreduce(union_find_buffer.Get_Array_Pointer(),final_union_find_buffer.Get_Array_Pointer(),1,union_find_type,union_find_merge_op);
{int position=0;MPI_UTILITIES::Unpack(final_union_find,final_union_find_buffer,position,*mpi_grid.comm);}
union_find_type.Free();union_find_merge_op.Free();}
// fix color map for global colors
number_of_regions=0;
ARRAY<int> global_to_final_color_map(total_global_colors);
for(int i=1;i<=total_global_colors;i++){
int root=final_union_find.Find(i);
if(!global_to_final_color_map(root)) global_to_final_color_map(root)=++number_of_regions;
global_to_final_color_map(i)=global_to_final_color_map(root);}
for(int i=1;i<=color_map.domain.max_corner.x;i++)if(color_map(i)>0) color_map(i)=global_to_final_color_map(color_map(i)+global_color_offset);
// find list of processes corresponding to each color
int end=0;
color_ranks.Clean_Memory();
color_ranks.Resize(number_of_regions);
for(int r=0;r<mpi_grid.number_of_processes;r++){
int start=end+1;end+=global_color_counts(r+1);
for(int i=start;i<=end;i++)color_ranks(global_to_final_color_map(i)).Append_Unique(r);}
for(int color=1;color<=color_ranks.m;color++) assert(color_ranks(color).m>1 || mpi_grid.side_neighbor_ranks.Contains(mpi_grid.rank));
// remap colors
Remap_Colors(color_map,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Centered_Box());
LOG::cout<<"final colors: "<<color_ranks.m<<" global, "<<number_of_regions-color_ranks.m<<" local"<<std::endl;
// remap color_touches_uncolorable
if(color_touches_uncolorable){
ARRAY<bool> new_color_touches_uncolorable(number_of_regions);
for(int i=1;i<=color_touches_uncolorable->m;i++)if(color_map(i)>0) new_color_touches_uncolorable(color_map(i))|=(*color_touches_uncolorable)(i);
color_touches_uncolorable->Exchange(new_color_touches_uncolorable);
// synchronize color_touches_uncolorable, TODO: this could be merged with above communication
ARRAY<bool> global_color_touches_uncolorable(color_ranks.m);
ARRAY<bool>::Get(global_color_touches_uncolorable,*color_touches_uncolorable);
mpi_grid.comm->Allreduce(&global_color_touches_uncolorable(1),&(*color_touches_uncolorable)(1),color_ranks.m,MPI_UTILITIES::Datatype<bool>(),MPI::LOR);}
// finish
MPI_UTILITIES::Wait_All(send_requests);
MPI_PACKAGE::Free_All(packages);
return color_ranks.m;
}
template<class T_GRID> int FLOOD_FILL_MPI<T_GRID>::
Synchronize_Colors_Threaded()
{
#ifdef USE_PTHREADS
ARRAY<RANGE<typename T_PARALLEL_GRID::VECTOR_INT> > boundary_regions;
mpi_grid.threaded_grid->Find_Boundary_Regions(boundary_regions,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Zero_Box(),false,RANGE<VECTOR<int,1> >(-1,0),false,true,local_grid);
// figure out which colors are global
int global_color_count=0;
ARRAY<int,VECTOR<int,1> > color_map(-1,number_of_regions);color_map(-1)=-1;color_map(0)=0;
{ARRAY<bool,VECTOR<int,1> > color_is_global(-1,number_of_regions);
Find_Global_Colors(color_is_global,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Centered_Box());
for(int color=1;color<=number_of_regions;color++)if(color_is_global(color)) color_map(color)=++global_color_count;}
// send numbers of global colors to everyone
ARRAY<int> global_color_counts(mpi_grid.threaded_grid->number_of_processes);
mpi_grid.threaded_grid->Allgather(global_color_counts);
int total_global_colors=ARRAYS_COMPUTATIONS::Sum(global_color_counts);
int global_color_offset=ARRAYS_COMPUTATIONS::Sum(global_color_counts.Prefix(mpi_grid.threaded_grid->rank));
LOG::cout<<"initial colors: "<<number_of_regions<<" total, "<<global_color_count<<" out of "<<total_global_colors<<" global"<<std::endl;
if(!total_global_colors){color_ranks.Clean_Memory();return 0;}
ARRAY<T_ARRAYS_INT> colors_copy(boundary_regions.m);
// send left (front) colors
for(int side=1;side<=T_PARALLEL_GRID::number_of_faces_per_cell;side+=2)if(mpi_grid.threaded_grid->side_neighbor_ranks(side)!=-1){
Resize_Helper(colors_copy(side),local_grid,boundary_regions(side));
Translate_Local_Colors_To_Global_Colors(color_map,colors_copy(side),boundary_regions(side),global_color_offset);
THREAD_PACKAGE pack=mpi_grid.threaded_grid->Package_Cell_Data(colors_copy(side),boundary_regions(side));pack.recv_tid=mpi_grid.threaded_grid->side_neighbor_ranks(side);
pthread_mutex_lock(mpi_grid.threaded_grid->lock);
mpi_grid.threaded_grid->buffers.Append(pack);
pthread_mutex_unlock(mpi_grid.threaded_grid->lock);}
// receive right (back) colors and initialize union find
UNION_FIND<> union_find(total_global_colors);
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
{for(int side=2;side<=T_PARALLEL_GRID::number_of_faces_per_cell;side+=2)if(mpi_grid.threaded_grid->side_neighbor_ranks(side)!=-1){
Resize_Helper(colors_copy(side),local_grid,boundary_regions(side));
int index=0;for(int i=1;i<=mpi_grid.threaded_grid->buffers.m;i++) if(mpi_grid.threaded_grid->buffers(i).send_tid==mpi_grid.threaded_grid->side_neighbor_ranks(side) && mpi_grid.threaded_grid->buffers(i).recv_tid==mpi_grid.threaded_grid->rank) index=i;
PHYSBAM_ASSERT(index);int position=0;
for(CELL_ITERATOR iterator(local_grid,boundary_regions(side));iterator.Valid();iterator.Next()) colors_copy(side).Unpack(mpi_grid.threaded_grid->buffers(index).buffer,position,iterator.Cell_Index());
Find_Color_Matches(color_map,union_find,colors_copy(side),boundary_regions(side),global_color_offset);}}
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
if(mpi_grid.threaded_grid->tid==1) mpi_grid.threaded_grid->buffers.m=0;
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
// synchronize union find
UNION_FIND<> final_union_find;
{THREAD_PACKAGE pack(sizeof(int)*(2+union_find.parents.m)+union_find.ranks.m);
{int position=0;*(int*)(&pack.buffer(position+1))=union_find.parents.m;position+=sizeof(int);*(int*)(&pack.buffer(position+1))=union_find.ranks.m;position+=sizeof(int);
for(int i=1;i<=union_find.parents.m;i++) union_find.parents.Pack(pack.buffer,position,i);for(int i=1;i<=union_find.ranks.m;i++) union_find.ranks.Pack(pack.buffer,position,i);
pthread_mutex_lock(mpi_grid.threaded_grid->lock);
mpi_grid.threaded_grid->buffers.Append(pack);
pthread_mutex_unlock(mpi_grid.threaded_grid->lock);}
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
for(int buf=1;buf<=mpi_grid.threaded_grid->buffers.m;buf++){int position=0;
union_find.parents.Resize(*(int*)(&pack.buffer(position+1)));position+=sizeof(int);union_find.ranks.Resize(*(int*)(&pack.buffer(position+1)));position+=sizeof(int);
for(int i=1;i<=union_find.parents.m;i++) union_find.parents.Unpack(mpi_grid.threaded_grid->buffers(buf).buffer,position,i);for(int i=1;i<=union_find.ranks.m;i++) union_find.ranks.Unpack(mpi_grid.threaded_grid->buffers(buf).buffer,position,i);
final_union_find.Merge(union_find);}
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
if(mpi_grid.threaded_grid->tid==1) mpi_grid.threaded_grid->buffers.m=0;
pthread_barrier_wait(mpi_grid.threaded_grid->barr);}
// fix color map for global colors
number_of_regions=0;
ARRAY<int> global_to_final_color_map(total_global_colors);
for(int i=1;i<=total_global_colors;i++){
int root=final_union_find.Find(i);
if(!global_to_final_color_map(root)) global_to_final_color_map(root)=++number_of_regions;
global_to_final_color_map(i)=global_to_final_color_map(root);}
for(int i=1;i<=color_map.domain.max_corner.x;i++)if(color_map(i)>0) color_map(i)=global_to_final_color_map(color_map(i)+global_color_offset);
// find list of processes corresponding to each color
int end=0;
color_ranks.Clean_Memory();
color_ranks.Resize(number_of_regions);
for(int r=0;r<mpi_grid.number_of_processes;r++){
int start=end+1;end+=global_color_counts(r+1);
for(int i=start;i<=end;i++)color_ranks(global_to_final_color_map(i)).Append_Unique(r);}
for(int color=1;color<=color_ranks.m;color++) assert(color_ranks(color).m>1 || mpi_grid.side_neighbor_ranks.Contains(mpi_grid.rank));
// remap colors
Remap_Colors(color_map,RANGE<typename T_PARALLEL_GRID::VECTOR_INT>::Centered_Box());
LOG::cout<<"final colors: "<<color_ranks.m<<" global, "<<number_of_regions-color_ranks.m<<" local"<<std::endl;
// remap color_touches_uncolorable
if(color_touches_uncolorable){
ARRAY<bool> new_color_touches_uncolorable(number_of_regions);
for(int i=1;i<=color_touches_uncolorable->m;i++)if(color_map(i)>0) new_color_touches_uncolorable(color_map(i))|=(*color_touches_uncolorable)(i);
color_touches_uncolorable->Exchange(new_color_touches_uncolorable);
// synchronize color_touches_uncolorable, TODO: this could be merged with above communication
ARRAY<bool> global_color_touches_uncolorable(color_ranks.m);
ARRAY<bool>::Get(global_color_touches_uncolorable,*color_touches_uncolorable);
THREAD_PACKAGE pack(sizeof(bool)*global_color_touches_uncolorable.m);
{int position=0;for(int i=1;i<=global_color_touches_uncolorable.m;i++) global_color_touches_uncolorable.Pack(pack.buffer,position,i);
pthread_mutex_lock(mpi_grid.threaded_grid->lock);
mpi_grid.threaded_grid->buffers.Append(pack);
pthread_mutex_unlock(mpi_grid.threaded_grid->lock);}
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
for(int buf=1;buf<=mpi_grid.threaded_grid->buffers.m;buf++){int position=0;
for(int i=1;i<=global_color_touches_uncolorable.m;i++) global_color_touches_uncolorable.Unpack(mpi_grid.threaded_grid->buffers(buf).buffer,position,i);
for(int i=1;i<=global_color_touches_uncolorable.m;i++) (*color_touches_uncolorable)(i)|=global_color_touches_uncolorable(i);}
pthread_barrier_wait(mpi_grid.threaded_grid->barr);
if(mpi_grid.threaded_grid->tid==1) mpi_grid.threaded_grid->buffers.m=0;
pthread_barrier_wait(mpi_grid.threaded_grid->barr);}
return color_ranks.m;
#endif
}
//#####################################################################
// Function Find_Global_Colors
//#####################################################################
template<class T_GRID> void FLOOD_FILL_MPI<T_GRID>::
Find_Global_Colors(ARRAY<bool,VECTOR<int,1> >& color_is_global,const RANGE<TV_INT>&) const
{
int proc_null=mpi_grid.threaded_grid?-1:MPI::PROC_NULL;
const ARRAY<int>& side_neighbor_ranks=mpi_grid.threaded_grid?mpi_grid.threaded_grid->side_neighbor_ranks:mpi_grid.side_neighbor_ranks;
for(int axis=1;axis<=T_GRID::dimension;axis++)for(int axis_side=0;axis_side<=1;axis_side++){
int side=2*axis-1+axis_side;
if(side_neighbor_ranks(side)!=proc_null){
for(typename T_GRID::FACE_ITERATOR iterator(local_grid,0,T_GRID::BOUNDARY_REGION,side);iterator.Valid();iterator.Next())if(!psi_N.Component(axis)(iterator.Face_Index())){
color_is_global(colors(iterator.First_Cell_Index()))=true;
color_is_global(colors(iterator.Second_Cell_Index()))=true;}}}
}
//#####################################################################
// Function Find_Global_Colors
//#####################################################################
template<class T_GRID> template<class T_BOX_HORIZONTAL_INT> void FLOOD_FILL_MPI<T_GRID>::
Find_Global_Colors(ARRAY<bool,VECTOR<int,1> >& color_is_global,const T_BOX_HORIZONTAL_INT&) const
{
T_GRID::template Horizontal_Face_Loop<Find_Global_Colors_Helper>(mpi_grid,mpi_grid.local_grid,psi_N,colors,color_is_global);
}
//#####################################################################
// Function Find_Global_Colors_Helper
//#####################################################################
template<class T_GRID> template<class T_FACE> void FLOOD_FILL_MPI<T_GRID>::
Find_Global_Colors_Helper::Apply(const T_MPI_GRID& mpi_grid,const T_GRID& local_grid,const ARRAY<bool>& psi_N,const ARRAY<int>& colors,ARRAY<bool,VECTOR<int,1> >& color_is_global)
{
int horizontal_axis=T_FACE::Horizontal_Axis();
ARRAY<typename T_GRID::BOX_HORIZONTAL_INT> boundary_regions;
mpi_grid.Find_Boundary_Regions(boundary_regions,CELL_ITERATOR::Sentinels(),false,RANGE<VECTOR<int,1> >(0,0),false,true,local_grid);
for(int axis_side=0;axis_side<=1;axis_side++){
int side=2*horizontal_axis-1+axis_side;
if(mpi_grid.side_neighbor_ranks(side)!=MPI::PROC_NULL){
typename T_GRID::BOX_HORIZONTAL_INT face_region=boundary_regions(side);if(axis_side) face_region+=T_GRID::VECTOR_HORIZONTAL_INT::Axis_Vector(horizontal_axis);
for(T_FACE face(local_grid,face_region);face;face++)if(!psi_N(face.Face())){int c1=face.cell1.Cell(),c2=face.cell2.Cell();
for(int i=0;i<=face.cell1.Long();i++)color_is_global(colors(c1+i))=true;
for(int i=0;i<=face.cell2.Long();i++)color_is_global(colors(c2+i))=true;}}}
}
//#####################################################################
// Function Translate_Local_Colors_To_Global_Colors
//#####################################################################
template<class T_GRID> void FLOOD_FILL_MPI<T_GRID>::
Translate_Local_Colors_To_Global_Colors(const ARRAY<int,VECTOR<int,1> >& color_map,T_ARRAYS_INT& colors_copy,const RANGE<TV_INT>& region,const int global_color_offset) const
{
for(CELL_ITERATOR iterator(local_grid,region);iterator.Valid();iterator.Next()){TV_INT cell_index=iterator.Cell_Index();
int new_color=color_map(colors(cell_index));colors_copy(cell_index)=new_color>0?new_color+global_color_offset:-1;}
}
//#####################################################################
// Function Translate_Local_Colors_To_Global_Colors
//#####################################################################
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
template<class T_GRID> template<class T_BOX_HORIZONTAL_INT> void FLOOD_FILL_MPI<T_GRID>::
Translate_Local_Colors_To_Global_Colors(const ARRAY<int,VECTOR<int,1> >& color_map,ARRAY<int>& colors_copy,const T_BOX_HORIZONTAL_INT& region,const int global_color_offset) const
{
for(RLE_GRID_SIMPLE_ITERATOR<T_GRID,CELL_ITERATOR> cell(local_grid,region);cell;cell++){int c=cell.index;
int new_color=color_map(colors(c));colors_copy(c)=new_color>0?new_color+global_color_offset:-1;}
}
#endif
//#####################################################################
// Function Find_Color_Matches
//#####################################################################
template<class T_GRID> void FLOOD_FILL_MPI<T_GRID>::
Find_Color_Matches(const ARRAY<int,VECTOR<int,1> >& color_map,UNION_FIND<>& union_find,T_ARRAYS_INT& colors_copy,const RANGE<TV_INT>& region,const int global_color_offset) const
{
for(CELL_ITERATOR iterator(local_grid,region);iterator.Valid();iterator.Next()){TV_INT cell_index=iterator.Cell_Index();if(colors_copy(cell_index)>0){
int local_color=color_map(colors(cell_index));
if(local_color>0) union_find.Union(global_color_offset+local_color,colors_copy(cell_index));}}
}
//#####################################################################
// Function Find_Color_Matches
//#####################################################################
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
template<class T_GRID> template<class T_BOX_HORIZONTAL_INT> void FLOOD_FILL_MPI<T_GRID>::
Find_Color_Matches(const ARRAY<int,VECTOR<int,1> >& color_map,UNION_FIND<>& union_find,ARRAY<int>& colors_copy,const T_BOX_HORIZONTAL_INT& region,const int global_color_offset) const
{
for(RLE_GRID_SIMPLE_ITERATOR<T_GRID,CELL_ITERATOR> cell(local_grid,region);cell;cell++){int color=colors_copy(cell.index);if(color>0){
int local_color=color_map(colors(cell.index));
if(local_color>0) union_find.Union(global_color_offset+local_color,color);}}
}
#endif
//#####################################################################
// Function Remap_Colors
//#####################################################################
template<class T_GRID> void FLOOD_FILL_MPI<T_GRID>::
Remap_Colors(ARRAY<int,VECTOR<int,1> >& color_map,const RANGE<TV_INT>&)
{
for(CELL_ITERATOR iterator(local_grid,1);iterator.Valid();iterator.Next()){TV_INT cell_index=iterator.Cell_Index();
int color=colors(cell_index);assert(color); // colors should either be -1 or positive
if(color_map(color)==0) color_map(color)=++number_of_regions;
colors(cell_index)=color_map(color);}
}
//#####################################################################
// Function Remap_Colors
//#####################################################################
template<class T_GRID> template<class T_BOX_HORIZONTAL_INT> void FLOOD_FILL_MPI<T_GRID>::
Remap_Colors(ARRAY<int,VECTOR<int,1> >& color_map,const T_BOX_HORIZONTAL_INT&)
{
for(int c=1;c<=colors.m;c++){
int color=colors(c);assert(color); // colors should either be -1 or positive
if(color_map(color)==0) color_map(color)=++number_of_regions;
colors(c)=color_map(color);}
}
//#####################################################################
#else
//#####################################################################
template<class T_GRID> int FLOOD_FILL_MPI<T_GRID>::Synchronize_Colors(){PHYSBAM_FUNCTION_IS_NOT_DEFINED();return 0;}
//#####################################################################
#endif
//#####################################################################
#define INSTANTIATION_HELPER(T,T_GRID) \
template FLOOD_FILL_MPI<T_GRID >::FLOOD_FILL_MPI(const T_MPI_GRID&,const T_GRID&,const T_FACE_ARRAYS_BOOL&,int&,T_ARRAYS_INT&,ARRAY<ARRAY<int> >&,ARRAY<bool>*); \
template FLOOD_FILL_MPI<T_GRID >::~FLOOD_FILL_MPI(); \
template int FLOOD_FILL_MPI<T_GRID >::Synchronize_Colors();
#define P(...) __VA_ARGS__
INSTANTIATION_HELPER(float,P(GRID<VECTOR<float,1> >));
INSTANTIATION_HELPER(float,P(GRID<VECTOR<float,2> >));
INSTANTIATION_HELPER(float,P(GRID<VECTOR<float,3> >));
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
INSTANTIATION_HELPER(double,P(GRID<VECTOR<double,1> >));
INSTANTIATION_HELPER(double,P(GRID<VECTOR<double,2> >));
INSTANTIATION_HELPER(double,P(GRID<VECTOR<double,3> >));
#endif
#ifndef COMPILE_WITHOUT_RLE_SUPPORT
INSTANTIATION_HELPER(float,RLE_GRID_2D<float>);
INSTANTIATION_HELPER(float,RLE_GRID_3D<float>);
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
INSTANTIATION_HELPER(double,RLE_GRID_2D<double>);
INSTANTIATION_HELPER(double,RLE_GRID_3D<double>);
#endif
#endif
| 64.709135 | 258 | 0.705933 | [
"vector"
] |
42fee5b586c51b6f224d64b1b7a85011a5d7c0b2 | 1,523 | hpp | C++ | src/marker_manager.hpp | krgamestudios/Dungeon | 828fe6adee17630a5bdb842cbc6d8a2b441dacc5 | [
"Zlib"
] | 3 | 2016-10-20T20:25:58.000Z | 2017-11-07T00:53:26.000Z | src/marker_manager.hpp | Ratstail91/Dungeon | 828fe6adee17630a5bdb842cbc6d8a2b441dacc5 | [
"Zlib"
] | 2 | 2018-03-19T12:57:23.000Z | 2018-03-19T13:14:05.000Z | src/marker_manager.hpp | Ratstail91/Dungeon | 828fe6adee17630a5bdb842cbc6d8a2b441dacc5 | [
"Zlib"
] | null | null | null | /* Copyright: (c) Kayne Ruse 2017
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "marker.hpp"
#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"
#include <functional>
#include <list>
class MarkerManager {
public:
MarkerManager() = default;
~MarkerManager();
TTF_Font* SetFont(TTF_Font* font);
TTF_Font* GetFont() const;
Marker* CreateMarker();
void ForEach(std::function<void(Marker*)> lambda);
void RemoveIf(std::function<bool(Marker*)> lambda);
void RemoveAll();
int Size();
//render
void DrawTo(SDL_Renderer* const renderer, int camX, int camY, double scaleX = 1.0, double scaleY = 1.0);
private:
std::list<Marker*> markerList;
TTF_Font* font = nullptr;
}; | 28.203704 | 105 | 0.731451 | [
"render"
] |
6e00befb1da14c37140e9a92c0f64ca71fd5646c | 5,518 | cpp | C++ | tests/vector/vector2/vector2_tests.cpp | Gordath/libhelmath | da60a56c84dd7702e9e0f662e2af8a5d83c40758 | [
"MIT"
] | null | null | null | tests/vector/vector2/vector2_tests.cpp | Gordath/libhelmath | da60a56c84dd7702e9e0f662e2af8a5d83c40758 | [
"MIT"
] | null | null | null | tests/vector/vector2/vector2_tests.cpp | Gordath/libhelmath | da60a56c84dd7702e9e0f662e2af8a5d83c40758 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "helmath.h"
using namespace hm;
class Vector2Fixture : public ::testing::Test {
protected:
Vec2f v1;
Vec2f v2;
void SetUp() override
{
v1 = Vec2f{1.0f, 2.0f};
v2 = Vec2f{3.0f, 2.0f};
}
};
TEST_F(Vector2Fixture, test_member_function_length)
{
float len{v1.length()};
EXPECT_FLOAT_EQ(len, 2.2360679774997898);
}
TEST_F(Vector2Fixture, test_member_function_normalize)
{
v1.normalize();
EXPECT_FLOAT_EQ(v1.x, 0.44721359f);
EXPECT_FLOAT_EQ(v1.y, 0.89442718f);
float len{v1.length()};
EXPECT_FLOAT_EQ(len, 1.0f);
}
TEST_F(Vector2Fixture, test_member_function_normalized)
{
Vec2f res{v1.normalized()};
EXPECT_FLOAT_EQ(res.x, 0.44721359f);
EXPECT_FLOAT_EQ(res.y, 0.89442718f);
float len = res.length();
EXPECT_FLOAT_EQ(len, 1.0f);
}
TEST_F(Vector2Fixture, test_member_function_dot)
{
double d{v1.dot(v2)};
EXPECT_DOUBLE_EQ(d, 7.0);
}
TEST_F(Vector2Fixture, test_member_function_reflect)
{
v1.reflect(Vec2f{1.0f, 0.0f});
EXPECT_FLOAT_EQ(v1.x, -1.0f);
EXPECT_FLOAT_EQ(v1.y, 2.0f);
}
TEST_F(Vector2Fixture, test_member_function_reflected)
{
Vec2f res{v1.reflected(Vec2f{1.0f, 0.0f})};
EXPECT_FLOAT_EQ(res.x, -1.0f);
EXPECT_FLOAT_EQ(res.y, 2.0f);
}
TEST_F(Vector2Fixture, test_member_function_transform)
{
Mat4f trans{1, 0, 0, 1,
0, 1, 0, 1,
0, 0, 1, 1,
0, 0, 0, 1};
v1.transform(trans);
EXPECT_FLOAT_EQ(v1.x, 2.0f);
EXPECT_FLOAT_EQ(v1.y, 3.0f);
}
TEST_F(Vector2Fixture, test_member_function_transformed)
{
Mat4f trans{1, 0, 0, 1,
0, 1, 0, 1,
0, 0, 1, 1,
0, 0, 0, 1};
Vec2f res{v1.transformed(trans)};
EXPECT_FLOAT_EQ(res.x, 2.0f);
EXPECT_FLOAT_EQ(res.y, 3.0f);
}
TEST_F(Vector2Fixture, test_implicit_conversion_to_pointer)
{
float *vec = v1;
const float *vec2 = v2;
EXPECT_FLOAT_EQ(*(++vec), 2.0f);
EXPECT_FLOAT_EQ(*(++vec2), 2.0f);
}
TEST_F(Vector2Fixture, test_vector_plus_vector)
{
Vec2f res{v1 + v2};
EXPECT_FLOAT_EQ(res.x, 4.0f);
EXPECT_FLOAT_EQ(res.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_minus_vector)
{
Vec2f res{v2 - v1};
EXPECT_FLOAT_EQ(res.x, 2.0f);
EXPECT_FLOAT_EQ(res.y, 0.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_mult_vector)
{
Vec2f res{v1 * v2};
EXPECT_FLOAT_EQ(res.x, 3.0f);
EXPECT_FLOAT_EQ(res.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_div_vector)
{
Vec2f res{v1 / v2};
EXPECT_FLOAT_EQ(res.x, 0.33333334);
EXPECT_FLOAT_EQ(res.y, 1.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_plus_scalar)
{
Vec2f res{v1 + 2.0f};
EXPECT_FLOAT_EQ(res.x, 3.0f);
EXPECT_FLOAT_EQ(res.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_minus_scalar)
{
Vec2f res{v1 - 2.0f};
EXPECT_FLOAT_EQ(res.x, -1.0f);
EXPECT_FLOAT_EQ(res.y, 0.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_mult_scalar)
{
Vec2f res{v1 * 2.0f};
EXPECT_FLOAT_EQ(res.x, 2.0f);
EXPECT_FLOAT_EQ(res.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_div_scalar)
{
Vec2f res{v1 / 2.0f};
EXPECT_FLOAT_EQ(res.x, 0.5f);
EXPECT_FLOAT_EQ(res.y, 1.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_plus_equals_vector)
{
v1 += v2;
EXPECT_FLOAT_EQ(v1.x, 4.0f);
EXPECT_FLOAT_EQ(v1.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_minus_equals_vector)
{
v1 -= v2;
EXPECT_FLOAT_EQ(v1.x, -2.0f);
EXPECT_FLOAT_EQ(v1.y, 0.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_mult_equals_vector)
{
v1 *= v2;
EXPECT_FLOAT_EQ(v1.x, 3.0f);
EXPECT_FLOAT_EQ(v1.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_div_equals_vector)
{
v1 /= v2;
EXPECT_FLOAT_EQ(v1.x, 0.3333334f);
EXPECT_FLOAT_EQ(v1.y, 1.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_plus_equals_scalar)
{
v1 += 2.0f;
EXPECT_FLOAT_EQ(v1.x, 3.0f);
EXPECT_FLOAT_EQ(v1.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_minus_equals_scalar)
{
v1 -= 2.0f;
EXPECT_FLOAT_EQ(v1.x, -1.0f);
EXPECT_FLOAT_EQ(v1.y, 0.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_mult_equals_scalar)
{
v1 *= 2.0f;
EXPECT_FLOAT_EQ(v1.x, 2.0f);
EXPECT_FLOAT_EQ(v1.y, 4.0f);
}
TEST_F(Vector2Fixture, test_operator_vector_div_equals_scalar)
{
v1 /= 2.0f;
EXPECT_FLOAT_EQ(v1.x, 0.5f);
EXPECT_FLOAT_EQ(v1.y, 1.0f);
}
TEST_F(Vector2Fixture, test_subscript_operator)
{
float val{v1[0]};
float val2{v1[1]};
EXPECT_FLOAT_EQ(val, 1.0f);
EXPECT_FLOAT_EQ(val2, 2.0f);
}
TEST_F(Vector2Fixture, test_non_member_function_length)
{
float len{length(v1)};
EXPECT_FLOAT_EQ(len, 2.2360679774997898);
}
TEST_F(Vector2Fixture, test_non_member_function_length_sqrd)
{
double len{length_sqrd(v1)};
EXPECT_DOUBLE_EQ(len, 5.0);
}
TEST_F(Vector2Fixture, test_non_member_function_dot)
{
double d{dot(v1, v2)};
EXPECT_DOUBLE_EQ(d, 7.0);
}
TEST_F(Vector2Fixture, test_non_member_function_reflect)
{
Vec2f res{reflect(v1, Vec2f{1.0f, 0.0f})};
EXPECT_FLOAT_EQ(res.x, -1.0f);
EXPECT_FLOAT_EQ(res.y, 2.0f);
}
TEST_F(Vector2Fixture, test_non_member_function_transform)
{
Mat4f trans{1, 0, 0, 1,
0, 1, 0, 1,
0, 0, 1, 1,
0, 0, 0, 1};
Vec2f res{transform(v1, trans)};
EXPECT_FLOAT_EQ(res.x, 2.0f);
EXPECT_FLOAT_EQ(res.y, 3.0f);
}
| 19.293706 | 64 | 0.66419 | [
"transform"
] |
6e09949909ec2a19e51278c62558d750befdbe62 | 6,132 | cpp | C++ | test/container/grid/object.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | test/container/grid/object.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | test/container/grid/object.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/make_int_range_count.hpp>
#include <fcppt/no_init.hpp>
#include <fcppt/cast/size.hpp>
#include <fcppt/cast/to_signed.hpp>
#include <fcppt/container/grid/object.hpp>
#include <fcppt/math/dim/comparison.hpp>
#include <fcppt/math/dim/output.hpp>
#include <fcppt/math/vector/comparison.hpp>
#include <fcppt/math/vector/output.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <iterator>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace
{
typedef
fcppt::container::grid::object<
int,
2
>
int2_grid;
struct nonpod
{
nonpod()
:
member_(
42
)
{
}
int member_;
};
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_init_reference
)
{
FCPPT_PP_POP_WARNING
int2_grid const test(
int2_grid::dim(
10u,
20u
),
42
);
BOOST_CHECK_EQUAL(
std::count(
test.begin(),
test.end(),
42
),
200
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_index_2d
)
{
FCPPT_PP_POP_WARNING
int2_grid test(
int2_grid::dim(
5u,
10u
),
fcppt::no_init{}
);
{
int entry = 0;
for(
int2_grid::pointer ptr = test.data();
ptr != test.data_end();
++ptr
)
*ptr = entry++;
}
for(
auto const y
:
fcppt::make_int_range_count(
test.size()[1]
)
)
for (
auto const x
:
fcppt::make_int_range_count(
test.size()[0]
)
)
{
BOOST_REQUIRE_EQUAL(
test[
int2_grid::pos(
x,
y
)
],
fcppt::cast::size<
int2_grid::value_type
>(
fcppt::cast::to_signed(
x + y * 5
)
)
);
}
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_index_3d
)
{
FCPPT_PP_POP_WARNING
typedef
fcppt::container::grid::object<
int,
3
>
int3_grid;
int3_grid test(
int3_grid::dim(
5u,
10u,
8u
),
fcppt::no_init{}
);
{
int entry{
0
};
for(
int3_grid::pointer ptr = test.data();
ptr != test.data_end();
++ptr
)
*ptr = entry++;
}
for(
auto const z
:
fcppt::make_int_range_count(
test.size()[2]
)
)
for(
auto const y
:
fcppt::make_int_range_count(
test.size()[1]
)
)
for(
auto const x
:
fcppt::make_int_range_count(
test.size()[0]
)
)
{
BOOST_CHECK_EQUAL(
test[
int3_grid::pos(
x,
y,
z
)
],
fcppt::cast::size<
int3_grid::value_type
>(
fcppt::cast::to_signed(
x + y * 5 + z * 5 * 10
)
)
);
}
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_const_data
)
{
FCPPT_PP_POP_WARNING
int2_grid const test(
int2_grid::dim(
5u,
2u
),
42
);
BOOST_CHECK_EQUAL(
std::count(
test.data(),
test.data_end(),
42
),
10
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_size
)
{
FCPPT_PP_POP_WARNING
int2_grid const test(
int2_grid::dim(
3u,
2u
),
fcppt::no_init{}
);
BOOST_CHECK_EQUAL(
test.content(),
6u
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_non_pod
)
{
FCPPT_PP_POP_WARNING
typedef
fcppt::container::grid::object<
nonpod,
2
>
grid2_nonpod;
grid2_nonpod const test(
grid2_nonpod::dim(
5u,
3u
),
nonpod()
);
for(
auto const &element
:
test
)
BOOST_CHECK_EQUAL(
element.member_,
42
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_resize
)
{
FCPPT_PP_POP_WARNING
int2_grid test(
int2_grid::dim(
10u,
5u
),
fcppt::no_init{}
);
test.resize(
int2_grid::dim(
5u,
3u
),
fcppt::no_init{}
);
BOOST_CHECK_EQUAL(
test.size(),
int2_grid::dim(
5u,
3u
)
);
BOOST_CHECK_EQUAL(
std::distance(
test.data(),
test.data_end()
),
fcppt::cast::to_signed(
test.content()
)
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_move
)
{
FCPPT_PP_POP_WARNING
int2_grid grid1(
int2_grid::dim(
2u,
3u
),
fcppt::no_init{}
);
grid1[
int2_grid::pos(
0u,
0u
)
] = 1;
grid1[
int2_grid::pos(
1u,
1u
)
] = 2;
int2_grid grid2(
std::move(
grid1
)
);
BOOST_CHECK(
grid2.size()
==
int2_grid::dim(
2u,
3u
)
);
BOOST_CHECK(
grid2[
int2_grid::pos(
0u,
0u
)
] == 1
);
BOOST_CHECK(
grid2[
int2_grid::pos(
1u,
1u
)
] == 2
);
BOOST_CHECK(
grid1.begin()
==
grid1.end()
);
int2_grid grid3;
grid3 =
std::move(
grid2
);
BOOST_CHECK(
grid3.size()
==
int2_grid::dim(
2u,
3u
)
);
BOOST_CHECK(
grid3[
int2_grid::pos(
0u,
0u
)
] == 1
);
BOOST_CHECK(
grid3[
int2_grid::pos(
1u,
1u
)
] == 2
);
BOOST_CHECK(
grid2.begin()
==
grid2.end()
);
}
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_grid_init_function
)
{
FCPPT_PP_POP_WARNING
int2_grid const grid(
int2_grid::dim(
2u,
3u
),
[](
int2_grid::pos const _pos
)
{
return
fcppt::cast::size<
int
>(
fcppt::cast::to_signed(
_pos.x()
*
_pos.y()
)
);
}
);
typedef
int2_grid::pos
pos;
BOOST_CHECK_EQUAL(
fcppt::cast::to_signed(
grid.content()
),
std::distance(
grid.begin(),
grid.end()
)
);
BOOST_CHECK_EQUAL(
grid[
pos(
0u,
0u
)
],
0
);
BOOST_CHECK_EQUAL(
grid[
pos(
1u,
2u
)
],
2
);
}
| 11.724665 | 61 | 0.613503 | [
"object",
"vector"
] |
6e14ad2376a0df22731b0d532dc3ca4e63277fd7 | 11,025 | hpp | C++ | include/jsoncons/json_array.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | null | null | null | include/jsoncons/json_array.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | null | null | null | include/jsoncons/json_array.hpp | watkinsr/jsoncons | c7ab614fe86670a423941b11704a02ad71d745a1 | [
"BSL-1.0"
] | null | null | null | // Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSON_ARRAY_HPP
#define JSONCONS_JSON_ARRAY_HPP
#include <string>
#include <vector>
#include <exception>
#include <cstring>
#include <algorithm> // std::sort, std::stable_sort, std::lower_bound, std::unique
#include <utility>
#include <initializer_list>
#include <iterator> // std::iterator_traits
#include <memory> // std::allocator
#include <utility> // std::move
#include <cassert> // assert
#include <type_traits> // std::enable_if
#include <jsoncons/json_exception.hpp>
#include <jsoncons/allocator_holder.hpp>
namespace jsoncons {
// json_array
template <class Json,template<typename,typename> class SequenceContainer = std::vector>
class json_array : public allocator_holder<typename Json::allocator_type>
{
public:
using allocator_type = typename Json::allocator_type;
using value_type = Json;
private:
using value_allocator_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type>;
using value_container_type = SequenceContainer<value_type,value_allocator_type>;
value_container_type elements_;
public:
using iterator = typename value_container_type::iterator;
using const_iterator = typename value_container_type::const_iterator;
using reference = typename std::iterator_traits<iterator>::reference;
using const_reference = typename std::iterator_traits<const_iterator>::reference;
using allocator_holder<allocator_type>::get_allocator;
json_array()
{
}
explicit json_array(const allocator_type& alloc)
: allocator_holder<allocator_type>(alloc),
elements_(value_allocator_type(alloc))
{
}
explicit json_array(std::size_t n,
const allocator_type& alloc = allocator_type())
: allocator_holder<allocator_type>(alloc),
elements_(n,Json(),value_allocator_type(alloc))
{
}
explicit json_array(std::size_t n,
const Json& value,
const allocator_type& alloc = allocator_type())
: allocator_holder<allocator_type>(alloc),
elements_(n,value,value_allocator_type(alloc))
{
}
template <class InputIterator>
json_array(InputIterator begin, InputIterator end, const allocator_type& alloc = allocator_type())
: allocator_holder<allocator_type>(alloc),
elements_(begin,end,value_allocator_type(alloc))
{
}
json_array(const json_array& val)
: allocator_holder<allocator_type>(val.get_allocator()),
elements_(val.elements_)
{
}
json_array(const json_array& val, const allocator_type& alloc)
: allocator_holder<allocator_type>(alloc),
elements_(val.elements_,value_allocator_type(alloc))
{
}
json_array(json_array&& val) noexcept
: allocator_holder<allocator_type>(val.get_allocator()),
elements_(std::move(val.elements_))
{
}
json_array(json_array&& val, const allocator_type& alloc)
: allocator_holder<allocator_type>(alloc),
elements_(std::move(val.elements_),value_allocator_type(alloc))
{
}
json_array(const std::initializer_list<Json>& init,
const allocator_type& alloc = allocator_type())
: allocator_holder<allocator_type>(alloc),
elements_(init,value_allocator_type(alloc))
{
}
~json_array() noexcept
{
flatten_and_destroy();
}
reference back()
{
return elements_.back();
}
const_reference back() const
{
return elements_.back();
}
void pop_back()
{
elements_.pop_back();
}
bool empty() const
{
return elements_.empty();
}
void swap(json_array<Json>& val) noexcept
{
elements_.swap(val.elements_);
}
std::size_t size() const {return elements_.size();}
std::size_t capacity() const {return elements_.capacity();}
void clear() {elements_.clear();}
void shrink_to_fit()
{
for (std::size_t i = 0; i < elements_.size(); ++i)
{
elements_[i].shrink_to_fit();
}
elements_.shrink_to_fit();
}
void reserve(std::size_t n) {elements_.reserve(n);}
void resize(std::size_t n) {elements_.resize(n);}
void resize(std::size_t n, const Json& val) {elements_.resize(n,val);}
#if !defined(JSONCONS_NO_DEPRECATED)
JSONCONS_DEPRECATED_MSG("Instead, use erase(const_iterator, const_iterator)")
void remove_range(std::size_t from_index, std::size_t to_index)
{
JSONCONS_ASSERT(from_index <= to_index);
JSONCONS_ASSERT(to_index <= elements_.size());
elements_.erase(elements_.cbegin()+from_index,elements_.cbegin()+to_index);
}
#endif
void erase(const_iterator pos)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it = elements_.begin() + (pos - elements_.begin());
elements_.erase(it);
#else
elements_.erase(pos);
#endif
}
void erase(const_iterator first, const_iterator last)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it1 = elements_.begin() + (first - elements_.begin());
iterator it2 = elements_.begin() + (last - elements_.begin());
elements_.erase(it1,it2);
#else
elements_.erase(first,last);
#endif
}
Json& operator[](std::size_t i) {return elements_[i];}
const Json& operator[](std::size_t i) const {return elements_[i];}
// push_back
template <class T, class A=allocator_type>
typename std::enable_if<type_traits::is_stateless<A>::value,void>::type
push_back(T&& value)
{
elements_.emplace_back(std::forward<T>(value));
}
template <class T, class A=allocator_type>
typename std::enable_if<!type_traits::is_stateless<A>::value,void>::type
push_back(T&& value)
{
elements_.emplace_back(std::forward<T>(value),get_allocator());
}
template <class T, class A=allocator_type>
typename std::enable_if<type_traits::is_stateless<A>::value,iterator>::type
insert(const_iterator pos, T&& value)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it = elements_.begin() + (pos - elements_.begin());
return elements_.emplace(it, std::forward<T>(value));
#else
return elements_.emplace(pos, std::forward<T>(value));
#endif
}
template <class T, class A=allocator_type>
typename std::enable_if<!type_traits::is_stateless<A>::value,iterator>::type
insert(const_iterator pos, T&& value)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it = elements_.begin() + (pos - elements_.begin());
return elements_.emplace(it, std::forward<T>(value), get_allocator());
#else
return elements_.emplace(pos, std::forward<T>(value), get_allocator());
#endif
}
template <class InputIt>
iterator insert(const_iterator pos, InputIt first, InputIt last)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it = elements_.begin() + (pos - elements_.begin());
elements_.insert(it, first, last);
return first == last ? it : it + 1;
#else
return elements_.insert(pos, first, last);
#endif
}
template <class A=allocator_type, class... Args>
typename std::enable_if<type_traits::is_stateless<A>::value,iterator>::type
emplace(const_iterator pos, Args&&... args)
{
#if defined(JSONCONS_NO_ERASE_TAKING_CONST_ITERATOR)
iterator it = elements_.begin() + (pos - elements_.begin());
return elements_.emplace(it, std::forward<Args>(args)...);
#else
return elements_.emplace(pos, std::forward<Args>(args)...);
#endif
}
template <class... Args>
Json& emplace_back(Args&&... args)
{
elements_.emplace_back(std::forward<Args>(args)...);
return elements_.back();
}
iterator begin() {return elements_.begin();}
iterator end() {return elements_.end();}
const_iterator begin() const {return elements_.begin();}
const_iterator end() const {return elements_.end();}
bool operator==(const json_array<Json>& rhs) const noexcept
{
return elements_ == rhs.elements_;
}
bool operator<(const json_array<Json>& rhs) const noexcept
{
return elements_ < rhs.elements_;
}
private:
json_array& operator=(const json_array<Json>&) = delete;
void flatten_and_destroy() noexcept
{
while (!elements_.empty())
{
value_type current = std::move(elements_.back());
elements_.pop_back();
switch (current.storage_kind())
{
case json_storage_kind::array_value:
{
for (auto&& item : current.array_range())
{
if (item.size() > 0) // non-empty object or array
{
elements_.push_back(std::move(item));
}
}
current.clear();
break;
}
case json_storage_kind::object_value:
{
for (auto&& kv : current.object_range())
{
if (kv.value().size() > 0) // non-empty object or array
{
elements_.push_back(std::move(kv.value()));
}
}
current.clear();
break;
}
default:
break;
}
}
}
};
} // namespace jsoncons
#endif
| 34.027778 | 139 | 0.567075 | [
"object",
"vector"
] |
6e1996e57c6afa51989d48538e3382952dae72c8 | 7,467 | cpp | C++ | qu3e/shared/common.cpp | Shchvova/solar2d-plugins | d207849706372ef3a611fcaac5a0b599d9023d22 | [
"MIT"
] | 12 | 2020-05-04T08:49:04.000Z | 2021-12-30T09:35:17.000Z | qu3e/shared/common.cpp | Shchvova/solar2d-plugins | d207849706372ef3a611fcaac5a0b599d9023d22 | [
"MIT"
] | null | null | null | qu3e/shared/common.cpp | Shchvova/solar2d-plugins | d207849706372ef3a611fcaac5a0b599d9023d22 | [
"MIT"
] | 3 | 2021-02-19T18:39:02.000Z | 2022-03-09T17:14:57.000Z | /*
* 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.
*
* [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
*/
#include "qu3e.h"
#include "utils/LuaEx.h"
q3AABB & AABB (lua_State * L, int arg)
{
return *LuaXS::CheckUD<q3AABB>(L, arg, "qu3e.AABB");
}
q3HalfSpace & HalfSpace (lua_State * L, int arg)
{
return *LuaXS::CheckUD<q3HalfSpace>(L, arg, "qu3e.HalfSpace");
}
q3RaycastData & Raycast (lua_State * L, int arg)
{
return *LuaXS::CheckUD<q3RaycastData>(L, arg, "qu3e.RaycastData");
}
static int AuxAABB (lua_State * L)
{
LuaXS::NewTyped<q3AABB>(L); // ..., aabb
LuaXS::AttachMethods(L, "qu3e.AABB", [](lua_State * L) {
luaL_Reg methods[] = {
{
"Contains", [](lua_State * L)
{
if (LuaXS::IsType(L, "qu3e.AABB", 2)) return LuaXS::PushArgAndReturn(L, AABB(L).Contains(AABB(L, 2))); // aabb1, aabb2, contained
else return LuaXS::PushArgAndReturn(L, AABB(L).Contains(Vector(L, 2))); // aabb, vec, contained
}
}, {
"__newindex", [](lua_State * L)
{
const char * str = luaL_checkstring(L, 2);
if (strcmp(str, "max") == 0) AABB(L).max = Vector(L, 3);
else if (strcmp(str, "min") == 0) AABB(L).min = Vector(L, 3);
else return luaL_error(L, "Invalid member");
return 0;
}
}, {
"SurfaceArea", [](lua_State * L)
{
return LuaXS::PushArgAndReturn(L, AABB(L).SurfaceArea()); // aabb, area
}
},
{ nullptr, nullptr }
};
luaL_register(L, nullptr, methods);
LuaXS::NewWeakKeyedTable(L);// aabb, aabb_mt, vec_to_aabb
LuaXS::AttachPropertyParams app;
app.mUpvalueCount = 1U;
LuaXS::AttachProperties(L, [](lua_State * L) {
q3Vec3 * pvec = nullptr;
if (lua_type(L, 2) == LUA_TSTRING)
{
const char * str = lua_tostring(L, 2);
if (strcmp(str, "max") == 0) pvec = &AABB(L).max;
else if (strcmp(str, "min") == 0) pvec = &AABB(L).min;
}
if (pvec) AddVectorRef(L, pvec);// aabb, k, vec
else lua_pushnil(L);// aabb, k, nil
return 1;
}, app);// aabb, aabb_mt
});
return 1;
}
void open_common (lua_State * L)
{
luaL_Reg funcs[] = {
{
"Combine", [](lua_State * L)
{
lua_settop(L, 2); // aabb1, aabb2
AuxAABB(L); // aabb1, aabb2, comb
AABB(L, 3) = q3Combine(AABB(L, 1), AABB(L, 2));
return 1;
}
}, {
"NewAABB", AuxAABB
}, {
"NewHalfSpace", [](lua_State * L)
{
q3HalfSpace * hs = LuaXS::NewTyped<q3HalfSpace>(L); // [normal, distance, ]halfspace
if (lua_gettop(L) > 1) *hs = q3HalfSpace{ Vector(L, 1), LuaXS::Float(L, 2) };
LuaXS::AttachMethods(L, "qu3e.HalfSpace", [](lua_State * L) {
luaL_Reg methods[] = {
{
"Distance", [](lua_State * L)
{
return LuaXS::PushArgAndReturn(L, HalfSpace(L).Distance(Vector(L, 2))); // hs, p, distance
}
}, {
"__newindex", [](lua_State * L)
{
const char * str = luaL_checkstring(L, 2);
if (strcmp(str, "normal") == 0) HalfSpace(L).normal = Vector(L, 3);
else if (strcmp(str, "distance") == 0) HalfSpace(L).distance = LuaXS::Float(L, 3);
else return luaL_error(L, "Invalid member");
return 0;
}
}, {
"Origin", [](lua_State * L)
{
return NewVector(L, HalfSpace(L).Origin()); // hs, origin
}
}, {
"Projected", [](lua_State * L)
{
return NewVector(L, HalfSpace(L).Projected(Vector(L, 2))); // hs, v, proj
}
}, {
"Set", [](lua_State * L)
{
if (lua_gettop(L) >= 4) HalfSpace(L).Set(Vector(L, 2), Vector(L, 3), Vector(L, 4));
else HalfSpace(L).Set(Vector(L, 2), Vector(L, 3));
return 0;
}
},
{ nullptr, nullptr }
};
luaL_register(L, nullptr, methods);
LuaXS::AttachProperties(L, [](lua_State * L) {
if (lua_type(L, 2) == LUA_TSTRING)
{
const char * str = lua_tostring(L, 2);
if (strcmp(str, "normal") == 0) return NewVector(L, HalfSpace(L).normal); // hs, key, normal
else if (strcmp(str, "distance") == 0) return LuaXS::PushArgAndReturn(L, HalfSpace(L).distance);// hs, key, distance
}
return LuaXS::PushArgAndReturn(L, LuaXS::Nil{});// hs, k, nil
});
});
return 1;
}
}, {
"NewRaycastData", [](lua_State * L)
{
LuaXS::NewTyped<q3RaycastData>(L); // raycast
LuaXS::AttachMethods(L, "qu3e.RaycastData", [](lua_State * L) {
luaL_Reg methods[] = {
{
"GetImpactPoint", [](lua_State * L)
{
return NewVector(L, Raycast(L).GetImpactPoint()); // raycast, impact
}
}, {
"__newindex", [](lua_State * L)
{
const char * str = luaL_checkstring(L, 2);
q3Vec3 * pvec = nullptr;
float * pfloat = nullptr;
if (strcmp(str, "start") == 0) pvec = &Raycast(L).start;
else if (strcmp(str, "dir") == 0) pvec = &Raycast(L).dir;
else if (strcmp(str, "normal") == 0) pvec = &Raycast(L).normal;
else if (strcmp(str, "t") == 0) pfloat = &Raycast(L).t;
else if (strcmp(str, "toi") == 0) pfloat = &Raycast(L).toi;
luaL_argcheck(L, pvec || pfloat, 2, "Invalid member");
if (pvec) *pvec = Vector(L, 3);
else *pfloat = LuaXS::Float(L, 3);
return 0;
}
}, {
"Set", [](lua_State * L)
{
Raycast(L).Set(Vector(L, 2), Vector(L, 3), LuaXS::Float(L, 4));
return 0;
}
},
{ nullptr, nullptr }
};
luaL_register(L, nullptr, methods);
LuaXS::AttachProperties(L, [](lua_State * L) {
if (lua_type(L, 2) == LUA_TSTRING)
{
const char * str = lua_tostring(L, 2);
q3Vec3 * pvec = nullptr;
float * pfloat = nullptr;
if (strcmp(str, "start") == 0) pvec = &Raycast(L).start;
else if (strcmp(str, "dir") == 0) pvec = &Raycast(L).dir;
else if (strcmp(str, "normal") == 0) pvec = &Raycast(L).normal;
else if (strcmp(str, "t") == 0) pfloat = &Raycast(L).t;
else if (strcmp(str, "toi") == 0) pfloat = &Raycast(L).toi;
if (pvec) NewVector(L, *pvec); // raycast, key, v
else if (pfloat) return LuaXS::PushArgAndReturn(L, *pfloat);// raycast, key, float
}
return LuaXS::PushArgAndReturn(L, LuaXS::Nil{});// raycast, k, nil
});
});
return 1;
}
},
{ nullptr, nullptr }
};
luaL_register(L, nullptr, funcs);
}
| 29.282353 | 134 | 0.57359 | [
"vector"
] |
6e26f402d411639604cf3200e2b963e65a7dcf19 | 9,220 | cpp | C++ | Tests/DiverApiTester/DiverApiTester.cpp | ShadowKnightMK4/DebugDotNet | e99fe2fe5da2bc2161d069ed12d035b7bce8d4b9 | [
"MIT"
] | null | null | null | Tests/DiverApiTester/DiverApiTester.cpp | ShadowKnightMK4/DebugDotNet | e99fe2fe5da2bc2161d069ed12d035b7bce8d4b9 | [
"MIT"
] | null | null | null | Tests/DiverApiTester/DiverApiTester.cpp | ShadowKnightMK4/DebugDotNet | e99fe2fe5da2bc2161d069ed12d035b7bce8d4b9 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <iostream>
#include <vector>
#include <process.h>
enum TypeHints : unsigned int
{
CanBeNull = 1,
AnsiCString = 2,
UnicodeCString = 4,
Uchar = 8,
Schar = 16,
Ushort = 32,
Sshort = 64,
Uint = 128,
Sint = 256,
Ulong = 512,
SLong = 1024,
Float = 2048,
Double = 4096
};
enum DEBUGGER_RESPONSE_FLAGS : unsigned int
{
NoResponse = 0,
// Detoured Function does not call original and instead returns struct.Arg1
ForceReturn = 2,
};
/// struct that a debugger fills out to control response.
/// Debugger may also modify arguments already passes as seen fit.
typedef struct DEBUGGER_RESPONSE
{
// Set to sizeof(DEBUGGER_RESPONSE) by detoured function
DWORD SizeOfThis;
// Set to sizeof(VOID*) By detoured function
DWORD SizeOfPtr;
// must be set by debugger to indicate that this was seen and modidied.
BOOL DebuggerSeenThis;
// Flags to change stuff
DEBUGGER_RESPONSE_FLAGS Flags;
// Argument for certain flags
DWORD Arg1;
};
using namespace std;
BOOL(WINAPI* IsDebuggerPresentPtr)();
BOOL (WINAPI* RaiseExceptionDiverCheck)();
BOOL(WINAPI* RaiseExceptionTrackFunc)(const wchar_t* FuncName,
vector<ULONG_PTR>& ArgPtrs,
vector<ULONG_PTR>& TypeHint,
ULONG_PTR* RetVal,
ULONG_PTR* RetHint,
DEBUGGER_RESPONSE* Debugger);
LONG (WINAPI* DetourUpdateThread)(
_In_ HANDLE hThread
);
LONG(WINAPI* DetourTransactionCommit)(VOID);
LONG(WINAPI* DetourDetach)(
_Inout_ PVOID* ppPointer,
_In_ PVOID pDetour
);
LONG(WINAPI* DetourTransactionBegin)(VOID);
LONG (WINAPI* DetourAttach)(
_Inout_ PVOID* ppPointer,
_In_ PVOID pDetour
);
using namespace std;
HMODULE DiverDll;
HMODULE NTDLL;
float TestsPassed;
float TestsFailed;
bool Fatal = false;
VOID* OriginalPtr = 0;
VOID* FixedPtr;
void _cdecl KernelJump()
{
unsigned long reg;
__asm
{
mov reg, eax
call OriginalPtr;
}
if (reg == 0x55)
{
cout << "File System was accessed" << endl;
}
}
BOOL WINAPI MyIsDebuggerPresent()
{
vector<ULONG_PTR> ArgPtrs;
vector<ULONG_PTR> TypeHints;
BOOL RetVal;
BOOL CallVal;
DEBUGGER_RESPONSE res;
ZeroMemory(&res, sizeof(DEBUGGER_RESPONSE));
res.SizeOfPtr = sizeof(ULONG_PTR);
res.SizeOfThis = sizeof(DEBUGGER_RESPONSE);
// there are no args to pack.
CallVal = RaiseExceptionTrackFunc(L"IsDebuggerPresent", ArgPtrs, TypeHints, (ULONG_PTR*)&RetVal, 0, &res);
res.DebuggerSeenThis = TRUE;
res.Flags = ForceReturn;
cout << "For normal debug purpose. Value of Debugger is " << res.DebuggerSeenThis << endl;
if (res.DebuggerSeenThis == FALSE)
{
cout << "Debugger did not understand this exception. Doing Defaults" << endl;
return IsDebuggerPresentPtr();
}
else
{
cout << "Debugger understood the track func exception " << endl;
if (res.Flags & (ForceReturn ))
{
cout << "Debugger forced return value of " << res.Arg1 << " with disabling the actuall call" << endl;
return res.Arg1;
}
else
{
return IsDebuggerPresentPtr();
}
}
}
void IniApp()
{
cout << "Loading Diver" << endl;
DiverDll = LoadLibrary(L"C:\\Users\\Thoma\\source\\repos\\DebugDotNet\\DebugDotNet\\bin\\Debug\\netstandard2.0\\DebugDotNetDiver.dll");
if (DiverDll == 0)
{
cout << "Failed to find Diver Dll" << "Last Error code is " << GetLastError() << endl;
Fatal = true;
return;
}
else
{
cout << "Diver Dll Ok." << " Linkning Routines" << endl;
DetourUpdateThread = (LONG (__stdcall*)(HANDLE)) GetProcAddress(DiverDll, (LPCSTR)8);
DetourTransactionCommit = (LONG(__stdcall*)()) GetProcAddress(DiverDll, (LPCSTR)7);
DetourAttach = (LONG(__stdcall*)(PVOID *, PVOID))GetProcAddress(DiverDll, (LPCSTR)5);
DetourDetach = (LONG(__stdcall*)(PVOID*, PVOID))GetProcAddress(DiverDll, (LPCSTR)6);
DetourTransactionBegin = (LONG(__stdcall*)()) GetProcAddress(DiverDll, (LPCSTR)4);
RaiseExceptionTrackFunc = (BOOL(WINAPI*)(const wchar_t*,
vector<ULONG_PTR>&,
vector<ULONG_PTR>&,
ULONG_PTR*,
ULONG_PTR*,
DEBUGGER_RESPONSE*)) GetProcAddress(DiverDll, (LPCSTR)3);
RaiseExceptionDiverCheck = (BOOL(__stdcall*)()) GetProcAddress(DiverDll, (LPCSTR)2);
if (RaiseExceptionDiverCheck == 0)
{
cout << "RaiseExceptionDiverCheck did not link" << endl;
Fatal = true;
}
if (DetourUpdateThread == 0)
{
cout << "DetourUpdateThread did not link" << endl;
Fatal = true;
}
if (DetourTransactionCommit == 0)
{
cout << "DetourTransactionCommit did not link" << endl;
Fatal = true;
}
if (DetourAttach == 0)
{
cout << "DetourAttach did not link" << endl;
Fatal = true;
}
if (DetourDetach == 0)
{
cout << "DetourDetach did not link" << endl;
Fatal = true;
}
if (DetourTransactionBegin == 0)
{
Fatal = true;
cout << "DetourTransactionBegin did not link" << endl;
}
if (RaiseExceptionTrackFunc == 0)
{
Fatal = true;
cout << "RaiseExceptionTrackFunc did not link" << endl;
}
TestsPassed++;
}
}
void Test1()
{
cout << "Test1. Calling the driver version func. If an attached debugger does not handle the exception (and modidify a value), this returns false" << endl;
auto result = RaiseExceptionDiverCheck();
cout << result << " is the result of the call ";
if (result != FALSE)
{
cout << "Debugger reconized and accepted communication via this protocal " << endl;
TestsPassed++;
}
else
{
cout << "Debugger did not accept or reconize this protocal " << endl;
TestsFailed++;
}
}
void Test2()
{
std::vector<ULONG_PTR> ArgList;
std::vector<ULONG_PTR> ArgHint;
DEBUGGER_RESPONSE Response;
ZeroMemory(&Response, sizeof(DEBUGGER_RESPONSE));
ULONG_PTR ret;
ULONG_PTR Hint;
ArgList.push_back(0);
ArgHint.push_back(0);
cout << "Raising an exception to se the argtype";
RaiseExceptionTrackFunc(L"Example", ArgList, ArgHint, &ret, &Hint, &Response);
}
void _cdecl Test2NukApplyDetourDummy(void* junk)
{
while (true)
{
OutputDebugStringW(L"Keep Alive\r\n");
cout << "IsDebugger Present in dummy thread returns " << IsDebuggerPresent() << endl;
Sleep(2000);
}
}
void _cdecl Test2Nukk(void* junk)
{
cout << "Test2 is ran in seperate thread" << endl;
cout << "Starting Test2. This detours IsDebuggerPresent(). It also calls it before detour" << endl;
IsDebuggerPresentPtr = IsDebuggerPresent;
long Start, enlist, attach, commit;
cout << "Original Debugger check of IsDebuggerPresent() returns " << IsDebuggerPresent() << endl;
Start = DetourTransactionBegin();
if (Start != 0)
{
cout << "Test Failed. DetourTransactionBegin() returned " << Start << endl;
TestsFailed++;
return;
}
else
{
cout << "DetourStarted" << endl;
enlist = DetourUpdateThread((HANDLE)junk);
if (enlist != 0)
{
cout << "Test Failed. DetourUpdateTHread() returned " << enlist;
TestsFailed++;
return;
}
else
{
attach = DetourAttach(&(PVOID&)IsDebuggerPresentPtr, MyIsDebuggerPresent);
if (attach != 0)
{
cout << "Test Failed. DetourAttach did not link with IsDebuggerPresent(). Error " << attach << endl;
}
commit = DetourTransactionCommit();
if (commit != 0)
{
cout << "Test Failed. Could not commit detour. Error " << commit << endl;
}
cout << "Sucess in detouring IsDebuggerPresent(). Calling my version thru that ptr" << endl;
cout << "IsDebuggerPresent() returns " << IsDebuggerPresent() << endl;
}
}
}
void RemoveRiteStuff(VOID* Target)
{
MEMORY_BASIC_INFORMATION Info;
ZeroMemory(&Info,sizeof(Info));
auto result1 =VirtualQuery(Target, &Info, sizeof(Info));
auto result2 = VirtualProtect(Target, Info.RegionSize, Info.Protect + PAGE_EXECUTE_READWRITE, 0);
return;
}
void Test3()
{
cout << "Test 3 is a little different. We place a detour trampoline at 0x7FFE0300 with a pointer to KernelJump() KernalJump just calls the original ptr" << endl;
// get a copy of the data the thing points too
FixedPtr = (VOID*)0x7FFE0300;
OriginalPtr = (VOID*) *((DWORD*)FixedPtr);
auto start = DetourTransactionBegin();
RemoveRiteStuff(OriginalPtr);
if (start != 0)
{
cout << "Failed to start detour" << start;
TestsFailed++;
return;
}
auto attach = DetourAttach(&(PVOID&)OriginalPtr, KernelJump);
if (attach != 0)
{
cout << "Failed to attach to target " << attach << endl;
TestsFailed++;
}
auto thread = DetourUpdateThread(GetCurrentThread());
if (thread != 0)
{
cout << "Failed to attach to target " << thread << endl;
TestsFailed++;
}
auto fin = DetourTransactionCommit();
if (fin != 0)
{
cout << "Failed to attach to target " << fin << endl;
TestsFailed++;
}
cout << "If you get here. We've modified the target pointer.";
cout << "Next Step we do is creata a file at C:\\Windows\\TEMP\\Discard.txt" << endl;
HANDLE fn = INVALID_HANDLE_VALUE;
__try
{
fn = CreateFile(L"C:\\Windows\\TEMP\\Discard.txt", GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY, NULL);
}
__finally
{
CloseHandle(fn);
}
}
int main()
{
IniApp();
if (!Fatal)
{
Test1();
Test2();
if (TestsFailed + TestsPassed != 0)
{
cout << "Percent passed (" << TestsPassed / (TestsFailed + TestsPassed) << ") Percent failed (" << TestsPassed / (TestsFailed + TestsPassed) << endl;
}
else
{
cout << "Error evaling tests" << endl;
}
return 0;
}
return -1;
} | 23.641026 | 163 | 0.685792 | [
"vector"
] |
6e359538419f2309aad3572325eb1a24bf2f9742 | 13,218 | cpp | C++ | src/cpp/eval/runtime/eval_object_data.cpp | paramah/hiphop-php-osx | 5ed8c24abe8ad9fd7bc6dd4c28b4ffff23e54362 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2015-11-05T21:45:07.000Z | 2015-11-05T21:45:07.000Z | src/cpp/eval/runtime/eval_object_data.cpp | brion/hiphop-php | df70a236e6418d533ac474be0c01f0ba87034d7f | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | src/cpp/eval/runtime/eval_object_data.cpp | brion/hiphop-php | df70a236e6418d533ac474be0c01f0ba87034d7f | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <cpp/eval/runtime/eval_object_data.h>
#include <cpp/eval/ast/method_statement.h>
#include <cpp/eval/ast/class_statement.h>
#include <cpp/base/hphp_system.h>
#include <cpp/eval/runtime/eval_state.h>
namespace HPHP {
namespace Eval {
/////////////////////////////////////////////////////////////////////////////
// constructor/destructor
IMPLEMENT_OBJECT_ALLOCATION_CLS(HPHP::Eval,EvalObjectData)
EvalObjectData::EvalObjectData(ClassEvalState &cls, const char* pname,
ObjectData* r /* = NULL */)
: DynamicObjectData(pname, r ? r : this), m_cls(cls) {
if (r == NULL) {
RequestEvalState::registerObject(this);
}
}
// Only used for cloning and so should not register object
EvalObjectData::EvalObjectData(ClassEvalState &cls) :
DynamicObjectData(NULL, this), m_cls(cls) {
}
ObjectData *EvalObjectData::dynCreate(CArrRef params, bool ini /* = true */) {
if (ini) {
init();
dynConstruct(params);
}
return this;
}
void EvalObjectData::init() {
m_cls.getClass()->initializeObject(this);
DynamicObjectData::init();
}
void EvalObjectData::dynConstruct(CArrRef params) {
const MethodStatement *ms = m_cls.getConstructor();
if (ms) {
ms->invokeInstance(Object(root), params);
} else {
DynamicObjectData::dynConstruct(params);
}
}
void EvalObjectData::destruct() {
const MethodStatement *ms;
incRefCount();
if (!inCtorDtor() && (ms = getMethodStatement("__destruct"))) {
setInDtor();
try {
ms->invokeInstance(Object(root),Array());
} catch (...) {
handle_destructor_exception();
}
}
DynamicObjectData::destruct();
if (root == this) {
RequestEvalState::deregisterObject(this);
}
}
void EvalObjectData::o_get(std::vector<ArrayElement *> &props) const {
return DynamicObjectData::o_get(props);
}
Variant EvalObjectData::o_get(CStrRef s, int64 hash) {
m_cls.getClass()->attemptPropertyAccess(s);
return DynamicObjectData::o_get(s, hash);
}
Variant EvalObjectData::o_getUnchecked(CStrRef s, int64 hash) {
return DynamicObjectData::o_get(s, hash);
}
Variant &EvalObjectData::o_lval(CStrRef s, int64 hash) {
return DynamicObjectData::o_lval(s, hash);
}
Variant EvalObjectData::o_set(CStrRef s, int64 hash, CVarRef v,
bool forInit /* = false */) {
if (!forInit) m_cls.getClass()->attemptPropertyAccess(s);
return DynamicObjectData::o_set(s, hash, v, forInit);
}
const char *EvalObjectData::o_getClassName() const {
return m_cls.getClass()->name().c_str();
}
const MethodStatement
*EvalObjectData::getMethodStatement(const char* name) const {
const hphp_const_char_imap<const MethodStatement*> &meths =
m_cls.getMethodTable();
hphp_const_char_imap<const MethodStatement*>::const_iterator it =
meths.find(name);
if (it != meths.end()) {
return it->second;
}
return NULL;
}
bool EvalObjectData::o_instanceof(const char *s) const {
return m_cls.getClass()->subclassOf(s) ||
(!parent.isNull() && parent->o_instanceof(s));
}
Variant EvalObjectData::o_invoke(const char *s, CArrRef params, int64 hash,
bool fatal /* = true */) {
const hphp_const_char_imap<const MethodStatement*> &meths =
m_cls.getMethodTable();
hphp_const_char_imap<const MethodStatement*>::const_iterator it =
meths.find(s);
if (it != meths.end()) {
if (it->second) {
return it->second->invokeInstance(Object(root), params);
} else {
return DynamicObjectData::o_invoke(s, params, hash, fatal);
}
} else {
return doCall(s, params, fatal);
}
}
Variant EvalObjectData::o_invoke_ex(const char *clsname, const char *s,
CArrRef params, int64 hash,
bool fatal /* = false */) {
if (m_cls.getClass()->subclassOf(clsname)) {
bool foundClass;
const MethodStatement *ms = RequestEvalState::findMethod(clsname, s,
foundClass);
if (ms) {
return ms->invokeInstance(Object(root), params);
} else {
// Possibly builtin class has this method
const hphp_const_char_imap<const MethodStatement*> &meths =
m_cls.getMethodTable();
if (meths.find(s) == meths.end()) {
// Absolutely nothing in the hierarchy has this method
return doCall(s, params, fatal);
}
}
// Know it's a builtin parent so no need for _ex
return DynamicObjectData::o_invoke(s, params, hash, fatal);
}
return DynamicObjectData::o_invoke_ex(clsname, s, params, hash, fatal);
}
Variant EvalObjectData::o_invoke_few_args(const char *s, int64 hash, int count,
CVarRef a0 /* = null_variant */,
CVarRef a1 /* = null_variant */,
CVarRef a2 /* = null_variant */
#if INVOKE_FEW_ARGS_COUNT > 3
,CVarRef a3 /* = null_variant */,
CVarRef a4 /* = null_variant */,
CVarRef a5 /* = null_variant */
#endif
#if INVOKE_FEW_ARGS_COUNT > 6
,CVarRef a6 /* = null_variant */,
CVarRef a7 /* = null_variant */,
CVarRef a8 /* = null_variant */,
CVarRef a9 /* = null_variant */
#endif
) {
switch (count) {
case 0: {
return o_invoke(s, Array(), hash);
}
case 1: {
Array params(NEW(ArrayElement)(a0), NULL);
return o_invoke(s, params, hash);
}
case 2: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1), NULL);
return o_invoke(s, params, hash);
}
case 3: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NULL);
return o_invoke(s, params, hash);
}
#if INVOKE_FEW_ARGS_COUNT > 3
case 4: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3), NULL);
return o_invoke(s, params, hash);
}
case 5: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NULL);
return o_invoke(s, params, hash);
}
case 6: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NEW(ArrayElement)(a5), NULL);
return o_invoke(s, params, hash);
}
#endif
#if INVOKE_FEW_ARGS_COUNT > 6
case 7: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NEW(ArrayElement)(a5),
NEW(ArrayElement)(a6), NULL);
return o_invoke(s, params, hash);
}
case 8: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NEW(ArrayElement)(a5),
NEW(ArrayElement)(a6), NEW(ArrayElement)(a7), NULL);
return o_invoke(s, params, hash);
}
case 9: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NEW(ArrayElement)(a5),
NEW(ArrayElement)(a6), NEW(ArrayElement)(a7),
NEW(ArrayElement)(a8), NULL);
return o_invoke(s, params, hash);
}
case 10: {
Array params(NEW(ArrayElement)(a0), NEW(ArrayElement)(a1),
NEW(ArrayElement)(a2), NEW(ArrayElement)(a3),
NEW(ArrayElement)(a4), NEW(ArrayElement)(a5),
NEW(ArrayElement)(a6), NEW(ArrayElement)(a7),
NEW(ArrayElement)(a8), NEW(ArrayElement)(a9), NULL);
return o_invoke(s, params, hash);
}
#endif
default:
ASSERT(false);
}
return null;
}
Variant EvalObjectData::doCall(Variant v_name, Variant v_arguments,
bool fatal) {
const MethodStatement *ms = getMethodStatement("__call");
if (ms) {
return ms->invokeInstance(Object(root),
CREATE_VECTOR2(v_name, v_arguments));
} else {
return DynamicObjectData::doCall(v_name, v_arguments, fatal);
}
}
Variant EvalObjectData::t___destruct() {
const MethodStatement *ms = getMethodStatement("__destruct");
if (ms) {
return ms->invokeInstance(Object(root), Array());
} else {
return DynamicObjectData::t___destruct();
}
}
Variant EvalObjectData::t___set(Variant v_name, Variant v_value) {
if (v_value.isReferenced()) {
v_value.setContagious();
}
const MethodStatement *ms = getMethodStatement("__set");
if (ms) {
return ms->invokeInstance(Object(root), CREATE_VECTOR2(v_name, v_value));
} else {
return DynamicObjectData::t___set(v_name, v_value);
}
}
Variant EvalObjectData::t___get(Variant v_name) {
const MethodStatement *ms = getMethodStatement("__get");
if (ms) {
return ms->invokeInstance(Object(root), CREATE_VECTOR1(v_name));
} else {
return DynamicObjectData::t___get(v_name);
}
}
bool EvalObjectData::t___isset(Variant v_name) {
const MethodStatement *ms = getMethodStatement("__isset");
if (ms) {
return ms->invokeInstance(Object(root), CREATE_VECTOR1(v_name));
} else {
return DynamicObjectData::t___isset(v_name);
}
}
Variant EvalObjectData::t___unset(Variant v_name) {
const MethodStatement *ms = getMethodStatement("__unset");
if (ms) {
return ms->invokeInstance(Object(root), CREATE_VECTOR1(v_name));
} else {
return DynamicObjectData::t___unset(v_name);
}
}
bool EvalObjectData::php_sleep(Variant &ret) {
ret = t___sleep();
return getMethodStatement("__sleep");
}
Variant EvalObjectData::t___sleep() {
const MethodStatement *ms = getMethodStatement("__sleep");
if (ms) {
return ms->invokeInstance(Object(root), Array());
} else {
return DynamicObjectData::t___sleep();
}
}
Variant EvalObjectData::t___wakeup() {
const MethodStatement *ms = getMethodStatement("__wakeup");
if (ms) {
return ms->invokeInstance(Object(root), Array());
} else {
return DynamicObjectData::t___wakeup();
}
}
Variant EvalObjectData::t___set_state(Variant v_properties) {
const MethodStatement *ms = getMethodStatement("__set_state");
if (ms) {
return ms->invokeInstance(Object(root), CREATE_VECTOR1(v_properties));
} else {
return DynamicObjectData::t___set_state(v_properties);
}
}
String EvalObjectData::t___tostring() {
const MethodStatement *ms = getMethodStatement("__tostring");
if (ms) {
return ms->invokeInstance(Object(root), Array());
} else {
return DynamicObjectData::t___tostring();
}
}
Variant EvalObjectData::t___clone() {
const MethodStatement *ms = getMethodStatement("__clone");
if (ms) {
return ms->invokeInstance(Object(root), Array());
} else {
return DynamicObjectData::t___clone();
}
}
ObjectData* EvalObjectData::cloneImpl() {
EvalObjectData *e = NEW(EvalObjectData)(m_cls);
if (!parent.isNull()) {
e->setParent(parent->clone());
} else {
cloneSet(e);
}
// Registration is done here because the clone constructor is not
// passed root.
if (root == this) {
RequestEvalState::registerObject(e);
}
return e;
}
Variant &EvalObjectData::___lval(Variant v_name) {
const MethodStatement *ms = getMethodStatement("__get");
if (ms) {
Variant &v = get_globals()->__lvalProxy;
v = ms->invokeInstance(Object(root), CREATE_VECTOR1(v_name));
return v;
} else {
return DynamicObjectData::___lval(v_name);
}
}
Variant &EvalObjectData::___offsetget_lval(Variant v_name) {
const MethodStatement *ms = getMethodStatement("offsetget");
if (ms) {
Variant &v = get_globals()->__lvalProxy;
v = ms->invokeInstance(Object(root), CREATE_VECTOR1(v_name));
return v;
} else {
return DynamicObjectData::___offsetget_lval(v_name);
}
}
///////////////////////////////////////////////////////////////////////////////
}
}
| 33.211055 | 79 | 0.605841 | [
"object",
"vector"
] |
6e35e0bbda849228f1c450c15b629b83466c7e92 | 8,895 | cpp | C++ | GraphicsCore/src/GLCore/Renderer/MeshRenderer.cpp | zixin96/GEngine | 43b63418ade5bdd49e81e16a077866cc3ff6dd06 | [
"Apache-2.0"
] | null | null | null | GraphicsCore/src/GLCore/Renderer/MeshRenderer.cpp | zixin96/GEngine | 43b63418ade5bdd49e81e16a077866cc3ff6dd06 | [
"Apache-2.0"
] | null | null | null | GraphicsCore/src/GLCore/Renderer/MeshRenderer.cpp | zixin96/GEngine | 43b63418ade5bdd49e81e16a077866cc3ff6dd06 | [
"Apache-2.0"
] | null | null | null | #include "glpch.h"
#include "MeshRenderer.h"
#include "GLCore/Util/PerlinNoise.h"
#include "GLCore/Renderer/VertexArray.h"
#include "GLCore/Renderer/Shader.h"
#include "GLCore/Renderer/PolyMesh.h"
#include <glad/glad.h>
#include <glfw/glfw3.h>
#include <glm/gtc/matrix_transform.hpp>
namespace GLCore
{
const glm::vec4 lightColor{ 1.0f, 1.0f, 1.0f, 1.0f };
glm::vec3 lightPos{ 5.0f, 20.0f, 5.0f };
struct MeshVertex
{
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoord;
};
struct RendererData
{
Ref<VertexArray> MeshVertexArray;
Ref<VertexBuffer> MeshVertexBuffer;
Ref<IndexBuffer> MeshIndexBuffer;
Ref<Shader> TerrainShader;
PolyMesh* Mesh;
PerlinNoise Noise;
float* NoiseMap;
uint32_t NoiseMapWidth = 512;
uint32_t NoiseMapHeight = 512;
uint32_t NumLayers = 5;
MeshRenderer::TerrainStats Stats;
Ref<VertexArray> LightSourceVertexArray;
Ref<VertexBuffer> LightSourceVertexBuffer;
Ref<IndexBuffer> LightSourceIndexBuffer;
Ref<Shader> LightSourceShader;
PerspectiveCamera* Cam;
};
static RendererData s_Data;
void MeshRenderer::Init()
{
// Initialize mesh and noise map
s_Data.Mesh = new PolyMesh(5, 5, 200, 200);
int seed = 1996;
s_Data.Noise = PerlinNoise(seed);
s_Data.NoiseMap = new float[s_Data.NoiseMapWidth * s_Data.NoiseMapHeight]{ 0 };
s_Data.TerrainShader = Shader::Create("terrain",
Shader::ReadFileAsString("assets/shaders/terrain.vert.glsl"),
Shader::ReadFileAsString("assets/shaders/terrain.frag.glsl"));
RecomputeTerrainData();
s_Data.MeshVertexArray = VertexArray::Create();
s_Data.MeshVertexBuffer = VertexBuffer::Create(sizeof(MeshVertex) * s_Data.Mesh->numVertices);
s_Data.MeshVertexBuffer->SetLayout({
{ ShaderDataType::Float3, "a_Position" },
{ ShaderDataType::Float3, "a_Normal" },
{ ShaderDataType::Float2, "a_TexCoord" },
});
s_Data.MeshVertexArray->AddVertexBuffer(s_Data.MeshVertexBuffer);
s_Data.MeshIndexBuffer = IndexBuffer::Create(s_Data.Mesh->m_NumFaces * 6, s_Data.Mesh->m_Indices);
s_Data.MeshVertexArray->SetIndexBuffer(s_Data.MeshIndexBuffer);
s_Data.LightSourceShader = Shader::Create("lightSource",
Shader::ReadFileAsString("assets/shaders/lightSource.vert.glsl"),
Shader::ReadFileAsString("assets/shaders/lightSource.frag.glsl"));
s_Data.LightSourceVertexArray = VertexArray::Create();
float cubeVertices[] = {
// front
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// back
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
-1.0, 1.0, -1.0
};
s_Data.LightSourceVertexBuffer = VertexBuffer::Create(sizeof(cubeVertices), cubeVertices);
s_Data.LightSourceVertexBuffer->SetLayout({
{ ShaderDataType::Float3, "a_Position" },
});
s_Data.LightSourceVertexArray->AddVertexBuffer(s_Data.LightSourceVertexBuffer);
uint32_t cubeIndices[] =
{
// front
0, 1, 2,
2, 3, 0,
// right
1, 5, 6,
6, 2, 1,
// back
7, 6, 5,
5, 4, 7,
// left
4, 0, 3,
3, 7, 4,
// bottom
4, 5, 1,
1, 0, 4,
// top
3, 2, 6,
6, 7, 3
};
s_Data.LightSourceIndexBuffer = IndexBuffer::Create(36, cubeIndices);
s_Data.LightSourceVertexArray->SetIndexBuffer(s_Data.LightSourceIndexBuffer);
}
void MeshRenderer::Shutdown()
{
delete s_Data.Mesh;
delete[] s_Data.NoiseMap;
}
void MeshRenderer::BeginScene(PerspectiveCamera& camera)
{
s_Data.Cam = &camera;
s_Data.TerrainShader->Bind();
glm::mat4 viewProj = camera.GetViewProjection();
s_Data.TerrainShader->SetMat4("u_ViewProjection",
viewProj);
s_Data.TerrainShader->SetMat4("u_Model",
glm::scale(glm::mat4(1.0f), glm::vec3(10.0f)));
float timeValue = static_cast<float>(glfwGetTime());
float changing = (sin(timeValue) / 2.0f) + 0.5f;
s_Data.TerrainShader->SetFloat("u_Changing",
changing);
s_Data.TerrainShader->SetVec4("u_LightColor",
lightColor);
s_Data.LightSourceShader->Bind();
s_Data.LightSourceShader->SetMat4("u_ViewProjection",
viewProj);
s_Data.LightSourceShader->SetVec4("u_LightColor",
lightColor);
}
void MeshRenderer::Draw()
{
lightPos.x = 1.0f + sin(static_cast<float>(glfwGetTime())) * 20.0f;
lightPos.z = sin(static_cast<float>(glfwGetTime() / 2.0f)) * 10.0f;
s_Data.TerrainShader->Bind();
s_Data.TerrainShader->SetVec3("u_ViewPos",
s_Data.Cam->GetPosition());
s_Data.TerrainShader->SetVec3("u_LightPos",
lightPos);
// Set dynamic vertex buffer
std::vector<float> vertices;
vertices.reserve(s_Data.Mesh->numVertices * 8);
for (size_t i = 0; i < s_Data.Mesh->numVertices; i++)
{
vertices.push_back(s_Data.Mesh->m_VerticesPos[i].x);
vertices.push_back(s_Data.Mesh->m_VerticesPos[i].y);
vertices.push_back(s_Data.Mesh->m_VerticesPos[i].z);
vertices.push_back(s_Data.Mesh->m_Normals[i].x);
vertices.push_back(s_Data.Mesh->m_Normals[i].y);
vertices.push_back(s_Data.Mesh->m_Normals[i].z);
vertices.push_back(s_Data.Mesh->m_TextureCoords[i].x);
vertices.push_back(s_Data.Mesh->m_TextureCoords[i].y);
}
s_Data.MeshVertexArray->Bind();
s_Data.MeshVertexBuffer->SetData(vertices.data(), static_cast<uint32_t>(vertices.size() * sizeof(float)));
glDrawElements(GL_TRIANGLES, s_Data.MeshIndexBuffer->GetCount(), GL_UNSIGNED_INT, nullptr);
s_Data.LightSourceShader->Bind();
s_Data.LightSourceShader->SetMat4("u_Model",
glm::translate(glm::mat4(1.0f), lightPos) * glm::scale(glm::mat4(1.0f), glm::vec3(1.0f)));
s_Data.LightSourceVertexArray->Bind();
glDrawElements(GL_TRIANGLES, s_Data.LightSourceIndexBuffer->GetCount(), GL_UNSIGNED_INT, nullptr);
}
void MeshRenderer::RecomputeTerrainData()
{
float maxVal = 0;
for (uint32_t j = 0; j < s_Data.NoiseMapHeight; ++j) {
for (uint32_t i = 0; i < s_Data.NoiseMapWidth; ++i) {
float fractal = 0;
float amplitude = 1;
glm::vec3 pt = glm::vec3(i, 0, j) * (1 / 128.f);
for (uint32_t k = 0; k < s_Data.NumLayers; ++k) {
fractal += (1.0f + s_Data.Noise.eval(pt)) * 0.5f * amplitude;
pt *= s_Data.Stats.Lacunarity;
amplitude *= s_Data.Stats.Persistance;
}
if (fractal > maxVal) maxVal = fractal;
s_Data.NoiseMap[j * s_Data.NoiseMapWidth + i] = fractal;
}
}
for (uint32_t i = 0; i < s_Data.NoiseMapWidth * s_Data.NoiseMapHeight; ++i)
{
s_Data.NoiseMap[i] /= maxVal;
}
// displace y coordinate of every vertex
for (uint32_t i = 0; i < s_Data.Mesh->numVertices; ++i) {
glm::vec2 st = s_Data.Mesh->m_TextureCoords[i];
uint32_t x = std::min(static_cast<uint32_t>(st.x * s_Data.NoiseMapWidth), s_Data.NoiseMapWidth - 1);
uint32_t y = std::min(static_cast<uint32_t>(st.y * s_Data.NoiseMapHeight), s_Data.NoiseMapHeight - 1);
s_Data.Mesh->m_VerticesPos[i].y = 2 * s_Data.NoiseMap[y * s_Data.NoiseMapWidth + x] - 1;
s_Data.Mesh->m_Normals[i] = glm::vec3(0.0f, 1.0f, 0.0f);
}
for (uint32_t k = 0, off = 0; k < s_Data.Mesh->m_NumFaces; ++k) {
uint32_t nverts = 4;
const glm::vec3& va = s_Data.Mesh->m_VerticesPos[s_Data.Mesh->verticesArray[off]];
const glm::vec3& vb = s_Data.Mesh->m_VerticesPos[s_Data.Mesh->verticesArray[off + 1]];
const glm::vec3& vc = s_Data.Mesh->m_VerticesPos[s_Data.Mesh->verticesArray[off + nverts - 1]];
glm::vec3 tangent = vb - va;
glm::vec3 bitangent = vc - va;
s_Data.Mesh->m_Normals[s_Data.Mesh->verticesArray[off]] = glm::normalize(glm::cross(bitangent, tangent));
off += nverts;
}
}
MeshRenderer::TerrainStats& MeshRenderer::GetTerrainStats()
{
return s_Data.Stats;
}
}
| 35.58 | 117 | 0.583249 | [
"mesh",
"vector"
] |
6e3cff91318169d2a83b7b93939ab49649af67b6 | 16,504 | cpp | C++ | src/smbioshandler.cpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | src/smbioshandler.cpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | src/smbioshandler.cpp | tohas1986/intel-ipmi-oem | ca99ef5912b9296e09c8f9cb246ce291f9970750 | [
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2018 Intel 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.
*/
#include <commandutils.hpp>
#include <cstdint>
#include <iostream>
#include <ipmid/api.hpp>
#include <ipmid/utils.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <smbioshandler.hpp>
#include <string>
#include <vector>
#include <xyz/openbmc_project/Common/error.hpp>
using InternalFailure =
sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
using level = phosphor::logging::level;
constexpr const char* DBUS_PROPERTIES = "org.freedesktop.DBus.Properties";
constexpr const char* MDRV1_PATH = "/xyz/openbmc_project/Smbios/MDR_V1";
constexpr const char* MDRV1_INTERFACE = "xyz.openbmc_project.Smbios.MDR_V1";
static void register_netfn_smbios_functions() __attribute__((constructor));
ipmi_ret_t cmd_region_status(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
auto requestData = reinterpret_cast<const RegionStatusRequest*>(request);
std::vector<uint8_t> status;
if (*data_len != sizeof(RegionStatusRequest))
{
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
uint8_t regionId = requestData->regionId - 1;
*data_len = 0;
if (regionId >= maxMDRId)
{
phosphor::logging::log<level::ERR>("Invalid region");
return IPMI_CC_PARM_OUT_OF_RANGE;
}
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
std::string service = ipmi::getService(*bus, MDRV1_INTERFACE, MDRV1_PATH);
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
MDRV1_INTERFACE, "RegionStatus");
method.append(regionId);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error get region status",
phosphor::logging::entry("SERVICE=%s", service.c_str()),
phosphor::logging::entry("PATH=%s", MDRV1_PATH));
return IPMI_CC_UNSPECIFIED_ERROR;
}
reply.read(status);
if (status.size() != sizeof(MDRState))
{
phosphor::logging::log<level::ERR>(
"Error get region status, return length invalid");
return IPMI_CC_UNSPECIFIED_ERROR;
}
*data_len = static_cast<size_t>(status.size());
auto dataOut = reinterpret_cast<uint8_t*>(response);
std::copy(&status[0], &status[*data_len], dataOut);
return IPMI_CC_OK;
}
int sdplus_mdrv1_get_property(
const std::string& name,
sdbusplus::message::variant<uint8_t, uint16_t>& value, std::string& service)
{
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
DBUS_PROPERTIES, "Get");
method.append(MDRV1_INTERFACE, name);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error getting property, sdbusplus call failed");
return -1;
}
reply.read(value);
return 0;
}
static int set_regionId(uint8_t regionId, std::string& service)
{
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
DBUS_PROPERTIES, "Set");
sdbusplus::message::variant<uint8_t> value{regionId};
method.append(MDRV1_INTERFACE, "RegionId", value);
auto region = bus->call(method);
if (region.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error setting regionID, sdbusplus call failed");
return -1;
}
return 0;
}
ipmi_ret_t cmd_region_complete(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
auto requestData = reinterpret_cast<const RegionCompleteRequest*>(request);
uint8_t status;
sdbusplus::message::variant<uint8_t, uint16_t> value;
if (*data_len != sizeof(RegionCompleteRequest))
{
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
uint8_t regionId = requestData->regionId - 1;
*data_len = 0;
if (regionId >= maxMDRId)
{
phosphor::logging::log<level::ERR>("Invalid region");
return IPMI_CC_PARM_OUT_OF_RANGE;
}
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
std::string service = ipmi::getService(*bus, MDRV1_INTERFACE, MDRV1_PATH);
if (set_regionId(regionId, service) < 0)
{
phosphor::logging::log<level::ERR>("Error setting regionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (0 > sdplus_mdrv1_get_property("LockPolicy", value, service))
{
phosphor::logging::log<level::ERR>("Error getting lockPolicy");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (regionLockUnlocked == std::get<uint8_t>(value))
{
return IPMI_CC_PARAMETER_NOT_SUPPORT_IN_PRESENT_STATE;
}
if (0 > sdplus_mdrv1_get_property("SessionId", value, service))
{
phosphor::logging::log<level::ERR>("Error getting sessionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (requestData->sessionId != std::get<uint8_t>(value))
{
return IPMI_CC_OEM_SET_IN_PROCESS;
}
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
MDRV1_INTERFACE, "RegionComplete");
method.append(regionId);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error set region complete",
phosphor::logging::entry("SERVICE=%s", service.c_str()),
phosphor::logging::entry("PATH=%s", MDRV1_PATH));
return IPMI_CC_UNSPECIFIED_ERROR;
}
reply.read(status);
if (status != 0)
phosphor::logging::log<level::ERR>(
"Error set region complete, unexpected error");
return IPMI_CC_UNSPECIFIED_ERROR;
return IPMI_CC_OK;
}
ipmi_ret_t cmd_region_read(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
auto requestData = reinterpret_cast<const RegionReadRequest*>(request);
auto responseData = reinterpret_cast<RegionReadResponse*>(response);
sdbusplus::message::variant<uint8_t, uint16_t> regUsedVal;
sdbusplus::message::variant<uint8_t, uint16_t> lockPolicyVal;
std::vector<uint8_t> res;
if (*data_len < sizeof(RegionReadRequest))
{
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
uint8_t regionId = requestData->regionId - 1;
*data_len = 0;
if (regionId >= maxMDRId)
{
phosphor::logging::log<level::ERR>("Invalid region");
return IPMI_CC_PARM_OUT_OF_RANGE;
}
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
std::string service = ipmi::getService(*bus, MDRV1_INTERFACE, MDRV1_PATH);
// TODO to make sure the interface can get correct LockPolicy even
// regionId changed by another task.
if (set_regionId(regionId, service) < 0)
{
phosphor::logging::log<level::ERR>("Error setting regionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (0 > sdplus_mdrv1_get_property("RegionUsed", regUsedVal, service))
{
phosphor::logging::log<level::ERR>("Error getting regionUsed");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (requestData->offset + requestData->length >
std::get<uint16_t>(regUsedVal))
{
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
if (0 > sdplus_mdrv1_get_property("LockPolicy", lockPolicyVal, service))
{
phosphor::logging::log<level::ERR>("Error getting lockPolicy");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (regionLockUnlocked != std::get<uint8_t>(lockPolicyVal))
{
return IPMI_CC_PARAMETER_NOT_SUPPORT_IN_PRESENT_STATE;
}
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
MDRV1_INTERFACE, "RegionRead");
method.append(regionId, requestData->length, requestData->offset);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error read region data",
phosphor::logging::entry("SERVICE=%s", service.c_str()),
phosphor::logging::entry("PATH=%s", MDRV1_PATH));
return IPMI_CC_UNSPECIFIED_ERROR;
}
reply.read(res);
*data_len = responseData->length = res[0];
responseData->updateCount = res[1];
if ((*data_len == 0) || (*data_len >= 254))
{
phosphor::logging::log<level::ERR>(
"Data length send from service is invalid");
*data_len = 0;
return IPMI_CC_RESPONSE_ERROR;
}
*data_len += 2 * sizeof(uint8_t);
std::copy(&res[2], &res[*data_len], responseData->data);
return IPMI_CC_OK;
}
ipmi_ret_t cmd_region_write(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
auto requestData = reinterpret_cast<const RegionWriteRequest*>(request);
uint8_t regionId = requestData->regionId - 1;
std::string res;
std::vector<uint8_t> writeData;
uint16_t index;
uint8_t tmp[255];
size_t minInputLen = &requestData->data[0] - &requestData->sessionId + 1;
if (*data_len < minInputLen)
{ // this command need at least 6 bytes input
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
sdbusplus::message::variant<uint8_t, uint16_t> value;
*data_len = 0;
if (regionId >= maxMDRId)
{
phosphor::logging::log<level::ERR>("Invalid region");
return IPMI_CC_PARM_OUT_OF_RANGE;
}
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
std::string service = ipmi::getService(*bus, MDRV1_INTERFACE, MDRV1_PATH);
if (set_regionId(regionId, service) < 0)
{
phosphor::logging::log<level::ERR>("Error setting regionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (0 > sdplus_mdrv1_get_property("LockPolicy", value, service))
{
phosphor::logging::log<level::ERR>("Error getting lockPolicy");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (regionLockUnlocked == std::get<uint8_t>(value))
{
return IPMI_CC_PARAMETER_NOT_SUPPORT_IN_PRESENT_STATE;
}
if (0 > sdplus_mdrv1_get_property("SessionId", value, service))
{
phosphor::logging::log<level::ERR>("Error getting sessionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (requestData->sessionId != std::get<uint8_t>(value))
{
return IPMI_CC_OEM_SET_IN_PROCESS;
}
std::copy(&(requestData->length), &(requestData->data[requestData->length]),
tmp);
writeData.push_back(regionId);
for (index = 0; index < minInputLen + requestData->length - 2; index++)
{
writeData.push_back(tmp[index]);
}
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
MDRV1_INTERFACE, "RegionWrite");
method.append(writeData);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error write region data",
phosphor::logging::entry("SERVICE=%s", service.c_str()),
phosphor::logging::entry("PATH=%s", MDRV1_PATH));
return IPMI_CC_UNSPECIFIED_ERROR;
}
reply.read(res);
if (res == "NoData")
{
return IPMI_CC_PARM_OUT_OF_RANGE;
}
else if (res != "Success")
{
phosphor::logging::log<level::ERR>(
"Error write region data, unexpected error");
return IPMI_CC_UNSPECIFIED_ERROR;
}
return IPMI_CC_OK;
}
ipmi_ret_t cmd_region_lock(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
auto requestData = reinterpret_cast<const RegionLockRequest*>(request);
uint8_t regionId = requestData->regionId - 1;
sdbusplus::message::variant<uint8_t, uint16_t> value;
auto res = reinterpret_cast<uint8_t*>(response);
uint8_t lockResponse;
if (*data_len != sizeof(RegionLockRequest))
{
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
*data_len = 0;
if (regionId >= maxMDRId)
{
phosphor::logging::log<level::ERR>("Invalid region");
return IPMI_CC_PARM_OUT_OF_RANGE;
}
std::shared_ptr<sdbusplus::asio::connection> bus = getSdBus();
std::string service = ipmi::getService(*bus, MDRV1_INTERFACE, MDRV1_PATH);
if (set_regionId(regionId, service) < 0)
{
phosphor::logging::log<level::ERR>("Error setting regionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (0 > sdplus_mdrv1_get_property("LockPolicy", value, service))
{
phosphor::logging::log<level::ERR>("Error getting lockPolicy");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (requestData->lockPolicy == regionLockUnlocked)
{
if (regionLockUnlocked == std::get<uint8_t>(value))
{
return IPMI_CC_PARAMETER_NOT_SUPPORT_IN_PRESENT_STATE;
}
}
if (regionLockUnlocked != std::get<uint8_t>(value))
{
if (0 > sdplus_mdrv1_get_property("SessionId", value, service))
{
phosphor::logging::log<level::ERR>("Error getting sessionId");
return IPMI_CC_UNSPECIFIED_ERROR;
}
if (requestData->sessionId != std::get<uint8_t>(value))
{
if (requestData->lockPolicy != regionLockStrict)
{
return IPMI_CC_OEM_SET_IN_PROCESS;
}
}
}
auto method = bus->new_method_call(service.c_str(), MDRV1_PATH,
MDRV1_INTERFACE, "RegionLock");
method.append(requestData->sessionId, regionId, requestData->lockPolicy,
requestData->msTimeout);
auto reply = bus->call(method);
if (reply.is_method_error())
{
phosphor::logging::log<level::ERR>(
"Error lock region ",
phosphor::logging::entry("SERVICE=%s", service.c_str()),
phosphor::logging::entry("PATH=%s", MDRV1_PATH));
return IPMI_CC_UNSPECIFIED_ERROR;
}
reply.read(lockResponse);
*data_len = sizeof(lockResponse);
*res = lockResponse;
return IPMI_CC_OK;
}
static void register_netfn_smbios_functions(void)
{
// MDR V1 Command
// <Get MDR Status Command>
ipmi_register_callback(ipmi::intel::netFnApp,
ipmi::intel::app::cmdMdrStatus, NULL,
cmd_region_status, PRIVILEGE_OPERATOR);
// <Update Complete Status Command>
ipmi_register_callback(ipmi::intel::netFnApp,
ipmi::intel::app::cmdMdrComplete, NULL,
cmd_region_complete, PRIVILEGE_OPERATOR);
// <Read MDR Command>
ipmi_register_callback(ipmi::intel::netFnApp, ipmi::intel::app::cmdMdrRead,
NULL, cmd_region_read, PRIVILEGE_OPERATOR);
// <Write MDR Command>
ipmi_register_callback(ipmi::intel::netFnApp, ipmi::intel::app::cmdMdrWrite,
NULL, cmd_region_write, PRIVILEGE_OPERATOR);
// <Lock MDR Command>
ipmi_register_callback(ipmi::intel::netFnApp, ipmi::intel::app::cmdMdrLock,
NULL, cmd_region_lock, PRIVILEGE_OPERATOR);
}
| 33.341414 | 80 | 0.639845 | [
"vector"
] |
6e4014ab0e16c1b445e0ff60d15d8e9bfa935fd3 | 14,746 | cxx | C++ | admin/netui/common/src/applib/applib/uidomain.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/src/applib/applib/uidomain.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/src/applib/applib/uidomain.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
uidomain.cxx
This file contains the class definitions for the UI_DOMAIN class.
The UI_DOMAIN class is somewhat similar to the "normal" DOMAIN class.
In fact, UI_DOMAIN *contains* a DOMAIN object. The only external
difference is that UI_DOMAIN::GetInfo will prompt the user for
the name of a known DC if either the MNetGetDCName or I_MNetGetDCList
API fails.
FILE HISTORY:
KeithMo 30-Aug-1992 Created.
*/
#include "pchapplb.hxx" // Precompiled header
//
// The maximum computer name length accepted by the dialog.
//
#define UI_MAX_COMPUTERNAME_LENGTH MAX_PATH
//
// UI_DOMAIN methods.
//
/*******************************************************************
NAME: UI_DOMAIN :: UI_DOMAIN
SYNOPSIS: UI_DOMAIN class constructor.
ENTRY: wndOwner - The "owning" window.
hc - Help context to be used if a
prompt dialog is necessary.
pszDomainName - Name of the target domain.
fBackupDCsOK - If TRUE, then QueryPDC may
actually return a BDC.
EXIT: The object is constructed.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
UI_DOMAIN :: UI_DOMAIN( PWND2HWND & wndOwner,
ULONG hc,
const TCHAR * pszDomainName,
BOOL fBackupDCsOK )
: BASE(),
_wndOwner( wndOwner ),
_hc( hc ),
_nlsDomainName( pszDomainName ),
_nlsBackupDC(),
_fBackupDCsOK( fBackupDCsOK ),
_pdomain( NULL )
{
UIASSERT( pszDomainName != NULL );
//
// Ensure everything constructed properly.
//
APIERR err;
if( ( ( err = QueryError() ) != NERR_Success ) ||
( ( err = _nlsDomainName.QueryError() ) != NERR_Success ) ||
( ( err = _nlsBackupDC.QueryError() ) != NERR_Success ) )
{
ReportError( err );
return;
}
} // UI_DOMAIN :: UI_DOMAIN
/*******************************************************************
NAME: UI_DOMAIN :: ~UI_DOMAIN
SYNOPSIS: UI_DOMAIN class destructor.
EXIT: The object is destroyed.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
UI_DOMAIN :: ~UI_DOMAIN( VOID )
{
delete _pdomain;
_pdomain = NULL;
} // UI_DOMAIN :: ~UI_DOMAIN
/*******************************************************************
NAME: UI_DOMAIN :: GetInfo
SYNOPSIS: Creates the actual DOMAIN object. May prompt the
user for a known DC in the domain.
EXIT: If successful, then a DOMAIN object is created.
RETURNS: APIERR - Any error encountered.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
APIERR UI_DOMAIN :: GetInfo( VOID )
{
UIASSERT( _pdomain == NULL );
//
// Create the domain object.
//
_pdomain = new DOMAIN( _nlsDomainName );
APIERR err = ( _pdomain == NULL ) ? ERROR_NOT_ENOUGH_MEMORY
: _pdomain->GetInfo();
if( ( err != NERR_DCNotFound ) || !_fBackupDCsOK )
{
return err;
}
//
// We no longer need the domain object.
//
delete _pdomain;
_pdomain = NULL;
//
// Loop until either success or the user bags out.
//
while( TRUE )
{
//
// Prompt the user for a known DC in the domain.
//
BOOL fUserPressedOK = FALSE;
PROMPT_FOR_ANY_DC_DLG * pDlg = new PROMPT_FOR_ANY_DC_DLG( _wndOwner,
_hc,
&_nlsDomainName,
&_nlsBackupDC );
err = ( pDlg == NULL ) ? ERROR_NOT_ENOUGH_MEMORY
: pDlg->Process( &fUserPressedOK );
delete pDlg;
if( err == NERR_Success )
{
//
// Ensure the string didn't barf.
//
err = _nlsBackupDC.QueryError();
}
if( err != NERR_Success )
{
break;
}
if( !fUserPressedOK )
{
//
// The user bagged-out.
//
err = NERR_DCNotFound;
break;
}
//
// Determine if the specified server is really a DC
// in the target domain. We do this by confirming
// that the machine's primary domain is the target
// domain and that the machine's role is backup or
// primary.
//
API_SESSION apisess( _nlsBackupDC );
err = apisess.QueryError();
if( err == NERR_Success )
{
WKSTA_10 wks( _nlsBackupDC );
err = wks.QueryError();
if( err == NERR_Success )
{
err = wks.GetInfo();
}
if( ( err == NERR_Success ) &&
!::I_MNetComputerNameCompare( _nlsDomainName,
wks.QueryWkstaDomain() ) )
{
//
// We now know that the server is indeed in
// the target domain. Now verify that it's
// role is backup or primary.
//
SERVER_1 srv( _nlsBackupDC );
err = srv.QueryError();
if( err == NERR_Success )
{
err = srv.GetInfo();
}
if( err == NERR_Success )
{
if( srv.QueryServerType() &
( SV_TYPE_DOMAIN_CTRL | SV_TYPE_DOMAIN_BAKCTRL ) )
{
//
// It is a backup or primary, so exit the loop
// with err == NERR_Success.
//
break;
}
}
}
}
if( ( err != NERR_Success ) &&
( err != NERR_NameNotFound ) &&
( err != NERR_NetNameNotFound ) &&
( err != ERROR_NOT_SUPPORTED ) &&
( err != ERROR_BAD_NETPATH ) &&
( err != ERROR_LOGON_FAILURE ) )
{
//
// Something fatal happened.
//
break;
}
}
return err;
} // UI_DOMAIN :: GetInfo
/*******************************************************************
NAME: UI_DOMAIN :: QueryName
SYNOPSIS: Returns the name of the target domain.
RETURNS: const TCHAR * - The target domain's name.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
const TCHAR * UI_DOMAIN :: QueryName( VOID ) const
{
const TCHAR * pszName = NULL;
if( _fBackupDCsOK && ( _pdomain == NULL ) )
{
pszName = _nlsDomainName;
}
else
{
pszName = _pdomain->QueryName();
}
return pszName;
} // UI_DOMAIN :: QueryName
/*******************************************************************
NAME: UI_DOMAIN :: QueryPDC
SYNOPSIS: Returns the name of the target domain's PDC. If
the object was constructed with fBackupDCsOK, then
this method may actually return the name of a BDC.
RETURNS: const TCHAR * - The PDC (BDC??) in the domain.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
const TCHAR * UI_DOMAIN :: QueryPDC( VOID ) const
{
const TCHAR * pszPDC = NULL;
if( _fBackupDCsOK && ( _pdomain == NULL ) )
{
pszPDC = _nlsBackupDC;
}
else
{
pszPDC = _pdomain->QueryPDC();
}
return pszPDC;
} // UI_DOMAIN :: QueryPDC
/*******************************************************************
NAME: UI_DOMAIN :: QueryAnyDC
SYNOPSIS: Returns the name of a DC in the target domain.
RETURNS: const TCHAR * - The target domain's name.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
const TCHAR * UI_DOMAIN :: QueryAnyDC( VOID ) const
{
const TCHAR * pszAnyDC = NULL;
if( _fBackupDCsOK && ( _pdomain == NULL ) )
{
pszAnyDC = _nlsBackupDC;
}
else
{
pszAnyDC = _pdomain->QueryAnyDC();
}
return pszAnyDC;
} // UI_DOMAIN :: QueryAnyDC
//
// PROMPT_FOR_ANY_DC_DLG methods.
//
/*******************************************************************
NAME: PROMPT_FOR_ANY_DC_DLG :: PROMPT_FOR_ANY_DC_DLG
SYNOPSIS: PROMPT_FOR_ANY_DC_DLG class constructor.
ENTRY: wndOwner - The "owning" window.
hc - Help context.
pnlsDomainName - Name of the target domain.
pnlsKnownDC - Will receive the DC name entered
by the user.
EXIT: The object is constructed.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
PROMPT_FOR_ANY_DC_DLG :: PROMPT_FOR_ANY_DC_DLG( PWND2HWND & wndOwner,
ULONG hc,
const NLS_STR * pnlsDomainName,
NLS_STR * pnlsKnownDC )
: DIALOG_WINDOW( IDD_PROMPT_FOR_ANY_DC_DLG,
wndOwner ),
_hc( hc ),
_pnlsKnownDC( pnlsKnownDC ),
_sltMessage( this, IDPDC_MESSAGE ),
_sleKnownDC( this, IDPDC_SERVER, UI_MAX_COMPUTERNAME_LENGTH )
{
UIASSERT( pnlsDomainName != NULL );
UIASSERT( pnlsKnownDC != NULL );
//
// Ensure everything constructed properly.
//
if( QueryError() != NERR_Success )
{
return;
}
//
// Load the message string.
//
RESOURCE_STR nlsMessage( IDS_APPLIB_PROMPT_FOR_ANY_DC );
APIERR err = nlsMessage.QueryError();
if( err == NERR_Success )
{
//
// Insert the domain name into the message string.
//
const NLS_STR * apnlsInsertParams[2];
apnlsInsertParams[0] = pnlsDomainName;
apnlsInsertParams[1] = NULL;
err = nlsMessage.InsertParams( apnlsInsertParams );
}
if( err == NERR_Success )
{
_sltMessage.SetText( nlsMessage );
}
if( err != NERR_Success )
{
ReportError( err );
}
} // PROMPT_FOR_ANY_DC_DLG :: PROMPT_FOR_ANY_DC_DLG
/*******************************************************************
NAME: PROMPT_FOR_ANY_DC_DLG :: ~PROMPT_FOR_ANY_DC_DLG
SYNOPSIS: PROMPT_FOR_ANY_DC_DLG class destructor.
EXIT: The object is destroyed.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
PROMPT_FOR_ANY_DC_DLG :: ~PROMPT_FOR_ANY_DC_DLG( VOID )
{
_pnlsKnownDC = NULL;
} // PROMPT_FOR_ANY_DC_DLG :: ~PROMPT_FOR_ANY_DC_DLG
/*******************************************************************
NAME: PROMPT_FOR_ANY_DC_DLG :: OnOK
SYNOPSIS: Invoked when the user presses the OK button.
RETURNS: BOOL - TRUE if we handled the message,
FALSE otherwise.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
BOOL PROMPT_FOR_ANY_DC_DLG :: OnOK( VOID )
{
NLS_STR nlsServer;
APIERR err = nlsServer.QueryError();
if( err == NERR_Success )
{
//
// Get the server from the edit field.
//
err = _sleKnownDC.QueryText( &nlsServer );
}
if( err == NERR_Success )
{
//
// Validate the server name.
//
if( ::I_MNetNameValidate( NULL,
nlsServer,
NAMETYPE_COMPUTER,
0L ) != NERR_Success )
{
_sleKnownDC.SelectString();
_sleKnownDC.ClaimFocus();
err = IDS_APPLIB_PROMPT_DC_INVALID_SERVER;
}
}
if( err == NERR_Success )
{
//
// Update the user's string.
//
err = _pnlsKnownDC->CopyFrom( SZ("\\\\") );
if( err == NERR_Success )
{
err = _pnlsKnownDC->Append( nlsServer );
}
}
if( err == NERR_Success )
{
//
// All OK, dismiss the dialog.
//
Dismiss( TRUE );
}
else
{
//
// An error occurred somewhere along the way.
//
::MsgPopup( this, err );
}
return TRUE;
} // PROMPT_FOR_ANY_DC_DLG :: OnOK
/*******************************************************************
NAME: PROMPT_FOR_ANY_DC_DLG :: QueryHelpContext
SYNOPSIS: Returns the help context.
RETURNS: ULONG - The help context for this dialog.
HISTORY:
KeithMo 30-Aug-1992 Created.
********************************************************************/
ULONG PROMPT_FOR_ANY_DC_DLG :: QueryHelpContext( VOID )
{
return _hc;
} // PROMPT_FOR_ANY_DC_DLG :: QueryHelpContext
| 25.915641 | 83 | 0.427235 | [
"object"
] |
6e4a4d9ae0da0a9198dde3c55d2c916dd63d5093 | 669 | cpp | C++ | Camp_1-2563/Greedy/PeatShare.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_1-2563/Greedy/PeatShare.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_1-2563/Greedy/PeatShare.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
void solve(){
int n;
cin >> n;
vector<int>dp(n+1);
for(int i=1; i<=n; ++i){
cin >> dp[i];
dp[i] += dp[i-1];
}
if(dp[n]%2 == 1){
cout << "NO" ;
return ;
}
for(int i=1; i<=n; ++i){
if(dp[n] - dp[i] == dp[i]){
cout << i ;
return ;
}
}
for(int i=1; i<=n; ++i){
if(dp[lower_bound(dp.begin()+1, dp.end(), dp[n]/2 + dp[i]) - dp.begin()] == dp[n/2] + dp[i]){
cout << i << lower_bound(dp.begin()+1, dp.end(), dp[n]/2 - dp[i]) - dp.begin();
return;
}
}
return ;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int q;
cin >> q;
while(q--){
solve();
cout << endl;
}
return 0;
}
| 15.204545 | 95 | 0.479821 | [
"vector"
] |
6e4fbf2f5660ceb09194d3ebb5b3c8b4015894c3 | 2,916 | cc | C++ | content/browser/background_fetch/storage/get_num_requests_task.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/background_fetch/storage/get_num_requests_task.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/background_fetch/storage/get_num_requests_task.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/background_fetch/storage/get_num_requests_task.h"
#include "content/browser/background_fetch/background_fetch.pb.h"
#include "content/browser/background_fetch/storage/database_helpers.h"
#include "content/browser/background_fetch/storage/get_metadata_task.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
namespace content {
namespace background_fetch {
namespace {
void HandleGetMetadataCallback(
GetNumRequestsTask::NumRequestsCallback callback,
blink::mojom::BackgroundFetchError error,
std::unique_ptr<proto::BackgroundFetchMetadata> metadata) {
if (error != blink::mojom::BackgroundFetchError::NONE) {
std::move(callback).Run(0u);
return;
}
DCHECK(metadata);
std::move(callback).Run(metadata->num_fetches());
}
} // namespace
GetNumRequestsTask::GetNumRequestsTask(
BackgroundFetchDataManager* data_manager,
const BackgroundFetchRegistrationId& registration_id,
RequestType type,
NumRequestsCallback callback)
: DatabaseTask(data_manager),
registration_id_(registration_id),
type_(type),
callback_(std::move(callback)),
weak_factory_(this) {}
GetNumRequestsTask::~GetNumRequestsTask() = default;
void GetNumRequestsTask::Start() {
switch (type_) {
case RequestType::kAny:
GetMetadata();
return;
case RequestType::kPending:
GetRequests(PendingRequestKeyPrefix(registration_id_.unique_id()));
return;
case RequestType::kActive:
GetRequests(ActiveRequestKeyPrefix(registration_id_.unique_id()));
return;
case RequestType::kCompleted:
GetRequests(CompletedRequestKeyPrefix(registration_id_.unique_id()));
return;
}
NOTREACHED();
}
void GetNumRequestsTask::GetMetadata() {
AddDatabaseTask(std::make_unique<GetMetadataTask>(
data_manager(), registration_id_.service_worker_registration_id(),
registration_id_.origin(), registration_id_.developer_id(),
base::BindOnce(&HandleGetMetadataCallback, std::move(callback_))));
Finished(); // Destroys |this|.
}
void GetNumRequestsTask::GetRequests(const std::string& key_prefix) {
service_worker_context()->GetRegistrationUserDataByKeyPrefix(
registration_id_.service_worker_registration_id(), key_prefix,
base::BindOnce(&GetNumRequestsTask::DidGetRequests,
weak_factory_.GetWeakPtr()));
}
void GetNumRequestsTask::DidGetRequests(const std::vector<std::string>& data,
ServiceWorkerStatusCode status) {
DCHECK_EQ(ToDatabaseStatus(status), DatabaseStatus::kOk);
std::move(callback_).Run(data.size());
Finished(); // Destroys |this|.
}
} // namespace background_fetch
} // namespace content
| 32.764045 | 77 | 0.739369 | [
"vector"
] |
6e50a4361c56c5cee64e233f5c40acafc3f76e68 | 2,281 | cpp | C++ | CSES/List_Removals.cpp | aldew5/Competitve-Programming | eb0b93a35af3bd5e806aedc44b835830af01d496 | [
"MIT"
] | 2 | 2020-05-09T15:54:18.000Z | 2021-01-23T22:32:53.000Z | CSES/List_Removals.cpp | aldew5/Competitive-Programming | fc93723fae739d0b06bcf2dbe3b9274584a79a66 | [
"MIT"
] | null | null | null | CSES/List_Removals.cpp | aldew5/Competitive-Programming | fc93723fae739d0b06bcf2dbe3b9274584a79a66 | [
"MIT"
] | null | null | null | /*
ID: alec3
LANG: C++14
PROG:
*/
/*
Credit to Benq
*/
#include <bits/stdc++.h>
#define check(x) cout<<(#x)<<": "<<x<<" " << endl;
#define line cout << "--------------------" << endl;
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ss second
#define ff first
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define mp make_pair
#define FOR(i, a, b) for (int i = a; i < b; i++)
#define F0R(i, a) for (int i = 0; i < (a); i++)
typedef long long ll;
typedef unsigned long long ull;
int pct(int x) { return __builtin_popcount(x); }
using namespace std;
void setIO(string name) {
freopen((name+".in").c_str(),"r",stdin);
freopen((name+".out").c_str(),"w",stdout);
ios_base::sync_with_stdio(0);
}
using namespace std;
const ll MOD = 1e9 + 7;
const ll INF = 1e10 + 70;
const ll MX = 2 * 1e6;
constexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...
return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x))
template <class T, int ...Ns> struct BIT {
T val = 0; void upd(T v) { val += v; }
T query() { return val; }
};
template <class T, int N, int... Ns> struct BIT<T, N, Ns...> {
BIT<T,Ns...> bit[N+1];
template<typename... Args> void upd(int pos, Args... args) { assert(pos > 0);
for (; pos<=N; pos+=pos&-pos) bit[pos].upd(args...); }
template<typename... Args> T sum(int r, Args... args) {
T res=0; for (;r;r-=r&-r) res += bit[r].query(args...);
return res; }
template<typename... Args> T query(int l, int r, Args...
args) { return sum(r,args...)-sum(l-1,args...); }
};
template<class T, int N> int get_kth(const BIT<T,N>& bit, T des) {
assert(des > 0);
int ind = 0;
for (int i = 1<<bits(N); i; i /= 2)
if (ind+i <= N && bit.bit[ind+i].val < des)
des -= bit.bit[ind += i].val;
assert(ind < N); return ind+1;
}
BIT<int, MX> bit;
int main()
{
int n;
cin >> n;
vector<ll> a(n);
for(auto& it : a) cin >> it;
vector<int> p(n);
for(auto& it : p) cin >> it;
for (int i = 1; i<= n; i++){
bit.upd(i, 1);
}
for (auto i : p){
int index = get_kth(bit, i);
cout << a[index-1] << " ";
bit.upd(index, -1);
}
return 0;
}
| 24.010526 | 95 | 0.543183 | [
"vector"
] |
6e77bcb71d83de666ab7f9da062feb89bda0616c | 7,474 | hpp | C++ | src/utils.hpp | tobiasmarschall/mosaicatcher | 42b078ec0964f3711f0f4871065be5157e63eb37 | [
"MIT"
] | 3 | 2019-12-26T01:36:59.000Z | 2021-11-30T00:28:01.000Z | src/utils.hpp | tobiasmarschall/mosaicatcher | 42b078ec0964f3711f0f4871065be5157e63eb37 | [
"MIT"
] | 5 | 2018-01-12T11:56:43.000Z | 2019-01-29T16:09:34.000Z | src/utils.hpp | tobiasmarschall/mosaicatcher | 42b078ec0964f3711f0f4871065be5157e63eb37 | [
"MIT"
] | 4 | 2018-05-24T09:12:56.000Z | 2021-07-02T11:33:28.000Z | /*
Copyright (C) 2017 Sascha Meiers
Distributed under the MIT software license, see the accompanying
file LICENSE.md or http://www.opensource.org/licenses/mit-license.php.
*/
#ifndef utils_hpp
#define utils_hpp
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/algorithm/string.hpp>
#include <htslib/sam.h>
inline uint32_t alignmentLength(bam1_t const* rec) {
uint32_t* cigar = bam_get_cigar(rec);
uint32_t alen = 0;
for (std::size_t i = 0; i < rec->core.n_cigar; ++i)
if (bam_cigar_op(cigar[i]) == BAM_CMATCH) alen+=bam_cigar_oplen(cigar[i]);
return alen;
}
struct CellInfo {
unsigned median_bin_count; /* raw counts */
float mean_bin_count; /* after removal of bad bins */
std::string sample_name;
std::string cell_name;
std::string bam_file;
int32_t id; /* position in conf.f_in */
float nb_p, nb_r, nb_a; /* NB parameters */
bool pass_qc; /* set to false if no (good) SS library */
/* Alignment statistics */
unsigned n_mapped, n_pcr_dups, n_supplementary, n_low_mapq, n_read2s;
unsigned n_counted, n_unmap;
CellInfo() : median_bin_count(0), mean_bin_count(0), id(-1), nb_p(0),
nb_r(0), nb_a(0), pass_qc(true), n_mapped(0), n_pcr_dups(0),
n_supplementary(0), n_low_mapq(0), n_read2s(0), n_counted(0),
n_unmap(0)
{}
};
struct SampleInfo {
std::vector<float> means;
std::vector<float> vars;
float p;
SampleInfo() : p(0.33) {}
};
/**
* Write CellInfo to file
*/
bool write_cell_info(std::string const & f_out,
std::vector<CellInfo> const & cells)
{
std::ofstream out(f_out);
if (out.is_open()) {
out << "# sample: Sample (has multiple cells)" << std::endl;
out << "# cell: Name of the cell." << std::endl;
out << "# mapped: Total number of reads seen" << std::endl;
out << "# suppl: Supplementary, secondary or QC-failed reads (filtered out)" << std::endl;
out << "# dupl: Reads filtered out as PCR duplicates" << std::endl;
out << "# mapq: Reads filtered out due to low mapping quality" << std::endl;
out << "# read2: Reads filtered out as 2nd read of pair" << std::endl;
out << "# good: Reads used for counting." << std::endl;
out << "# pass1: Enough coverage? If false, ignore all columns from now" << std::endl;
out << "# nb_p: Negative Binomial parameter p. Constant for one sample." << std::endl;
out << "# nb_r: Negative Binomial parameter r. We use NB(p,r/2) * NB(p,r/2) in WC states, but NB(p,(1-a)*r)*NB(p,a*r) in WW or CC states." << std::endl;
out << "# nb_a: Negative Binomial parameter a (alpha) used for zero expectation (see above)." << std::endl;
out << "# bam: Bam file of this cell" << std::endl;
out << "sample\tcell\tmedbin\tmapped\tsuppl\tdupl\tmapq\tread2\tgood\tpass1\tnb_p\tnb_r\tnb_a\tbam" << std::endl;
for (CellInfo const & cell : cells) {
out << cell.sample_name << "\t";
out << cell.cell_name << "\t";
out << cell.median_bin_count << "\t";
out << cell.n_mapped << "\t";
out << cell.n_supplementary << "\t";
out << cell.n_pcr_dups << "\t";
out << cell.n_low_mapq << "\t";
out << cell.n_read2s << "\t";
out << cell.n_counted << "\t";
out << cell.pass_qc << "\t";
out << cell.nb_p << "\t";
out << cell.nb_r << "\t";
out << cell.nb_a << "\t";
out << cell.bam_file << std::endl;
}
} else {
std::cerr << "[Warning] Cannot write to " << f_out << std::endl;
return false;
}
return true;
}
template <typename TReturn>
using TMedianAccumulator = boost::accumulators::accumulator_set<TReturn, boost::accumulators::stats<boost::accumulators::tag::median> >;
template <typename TReturn>
using TMeanVarAccumulator = boost::accumulators::accumulator_set<TReturn, boost::accumulators::stats<boost::accumulators::tag::mean, boost::accumulators::tag::variance> >;
double sum(std::vector<double> const & vec)
{
double sum = 0;
for (double d : vec)
sum += d;
return(sum);
}
// from Delly
inline bool get_RG_tag(std::string const & tag,
std::string const& header,
std::string& output,
bool allow_multiple_matches = false)
{
std::set<std::string> values;
typedef std::vector<std::string> TStrParts;
TStrParts lines;
boost::split(lines, header, boost::is_any_of("\n"));
TStrParts::const_iterator itH = lines.begin();
TStrParts::const_iterator itHEnd = lines.end();
for(;itH!=itHEnd; ++itH) {
if (itH->find("@RG")==0) {
TStrParts keyval;
boost::split(keyval, *itH, boost::is_any_of("\t "));
TStrParts::const_iterator itKV = keyval.begin();
TStrParts::const_iterator itKVEnd = keyval.end();
for(;itKV != itKVEnd; ++itKV) {
size_t sp = itKV->find(":");
if (sp != std::string::npos) {
std::string field = itKV->substr(0, sp);
if (field == tag) {
std::string value = itKV->substr(sp+1);
values.insert(value);
}
}
}
}
}
if (values.size() == 1) {
output = *(values.begin());
return true;
} else if (values.size() > 1) {
if (allow_multiple_matches) {
output = *(values.begin());
return true;
} else {
output = "";
return false;
}
} else {
output = "";
return false;
}
}
/**
* template <class InputIter, class ForwardIter, class BinaryPredicate, class BinaryFunction> ForwardIter reduce_adjacent(InputIter first, InputIter last,ForwardIter result, BinaryPredicate _bool_mergeable, BinaryFunction _merge_func)
* STL-style algorithm to merge/reduce adjacent elements (if they are mergeable) and return a shortened list
*
* @param first input iterator.
* @param end input iterator end.
* @param result output iterator. Can point to *first to do inplace operations.
* @param _bool_mergeable Function stating whether two consecutive elements are mergeable.
* @param _merge_func Funciton to merge to consecutive elements. Must return same type.
*/
template <class InputIter, class ForwardIter, class BinaryPredicate, class BinaryFunction>
ForwardIter reduce_adjacent(InputIter first, InputIter last,
ForwardIter result,
BinaryPredicate _bool_mergeable,
BinaryFunction _merge_func)
{
if (first == last) return result; // skip empty container
auto elem = *first; // copy first element anyways.
while (++first != last) { // loop skippes first elem
if ( !_bool_mergeable(elem, *first) ) {
*(result++) = elem;
elem = *first;
} else {
elem = _merge_func(elem, *first);
}
}
*(result++) = elem;
return result;
}
#endif /* utils_hpp */
| 35.932692 | 234 | 0.582018 | [
"vector"
] |
6e77f1c9746d9c2deb79fa1ee6437cbbaf5df42d | 1,417 | cpp | C++ | USACO/friday.cpp | tapaswenipathak/Competitive-Programming | 97bba0f2ccdf587df93244a027050489f0905480 | [
"MIT"
] | 2 | 2019-04-20T18:03:20.000Z | 2019-08-17T21:20:47.000Z | USACO/friday.cpp | tapaswenipathak/Competitive-Programming | 97bba0f2ccdf587df93244a027050489f0905480 | [
"MIT"
] | null | null | null | USACO/friday.cpp | tapaswenipathak/Competitive-Programming | 97bba0f2ccdf587df93244a027050489f0905480 | [
"MIT"
] | 1 | 2019-04-20T18:03:26.000Z | 2019-04-20T18:03:26.000Z |
/*
ID : tapaswe1
PROG : friday
LANG : C++
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cctype>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <climits>
#include <cstdlib>
#include <fstream>
#define FORALL(i,a,b) for(int i=a;i<b;++i)
#define FOREACH(i,a,b) for(int i=a;i<=b;++i)
#define MAX(a,b) ( (a) > (b) ? (a) : (b))
#define MIN(a,b) ( (a) < (b) ? (a) : (b))
#define CHECKBIT(n,b) ( (n >> b) & 1)
#define ODD(a) (a&1?1:0)
#define EVEN(a) (a&1?0:1)
#define MOD 1000000007
#define PI 3.1415925535897932384626433832795
#define lli long long int
#define ulli unsigned long long int
using namespace std;
int main()
{
//ios_base::sync_with_stdio(0);
ofstream fout ("friday.out");
ifstream fin ("friday.in");
int a, val = 3;
fin >> a;
int days_in_month[12] = {31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
int output[7] = {0};
for (int year = 1900; (year < (1900 + a)); ++ year){
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
days_in_month[2] = 29;
}
for (int month = 0; month < 12; ++month){
val = (val + days_in_month[month]) % 7;
++output[val];
}
days_in_month[2] = 28;
}
for (int i = 0; i < 6; ++i){
fout << output[(i + 6) % 7] << " ";
}
fout << output[5] << "\n";
fin.close();
fout.close();
return 0;
}
| 21.149254 | 74 | 0.564573 | [
"vector"
] |
6e7965c7b6242a5bb0c1f80ca2d39b0cf62bad61 | 2,741 | cxx | C++ | visualization/Brush.cxx | RENCI/Segmentor | 9a8cd6679626b656790c0fdc60892de531c3e80b | [
"MIT"
] | 11 | 2021-01-17T04:52:29.000Z | 2022-02-25T20:42:41.000Z | visualization/Brush.cxx | RENCI/Segmentor | 9a8cd6679626b656790c0fdc60892de531c3e80b | [
"MIT"
] | 42 | 2021-01-15T14:17:16.000Z | 2022-03-21T23:30:25.000Z | visualization/Brush.cxx | RENCI/Segmentor | 9a8cd6679626b656790c0fdc60892de531c3e80b | [
"MIT"
] | null | null | null | #include "Brush.h"
#include <vtkActor.h>
#include <vtkCutter.h>
#include <vtkExtractVOI.h>
#include <vtkGeometryFilter.h>
#include <vtkImageCast.h>
#include <vtkImageChangeInformation.h>
#include <vtkImageData.h>
#include <vtkPlane.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkThreshold.h>
#include <vtkTransform.h>
#include "vtkImageDataCells.h"
Brush::Brush() {
radius = 1;
cast = vtkSmartPointer<vtkImageCast>::New();
cast->SetOutputScalarTypeToUnsignedShort();
voi = vtkSmartPointer<vtkExtractVOI>::New();
voi->SetInputConnection(cast->GetOutputPort());
vtkSmartPointer<vtkImageChangeInformation> info = vtkSmartPointer<vtkImageChangeInformation>::New();
info->CenterImageOn();
info->SetInputConnection(voi->GetOutputPort());
vtkSmartPointer<vtkImageDataCells> cells = vtkSmartPointer<vtkImageDataCells>::New();
cells->SetInputConnection(info->GetOutputPort());
vtkSmartPointer<vtkThreshold> threshold = vtkSmartPointer<vtkThreshold>::New();
threshold->ThresholdByUpper(1);
threshold->SetInputConnection(cells->GetOutputPort());
vtkSmartPointer<vtkGeometryFilter> geometry = vtkSmartPointer<vtkGeometryFilter>::New();
geometry->SetInputConnection(threshold->GetOutputPort());
vtkSmartPointer<vtkPlane> plane = vtkSmartPointer<vtkPlane>::New();
plane->SetNormal(0, 0, 1);
vtkSmartPointer<vtkCutter> cut = vtkSmartPointer<vtkCutter>::New();
cut->SetCutFunction(plane);
cut->SetInputConnection(geometry->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->ScalarVisibilityOff();
mapper->SetInputConnection(cut->GetOutputPort());
actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(1, 1, 1);
actor->GetProperty()->SetOpacity(0.25);
actor->GetProperty()->LightingOff();
actor->GetProperty()->SetLineWidth(2);
actor->VisibilityOff();
actor->PickableOff();
}
Brush::~Brush() {
}
void Brush::UpdateData(vtkImageData* data) {
cast->SetInputDataObject(data);
UpdateBrush();
}
void Brush::SetRadius(int BrushRadius) {
radius = BrushRadius;
UpdateBrush();
}
int Brush::GetRadius() {
return radius;
}
vtkActor* Brush::GetActor() {
return actor;
}
void Brush::UpdateBrush() {
if (!voi->GetInput() || radius <= 1) return;
int w = radius * 2 - 2;
int c = radius - 1;
int r2 = c * c;
voi->SetVOI(0, w, 0, w, 0, 0);
voi->Update();
vtkImageData* data = voi->GetOutput();
for (int x = 0; x <= w; x++) {
for (int y = 0; y <= w; y++) {
int xd = c - x;
int yd = c - y;
int d2 = xd * xd + yd * yd;
unsigned short* p = static_cast<unsigned short*>(data->GetScalarPointer(x, y, 0));
*p = d2 <= r2 ? 1 : 0;
}
}
data->Modified();
} | 24.918182 | 101 | 0.711054 | [
"geometry"
] |
6e7972b566daa42d68da24d3d0c86f6e1e9e8442 | 17,121 | cpp | C++ | tf2v2/ESP.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | 1 | 2021-11-14T17:29:05.000Z | 2021-11-14T17:29:05.000Z | tf2v2/ESP.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | null | null | null | tf2v2/ESP.cpp | matej0/source-engine-internals | c2d2014245e1ea901854280bf5f0b30f3c5aaa95 | [
"MIT"
] | 5 | 2021-09-18T01:13:24.000Z | 2021-12-18T22:20:53.000Z | #include "ESP.h"
#include "CDrawManager.h"
#include "CMenu.h"
#include "Aimbot.h"
CEsp gESP;
CRadar gRadar;
void CEsp::Think(CBaseEntity* pLocal)
{
//gESP.m_Players.clear();
//gESP.m_Buildings.clear();
for (int i = 1; i <= gInts.EntList->GetHighestEntityIndex(); i++)
{
CBaseEntity* pEntity = GetBaseEntity(i);
if (!pEntity || pEntity == pLocal)
continue;
if (pEntity->GetTeam() == pLocal->GetTeam() && !gPlayerVars.bTeammates)
continue;
if (!pEntity->IsAlive() || pEntity->IsDormant())
continue;
Players(pLocal, pEntity);
Buildings(pLocal, pEntity);
//this is completely unneccessary but i just wanted to see if it would work.
/*if (pEntity->IsPlayer()) //if entity is player, populate player vector.
{
IEspPlayerData playerData;
playerData.m_pEntity = pEntity;
playerData.m_Index = i;
gESP.m_Players.emplace_back(playerData);
}
else if (pEntity->IsBuilding()) //same as above.
{
IEspBuildingsData buildingsData;
buildingsData.m_pEntity = pEntity;
buildingsData.m_Index = i;
gESP.m_Buildings.emplace_back(buildingsData);
}
else
{
if (gPlayerVars.bOther)
{
static DWORD dwClr;
switch (pEntity->GetTeam())
{
case AXIS:
dwClr = COLOR_DOD_GREEN; break;
case WEHRMACHT:
dwClr = COLOR_DOD_RED; break;
}
Vector vS;
if (!gDrawManager.WorldToScreen(pEntity->GetAbsOrigin(), vS))
return;
switch (pEntity->GetClientClass()->iClassID)
{
case CTFGrenadePipebombProjectile:
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, vS.x, vS.y, dwClr, "<->"); break;
case CTFProjectile_Rocket:
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, vS.x, vS.y, dwClr, "[==]"); break;
case CCaptureFlag:
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, vS.x, vS.y, dwClr, "Capture"); break;
case CTFProjectile_Arrow:
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, vS.x, vS.y, dwClr, "[->]"); break;
}
}
}*/
}
}
void Skeleton(CBaseEntity* pEntity)
{
if (!gPlayerVars.bAimbot)
return; //we use the aimbot matrix.
int parent;
studiohdr_t* pHdr;
mstudiobone_t* pStudioBone;
matrix3x4 matrix[128];
Vector vBonePos, vParentPos, vBonePosScreen, vParentPosScreen;
const DWORD* dwModel = pEntity->GetModel();
if (!dwModel)
return;
pHdr = gInts.ModelInfo->GetStudiomodel(dwModel);
if (!pHdr)
return;
//get bone matrix.
//if (!pEntity->SetupBones(matrix, 128, 0x0007FF00, gInts.Globals->curtime))
// return;
for (int i{ }; i < pHdr->numbones; ++i)
{
pStudioBone = pHdr->GetBone(i);
if (!pStudioBone || !(pStudioBone->flags & 256))
continue;
//get parent bone.
parent = pStudioBone->parent;
if (parent == -1)
continue;
vBonePos = { gAim.m_Matrix[pEntity->GetIndex()][i][0][3], gAim.m_Matrix[pEntity->GetIndex()][i][1][3], gAim.m_Matrix[pEntity->GetIndex()][i][2][3] };
vParentPos = { gAim.m_Matrix[pEntity->GetIndex()][parent][0][3], gAim.m_Matrix[pEntity->GetIndex()][parent][1][3], gAim.m_Matrix[pEntity->GetIndex()][parent][2][3] };
if (gDrawManager.WorldToScreen(vBonePos, vBonePosScreen) && gDrawManager.WorldToScreen(vParentPos, vParentPosScreen))
gDrawManager.DrawLine(vBonePosScreen.x, vBonePosScreen.y, vParentPosScreen.x, vParentPosScreen.y, COLORCODE(255, 255, 255, 200));
}
}
void CEsp::Players(CBaseEntity* pLocal, CBaseEntity* pEntity)
{
if (!gPlayerVars.bEspPlayers)
return;
if (!pEntity || !pEntity->IsPlayer())
return;
int x, y, w, h;
if (!gDrawManager.CalculatePlayerBounds(pEntity, x, y, w, h))
return;
player_info_t info;
gInts.Engine->GetPlayerInfo(pEntity->GetIndex(), &info);
int nOffset = 0;
static DWORD dwPlayerColor;
if (gPlayerVars.bTeamColored)
{
switch (pEntity->GetTeam())
{
case AXIS:
dwPlayerColor = COLOR_DOD_GREEN; break;
case WEHRMACHT:
dwPlayerColor = COLOR_DOD_RED; break;
}
}
else
{
dwPlayerColor = COLOR_WHITE;
}
if (gPlayerVars.bBox)
{
gDrawManager.OutlineRect(x - 1, y - 1, w + 2, h + 2, COLORCODE(0, 0, 0, 255));
gDrawManager.OutlineRect(x, y, w, h, dwPlayerColor);
gDrawManager.OutlineRect(x + 1, y + 1, w - 2, h - 2, COLORCODE(0, 0, 0, 255));
}
if (gPlayerVars.bName)
{
//wchar_t szString[1024];
//memset(szString, 0, sizeof(wchar_t) * 1024);
//if (MultiByteToWideChar(CP_UTF8, 0, info.name, MAX_PLAYER_NAME_LENGTH, szString, 1024))
// gDrawManager.DrawString(xP, yP - 15, dColor, szString);
//else
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, (x + (w / 2)), y - 15, COLOR_WHITE, "%s", info.name);
}
if (gPlayerVars.bHealth)
{
int iMaxHP = pEntity->GetMaxHealth();
int iHP = pEntity->GetHealth();
int iGreen = (255 * pEntity->GetHealth()) / iMaxHP;
int iRed = 255 - iGreen;
if (iHP > iMaxHP)
{
iHP = iMaxHP;
iGreen = 255, iRed = 0;
}
int iFill = (int)std::round(h * iHP / iMaxHP);
gDrawManager.DrawRect(x - 8, y - 1, 5, h + 2, COLORCODE(25, 25, 25, 230));
gDrawManager.DrawRect(x - 7, y + h - iFill, 3, iFill, COLORCODE(iRed, iGreen, 0, 240));
}
if (gPlayerVars.bWeapon)
{
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, (x + (w / 2)), y + h, COLOR_WHITE, gDrawManager.szCurrentWeaponName(pEntity));
}
if (gPlayerVars.bSkeleton)
Skeleton(pEntity);
if (pEntity->GetClassNum() == TF2_Medic)
{
CBaseCombatWeapon* pMedigun = pEntity->GetWeaponFromSlot(TF_WEAPONSLOT_SECONDARY);
if (pMedigun)
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y + nOffset, COLOR_WHITE, "%.0f%%", pMedigun->GetUberCharge() * 100);
nOffset += 15;
}
}
if (gPlayerVars.bConditions)
{
std::vector<std::string> rgConds = { };
//wow.
if (pEntity->GetCond() & TFCond_Ubercharged || pEntity->GetCond() & TFCond_UberchargeFading)
rgConds.push_back("UBERCHARGED");
if (pEntity->GetCond() & TFCond_Cloaked)
rgConds.push_back("CLOAKED");
if (pEntity->GetCond() & TFCond_Zoomed)
rgConds.push_back("ZOOMED");
if (pEntity->GetCond() & TFCond_Jarated)
rgConds.push_back("JARATE");
if (pEntity->GetCond() & TFCond_Milked)
rgConds.push_back("MILK");
if (pEntity->GetCond() & TFCond_Disguised)
rgConds.push_back("DISGUISED");
if (pEntity->GetCond() & TFCond_Disguising)
rgConds.push_back("DISGUISING");
if (pEntity->GetCond() & TFCond_Bonked)
rgConds.push_back("BONKED");
if (pEntity->GetCond() & TFCond_Kritzkrieged)
rgConds.push_back("KRITZ");
if (pEntity->GetCond() & TFCond_Overhealed)
rgConds.push_back("OVERHEALED");
for (size_t i = 0; i < rgConds.size(); i++)
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y + (i * 15) + nOffset, COLOR_WHITE, rgConds[i].c_str());
nOffset += 15;
}
}
}
void CEsp::Buildings(CBaseEntity* pLocal, CBaseEntity* pEntity)
{
//this function is a mess if ive ever seen one.
if (!gPlayerVars.bEspBuildings)
return;
if (!pEntity || !pEntity->IsBuilding())
return;
int x, y, w, h;
if (!gDrawManager.CalculateBounds(pEntity, x, y, w, h))
return;
static DWORD dwPlayerColor;
if (gPlayerVars.bTeamColored)
{
switch (pEntity->GetTeam())
{
case AXIS:
dwPlayerColor = COLOR_DOD_GREEN; break;
case WEHRMACHT:
dwPlayerColor = COLOR_DOD_RED; break;
}
}
else
{
dwPlayerColor = COLOR_WHITE;
}
switch (pEntity->GetClientClass()->iClassID)
{
case CObjectSentrygun:
{
CTFObjectSentryGun* pSentryGun = reinterpret_cast<CTFObjectSentryGun*>(pEntity);
if (pSentryGun && pSentryGun->IsAlive())
{
if (gPlayerVars.bBoxBuildings)
{
gDrawManager.OutlineRect(x - 1, y - 1, w + 2, h + 2, COLORCODE(0, 0, 0, 255));
gDrawManager.OutlineRect(x, y, w, h, dwPlayerColor);
gDrawManager.OutlineRect(x + 1, y + 1, w - 2, h - 2, COLORCODE(0, 0, 0, 255));
}
if (gPlayerVars.bNameBuildings)
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, x + (w / 2), (y - 15), COLOR_WHITE, "Sentry");
if (gPlayerVars.bBuildingLevel)
{
if (!pSentryGun->IsBuilding())
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y, COLOR_WHITE, "Level: %i", pSentryGun->GetLevel());
}
}
if (gPlayerVars.bHealthBuildings)
{
int iHP = pSentryGun->GetHealth();
int iMaxHP = pSentryGun->GetMaxHealth();
int iGreen = (255 * iHP) / iMaxHP;
int iRed = 255 - iGreen;
gDrawManager.DrawRect(x - 1, y + h + 4, w + 2, 5, COLORCODE(25, 25, 25, 230));
gDrawManager.DrawRect(x, y + h + 5, (pSentryGun->GetHealth() * w) / pSentryGun->GetMaxHealth(), 3, COLORCODE(iRed, iGreen, 0, 240));
}
}
} break;
case CObjectDispenser:
{
CTFObjectDispenser* pDispenser = reinterpret_cast<CTFObjectDispenser*>(pEntity);
if (pDispenser && pDispenser->IsAlive())
{
if (gPlayerVars.bBoxBuildings)
{
gDrawManager.OutlineRect(x - 1, y - 1, w + 2, h + 2, COLORCODE(0, 0, 0, 255));
gDrawManager.OutlineRect(x, y, w, h, dwPlayerColor);
gDrawManager.OutlineRect(x + 1, y + 1, w - 2, h - 2, COLORCODE(0, 0, 0, 255));
}
if (gPlayerVars.bNameBuildings)
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, x + (w / 2), (y - 15), COLOR_WHITE, "Dispenser");
if (gPlayerVars.bBuildingLevel)
{
if (!pDispenser->IsBuilding())
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y, COLOR_WHITE, "Level: %i", pDispenser->GetLevel());
}
if (gPlayerVars.bHealthBuildings)
{
int iHP = pDispenser->GetHealth();
int iMaxHP = pDispenser->GetMaxHealth();
int iGreen = (255 * iHP) / iMaxHP;
int iRed = 255 - iGreen;
gDrawManager.DrawRect(x - 1, y + h + 4, w + 2, 5, COLORCODE(25, 25, 25, 230));
gDrawManager.DrawRect(x, y + h + 5, (pDispenser->GetHealth() * w) / pDispenser->GetMaxHealth(), 3, COLORCODE(iRed, iGreen, 0, 240));
}
}
} break;
case CObjectTeleporter:
{
CTFObjectTeleporter* pTeleporter = reinterpret_cast<CTFObjectTeleporter*>(pEntity);
if (pTeleporter && pTeleporter->IsAlive())
{
if (gPlayerVars.bBoxBuildings)
{
gDrawManager.OutlineRect(x - 1, y - 1, w + 2, h + 2, COLORCODE(0, 0, 0, 255));
gDrawManager.OutlineRect(x, y, w, h, dwPlayerColor);
gDrawManager.OutlineRect(x + 1, y + 1, w - 2, h - 2, COLORCODE(0, 0, 0, 255));
}
if (gPlayerVars.bNameBuildings)
gDrawManager.DrawStringA(gDrawManager.GetAltFont(), true, x + (w / 2), (y - 15), COLOR_WHITE, "Teleporter");
if (gPlayerVars.bBuildingLevel)
{
if (!pTeleporter->IsBuilding())
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y, COLOR_WHITE, "Level: %i", pTeleporter->GetLevel());
}
}
if (gPlayerVars.bHealthBuildings)
{
int iHP = pTeleporter->GetHealth();
int iMaxHP = pTeleporter->GetMaxHealth();
int iGreen = (255 * iHP) / iMaxHP;
int iRed = 255 - iGreen;
gDrawManager.DrawRect(x - 1, y + h + 4, w + 2, 5, COLORCODE(25, 25, 25, 230));
gDrawManager.DrawRect(x, y + h + 5, (pTeleporter->GetHealth() * w) / pTeleporter->GetMaxHealth(), 3, COLORCODE(iRed, iGreen, 0, 240));
}
if (gPlayerVars.bNameBuildings)
{
switch (pTeleporter->GetObjectMode())
{
case TFObjectMode_Entrance:
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y + 15, COLOR_WHITE, "Tele in");
} break;
case TFObjectMode_Exit:
{
gDrawManager.DrawString(gDrawManager.GetAltFont(), x + w + 3, y + 15, COLOR_WHITE, "Tele out");
}break;
}
}
}
} break;
}
}
void CEsp::FakeLagIndicator(CBaseEntity* pLocal)
{
if (!pLocal || !pLocal->IsAlive())
return;
if (!pLocal->GetActiveWeapon())
return;
int x, y;
gInts.Engine->GetScreenSize(x, y);
x /= 2;
y /= 2;
if (GetAsyncKeyState(VK_XBUTTON1))
{
gDrawManager.DrawRect(x - 30, y + 25, 60, 6, COLORCODE(25, 25, 25, 200));
CNetChannel* pNetChannel = gInts.Engine->GetNetChannelInfo();
int w;
if (pNetChannel->m_nChokedPackets)
w = 60 * pNetChannel->m_nChokedPackets / gPlayerVars.iFakeLagAmount;
else
w = 0;
gDrawManager.DrawRect(x - 30, y + 25, w, 6, COLORCODE(255, 120, 25, 250));
}
}
void CEsp::SpectatorsList(CBaseEntity* pLocal)
{
if (!gPlayerVars.bSpecList)
return;
int x, y;
gInts.Engine->GetScreenSize(x, y);
x /= 2;
std::vector< std::string > spectators;
int h = 25;
for (int i{ 1 }; i <= gInts.Engine->GetMaxClients(); ++i)
{
CBaseEntity* player = GetBaseEntity(i);
if (!player)
continue;
if (player == pLocal)
continue;
if (player->IsDormant())
continue;
if (player->IsAlive())
continue;
if (player->GetObserverTarget() != pLocal)
continue;
if (player->GetTeam() != pLocal->GetTeam())
continue;
player_info_t info;
if (!gInts.Engine->GetPlayerInfo(i, &info))
continue;
spectators.push_back(std::string(info.name).substr(0, 24));
}
size_t total_size = spectators.size() * (h - 1);
for (size_t i{ }; i < spectators.size(); ++i)
{
const std::string& name = spectators[i];
gDrawManager.DrawStringA(gDrawManager.GetFont(), true, x, 100 + (total_size / 2) + (i * (h - 1)), COLORCODE(255, 255, 255, 255), name.c_str());
}
}
void CRadar::DrawRadarPoint(Vector vOriginX, Vector vOriginY, Vector qAngle, CBaseEntity *pBaseEntity, DWORD dwTeamColor)
{
if (!gPlayerVars.bRadar)
return;
float flDeltaX = vOriginX.x - vOriginY.x;
float flDeltaY = vOriginX.y - vOriginY.y;
float flAngle = qAngle.y;
float flYaw = (flAngle)* (PI / 180.0);
float flMainViewAngles_CosYaw = cos(flYaw);
float flMainViewAngles_SinYaw = sin(flYaw);
// rotate
float x = flDeltaY * (-flMainViewAngles_CosYaw) + flDeltaX * flMainViewAngles_SinYaw;
float y = flDeltaX * (-flMainViewAngles_CosYaw) - flDeltaY * flMainViewAngles_SinYaw;
float flRange = 2000;
if (fabs(x) > flRange || fabs(y) > flRange)
{
// clipping
if (y > x)
{
if (y > -x)
{
x = flRange * x / y;
y = flRange;
}
else
{
y = -flRange * y / x;
x = -flRange;
}
}
else
{
if (y > -x)
{
y = flRange * y / x;
x = flRange;
}
else
{
x = -flRange * x / y;
y = -flRange;
}
}
}
int iScreenX = gPlayerVars.iRadarPosX + int(x / flRange * gPlayerVars.iRadarSize);
int iScreenY = gPlayerVars.iRadarPosY + int(y / flRange * gPlayerVars.iRadarSize);
gDrawManager.DrawRect(iScreenX - 3, iScreenY - 3, 7, 7, COLORCODE(0, 0, 0, 255));
gDrawManager.DrawRect(iScreenX - 2, iScreenY - 2, 5, 5, dwTeamColor);
}
//===================================================================================
void CRadar::DrawRadarBack()
{
GetCursorPos(&Mouse);
int iSize = gPlayerVars.iRadarSize;
int iCenterX = gPlayerVars.iRadarPosX;
int iCenterY = gPlayerVars.iRadarPosY;
if (gMenu.MouseInRegion(iCenterX - iSize, iCenterY - iSize, iSize * 2, iSize * 2) && GetAsyncKeyState(VK_LBUTTON))
{
if (!bRadarPos)
{
SavedRadarX = Mouse.x - gPlayerVars.iRadarPosX;
SavedRadarY = Mouse.y - gPlayerVars.iRadarPosY;
bRadarPos = true;
}
gPlayerVars.iRadarPosX = Mouse.x;
gPlayerVars.iRadarPosY = Mouse.y;
gPlayerVars.iRadarPosX -= SavedRadarX;
gPlayerVars.iRadarPosY -= SavedRadarY;
}
else
{
bRadarPos = false;
}
if (gPlayerVars.bRadar)
{
gDrawManager.OutlineRect(iCenterX - iSize - 7, iCenterY - iSize - 17, 2 * iSize + 16, 2 * iSize + 25, COLORCODE(0, 0, 0, 150));
gDrawManager.DrawRect(iCenterX - iSize - 6, iCenterY - iSize - 16, 2 * iSize + 14, 2 * iSize + 23, COLORCODE(255, 120, 25, 250));
gDrawManager.DrawString(gDrawManager.GetFont(), iCenterX - iSize, iCenterY - iSize - 16, COLOR_WHITE, "Radar");
gDrawManager.DrawRect(iCenterX - iSize, iCenterY - iSize, 2 * iSize + 2, 2 * iSize + 2, COLORCODE(30, 30, 30, 255));
gDrawManager.DrawRect(iCenterX, iCenterY - iSize, 1, 2 * iSize + 2, COLORCODE(255, 120, 25, 250));
gDrawManager.DrawRect(iCenterX - iSize, iCenterY, 2 * iSize + 2, 1, COLORCODE(255, 120, 25, 250));
}
}
void CRadar::Think(CBaseEntity* pLocal)
{
if (!gPlayerVars.bRadar)
return;
//Draw the radar before drawing the player.
DrawRadarBack();
for (int i = 1; i <= gInts.Engine->GetMaxClients(); i++)
{
CBaseEntity* pEntity = GetBaseEntity(i);
if (!pEntity)
continue;
if (!pEntity->IsAlive() || pEntity->IsDormant())
continue;
if (pEntity->GetTeam() == pLocal->GetTeam() && !gPlayerVars.bTeammates)
continue;
static DWORD dwColor;
switch (pEntity->GetTeam())
{
case AXIS:
dwColor = COLOR_DOD_GREEN; break;
case WEHRMACHT:
dwColor = COLOR_DOD_RED; break;
}
DrawRadarPoint(pEntity->GetAbsOrigin(), pLocal->GetAbsOrigin(), pLocal->GetAbsAngles(), pEntity, dwColor);
}
}
| 27.047393 | 169 | 0.630804 | [
"vector"
] |
6e7d879dde3e6f6c498db9d4f0b4a21527dfc1bf | 574 | hpp | C++ | include/BoardComputer.hpp | asiajo/Battlefield | 6734f7dd29930b0bc8c243505e879703b27e8a15 | [
"Apache-2.0"
] | null | null | null | include/BoardComputer.hpp | asiajo/Battlefield | 6734f7dd29930b0bc8c243505e879703b27e8a15 | [
"Apache-2.0"
] | null | null | null | include/BoardComputer.hpp | asiajo/Battlefield | 6734f7dd29930b0bc8c243505e879703b27e8a15 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Board.hpp"
#include "Position.hpp"
#include <random>
#include <cstdlib> //abs
class BoardComputer : public Board
{
std::vector<std::vector<FieldStatus>> hideBattleField;
Position generatePosition(const int dirX, const int len);
bool generateShip(const int len);
bool checkSurrounding(const Position& p) const;
void fillComputerField();
public:
BoardComputer();
void crossFields();
void setVisibleField(const Position& p, const FieldStatus val);
FieldStatus getVisibleFieldInfo(const Position& p) const;
}; | 26.090909 | 67 | 0.722997 | [
"vector"
] |
6e814df35e68a27d24659156f75e3f7aca664e21 | 2,406 | hpp | C++ | include/protoc/msgpack/detail/decoder.hpp | skyformat99/protoc | f0a72275c92bedc8492524cb98cc24c5821c4f11 | [
"BSL-1.0"
] | null | null | null | include/protoc/msgpack/detail/decoder.hpp | skyformat99/protoc | f0a72275c92bedc8492524cb98cc24c5821c4f11 | [
"BSL-1.0"
] | null | null | null | include/protoc/msgpack/detail/decoder.hpp | skyformat99/protoc | f0a72275c92bedc8492524cb98cc24c5821c4f11 | [
"BSL-1.0"
] | null | null | null | #ifndef PROTOC_MSGPACK_DETAIL_DECODER_HPP
#define PROTOC_MSGPACK_DETAIL_DECODER_HPP
///////////////////////////////////////////////////////////////////////////////
//
// http://protoc.sourceforge.net/
//
// Copyright (C) 2014 Bjorn Reese <breese@users.sourceforge.net>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
///////////////////////////////////////////////////////////////////////////////
#include <string>
#include <vector>
#include <protoc/types.hpp>
#include <protoc/input_range.hpp>
#include <protoc/msgpack/detail/token.hpp>
namespace protoc
{
namespace msgpack
{
namespace detail
{
class decoder
{
public:
typedef const unsigned char value_type;
typedef protoc::input_range<value_type> input_range;
decoder(input_range::const_iterator begin, input_range::const_iterator end);
decoder(const decoder&);
token type() const;
void next();
protoc::int8_t get_int8() const;
protoc::int16_t get_int16() const;
protoc::int32_t get_int32() const;
protoc::int64_t get_int64() const;
protoc::uint8_t get_uint8() const;
protoc::uint16_t get_uint16() const;
protoc::uint32_t get_uint32() const;
protoc::uint64_t get_uint64() const;
protoc::float32_t get_float32() const;
protoc::float64_t get_float64() const;
std::string get_string() const;
// Decoder does not enforces that maps must have a even number of objects
protoc::uint32_t get_count() const;
const input_range& get_range() const;
private:
token next_int8();
token next_int16();
token next_int32();
token next_int64();
token next_uint8();
token next_uint16();
token next_uint32();
token next_uint64();
token next_float32();
token next_float64();
token next_fixstr();
token next_str8();
token next_str16();
token next_str32();
token next_bin8();
token next_bin16();
token next_bin32();
token next_array8();
token next_array16();
token next_array32();
token next_map8();
token next_map16();
token next_map32();
private:
input_range input;
struct
{
token type;
input_range range;
} current;
};
} // namespace detail
} // namespace msgpack
} // namespace protoc
#endif /* PROTOC_MSGPACK_DETAIL_DECODER_HPP */
| 25.326316 | 80 | 0.645885 | [
"vector"
] |
6e8488233f2d24116742f9b4bacc013cf4bf4362 | 5,490 | cpp | C++ | fancy2d/Sound/f2dWaveDecoder.cpp | Legacy-LuaSTG-Engine/Legacy-LuaSTG-Ex-Plus | 1266de6c56f7486e95567c5bfb092294fa363c10 | [
"MIT"
] | 3 | 2021-08-07T16:07:59.000Z | 2021-08-18T14:15:35.000Z | fancy2d/Sound/f2dWaveDecoder.cpp | Legacy-LuaSTG-Engine/Legacy-LuaSTG-Ex-Plus | 1266de6c56f7486e95567c5bfb092294fa363c10 | [
"MIT"
] | null | null | null | fancy2d/Sound/f2dWaveDecoder.cpp | Legacy-LuaSTG-Engine/Legacy-LuaSTG-Ex-Plus | 1266de6c56f7486e95567c5bfb092294fa363c10 | [
"MIT"
] | null | null | null | #include "f2dWaveDecoder.h"
#include "fcyException.h"
#include "fcyOS/fcyDebug.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////
const char* f2dWaveDecoder::tagRIFF = "RIFF";
const char* f2dWaveDecoder::tagFMT = "fmt ";
const char* f2dWaveDecoder::tagFACT = "fact";
const char* f2dWaveDecoder::tagDATA = "data";
f2dWaveDecoder::CWaveChunk::CWaveChunk(fChar* ID, fuInt Size, fcyBinaryReader* pReader)
: IChunk(ID, Size)
{
pReader->ReadChars(m_Type, 4);
}
f2dWaveDecoder::CWaveChunk::~CWaveChunk()
{}
f2dWaveDecoder::CFormatChunk::CFormatChunk(fChar* ID, fuInt Size, fcyBinaryReader* pReader)
: IChunk(ID, Size)
{
m_FormatTag = pReader->ReadUInt16();
m_Channels = pReader->ReadUInt16();
m_SamplesPerSec = pReader->ReadUInt32();
m_AvgBytesPerSec = pReader->ReadUInt32();
m_BlockAlign = pReader->ReadUInt16();
m_BitsPerSample = pReader->ReadUInt16();
if(Size > 16)
m_Reserved = pReader->ReadUInt16();
else
m_Reserved = 0;
}
f2dWaveDecoder::CFormatChunk::~CFormatChunk()
{}
f2dWaveDecoder::CFactChunk::CFactChunk(fChar* ID, fuInt Size, fcyBinaryReader* pReader)
: IChunk(ID, Size)
{
m_Data = pReader->ReadUInt32();
}
f2dWaveDecoder::CFactChunk::~CFactChunk()
{}
f2dWaveDecoder::CDataChunk::CDataChunk(fChar* ID, fuInt Size, fcyBinaryReader* pReader)
: IChunk(ID, Size)
{
m_BasePointer = pReader->GetBaseStream()->GetPosition();
// 跳过Size
pReader->GetBaseStream()->SetPosition(FCYSEEKORIGIN_CUR, Size);
}
f2dWaveDecoder::CDataChunk::~CDataChunk()
{}
f2dWaveDecoder::f2dWaveDecoder(f2dStream* pStream)
: m_pStream(pStream), m_cPointer(0)
{
if(!m_pStream)
throw fcyException("f2dWaveDecoder::f2dWaveDecoder", "Invalid Pointer.");
m_pStream->AddRef();
// 锁定
m_pStream->Lock();
m_pStream->SetPosition(FCYSEEKORIGIN_BEG, 0);
// 读取所有RIFF块
try
{
fcyBinaryReader tReader(pStream);
while(pStream->GetPosition() < pStream->GetLength())
{
char tID[4];
fuInt tSize = 0;
tReader.ReadChars(tID, 4);
tSize = tReader.ReadUInt32();
IChunk* pChunk = NULL;
if(strncmp(tID, tagRIFF, 4) == 0)
pChunk = new CWaveChunk(tID, tSize, &tReader);
else if(strncmp(tID, tagFMT, 4) == 0)
pChunk = new CFormatChunk(tID, tSize, &tReader);
else if(strncmp(tID, tagFACT, 4) == 0)
pChunk = new CFactChunk(tID, tSize, &tReader);
else if(strncmp(tID, tagDATA, 4) == 0)
pChunk = new CDataChunk(tID, tSize, &tReader);
else
{
// 跳过不支持的chunk
pStream->SetPosition(FCYSEEKORIGIN_CUR, tSize);
}
if(pChunk)
{
m_ChunkList.push_back(pChunk);
m_Chunk[pChunk->m_ID] = pChunk;
}
}
}
catch(const fcyException& e) // 处理读取异常
{
FCYDEBUGEXCPT(e);
m_pStream->Unlock();
clear(); // 清除无用数据
FCYSAFEKILL(m_pStream); // 释放引用
throw;
}
// 解锁
m_pStream->Unlock();
// 检查区块完整性
if(m_Chunk.find(tagRIFF) == m_Chunk.end() || m_Chunk.find(tagFMT) == m_Chunk.end() || m_Chunk.find(tagDATA) == m_Chunk.end())
{
clear();
FCYSAFEKILL(m_pStream);
throw fcyException("f2dWaveDecoder::f2dWaveDecoder", "Chunk Error.");
};
}
f2dWaveDecoder::~f2dWaveDecoder()
{
clear();
FCYSAFEKILL(m_pStream);
}
void f2dWaveDecoder::clear()
{
vector<IChunk*>::iterator i = m_ChunkList.begin();
while(i != m_ChunkList.end())
{
FCYSAFEDEL(*i);
++i;
}
}
fuInt f2dWaveDecoder::GetBufferSize()
{
CDataChunk* tChunk = (CDataChunk*)(m_Chunk[tagDATA]);
return tChunk->m_Size;
}
fuInt f2dWaveDecoder::GetAvgBytesPerSec()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_AvgBytesPerSec;
}
fuShort f2dWaveDecoder::GetBlockAlign()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_BlockAlign;
}
fuShort f2dWaveDecoder::GetChannelCount()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_Channels;
}
fuInt f2dWaveDecoder::GetSamplesPerSec()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_SamplesPerSec;
}
fuShort f2dWaveDecoder::GetFormatTag()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_FormatTag;
}
fuShort f2dWaveDecoder::GetBitsPerSample()
{
CFormatChunk* tChunk = (CFormatChunk*)(m_Chunk[tagFMT]);
return tChunk->m_BitsPerSample;
}
fLen f2dWaveDecoder::GetPosition()
{
return m_cPointer;
}
fResult f2dWaveDecoder::SetPosition(F2DSEEKORIGIN Origin, fInt Offset)
{
switch(Origin)
{
case FCYSEEKORIGIN_CUR:
break;
case FCYSEEKORIGIN_BEG:
m_cPointer = 0;
break;
case FCYSEEKORIGIN_END:
m_cPointer = GetBufferSize();
break;
default:
return FCYERR_INVAILDPARAM;
}
if(Offset<0 && ((fuInt)(-Offset))>m_cPointer)
{
m_cPointer = 0;
return FCYERR_OUTOFRANGE;
}
else if(Offset>0 && Offset+m_cPointer>=GetBufferSize())
{
m_cPointer = GetBufferSize();
return FCYERR_OUTOFRANGE;
}
m_cPointer+=Offset;
return FCYERR_OK;
}
fResult f2dWaveDecoder::Read(fData pBuffer, fuInt SizeToRead, fuInt* pSizeRead)
{
// 锁定流
m_pStream->Lock();
// 寻址
CDataChunk* tChunk = (CDataChunk*)(m_Chunk[tagDATA]);
m_pStream->SetPosition(FCYSEEKORIGIN_BEG, tChunk->m_BasePointer + m_cPointer);
// 计算读取大小
fuInt tRest = tChunk->m_Size - m_cPointer;
if(SizeToRead > tRest)
SizeToRead = tRest;
// 从流中读取数据
fLen tStreamRead = 0;
m_pStream->ReadBytes(pBuffer, SizeToRead, &tStreamRead);
if(SizeToRead != tStreamRead)
SizeToRead = (fuInt)tStreamRead;
if(pSizeRead)
*pSizeRead = SizeToRead;
// 指针后移
m_cPointer += SizeToRead;
// 解锁流
m_pStream->Unlock();
return FCYERR_OK;
}
| 21.96 | 126 | 0.698725 | [
"vector"
] |
6e851c3e26893b1436c101793be2eee8c27091e5 | 1,042 | cc | C++ | leet_code/Longest_Consecutive_Sequence/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Longest_Consecutive_Sequence/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Longest_Consecutive_Sequence/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, bool> hash;
vector<int> key;
int answer = 0;
for_each(nums.begin(), nums.end(), [&hash, &key](const auto num) {
if (hash.find(num) == hash.end()) {
key.push_back(num);
hash[num] = true;
}
});
for_each(key.begin(), key.end(), [&hash, &answer](const auto num) {
if (!hash[num]) {
return;
} else {
hash[num] = false;
}
int len = 1;
for (int i = num - 1; hash.find(i) != hash.end() && hash[i]; --i) {
hash[i] = false;
++len;
}
for (int i = num + 1; hash.find(i) != hash.end() && hash[i]; ++i) {
hash[i] = false;
++len;
}
if (answer < len) {
answer = len;
}
});
return answer;
}
};
| 28.944444 | 79 | 0.378119 | [
"vector"
] |
6e86443590becb7666287ac3062acb9abaf9bd66 | 6,479 | cpp | C++ | game/code/common/engine/render/ogl/oglrendertarget.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | null | null | null | game/code/common/engine/render/ogl/oglrendertarget.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | null | null | null | game/code/common/engine/render/ogl/oglrendertarget.cpp | justinctlam/MarbleStrike | 64fe36a5a4db2b299983b0e2556ab1cd8126259b | [
"MIT"
] | 2 | 2019-03-08T03:02:45.000Z | 2019-05-14T08:41:26.000Z | #if defined( RENDER_PLAT_OPENGL )
//////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////
#include "common/engine/database/database.hpp"
#include "common/engine/game/gameapp.hpp"
#include "common/engine/render/ogl/oglrenderer.hpp"
#include "common/engine/render/ogl/oglrendertarget.hpp"
#include "common/engine/render/ogl/ogltexture.hpp"
#include "common/engine/render/ogl/oglwrapper.hpp"
#include "common/engine/render/renderstatemanager.hpp"
#include "common/engine/render/renderstateshadowing.hpp"
#include "common/engine/render/samplerstate.hpp"
#include "common/engine/render/texture.hpp"
#include "common/engine/system/assert.hpp"
#include "common/engine/system/memory.hpp"
#include <gl/glew.h>
#include <stdio.h>
//////////////////////////////////////////////////////
// GLOBALS
//////////////////////////////////////////////////////
ResourceHandle<SamplerState> OGLRenderTarget::mDefaultSamplerState;
//////////////////////////////////////////////////////
// CLASS METHODS
//////////////////////////////////////////////////////
OGLRenderTarget::OGLRenderTarget()
{
if ( mDefaultSamplerState.IsNull() )
{
mDefaultSamplerState = GameApp::Get()->GetRenderStateManager()->GetSamplerState( "default" );
}
}
//===========================================================================
OGLRenderTarget::~OGLRenderTarget()
{
}
//===========================================================================
void OGLRenderTarget::CreateColorTarget( RenderTargetFormat renderTargetFormat, bool renderToTexture )
{
Assert( mWidth > 0, "Width is not valid." );
Assert( mHeight > 0, "Height is not valid." );
Texture* texture = NULL;
unsigned int renderBuffer = 0;
if ( renderToTexture )
{
texture = NEW_PTR( "Render Target OGL Texture" ) OGLTexture;
texture->SetName( "RenderTargetTexture" );
TextureFormat textureFormat = TEXTURE_FORMAT_RGBA8;
switch ( renderTargetFormat )
{
case RT_FORMAT_RGBA8:
textureFormat = TEXTURE_FORMAT_RGBA8;
break;
case RT_FORMAT_RGBA16:
textureFormat = TEXTURE_FORMAT_RGBA16;
break;
case RT_FORMAT_RGBA32:
textureFormat = TEXTURE_FORMAT_RGBA32;
break;
case RT_FORMAT_RG32:
textureFormat = TEXTURE_FORMAT_RG32;
break;
default:
Assert( false, "Cannot find format." );
break;
}
texture->CreateTexture( mWidth, mHeight, textureFormat );
SamplerState* samplerState = GameApp::Get()->GetRenderStateManager()->GetSamplerStateByHandle( mDefaultSamplerState );
Assert( samplerState->GetData()->mMipFilter == Filter_None, "" );
RenderStateShadowing renderStateShadowing;
samplerState->Dispatch( &renderStateShadowing, NULL, 0, true );
}
else
{
OGL::oglGenRenderbuffersEXT( 1, &renderBuffer );
OGL::oglBindRenderbufferEXT( GL_RENDERBUFFER_EXT, renderBuffer );
GLenum internalFormat = GL_RGBA8_EXT;
OGL::oglRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, internalFormat, mWidth, mHeight );
}
mColorTargetData.mTexture = texture;
mColorTargetData.mRenderBuffer = renderBuffer;
OGLRenderer* oglRenderer = reinterpret_cast<OGLRenderer*>( Renderer::Get() );
oglRenderer->AddColorTarget( mColorTargetData );
}
//===========================================================================
void OGLRenderTarget::CreateDepthTarget( RenderTargetFormat renderTargetFormat, bool renderToTexture )
{
Assert( mWidth > 0, "Width is not valid." );
Assert( mHeight > 0, "Height is not valid." );
Assert( renderTargetFormat == RT_FORMAT_DEPTH, "Not a valid target format." );
UNUSED_ALWAYS( renderTargetFormat );
Texture* texture = NULL;
unsigned int renderBuffer = 0;
if ( renderToTexture )
{
texture = NEW_PTR( "Render Target OGL Texture" ) OGLTexture;
texture->SetName( "RenderTargetTexture" );
TextureFormat textureFormat = TEXTURE_FORMAT_DEPTH;
texture->CreateTexture( mWidth, mHeight, textureFormat );
SamplerState* samplerState = GameApp::Get()->GetRenderStateManager()->GetSamplerStateByHandle( mDefaultSamplerState );
Assert( samplerState->GetData()->mMipFilter == Filter_None, "" );
RenderStateShadowing renderStateShadowing;
samplerState->Dispatch( &renderStateShadowing, NULL, 0, true );
}
else
{
OGL::oglGenRenderbuffersEXT( 1, &renderBuffer );
OGL::oglBindRenderbufferEXT( GL_RENDERBUFFER_EXT, renderBuffer );
GLenum internalFormat = GL_DEPTH_COMPONENT24_ARB;
OGL::oglRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, internalFormat, mWidth, mHeight );
}
mDepthTargetData.mTexture = texture;
mDepthTargetData.mRenderBuffer = renderBuffer;
OGLRenderer* oglRenderer = reinterpret_cast<OGLRenderer*>( Renderer::Get() );
oglRenderer->AddDepthTarget( mDepthTargetData );
}
//===========================================================================
void OGLRenderTarget::SetColorTarget( RenderTarget* renderTarget )
{
Assert( mWidth == renderTarget->GetWidth(), "Width does not match" );
Assert( mHeight == renderTarget->GetHeight(), "Width does not match" );
OGLRenderTarget* oglRenderTarget = reinterpret_cast<OGLRenderTarget*>( renderTarget );
mColorTargetData.mTexture = oglRenderTarget->GetColorTexture();
mColorTargetData.mRenderBuffer = oglRenderTarget->GetColorRenderBuffer();
}
//===========================================================================
void OGLRenderTarget::SetDepthTarget( RenderTarget* renderTarget )
{
Assert( mWidth == renderTarget->GetWidth(), "Width does not match" );
Assert( mHeight == renderTarget->GetHeight(), "Width does not match" );
OGLRenderTarget* oglRenderTarget = reinterpret_cast<OGLRenderTarget*>( renderTarget );
mDepthTargetData.mTexture = oglRenderTarget->GetDepthTexture();
mDepthTargetData.mRenderBuffer = oglRenderTarget->GetDepthRenderBuffer();
}
//===========================================================================
Texture* OGLRenderTarget::GetColorTexture()
{
return mColorTargetData.mTexture;
}
//===========================================================================
Texture* OGLRenderTarget::GetDepthTexture()
{
return mDepthTargetData.mTexture;
}
//===========================================================================
unsigned int OGLRenderTarget::GetColorRenderBuffer()
{
return mColorTargetData.mRenderBuffer;
}
//===========================================================================
unsigned int OGLRenderTarget::GetDepthRenderBuffer()
{
return mDepthTargetData.mRenderBuffer;
}
#endif | 32.557789 | 126 | 0.64084 | [
"render"
] |
6e8a0653c1132cb0a2796e61f8e3bd303105f2a9 | 241 | cpp | C++ | Practice/chapter_10/exercise_10_03.cpp | cotecsz/Cpp-Primer-Note | 1f1bc0a3a23651a98afdf85e86852642fce526fa | [
"Apache-2.0"
] | 2 | 2022-03-21T07:08:08.000Z | 2022-03-21T07:08:13.000Z | Practice/chapter_10/exercise_10_03.cpp | cotecsz/Cpp-Primer-Note | 1f1bc0a3a23651a98afdf85e86852642fce526fa | [
"Apache-2.0"
] | null | null | null | Practice/chapter_10/exercise_10_03.cpp | cotecsz/Cpp-Primer-Note | 1f1bc0a3a23651a98afdf85e86852642fce526fa | [
"Apache-2.0"
] | 1 | 2021-12-27T01:00:18.000Z | 2021-12-27T01:00:18.000Z | #include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main(){
vector<int> ivec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int result = accumulate(ivec.cbegin(), ivec.cend(), 0);
cout << result << endl;
return 0;
}
| 16.066667 | 56 | 0.614108 | [
"vector"
] |
6e9228029ecdc4246d1227bfd30f6f5ce443d0e6 | 1,941 | hpp | C++ | source/toy/canvas/detail/ImageA.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 4 | 2017-07-06T22:18:41.000Z | 2021-05-24T21:28:37.000Z | source/toy/canvas/detail/ImageA.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | null | null | null | source/toy/canvas/detail/ImageA.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 1 | 2020-08-02T13:00:38.000Z | 2020-08-02T13:00:38.000Z |
#pragma once
#include <atomic>
#include "toy/canvas/Standard.hpp"
#include "toy/canvas/detail/Image.hpp"
#include "toy/canvas/Array.hpp"
namespace toy{
namespace canvas{
namespace _detail{
class GcArrayBufferA;
class GcIndicesA;
}}}
#define BRUSH_PTR std::shared_ptr<::toy::canvas::Brush>
#define F_ARRAY_PTR std::shared_ptr<::toy::canvas::Array3<float>>
#define GEOMETRY_PTR std::shared_ptr<::toy::canvas::_detail::GcArrayBufferA>
#define INDICES_PTR std::shared_ptr<::toy::canvas::_detail::GcIndicesA>
#define PROGRAM_PTR std::shared_ptr<::toy::canvas::Program>
namespace toy{
namespace canvas{
namespace _detail{
class ImageA : public toy::canvas::_detail::Image
{
public:
ImageA(BRUSH_PTR);
~ImageA();
void visible(bool show);
bool isVisible() const;
void setModel(BRUSH_PTR brush,const ::toy::canvas::ModelBuffer &data);
void setTexture(::toy::canvas::Texture id);
auto getTexture(int index)->::toy::canvas::Texture;
void pushMoreTexture(::toy::canvas::Texture id);
void setProgram(PROGRAM_PTR program);
auto getProgram()->PROGRAM_PTR;
void bind(BRUSH_PTR brush);
void render(toy::canvas::Brush *brush,float diff);
void update(float);
void setPosition(const float* data);
private:
struct ShaderPak
{
GLint textureCoord = -1;
GLint texture0 = -1;
GLint texture1 = -1;
GLint textureCount = -1;
};
GEOMETRY_PTR _vList = nullptr; // Vertex array
INDICES_PTR _iList = nullptr; // Indices
Texture _texture = nullptr; // For GL_TEXTURE0
PROGRAM_PTR _program = nullptr;
std::vector<Texture> _multiTextureList; // For GL_TEXTURE{1~n}
ShaderPak _var;
bool _isVisible = false;
};
}}}
#undef PROGRAM_PTR
#undef INDICES_PTR
#undef GEOMETRY_PTR
#undef F_ARRAY_PTR
#undef BRUSH_PTR
| 26.22973 | 76 | 0.658423 | [
"render",
"vector"
] |
6e98407dd54dfcec46ee3ee2e0eafdc6703dc0e3 | 1,183 | cpp | C++ | Cpp/Sorting/mergesort.cpp | gankoji/datastructures | b09a463ef9cce4d0729568dae7b55c6b159dbdcf | [
"MIT"
] | null | null | null | Cpp/Sorting/mergesort.cpp | gankoji/datastructures | b09a463ef9cce4d0729568dae7b55c6b159dbdcf | [
"MIT"
] | null | null | null | Cpp/Sorting/mergesort.cpp | gankoji/datastructures | b09a463ef9cce4d0729568dae7b55c6b159dbdcf | [
"MIT"
] | null | null | null | #include "mergesort.h"
// Basic mergesort
std::vector<int> mergeSort(std::vector<int> arr) {
// Check the base case, a 1 element array is vacuously sorted
int len = arr.size();
if (len <= 1) {
return arr;
}
// Split the array in two
int halflen = len/2;
std::vector<int> a, b;
for (int i=0; i<halflen; i++) {
a.push_back(arr.at(i));
}
for (int i=halflen; i<len; i++) {
b.push_back(arr.at(i));
}
// Recurse on halves
std::vector<int> asorted = mergeSort(a);
std::vector<int> bsorted = mergeSort(b);
// Merge sorted halves
std::vector<int> output;
int i=0, j=0, k=0;
while (k < len) {
if ((i < (halflen)) && (j < (len - halflen))) {
if (asorted[i] <= bsorted[j]) {
output.push_back(asorted[i]);
i++; k++;
} else {
output.push_back(bsorted[j]);
j++; k++;
}
} else if (i < (halflen)) {
output.push_back(asorted[i]);
i++; k++;
} else {
output.push_back(bsorted[j]);
j++; k++;
}
}
return output;
} | 24.142857 | 66 | 0.469146 | [
"vector"
] |
6e9e774c445e380ecacb0b6b9f2ff910c1a112f8 | 3,057 | cpp | C++ | leetcode/cpp/qt_longest_absolute_path.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | leetcode/cpp/qt_longest_absolute_path.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | leetcode/cpp/qt_longest_absolute_path.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | /*
Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
subdir1
subdir2
file.ext
The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).
Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.
Note:
The name of a file contains at least a . and an extension.
The name of a directory or sub-directory will not contain a ..
Time complexity required: O(n) where n is the size of the input string.
Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
*/
class Solution {
public:
int lengthLongestPath(string input) {
if(input.empty()) return 0;
input += '\n';
int n = input.size();
int ans = INT_MIN;
vector<int> dp(1000, 0); // dp[1]表示第1级目录的长度
string cur = ""; // 当前字符串
int cnt = 0; // 当前字符串所处层级, cnt=0表示根目录,即\t的个数
for(int i=0; i<n; i++) {
if(input[i]=='\t') cnt++; // 新字符串开始
else if(input[i]=='\n') { // 字符串结束
// cout << dp[-1] << endl; // 竟然没有报错,而且输出0!!!
dp[cnt] = (cnt>0?dp[cnt-1]:0)+(int)cur.size();
if(cur.find('.')!=string::npos)
ans = max(ans, dp[cnt]+cnt); //将‘/’的数目计算在内
cur = "";
cnt = 0;
}
else cur+=input[i];
}
return ans==INT_MIN?0:ans;
}
};
// Using StringStream
// https://discuss.leetcode.com/topic/55729/13-line-0ms-c-solution-using-string-stream/2
class Solution {
public:
int lengthLongestPath(string input) {
vector<int> rec;
int max_val = 0;
stringstream ss(input);
string cur;
while(getline(ss, cur, '\n')){
int i = 0;
while(cur[i] == '\t')++i;
if(i+1 > rec.size())
rec.push_back(0);
rec[i] = (i ? rec[i-1] : 0) + cur.size()-i+1;
if(cur.find('.') != string::npos)max_val = max(max_val, rec[i]-1);
}
return max_val;
}
};
| 36.831325 | 274 | 0.60844 | [
"vector"
] |
6ea2522255dc0f93342f1ad1d0e2c2319f2a2300 | 5,495 | cpp | C++ | path.cpp | mraggi/LongestSimplePath | 7bc58044f32970481aba6d5c859975c30d2e0915 | [
"Apache-2.0"
] | 9 | 2017-02-23T15:18:26.000Z | 2022-01-14T15:17:01.000Z | LongestSimplePath/path.cpp | eddiehung/nextpnr-lsp | de4deb5f973b0a2d4600c47bf6fbfaeaca6bb200 | [
"0BSD"
] | 1 | 2020-07-16T09:41:09.000Z | 2020-07-16T13:42:15.000Z | path.cpp | mraggi/LongestSimplePath | 7bc58044f32970481aba6d5c859975c30d2e0915 | [
"Apache-2.0"
] | 2 | 2019-08-20T07:14:10.000Z | 2021-01-06T01:45:40.000Z | #include "path.hpp"
#include <cassert>
void Path::AddNodeBack(node_t t)
{
m_explored[t] = true;
node_t l = m_path.back();
m_totalvalue += m_parent->edge_value(l,t);
m_path.push_back(t);
}
void Path::AddNodeFront(node_t t)
{
m_explored[t] = true;
node_t l = m_path.front();
m_totalvalue += m_parent->edge_value(t,l);
m_path.push_front(t);
}
void Path::PopBack()
{
// assert (m_path.size() > 1 && "Cannot have empty paths!");
if (m_path.size() < 2) return;
node_t l = m_path.back();
m_explored[l] = false;
m_path.pop_back();
node_t ntl = m_path.back();
m_totalvalue -= m_parent->edge_value(ntl,l);
}
void Path::PopFront()
{
if (m_path.size() < 2) return;
node_t first = m_path.front();
m_explored[first] = false;
m_path.pop_front();
node_t second = m_path.front();
m_totalvalue -= m_parent->edge_value(first,second);
}
void Path::ExpandGreedyBack()
{
while (true)
{
auto l = m_path.back();
auto& Neighs = m_parent->exneighbors(l);
auto t = FirstNotExplored(Neighs);
if (t == INVALID_NODE)
break;
AddNodeBack(t);
}
}
void Path::transform_nodes(const vector< node_t >& m_removalfunctioninverse)
{
for (auto& x : m_path)
x = m_removalfunctioninverse[x];
}
void Path::ExpandGreedyFront()
{
while (true)
{
auto l = m_path.front();
auto& Neighs = m_parent->inneighbors(l);
auto t = FirstNotExplored(Neighs);
if (t == INVALID_NODE)
break;
AddNodeFront(t);
}
}
int Path::FirstNotExploredEX(const vector<node_t>& Nodes, node_t start) const
{
auto it = std::upper_bound(Nodes.begin(), Nodes.end(), start, [this] (node_t a, node_t b) -> bool
{
return m_parent->ex_compare(a,b);
});
// ++it;
while (it != Nodes.end() && m_explored[*it])
++it;
if (it == Nodes.end())
return INVALID_NODE;
return *it;
}
int Path::FirstNotExploredIN(const vector<node_t>& Nodes, node_t start) const
{
auto it = std::upper_bound(Nodes.begin(), Nodes.end(), start, [this] (node_t a, node_t b) -> bool
{
return m_parent->in_compare(a,b);
});
// ++it;
while (it != Nodes.end() && m_explored[*it])
++it;
if (it == Nodes.end())
return INVALID_NODE;
return *it;
}
node_t Path::FirstNotExplored(const vector<node_t>& Nodes, node_t start) const
{
bool seenstart = false;
for (auto x : Nodes)
{
if (x == start)
{
seenstart = true;
continue;
}
if (seenstart && m_explored[x] == false)
return x;
}
return INVALID_NODE;
}
bool Path::DFSBackNext(int maxbacktrack)
{
int lastNode = m_path.back();
const vector<node_t>* Neighs = &(m_parent->exneighbors(lastNode));
int t = FirstNotExplored(*Neighs);
while (t == -1 && m_path.size() > 1 && maxbacktrack > 0) //this means all nodes in Neigh have been explored
{
--maxbacktrack;
lastNode = m_path.back();
PopBack();
int father = m_path.back();
Neighs = &(m_parent->exneighbors(father));
t = FirstNotExploredEX(*Neighs,lastNode);
}
if (t == -1)
return false; // this means we have finished DFS!!
AddNodeBack(t);
ExpandGreedyBack();
return true;
}
bool Path::DFSFrontNext(int maxbacktrack)
{
int lastNode = m_path.front();
// cout << "lastnode = " << lastNode << endl;
const vector<node_t>* Neighs = &(m_parent->inneighbors(lastNode));
// cout << "Neighs = " << *Neighs << endl;
int t = FirstNotExplored(*Neighs);
// cout << "t = " << t << endl;
while (t == -1 && m_path.size() > 1 && maxbacktrack > 0) //this means all nodes in Neigh have been explored
{
--maxbacktrack;
lastNode = m_path.front();
PopFront();
int father = m_path.front();
Neighs = &(m_parent->inneighbors(father));
t = FirstNotExploredIN(*Neighs,lastNode);
}
if (t == -1)
return false;
AddNodeFront(t);
ExpandGreedyFront();
return true;
}
Path::Path(const DiGraph* const parent, const deque<node_t>& path) : m_parent(parent),
m_totalvalue(0),
m_path(path),
m_explored(m_parent->get_size(),0)
{
node_t prev = m_path.front();
for (auto x : m_path)
{
m_explored[x] = true;
m_totalvalue += m_parent->edge_value(prev,x);
prev = x;
}
}
Path::Path(const DiGraph* const parent, const deque<node_t>& path, sumweight_t value) : m_parent(parent),
m_totalvalue(value),
m_path(path),
m_explored(m_parent->get_size(),0)
{
for (auto x : m_path)
{
m_explored[x] = true;
}
}
void Path::Reset()
{
for (auto x : m_path)
{
m_explored[x] = 0;
}
m_path.clear();
m_totalvalue = 0;
}
Path Path::BestCompletion()
{
Path best = *this;
vector<Path> frontier = {*this};
while (!frontier.empty())
{
Path P = frontier.back();
frontier.pop_back();
if (P.m_totalvalue > best.m_totalvalue)
best = P;
int lastnode = P.m_path.back();
auto exx = m_parent->exneighbors(lastnode);
random_shuffle(exx.begin(), exx.end());
for (auto x : exx)
{
if (P.m_explored[x] == false)
{
Path PP = P;
PP.AddNodeBack(x);
frontier.push_back(PP);
}
}
}
return best;
}
bool Path::operator==(const Path& P) const
{
return (m_totalvalue == P.m_totalvalue && m_path == P.m_path);
}
bool Path::operator!=(const Path& P) const
{
return !(*this == P);
}
std::ostream& operator<<(std::ostream& os, const Path& P)
{
auto B = P.get_path();
for (size_t i = 0; i < B.size()-1; ++i)
{
os << P.get_digraph()->get_vertex_name(B[i]) << u8" ⟼ ";
}
os << P.get_digraph()->get_vertex_name(B.back()) << endl;
return os;
}
| 21.134615 | 111 | 0.62202 | [
"vector"
] |
6ea7f3000197ba9a6d127e9bfeceb65cd47dab49 | 7,561 | cpp | C++ | dp/sg/xbar/src/ObjectObserver.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 217 | 2015-01-06T09:26:53.000Z | 2022-03-23T14:03:18.000Z | dp/sg/xbar/src/ObjectObserver.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 10 | 2015-01-25T12:42:05.000Z | 2017-11-28T16:10:16.000Z | dp/sg/xbar/src/ObjectObserver.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 44 | 2015-01-13T01:19:41.000Z | 2022-02-21T21:35:08.000Z | // Copyright (c) 2010-2016, NVIDIA CORPORATION. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <dp/sg/xbar/inc/ObjectObserver.h>
namespace dp
{
namespace sg
{
namespace xbar
{
ObjectObserver::~ObjectObserver()
{
}
void ObjectObserver::attach( dp::sg::core::ObjectSharedPtr const& obj, ObjectTreeIndex index )
{
DP_ASSERT( m_indexMap.find(index) == m_indexMap.end() );
PayloadSharedPtr payload( Payload::create( index ) );
Observer<ObjectTreeIndex>::attach( obj, payload );
// fill cache data entry with current data
CacheData data;
data.m_hints = obj->getHints();
data.m_mask = obj->getTraversalMask();
m_newCacheData[index] = data;
}
void ObjectObserver::onDetach( ObjectTreeIndex index )
{
// remove NewCacheData entry
NewCacheData::iterator it = m_newCacheData.find( index );
if (it != m_newCacheData.end() )
{
m_newCacheData.erase( it );
}
}
void ObjectObserver::onNotify( const dp::util::Event &event, dp::util::Payload * payload )
{
switch ( event.getType() )
{
case dp::util::Event::Type::PROPERTY:
{
dp::util::Reflection::PropertyEvent const& propertyEvent = static_cast<dp::util::Reflection::PropertyEvent const&>(event);
dp::util::PropertyId propertyId = propertyEvent.getPropertyId();
if( propertyId == dp::sg::core::Object::PID_Hints || propertyId == dp::sg::core::Object::PID_TraversalMask )
{
dp::sg::core::Object const* o = static_cast<dp::sg::core::Object const*>(propertyEvent.getSource());
CacheData data;
data.m_hints = o->getHints();
data.m_mask = o->getTraversalMask();
DP_ASSERT( dynamic_cast<Payload*>(payload) );
m_newCacheData[static_cast<Payload*>(payload)->m_index] = data;
}
}
break;
case dp::util::Event::Type::DP_SG_CORE:
{
dp::sg::core::Event const& coreEvent = static_cast<dp::sg::core::Event const&>(event);
if ( coreEvent.getType() == dp::sg::core::Event::Type::GROUP )
{
dp::sg::core::Group::Event const& groupEvent = static_cast<dp::sg::core::Group::Event const&>(coreEvent);
DP_ASSERT( dynamic_cast<Payload*>(payload) );
Payload* groupPayload = static_cast<Payload*>(payload);
switch ( groupEvent.getType() )
{
case dp::sg::core::Group::Event::Type::POST_CHILD_ADD:
onPostAddChild( groupEvent.getGroup(), groupEvent.getChild(), groupEvent.getIndex(), groupPayload );
break;
case dp::sg::core::Group::Event::Type::PRE_CHILD_REMOVE:
onPreRemoveChild( groupEvent.getGroup(), groupEvent.getChild(), groupEvent.getIndex(), groupPayload );
break;
case dp::sg::core::Group::Event::Type::POST_GROUP_EXCHANGED:
m_sceneTree->replaceSubTree( groupEvent.getGroup(), groupPayload->m_index );
break;
case dp::sg::core::Group::Event::Type::CLIP_PLANES_CHANGED:
DP_ASSERT( !"clipplanes not supported" );
break;
}
}
}
break;
}
}
void ObjectObserver::onPreRemoveChild( dp::sg::core::GroupSharedPtr const& group, dp::sg::core::NodeSharedPtr const & child, unsigned int index, Payload * payload )
{
ObjectTreeIndex objectIndex = payload->m_index;
// determine the index of child in the ObjectTree3
ObjectTree& tree = m_sceneTree->getObjectTree();
unsigned int i=0;
ObjectTreeIndex childIndex = tree[objectIndex].m_firstChild;
bool handleAsGroup = true;
if ( group->getObjectCode() == dp::sg::core::ObjectCode::SWITCH )
{
DP_ASSERT(std::dynamic_pointer_cast<dp::sg::core::Switch>(group));
handleAsGroup = !!std::static_pointer_cast<dp::sg::core::Switch>(group)->getHints(dp::sg::core::Object::DP_SG_HINT_DYNAMIC);
}
if ( handleAsGroup )
{
DP_ASSERT( childIndex != ~0 );
while( i != index )
{
childIndex = tree[childIndex].m_nextSibling;
DP_ASSERT( childIndex != ~0 );
++i;
}
}
else
{
DP_ASSERT( group->getObjectCode() == dp::sg::core::ObjectCode::SWITCH );
DP_ASSERT(std::dynamic_pointer_cast<dp::sg::core::Switch>(group));
dp::sg::core::SwitchSharedPtr s = std::static_pointer_cast<dp::sg::core::Switch>(group);
if ( ! s->isActive( index ) )
{
childIndex = ~0;
}
while ( ( childIndex != ~0 ) && ( i != index ) )
{
if ( s->isActive( i ) )
{
childIndex = tree[childIndex].m_nextSibling;
}
++i;
}
}
if ( childIndex != ~0 )
{
m_sceneTree->removeObjectTreeIndex( childIndex );
}
}
void ObjectObserver::onPostAddChild( dp::sg::core::GroupSharedPtr const& group, dp::sg::core::NodeSharedPtr const & child, unsigned int index, Payload * payload )
{
ObjectTreeIndex objectIndex = payload->m_index;
// find the left sibling and the left transform of our new child
ObjectTree& tree = m_sceneTree->getObjectTree();
ObjectTreeIndex leftSibling = tree[objectIndex].m_firstChild;
ObjectTreeIndex currentLeftSibling = ~0;
while ( index > 0 )
{
currentLeftSibling = leftSibling;
leftSibling = tree[leftSibling].m_nextSibling;
--index;
}
// leftSibling advanced one step too far.
leftSibling = currentLeftSibling;
m_sceneTree->addSubTree(child, objectIndex, leftSibling);
}
} // namespace xbar
} // namespace sg
} // namespace dp
| 39.380208 | 170 | 0.609311 | [
"object",
"transform"
] |
6eab05a1aed0e7f0e9edea9a77cb6484210aba38 | 926 | hpp | C++ | include/athena/fields/Box.hpp | marovira/marching_rings | d4dbf3834a0a6b89801f6680c07303dbb7902ea0 | [
"BSD-3-Clause"
] | null | null | null | include/athena/fields/Box.hpp | marovira/marching_rings | d4dbf3834a0a6b89801f6680c07303dbb7902ea0 | [
"BSD-3-Clause"
] | null | null | null | include/athena/fields/Box.hpp | marovira/marching_rings | d4dbf3834a0a6b89801f6680c07303dbb7902ea0 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ATHENA_INCLUDE_ATHENA_FIELDS_CYLINDER_HPP
#define ATHENA_INCLUDE_ATHENA_FIELDS_CYLINDER_HPP
#pragma once
#include "ImplicitField.hpp"
namespace athena
{
namespace fields
{
class Box : public ImplicitField
{
public:
Box()
{ }
atlas::math::Normal grad(atlas::math::Point const& p) const override
{
return atlas::math::Normal();
}
std::vector<atlas::math::Point> getSeeds(atlas::math::Normal const& u,
float offset) const override
{
return {};
}
private:
float sdf(atlas::math::Point const& p) const override
{
return 0.0f;
}
atlas::utils::BBox box() const override
{
return atlas::utils::BBox();
}
};
}
}
#endif | 21.045455 | 82 | 0.49676 | [
"vector"
] |
6eb464e55211a68c4e06db2a094b01eff836b1ac | 13,157 | cpp | C++ | src/ImguiRenderer.cpp | am-lola/ARVisualizer | b262a0ee5ffb9de1a4ccac16eb5c6b8deacba16d | [
"MIT"
] | 1 | 2018-05-29T07:55:52.000Z | 2018-05-29T07:55:52.000Z | src/ImguiRenderer.cpp | am-lola/ARVisualizer | b262a0ee5ffb9de1a4ccac16eb5c6b8deacba16d | [
"MIT"
] | null | null | null | src/ImguiRenderer.cpp | am-lola/ARVisualizer | b262a0ee5ffb9de1a4ccac16eb5c6b8deacba16d | [
"MIT"
] | null | null | null | // ImGui GLFW3 binding with OpenGL3 + shaders. Adapted from imgui_impl_glfw_gl3.cpp.
// https://github.com/ocornut/imgui
#include "ImguiRenderer.hpp"
#include "common.hpp"
#include <mutex>
#include <imgui.h>
namespace ar
{
static int _openInstances = 0;
static std::mutex _mutex;
ImguiRenderer::ImguiRenderer(GLFWwindow* window)
: _window(window)
{
}
void ImguiRenderer::Init()
{
MutexLockGuard guard(_mutex);
_openInstances++;
if (_openInstances > 1)
return;
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
io.RenderDrawListsFn = nullptr;
#ifdef _WIN32
io.ImeWindowHandle = glfwGetWin32Window(window);
#endif
}
void ImguiRenderer::Shutdown()
{
MutexLockGuard guard(_mutex);
if (_openInstances == 1)
{
InvalidateDeviceObjects();
ImGui::Shutdown();
}
_openInstances--;
}
void ImguiRenderer::RenderDrawLists(ImDrawData* draw_data)
{
// Backup GL state
GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] =
{
{ 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{-1.0f, 1.0f, 0.0f, 1.0f },
};
glUseProgram(_shaderHandle);
glUniform1i(_attribLocationTex, 0);
glUniformMatrix4fv(_attribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
glBindVertexArray(_vaoHandle);
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawIdx* idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, _vboHandle);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementsHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
{
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBindVertexArray(last_vertex_array);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFunc(last_blend_src, last_blend_dst);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
void ImguiRenderer::NewFrame()
{
if (!_fontTexture)
CreateDeviceObjects();
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(_window, &w, &h);
glfwGetFramebufferSize(_window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step
double current_time = glfwGetTime();
io.DeltaTime = _time > 0.0 ? (float)(current_time - _time) : (float)(1.0f/60.0f);
_time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
if (glfwGetWindowAttrib(_window, GLFW_FOCUSED))
{
double mouse_x, mouse_y;
glfwGetCursorPos(_window, &mouse_x, &mouse_y);
io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
}
else
{
io.MousePos = ImVec2(-1,-1);
}
for (int i = 0; i < 3; i++)
{
io.MouseDown[i] = _mousePressed[i] || glfwGetMouseButton(_window, i) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
_mousePressed[i] = false;
}
io.MouseWheel = (float)_mouseWheel;
_mouseWheel = 0.0;
// Hide OS mouse cursor if ImGui is drawing it
glfwSetInputMode(_window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
// Start the frame
ImGui::NewFrame();
}
void ImguiRenderer::InvalidateDeviceObjects()
{
if (_vaoHandle) glDeleteVertexArrays(1, &_vaoHandle);
if (_vboHandle) glDeleteBuffers(1, &_vboHandle);
if (_elementsHandle) glDeleteBuffers(1, &_elementsHandle);
_vaoHandle = _vboHandle = _elementsHandle = 0;
glDetachShader(_shaderHandle, _vertHandle);
glDeleteShader(_vertHandle);
_vertHandle = 0;
glDetachShader(_shaderHandle, _fragHandle);
glDeleteShader(_fragHandle);
_fragHandle = 0;
glDeleteProgram(_shaderHandle);
_shaderHandle = 0;
if (_fontTexture)
{
glDeleteTextures(1, &_fontTexture);
ImGui::GetIO().Fonts->TexID = 0;
_fontTexture = 0;
}
}
void ImguiRenderer::CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer, last_vertex_array;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
const GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
_shaderHandle = glCreateProgram();
_vertHandle = glCreateShader(GL_VERTEX_SHADER);
_fragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(_vertHandle, 1, &vertex_shader, 0);
glShaderSource(_fragHandle, 1, &fragment_shader, 0);
glCompileShader(_vertHandle);
glCompileShader(_fragHandle);
glAttachShader(_shaderHandle, _vertHandle);
glAttachShader(_shaderHandle, _fragHandle);
glLinkProgram(_shaderHandle);
_attribLocationTex = glGetUniformLocation(_shaderHandle, "Texture");
_attribLocationProjMtx = glGetUniformLocation(_shaderHandle, "ProjMtx");
_attribLocationPosition = glGetAttribLocation(_shaderHandle, "Position");
_attribLocationUV = glGetAttribLocation(_shaderHandle, "UV");
_attribLocationColor = glGetAttribLocation(_shaderHandle, "Color");
glGenBuffers(1, &_vboHandle);
glGenBuffers(1, &_elementsHandle);
glGenVertexArrays(1, &_vaoHandle);
glBindVertexArray(_vaoHandle);
glBindBuffer(GL_ARRAY_BUFFER, _vboHandle);
glEnableVertexAttribArray(_attribLocationPosition);
glEnableVertexAttribArray(_attribLocationUV);
glEnableVertexAttribArray(_attribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
glVertexAttribPointer(_attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(_attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(_attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindVertexArray(last_vertex_array);
}
void ImguiRenderer::CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &_fontTexture);
glBindTexture(GL_TEXTURE_2D, _fontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)_fontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
}
void ImguiRenderer::OnKeyPress(int key, int, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
io.KeysDown[key] = true;
if (action == GLFW_RELEASE)
io.KeysDown[key] = false;
(void)mods; // Modifiers are not reliable across systems
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
}
void ImguiRenderer::OnKeyChar(unsigned int codepoint)
{
ImGuiIO& io = ImGui::GetIO();
if (codepoint > 0 && codepoint < 0x10000)
io.AddInputCharacter((unsigned short)codepoint);
}
void ImguiRenderer::OnMouseButton(int button, int action, int mods)
{
if (action == GLFW_PRESS && button >= 0 && button < 3)
_mousePressed[button] = true;
}
void ImguiRenderer::OnScroll(double /*xoffset*/, double yoffset)
{
_mouseWheel += yoffset;
}
}
| 35.948087 | 222 | 0.733222 | [
"render"
] |
6eb9da780d8d5c0863a0a4680994df20b2e03264 | 1,223 | cpp | C++ | src/study/FindPrimesWithThreads.cpp | ViniciusCampanha/cpp_basic | d80a64c35791dd4525a08ecceb6ac08168b7601d | [
"Unlicense"
] | null | null | null | src/study/FindPrimesWithThreads.cpp | ViniciusCampanha/cpp_basic | d80a64c35791dd4525a08ecceb6ac08168b7601d | [
"Unlicense"
] | null | null | null | src/study/FindPrimesWithThreads.cpp | ViniciusCampanha/cpp_basic | d80a64c35791dd4525a08ecceb6ac08168b7601d | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <ctime>
#include <mutex>
#include <thread>
std::vector<unsigned int> primeVect;
std::mutex vectLock;
void FindPrimes(unsigned int start,
unsigned int end)
{
for(unsigned int x = start; x <= end; x+=2)
{
for(unsigned int y = 2; y < x; y++)
{
if((x% y) == 0)
{
break;
}
else if ((y + 1) == x)
{
std::lock_guard<std::mutex> gard(vectLock);
primeVect.push_back(x);
}
}
}
}
void FindPrimesWithThreads(unsigned int start,
unsigned int end,
unsigned int numThreads)
{
std::vector<std::thread> threadVect;
unsigned int threadSpread = end / numThreads;
unsigned int newEnd = start + threadSpread - 1;
for(unsigned int x = 0; x < numThreads; x++)
{
threadVect.emplace_back(FindPrimes, start, newEnd);
start += threadSpread;
newEnd += threadSpread;
}
for(auto& t : threadVect)
{
t.join();
}
}
int main()
{
auto startTime = clock();
FindPrimesWithThreads(1, 100000, 3);
auto endTime = clock();
for(auto i : primeVect)
std::cout << i << std::endl;
std::cout << "Execution time: "
<< (endTime-startTime)/CLOCKS_PER_SEC << std::endl;
return 0;
} | 18.530303 | 54 | 0.60507 | [
"vector"
] |
6ebc5291a945d4022e2056b5ae49019a25efac38 | 2,109 | cpp | C++ | wangha/test/rgb2nv21.cpp | wanghaMAX/yeah2020 | efcb6d51d498bff9732f05396694ce7bf9b3a1fc | [
"MIT"
] | 3 | 2019-12-11T03:08:50.000Z | 2019-12-12T04:54:08.000Z | wangha/test/rgb2nv21.cpp | wanghaMAX/fwwb2020 | efcb6d51d498bff9732f05396694ce7bf9b3a1fc | [
"MIT"
] | null | null | null | wangha/test/rgb2nv21.cpp | wanghaMAX/fwwb2020 | efcb6d51d498bff9732f05396694ce7bf9b3a1fc | [
"MIT"
] | 1 | 2019-12-23T11:31:59.000Z | 2019-12-23T11:31:59.000Z | #include <iostream>
#include <cstdlib>
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <vector>
#include <fstream>
#include <string>
using namespace std;
using namespace cv;
void opencvRGB2NV21(string infile, char* outfile){
Mat Img = cv::imread(infile);
int buflen = (int)(Img.rows * Img.cols * 3 / 2);
unsigned char* pYuvBuf = new unsigned char[buflen];
Mat OpencvYUV;
FILE* fout = fopen(outfile, "wb");
cvtColor(Img, OpencvYUV, CV_BGR2YUV_YV12);
memcpy(pYuvBuf, OpencvYUV.data, buflen*sizeof(unsigned char));
fwrite(pYuvBuf, buflen*sizeof(unsigned char), 1, fout);
fclose(fout);
}
void RGB2NV21(string infile, char* outfile){
cv::Mat Img = cv::imread(infile);
FILE *fp = fopen(outfile, "wb");
if (Img.empty()){
std::cout << "empty!check your image";
return;
}
int cols = Img.cols;
int rows = Img.rows;
int Yindex = 0;
int UVindex = rows * cols;
unsigned char* yuvbuff = new unsigned char[int(1.5 * rows * cols)];
cv::Mat OpencvYUV;
cv::Mat OpencvImg;
cv::cvtColor(Img, OpencvYUV, CV_BGR2YUV_YV12);
int UVRow{ 0 };
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
int B = Img.at<cv::Vec3b>(i, j)[0];
int G = Img.at<cv::Vec3b>(i, j)[1];
int R = Img.at<cv::Vec3b>(i, j)[2];
//计算Y的值
int Y = (77 * R + 150 * G + 29 * B) >> 8;
yuvbuff[Yindex++] = (Y < 0) ? 0 : ((Y > 255) ? 255 : Y);
//计算U、V的值,进行2x2的采样
if (i%2==0&&(j)%2==0)
{
int U = ((-44 * R - 87 * G + 131 * B) >> 8) + 128;
int V = ((131 * R - 110 * G - 21 * B) >> 8) + 128;
yuvbuff[UVindex++] = (V < 0) ? 0 : ((V > 255) ? 255 : V);
yuvbuff[UVindex++] = (U < 0) ? 0 : ((U > 255) ? 255 : U);
}
}
}
for (int i=0;i< 1.5 * rows * cols;i++){
fwrite(&yuvbuff[i], 1, 1, fp);
}
fclose(fp);
std::cout << "write to file ok!" << std::endl;
std::cout << "srcImg: " << "rows:" << Img.rows << "cols:" << Img.cols << std::endl;
}
int main(){
//RGB2NV21(INPUTFILE, OUTPUTFILE);
RGB2NV21("1.jpg", "direct.yuv");
opencvRGB2NV21("1.jpg", "opencv.yuv");
}
| 26.3625 | 87 | 0.573257 | [
"vector"
] |
6ebf69146c5e3061216e7b4734129013b9b1cbbe | 576 | cpp | C++ | 941.cpp | zhulk3/leetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | 2 | 2020-03-13T08:14:01.000Z | 2021-09-03T15:27:49.000Z | 941.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | 941.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
bool validMountainArray(vector<int>& A) {
bool up = true;
bool down = false;
int len = A.size();
int left = 0;
int right = len - 1;
if (len < 3)
return false;
for (int i = 1; i < len; i++) {
if (A[i] > A[i - 1])
continue;
else {
left = i - 1;
break;
}
}
for (int i = len - 1; i > 0; i--) {
if(A[i]<A[i-1])
continue;
else {
right = i;
break;
}
}
if (left == right)
return true;
return false;
}
}; | 15.567568 | 42 | 0.524306 | [
"vector"
] |
6ebfea4240daa131495253ff0d70a6f4f908e84b | 13,343 | cpp | C++ | RcsPySim/src/cpp/pyEnv/config/PropertySourceDict.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 52 | 2020-05-02T13:55:09.000Z | 2022-03-09T14:49:36.000Z | RcsPySim/src/cpp/pyEnv/config/PropertySourceDict.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 40 | 2020-09-01T15:19:22.000Z | 2021-11-02T14:51:41.000Z | RcsPySim/src/cpp/pyEnv/config/PropertySourceDict.cpp | theogruner/SimuRLacra | 4893514ccdeb10a736c55de9aa7753fd51c5afec | [
"DOC",
"Zlib",
"BSD-3-Clause"
] | 13 | 2020-07-03T11:39:21.000Z | 2022-02-20T01:12:42.000Z | /*******************************************************************************
Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
Technical University of Darmstadt.
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.
3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,
or Technical University of Darmstadt, nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,
OR TECHNICAL UNIVERSITY OF DARMSTADT 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 "PropertySourceDict.h"
#include "../util/pybind_dict_utils.h"
#include "../util/type_casters.h"
#include <libxml/tree.h>
#include <algorithm>
namespace Rcs
{
PropertySourceDict::PropertySourceDict(
pybind11::dict dict,
PropertySourceDict* parent, const char* prefix, bool exists) :
dict(dict), parent(parent), prefix(prefix), _exists(exists)
{
// internal ctor, sets all parts
}
PropertySourceDict::PropertySourceDict(pybind11::dict dict) :
dict(dict), parent(NULL), prefix(NULL), _exists(true)
{
// nothing special to do
}
PropertySourceDict::~PropertySourceDict()
{
// delete children where needed
for (auto& it: children) {
if (it.second != empty()) {
delete it.second;
}
}
for (auto& it: listChildren) {
for (auto le : it.second) {
delete le;
}
}
}
bool PropertySourceDict::exists()
{
return _exists;
}
bool PropertySourceDict::getProperty(std::string& out, const char* property)
{
if (!_exists) {
return false;
}
// try to retrieve
pybind11::handle elem;
if (!try_get(dict, property, elem) || elem.is_none()) {
return false;
}
// cast to string
pybind11::str str(elem);
out = str;
return true;
}
bool PropertySourceDict::getProperty(std::vector<std::string> &out, const char *property) {
if (!_exists) {
return false;
}
// try to retrieve
pybind11::handle elem;
if (!try_get(dict, property, elem) || elem.is_none()) {
return false;
}
if (py::isinstance<py::str>(elem)) {
py::str str(elem);
out.push_back(str);
return true;
} else if (py::isinstance<py::iterable>(elem)) {
for (auto part : elem) {
py::str str(part);
out.push_back(str);
}
return true;
} else {
std::ostringstream os;
os << "Unsupported value for property entry at ";
appendPrefix(os);
os << property << ": Expected string or iterable of string, but got ";
auto childType = py::str(elem.get_type());
os << childType.cast<std::string>();
throw std::invalid_argument(os.str());
}
}
bool PropertySourceDict::getProperty(double& out, const char* property)
{
if (!_exists) {
return false;
}
// try to retrieve
pybind11::handle elem;
if (!try_get(dict, property, elem) || elem.is_none()) {
return false;
}
// cast
out = elem.cast<double>();
return true;
}
bool PropertySourceDict::getProperty(int& out, const char* property)
{
if (!_exists) {
return false;
}
// try to retrieve
pybind11::handle elem;
if (!try_get(dict, property, elem) || elem.is_none()) {
return false;
}
// cast
out = elem.cast<int>();
return true;
}
bool PropertySourceDict::getProperty(MatNd*& out, const char* property)
{
if (!_exists) {
return false;
}
// try to retrieve
pybind11::handle elem;
if (!try_get(dict, property, elem) || elem.is_none()) {
return false;
}
// cast. must use internals since handle.cast() doesn't allow pointers
py::detail::make_caster<MatNd> caster;
py::detail::load_type(caster, elem);
out = MatNd_clone(py::detail::cast_op<MatNd*>(caster));
return true;
}
bool PropertySourceDict::getPropertyBool(const char* property, bool def)
{
if (!_exists) {
return def;
}
return get_cast<bool>(dict, property, def);
}
PropertySink* PropertySourceDict::getChild(const char* prefix)
{
std::string prefixStr = prefix;
// check if it exists already
auto iter = children.find(prefixStr);
if (iter != children.end()) {
return iter->second;
}
// try to get child dict
pybind11::object child;
bool exists = this->_exists;
if (exists) {
exists = try_get(dict, prefix, child) && !child.is_none();
}
if (!exists) {
// not found, use a fresh dict
child = pybind11::dict();
}
else if (!pybind11::isinstance<pybind11::dict>(child)) {
// exists but not a dict
std::ostringstream os;
os << "Unsupported value for child property entry at ";
appendPrefix(os);
os << prefix << ": Expected dict, but got ";
auto childType = pybind11::str(child.get_type());
os << childType.cast<std::string>();
throw std::invalid_argument(os.str());
}
auto* result = new PropertySourceDict(child, this, prefix, exists);
children[prefixStr] = result;
return result;
}
void PropertySourceDict::appendPrefix(std::ostream& os)
{
if (parent != NULL) {
parent->appendPrefix(os);
os << prefix << ".";
}
}
// most of these are easy
void PropertySourceDict::setProperty(
const char* property,
const std::string& value)
{
dict[property] = value;
onWrite();
}
void PropertySourceDict::setProperty(const char* property, bool value)
{
dict[property] = value;
onWrite();
}
void PropertySourceDict::setProperty(const char* property, int value)
{
dict[property] = value;
onWrite();
}
void PropertySourceDict::setProperty(const char* property, double value)
{
dict[property] = value;
onWrite();
}
void PropertySourceDict::setProperty(const char* property, MatNd* value)
{
// make sure we use a copy
dict[property] = pybind11::cast(value, pybind11::return_value_policy::copy);
onWrite();
}
void PropertySourceDict::onWrite()
{
if (parent != NULL) {
// notify parent
parent->onWrite();
// put to parent if new
if (!_exists) {
parent->dict[prefix] = dict;
}
}
}
const std::vector<PropertySource*>& PropertySourceDict::getChildList(const char* prefix)
{
std::string prefixStr = prefix;
// Check if it exists already
auto iter = listChildren.find(prefixStr);
if (iter != listChildren.end()) {
return iter->second;
}
// Create new entry
auto& list = listChildren[prefixStr];
// Retrieve entry from dict
pybind11::object child;
bool exists = this->_exists;
if (exists) {
exists = try_get(dict, prefix, child) && !child.is_none();
}
if (exists) {
// Parse entry sequence
if (pybind11::isinstance<pybind11::dict>(child)) {
// Single element
list.push_back(new PropertySourceDict(child, this, prefix, true));
}
else if (pybind11::isinstance<pybind11::iterable>(child)) {
// Element sequence
unsigned int i = 0;
for (auto elem : child) {
if (pybind11::isinstance<pybind11::dict>(elem)) {
std::ostringstream itemPrefix;
itemPrefix << prefix << "[" << i << "]";
// Add element
list.push_back(new PropertySourceDict(pybind11::reinterpret_borrow<pybind11::dict>(elem), this,
itemPrefix.str().c_str(), true));
}
else {
// Exists but not a dict
std::ostringstream os;
os << "Unsupported element for child property entry at ";
appendPrefix(os);
os << prefix << "[" << i << "]" << ": Expected dict, but got ";
auto childType = pybind11::str(child.get_type());
os << childType.cast<std::string>();
throw std::invalid_argument(os.str());
}
i++;
}
}
else {
// Exists but not a dict
std::ostringstream os;
os << "Unsupported value for child list property entry at ";
appendPrefix(os);
os << prefix << ": Expected list of dict or dict, but got ";
auto childType = pybind11::str(child.get_type());
os << childType.cast<std::string>();
throw std::invalid_argument(os.str());
}
}
return list;
}
PropertySink* PropertySourceDict::clone() const
{
// use python deepcopy to copy the dict.
py::object copymod = py::module::import("copy");
py::dict cpdict = copymod.attr("deepcopy")(dict);
return new PropertySourceDict(cpdict);
}
static std::string spaceJoinedString(py::handle iterable)
{
std::ostringstream os;
for (auto ele : iterable) {
// Append stringified element
os << py::cast<std::string>(py::str(ele)) << ' ';
}
std::string result = os.str();
// Remove trailing ' '
if (!result.empty()) {
result.erase(result.end() - 1);
}
return result;
}
static xmlNodePtr dict2xml(const py::dict& data, xmlDocPtr doc, const char* nodeName)
{
xmlNodePtr node = xmlNewDocNode(doc, NULL, BAD_CAST nodeName, NULL);
// add children
for (auto entry : data) {
auto key = py::cast<std::string>(entry.first);
auto value = entry.second;
std::string valueStr;
// check value type
if (py::isinstance<py::dict>(value)) {
// as sub node
xmlNodePtr subNode = dict2xml(py::reinterpret_borrow<py::dict>(value), doc, key.c_str());
xmlAddChild(node, subNode);
continue;
}
else if (py::isinstance<py::str>(value)) {
// handle strings before catching them as iterable
valueStr = py::cast<std::string>(value);
}
else if (py::isinstance<py::array>(value)) {
// handle arrays first before catching them as iterable
// we don't really have a proper 2d format, just flatten if needed
valueStr = spaceJoinedString(value.attr("flatten")().attr("tolist")());
}
else if (py::isinstance<py::iterable>(value)) {
// an iterable
auto it = value.begin();
// check if empty
if (it == value.end()) continue;
// check if child list
if (std::all_of(it, value.end(), [](py::handle ele) {
return py::isinstance<py::dict>(ele);
})) {
// child list, add one element per child
for (auto ele : value) {
xmlNodePtr subNode = dict2xml(py::reinterpret_borrow<py::dict>(ele), doc, key.c_str());
xmlAddChild(node, subNode);
}
continue;
}
// treat as array-like; a space-joined string
valueStr = spaceJoinedString(value);
}
else {
// use default str() format for other cases
valueStr = py::cast<std::string>(py::str(value));
}
xmlSetProp(node, BAD_CAST key.c_str(), BAD_CAST valueStr.c_str());
}
return node;
}
void PropertySourceDict::saveXML(const char* fileName, const char* rootNodeName)
{
// create xml doc
std::unique_ptr<xmlDoc, void (*)(xmlDocPtr)> doc(xmlNewDoc(NULL), xmlFreeDoc);
// convert root node
xmlNodePtr rootNode = dict2xml(dict, doc.get(), rootNodeName);
xmlDocSetRootElement(doc.get(), rootNode);
// perform save
xmlIndentTreeOutput = 1;
xmlSaveFormatFile(fileName, doc.get(), 1);
}
} /* namespace Rcs */
| 30.603211 | 115 | 0.590572 | [
"object",
"vector"
] |
6ec767aa77903838782e1f51738081fd02208500 | 4,655 | cc | C++ | src/Protocols/HTTP/Request.cc | fuzziqersoftware/libevent-async | 2054586d9de8e5c877f453a0d48d1bb8c4df1619 | [
"MIT"
] | 2 | 2021-11-07T15:00:33.000Z | 2022-01-08T13:16:50.000Z | src/Protocols/HTTP/Request.cc | fuzziqersoftware/libevent-async | 2054586d9de8e5c877f453a0d48d1bb8c4df1619 | [
"MIT"
] | null | null | null | src/Protocols/HTTP/Request.cc | fuzziqersoftware/libevent-async | 2054586d9de8e5c877f453a0d48d1bb8c4df1619 | [
"MIT"
] | null | null | null | #include "Request.hh"
#include <phosg/Strings.hh>
#include <phosg/Time.hh>
#include "Connection.hh"
using namespace std;
namespace EventAsync::HTTP {
Request::Request(Base& base)
: base(base),
req(evhttp_request_new(&Request::on_response, this)),
owned(false),
is_complete(false),
awaiter(nullptr) {
if (!this->req) {
throw bad_alloc();
}
}
Request::Request(Base& base, struct evhttp_request* req)
: base(base), req(req), owned(false) { }
Request::Request(Request&& other)
: base(other.base), req(other.req), owned(other.owned) {
other.owned = false;
}
Request::~Request() {
if (this->owned && this->req) {
evhttp_request_free(this->req);
}
}
unordered_multimap<string, string> Request::parse_url_params() {
const struct evhttp_uri* uri = evhttp_request_get_evhttp_uri(this->req);
const char* query = evhttp_uri_get_query(uri);
return this->parse_url_params(query);
}
unordered_multimap<string, string> Request::parse_url_params(const char* query) {
unordered_multimap<string, string> params;
if (*query == '\0') {
return params;
}
for (auto it : split(query, '&')) {
size_t first_equals = it.find('=');
if (first_equals != string::npos) {
string value(it, first_equals + 1);
size_t write_offset = 0, read_offset = 0;
for (; read_offset < value.size(); write_offset++) {
if ((value[read_offset] == '%') && (read_offset < value.size() - 2)) {
value[write_offset] =
static_cast<char>(value_for_hex_char(value[read_offset + 1]) << 4) |
static_cast<char>(value_for_hex_char(value[read_offset + 2]));
read_offset += 3;
} else if (value[write_offset] == '+') {
value[write_offset] = ' ';
read_offset++;
} else {
value[write_offset] = value[read_offset];
read_offset++;
}
}
value.resize(write_offset);
params.emplace(piecewise_construct, forward_as_tuple(it, 0, first_equals),
forward_as_tuple(value));
} else {
params.emplace(it, "");
}
}
return params;
}
unordered_map<string, string> Request::parse_url_params_unique() {
const struct evhttp_uri* uri = evhttp_request_get_evhttp_uri(this->req);
const char* query = evhttp_uri_get_query(uri);
return this->parse_url_params_unique(query);
}
unordered_map<string, string> Request::parse_url_params_unique(
const char* query) {
unordered_map<string, string> ret;
for (const auto& it : Request::parse_url_params(query)) {
ret.emplace(it.first, move(it.second));
}
return ret;
}
enum evhttp_cmd_type Request::get_command() const {
return evhttp_request_get_command(this->req);
}
struct evhttp_connection* Request::get_connection() {
return evhttp_request_get_connection(this->req);
}
const struct evhttp_uri* Request::get_evhttp_uri() const {
return evhttp_request_get_evhttp_uri(this->req);
}
const char* Request::get_host() const {
return evhttp_request_get_host(this->req);
}
Buffer Request::get_input_buffer() {
return Buffer(this->base, evhttp_request_get_input_buffer(this->req));
}
Buffer Request::get_output_buffer() {
return Buffer(this->base, evhttp_request_get_output_buffer(this->req));
}
struct evkeyvalq* Request::get_input_headers() {
return evhttp_request_get_input_headers(this->req);
}
struct evkeyvalq* Request::get_output_headers() {
return evhttp_request_get_output_headers(this->req);
}
const char* Request::get_input_header(const char* header_name) {
struct evkeyvalq* in_headers = this->get_input_headers();
return evhttp_find_header(in_headers, header_name);
}
void Request::add_output_header(const char* header_name, const char* value) {
struct evkeyvalq* out_headers = this->get_output_headers();
evhttp_add_header(out_headers, header_name, value);
}
int Request::get_response_code() {
return evhttp_request_get_response_code(this->req);
}
const char* Request::get_uri() {
return evhttp_request_get_uri(this->req);
}
void Request::on_response(struct evhttp_request*, void* ctx) {
auto* req = reinterpret_cast<Request*>(ctx);
// By default, calling evhttp_make_request causes the request to become owned
// by the connection object. We don't want that here - the caller is a
// coroutine, and will need to examine the result after this callback returns.
// Fortunately, libevent allows us to override the default ownership behavior.
evhttp_request_own(req->req);
req->is_complete = true;
if (req->awaiter) {
auto* aw = reinterpret_cast<Connection::Awaiter*>(req->awaiter);
aw->on_response();
}
}
} // namespace EventAsync::HTTP
| 28.558282 | 82 | 0.697959 | [
"object"
] |
6ec776771985147e3fb23f6f888cf80cac383a25 | 2,191 | cpp | C++ | learncpp.com/0P_Arrays_Strings_Pointers_and_References/Question02/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | learncpp.com/0P_Arrays_Strings_Pointers_and_References/Question02/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | learncpp.com/0P_Arrays_Strings_Pointers_and_References/Question02/src/Main.cpp | KoaLaYT/Learn-Cpp | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | [
"MIT"
] | null | null | null | /**
* Chapter P :: Question 2
*
* Prompt user to input student infos,
* and then list them by grade.
*
* KoaLaYT 20:56 31/01/2020
*
*/
#include <iostream>
#include <limits>
#include <vector>
struct Student {
std::string name;
int grade;
};
int get_number() {
while (true) {
std::cout << "How many students would you like to enter? ";
int input{};
std::cin >> input;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please input an integer!\n";
} else {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (input <= 0) {
std::cout << "Please input an POSITIVE integer!\n";
} else {
return input;
}
}
}
}
std::string get_name(int index) {
std::cout << "Student #" << index+1 << " name: ";
std::string name{};
std::getline(std::cin, name);
return name;
}
int get_grade(int index) {
while (true) {
std::cout << "Student #" << index+1 << " grade (0 - 100): ";
int input{};
std::cin >> input;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please input an integer!\n";
} else {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (input < 0 || input > 100) {
std::cout << "Please input an integer between 0 to 100\n";
} else {
return input;
}
}
}
}
void get_students(std::vector<Student> &students, int size) {
for (int i{0}; i < size; ++i) {
students[i].name = get_name(i);
students[i].grade = get_grade(i);
}
}
bool sort_by_grade(const Student &s1, const Student &s2) { return s1.grade > s2.grade; }
void print_students(const std::vector<Student> &students) {
std::cout << '\n';
for (auto &s : students) {
std::cout << s.name << " got a grade of " << s.grade << '\n';
}
}
int main() {
int nums{get_number()};
std::vector<Student> students(nums);
get_students(students, nums);
std::sort(students.begin(), students.end(), sort_by_grade);
print_students(students);
}
| 22.131313 | 88 | 0.571885 | [
"vector"
] |
6ecb4ab9bd8237c336f237c71bd8c252367d9541 | 1,013 | cpp | C++ | src/playground/menu.cpp | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | src/playground/menu.cpp | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | src/playground/menu.cpp | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | #include <shaders/texture_vert_glsl.h>
#include <shaders/texture_frag_glsl.h>
#include <iostream>
#include "menu.h"
#include "scene.h"
Menu::Menu(){
if (!shader) shader = std::make_unique<ppgso::Shader>(texture_vert_glsl, texture_frag_glsl);
if (!texture) texture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("menu.bmp"));
if (!mesh) mesh = std::make_unique<ppgso::Mesh>("quad.obj");
}
bool Menu::update(Scene &scene, float dt){
generateModelMatrix();
return true;
}
void Menu::render(Scene &scene){
glDepthMask(GL_FALSE);
shader->use();
// Set up light
// shader->setUniform("LightDirection", scene.lightDirection);
// use camera
shader->setUniform("TextureOffset", textureOffset);
shader->setUniform("ModelMatrix", modelMatrix);
shader->setUniform("ProjectionMatrix", glm::mat4(1.0f));
shader->setUniform("ViewMatrix", glm::mat4(1.0f));
// render mesh
shader->setUniform("Texture", *texture);
mesh->render();
glDepthMask(GL_TRUE);
}
| 26.657895 | 93 | 0.688055 | [
"mesh",
"render"
] |
6ed09ee54b1770bbb12f33a10c6a8e4ed4f711de | 4,413 | cpp | C++ | Engine/addons/myguiplatforms/src/MyGUI_GenesisVertexBuffer.cpp | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 26 | 2015-01-15T12:57:40.000Z | 2022-02-16T10:07:12.000Z | Engine/addons/myguiplatforms/src/MyGUI_GenesisVertexBuffer.cpp | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | null | null | null | Engine/addons/myguiplatforms/src/MyGUI_GenesisVertexBuffer.cpp | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 17 | 2015-02-18T07:51:31.000Z | 2020-06-01T01:10:12.000Z | /*!
@file
@author Albert Semenov
@date 04/2009
*/
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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 "stdneb.h"
#include "MyGUI_GenesisVertexBuffer.h"
#include "memory/memory.h"
#include "graphicsystem/GraphicSystem.h"
#include "MyGUI_GenesisVertexBufferManager.h"
using namespace Graphic;
namespace MyGUI
{
const size_t VERTEX_IN_QUAD = 6;
const size_t RENDER_ITEM_STEEP_REALLOCK = 5 * VERTEX_IN_QUAD;
//const size_t RENDER_ITEM_STEEP_REALLOCK = 0;
GenesisVertexBuffer::GenesisVertexBuffer()
: mVertexCount(0)//(RENDER_ITEM_STEEP_REALLOCK)
, mNeedVertexCount(0)
{
GenesisVertexBufferMgr::Instance()->AddVertexBuffer(this);
}
GenesisVertexBuffer::~GenesisVertexBuffer()
{
destroyVertexBuffer();
}
bool _createVertexComponent(Util::Array<RenderBase::VertexComponent>& vertexComponents)
{
vertexComponents.Append(RenderBase::VertexComponent(RenderBase::VertexComponent::Position, 0, RenderBase::VertexComponent::Float3));
vertexComponents.Append(RenderBase::VertexComponent(RenderBase::VertexComponent::Color, 0, RenderBase::VertexComponent::ColorBGRA));
vertexComponents.Append(RenderBase::VertexComponent(RenderBase::VertexComponent::TexCoord, 0, RenderBase::VertexComponent::Float2));
return false;
}
void GenesisVertexBuffer::createVertexBuffer()
{
n_assert(!m_primHandle.IsValid());
static Util::Array<RenderBase::VertexComponent> vertexComponents;
static bool ______x = _createVertexComponent(vertexComponents);
mVertexBufferSize = mVertexCount * sizeof(Vertex);
VertexBufferData2 vbd2;
vbd2.GetVertexComponents() = vertexComponents;
vbd2.Setup(mVertexCount, sizeof(Vertex), RenderBase::BufferData::Dynamic, RenderBase::PrimitiveTopology::TriangleList, false);
m_primHandle = Graphic::GraphicSystem::Instance()->CreatePrimitiveHandle(&vbd2, NULL);
//m_primHandle = Graphic::GraphicSystem::Instance()->CreatePrimitiveGroup(RenderBase::PrimitiveTopology::TriangleList, Math::bbox::Zero, vb);
}
void GenesisVertexBuffer::destroyVertexBuffer()
{
GraphicSystem::Instance()->RemovePrimitive(m_primHandle);
m_primHandle = RenderBase::PrimitiveHandle();
}
void GenesisVertexBuffer::resizeVertexBuffer()
{
mVertexCount = mNeedVertexCount + RENDER_ITEM_STEEP_REALLOCK;
destroyVertexBuffer();
createVertexBuffer();
}
void GenesisVertexBuffer::setVertexCount(size_t _count)
{
mNeedVertexCount = _count;
}
size_t GenesisVertexBuffer::getVertexCount()
{
return mNeedVertexCount;
}
Vertex* GenesisVertexBuffer::lock()
{
if (mNeedVertexCount > mVertexCount)
{
resizeVertexBuffer();
}
//return m_vBuffer;
//RenderBase::PrimitiveGroup* pg = Graphic::GraphicSystem::Instance()->GetPrimitiveGroup(m_primHandle);
//return pg->GetVertexBuffer()->Lock<Vertex>();
mDynamicBuffer.SetSize(mVertexBufferSize);
return mDynamicBuffer.GetBufferPtr<Vertex>();
}
void GenesisVertexBuffer::unlock()
{
//RenderBase::PrimitiveGroup* pg = Graphic::GraphicSystem::Instance()->GetPrimitiveGroup(m_primHandle);
//pg->GetVertexBuffer()->Unlock();
//pg->GetVertexBuffer()->Flush();
Graphic::GraphicSystem::Instance()->UpdatePrimitiveHandle(m_primHandle, &mDynamicBuffer, NULL);
}
} // namespace MyGUI
| 36.471074 | 143 | 0.754589 | [
"3d"
] |
6ed4d23e75119015e284fbca2453eef6de56be71 | 665 | cpp | C++ | src/core/object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | src/core/object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | src/core/object.cpp | trukanduk/lispp | 9fe4564b2197ae216214fa0408f1e5c4c5105237 | [
"MIT"
] | null | null | null | #include <lispp/object.h>
namespace lispp {
Object::~Object() { }
std::string Object::GetTypeName() {
return "object";
}
int Object::get_ref_count() const {
return ref_count_;
}
int Object::ref() {
return ++ref_count_;
}
int Object::unref() {
const int result = unref_nodelete();
if (result == 0) {
delete this;
}
return result;
}
int Object::unref_nodelete() {
assert(ref_count_ > 0);
return --ref_count_;
}
std::ostream& operator<<(std::ostream& out, const Object& obj) {
return (out << obj.to_string());
}
std::ostream& operator<<(std::ostream& out, const DecoratorObject& obj) {
return (out << obj.to_string());
}
} // lispp
| 16.219512 | 73 | 0.645113 | [
"object"
] |
6ed54600978f1d5d7cdc6eb38137667802a62f95 | 1,110 | hpp | C++ | include/runtime/Frame.hpp | Skalwalker/JVM | ac71e17cd224b5dee7ae421edc78ea1d186bdecf | [
"MIT"
] | 1 | 2020-10-15T07:30:56.000Z | 2020-10-15T07:30:56.000Z | include/runtime/Frame.hpp | Skalwalker/JVM | ac71e17cd224b5dee7ae421edc78ea1d186bdecf | [
"MIT"
] | 27 | 2019-10-14T13:27:20.000Z | 2019-12-04T19:43:32.000Z | include/runtime/Frame.hpp | Skalwalker/JVM | ac71e17cd224b5dee7ae421edc78ea1d186bdecf | [
"MIT"
] | null | null | null | #ifndef FRAME_H_INCLUDED
#define FRAME_H_INCLUDED
#include <cstdint>
#include <vector>
#include <stack>
#include "../models/CPInfo.hpp"
#include "../models/MethodInfo.hpp"
#define TAG_EMPTY 0
#define TAG_BOOL 1
#define TAG_BYTE 2
#define TAG_CHAR 3
#define TAG_SHORT 4
#define TAG_INT 5
#define TAG_FLOAT 6
#define TAG_REFERENCE 7
#define TAG_RETURN 8
#define TAG_LONG 9
#define TAG_DOUBLE 10
struct Type {
uint8_t tag;
union {
uint32_t type_empty;
uint32_t type_boolean;
int8_t type_byte;
uint8_t type_char;
int16_t type_short;
int32_t type_int;
float type_float;
uint64_t type_reference;
uint32_t type_returnAddress;
int64_t type_long;
double type_double;
};
};
class Frame {
public:
MethodInfo method;
CodeAttribute codeAttribute;
stack<Type> operandStack;
vector<Type> localVariables;
vector<CPInfo> constantPool;
stack<Frame>* jvmStack;
uint32_t local_pc;
Frame(vector<CPInfo>, MethodInfo, stack<Frame>*);
vector<Type> intializeLocalVariable(uint16_t);
};
#endif
| 20.555556 | 53 | 0.696396 | [
"vector"
] |
6ed5c1795e35ac33c9d7db1eef3101e9a410fb7a | 1,723 | cpp | C++ | LightOJ/LightOJ - 1128/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | LightOJ/LightOJ - 1128/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | LightOJ/LightOJ - 1128/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2018-08-12 20:05:56
* solution_verdict: Accepted language: C++
* run_time (ms): 536 memory_used (MB): 20.6
* problem: https://vjudge.net/problem/LightOJ-1128
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
int t,n,q,pi,cost[N+2],sp[N+2][20];
int level[N+2],parent[N+2],tc;
vector<int>adj[N+2];
void dfs(int node,int par,int h)
{
level[node]=h;parent[node]=par;
for(int i=0;i<adj[node].size();i++)
{
int xx=adj[node][i];
if(xx==par)continue;
dfs(xx,node,h+1);
}
}
void sparse(void)
{
memset(sp,-1,sizeof(sp));
for(int i=0;i<n;i++)
sp[i][0]=parent[i];
for(int j=1;j<=18;j++)
{
for(int i=0;i<n;i++)
{
if(sp[i][j-1]==-1)continue;
sp[i][j]=sp[sp[i][j-1]][j-1];
}
}
}
void query(int node,int vl)
{
for(int i=18;i>=0;i--)
{
if(sp[node][i]==-1)continue;
if(cost[sp[node][i]]>=vl)node=sp[node][i];
}
printf("%d\n",node);
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&q);cost[0]=1;
for(int i=0;i<n;i++)adj[i].clear();
for(int i=1;i<n;i++)
{
scanf("%d%d",&pi,&cost[i]);
adj[pi].push_back(i);
}
dfs(0,-1,0);sparse();
printf("Case %d:\n",++tc);
while(q--)
{
int node,vl;scanf("%d%d",&node,&vl);
query(node,vl);
}
}
return 0;
} | 25.338235 | 111 | 0.418456 | [
"vector"
] |
6ee5177ee99226d664f9154722b0b6b015155553 | 10,788 | cpp | C++ | CRAB/gameeventmanager.cpp | arvindrajayadav/unrest | d89f20e95fbcdef37a47ab1454b2479522a0e43f | [
"MIT"
] | 11 | 2020-08-04T08:37:46.000Z | 2022-03-31T22:35:15.000Z | CRAB/gameeventmanager.cpp | arvindrajayadav/unrest | d89f20e95fbcdef37a47ab1454b2479522a0e43f | [
"MIT"
] | 1 | 2020-12-16T16:51:52.000Z | 2020-12-18T06:35:38.000Z | Unrest-iOS/gameeventmanager.cpp | arvindrajayadav/unrest | d89f20e95fbcdef37a47ab1454b2479522a0e43f | [
"MIT"
] | 7 | 2020-08-04T09:34:20.000Z | 2021-09-11T03:00:16.000Z | #include "stdafx.h"
#include "gameeventmanager.h"
using namespace pyrodactyl::people;
using namespace pyrodactyl::event;
using namespace pyrodactyl::level;
using namespace pyrodactyl::image;
using namespace pyrodactyl::ui;
void Manager::Init()
{
event_map.clear();
active_seq = UINT_MAX;
cur_sp = nullptr;
player = false;
cur_event = nullptr;
draw_game = true;
}
//------------------------------------------------------------------------
// Purpose: Load this
//------------------------------------------------------------------------
void Manager::Load(rapidxml::xml_node<char> *node, ParagraphData &popup)
{
if (NodeValid(node))
{
XMLDoc conf(node->first_attribute("list")->value());
if (conf.ready())
{
rapidxml::xml_node<char> *lnode = conf.Doc()->first_node("event_list");
for (rapidxml::xml_node<char> *loc = lnode->first_node("loc"); loc != NULL; loc = loc->next_sibling("loc"))
{
std::string loc_name;
LoadStr(loc_name, "name", loc);
for (auto n = loc->first_node("file"); n != NULL; n = n->next_sibling("file"))
{
unsigned int id;
std::string path;
LoadNum(id, "name", n);
LoadStr(path, "path", n);
event_map[loc_name].AddSeq(id, path);
}
}
}
active_seq = UINT_MAX;
conf.Load(node->first_attribute("layout")->value());
if (conf.ready())
{
rapidxml::xml_node<char> *layout = conf.Doc()->first_node("layout");
if (NodeValid(layout))
{
if (NodeValid("character", layout))
oh.Load(layout->first_node("character"));
if (NodeValid("popup", layout))
popup.Load(layout->first_node("popup"));
if (NodeValid("intro", layout))
intro.Load(layout->first_node("intro"));
}
}
reply.Load(node->first_attribute("conversation")->value());
per.Load(node->first_attribute("char")->value());
}
}
//------------------------------------------------------------------------
// Purpose: Handle events
//------------------------------------------------------------------------
void Manager::HandleEvents(Info &info, const std::string &player_id, SDL_Event &Event, HUD &hud, Level &level, std::vector<EventResult> &result)
{
//If an event is already being performed
if (event_map.count(info.CurLocID()) > 0 && event_map[info.CurLocID()].EventInProgress(active_seq))
{
switch (cur_event->type)
{
case EVENT_DIALOG:
if (oh.show_journal)
{
info.journal.HandleEvents(player_id, Event);
if (hud.back.HandleEvents(Event) == BUAC_LCLICK || hud.pausekey.HandleEvents(Event))
oh.show_journal = false;
}
else
{
//If journal button is select from within an event, go to the entry corresponding to that person's name
if (oh.HandleCommonEvents(Event))
{
if (info.PersonValid(cur_event->title))
{
Person &p = info.PersonGet(cur_event->title);
if (p.alt_journal_name)
info.journal.Open(player_id, JE_PEOPLE, p.journal_name);
else
info.journal.Open(player_id, JE_PEOPLE, p.name);
}
}
if (oh.HandleDlboxEvents(Event))
{
event_map[info.CurLocID()].NextEvent(active_seq, info, player_id, result, end_seq);
oh.show_journal = false;
}
}
break;
case EVENT_ANIM:
//Skip animation if key pressed or mouse pressed
if (Event.type == SDL_KEYUP || Event.type == SDL_MOUSEBUTTONUP)
event_map[info.CurLocID()].NextEvent(active_seq, info, player_id, result, end_seq);
break;
case EVENT_REPLY:
if (oh.show_journal)
{
info.journal.HandleEvents(player_id, Event);
if (hud.back.HandleEvents(Event) == BUAC_LCLICK || hud.pausekey.HandleEvents(Event))
oh.show_journal = false;
}
else
{
//If journal button is select from within an event, go to the entry corresponding to that person's name
if (oh.HandleCommonEvents(Event))
if (info.PersonValid(cur_event->title))
info.journal.Open(player_id, JE_PEOPLE, info.PersonGet(cur_event->title).name);
int choice = reply.HandleEvents(info, gEventStore.con.at(cur_event->special), cur_event->title, oh, Event);
if (choice >= 0)
{
event_map[info.CurLocID()].NextEvent(active_seq, info, player_id, result, end_seq, choice);
oh.show_journal = false;
}
}
break;
case EVENT_TEXT:
//If journal button is select from within an event, go to the entry corresponding to that person's name
if (oh.HandleCommonEvents(Event))
if (info.PersonValid(cur_event->title))
info.journal.Open(player_id, JE_PEOPLE, info.PersonGet(cur_event->title).name);
if (textin.HandleEvents(Event))
event_map[info.CurLocID()].NextEvent(active_seq, info, player_id, result, end_seq);
break;
case EVENT_SPLASH:
if (intro.show_traits)
{
per.HandleEvents(info, cur_event->title, Event);
if (hud.back.HandleEvents(Event) == BUAC_LCLICK || hud.pausekey.HandleEvents(Event))
intro.show_traits = false;
}
else
{
if (intro.HandleEvents(Event))
event_map[info.CurLocID()].NextEvent(active_seq, info, player_id, result, end_seq);
if (intro.show_traits)
per.Cache(info, level.PlayerID(), level);
}
break;
default: break;
}
EndSequence(info.CurLocID());
}
}
//------------------------------------------------------------------------
// Purpose: Internal Events
//------------------------------------------------------------------------
void Manager::InternalEvents(Info &info, Level &level, std::vector<EventResult> &result)
{
if (event_map.count(info.CurLocID()) > 0)
{
if (event_map[info.CurLocID()].EventInProgress(active_seq))
{
switch (cur_event->type)
{
case EVENT_DIALOG:
UpdateDialogBox(info, level);
break;
case EVENT_ANIM:
{
using namespace pyrodactyl::anim;
DrawType draw_val = DRAW_SAME;
if (gEventStore.anim.at(cur_event->special).InternalEvents(draw_val))
event_map[info.CurLocID()].NextEvent(active_seq, info, level.PlayerID(), result, end_seq);
if (draw_val == DRAW_STOP)
draw_game = false;
else if (draw_val == DRAW_START)
draw_game = true;
}
break;
case EVENT_SILENT:
event_map[info.CurLocID()].NextEvent(active_seq, info, level.PlayerID(), result, end_seq);
break;
case EVENT_REPLY:
UpdateDialogBox(info, level);
break;
case EVENT_SPLASH:
UpdateDialogBox(info, level);
break;
default: break;
}
EndSequence(info.CurLocID());
}
else
{
event_map[info.CurLocID()].InternalEvents(info);
CalcActiveSeq(info, level, level.Camera());
}
}
}
void Manager::UpdateDialogBox(Info &info, Level &level)
{
oh.InternalEvents(cur_event->state, cur_sp);
}
//------------------------------------------------------------------------
// Purpose: Draw
//------------------------------------------------------------------------
void Manager::Draw(Info &info, HUD &hud, Level &level)
{
if (event_map.count(info.CurLocID()) > 0 && event_map[info.CurLocID()].EventInProgress(active_seq))
{
switch (cur_event->type)
{
case EVENT_ANIM:
gEventStore.anim.at(cur_event->special).Draw();
break;
case EVENT_DIALOG:
gImageManager.DimScreen();
if (oh.show_journal)
{
info.journal.Draw(level.PlayerID());
hud.back.Draw();
}
else
oh.Draw(info, cur_event, cur_event->title, player, cur_sp);
break;
case EVENT_REPLY:
gImageManager.DimScreen();
if (oh.show_journal)
{
info.journal.Draw(level.PlayerID());
hud.back.Draw();
}
else
{
oh.Draw(info, cur_event, cur_event->title, player, cur_sp);
reply.Draw();
}
break;
case EVENT_TEXT:
oh.Draw(info, cur_event, cur_event->title, player, cur_sp);
textin.Draw();
break;
case EVENT_SPLASH:
gImageManager.DimScreen();
if (intro.show_traits)
{
per.Draw(info, cur_event->title);
hud.back.Draw();
}
else
intro.Draw(info, cur_event->dialog, cur_sp, cur_event->state);
break;
default:
break;
}
}
}
//------------------------------------------------------------------------
// Purpose: Calculate the current sequence in progress
//------------------------------------------------------------------------
void Manager::CalcActiveSeq(Info &info, Level &level, const Rect &camera)
{
if (event_map[info.CurLocID()].ActiveSeq(active_seq))
{
//Set all the pointers to the new values
cur_event = event_map[info.CurLocID()].CurEvent(active_seq);
oh.Reset(cur_event->title);
cur_sp = level.GetSprite(cur_event->title);
//The player character's dialog is drawn a bit differently compared to others
player = (cur_event->title == level.PlayerID());
switch (cur_event->type)
{
case EVENT_ANIM: gEventStore.anim.at(cur_event->special).Start(); break;
case EVENT_REPLY: reply.Cache(info, gEventStore.con.at(cur_event->special)); break;
default:break;
}
}
}
//------------------------------------------------------------------------
// Purpose: Get/set info
//------------------------------------------------------------------------
void Manager::EndSequence(const std::string &curloc)
{
if (end_seq.empty() == false)
{
for (auto i = end_seq.begin(); i != end_seq.end(); ++i)
if (i->cur)
event_map[curloc].EndSeq(active_seq);
else if (event_map.count(i->loc) > 0)
event_map.at(i->loc).EndSeq(StringToNumber<unsigned int>(i->val));
active_seq = UINT_MAX;
end_seq.clear();
}
}
bool Manager::EventInProgress()
{
if (active_seq == UINT_MAX)
return false;
return true;
}
//------------------------------------------------------------------------
// Purpose: Save the state of the object
//------------------------------------------------------------------------
void Manager::SaveState(rapidxml::xml_document<> &doc, rapidxml::xml_node<char> *root)
{
for (auto i = event_map.begin(); i != event_map.end(); ++i)
{
rapidxml::xml_node<char> *child = doc.allocate_node(rapidxml::node_element, "loc");
child->append_attribute(doc.allocate_attribute("name", i->first.c_str()));
i->second.SaveState(doc, child);
root->append_node(child);
}
}
//------------------------------------------------------------------------
// Purpose: Load the state of the object
//------------------------------------------------------------------------
void Manager::LoadState(rapidxml::xml_node<char> *node)
{
for (auto n = node->first_node("loc"); n != NULL; n = n->next_sibling("loc"))
{
if (n->first_attribute("name") != NULL)
{
std::string name = n->first_attribute("name")->value();
if (event_map.count(name) > 0)
event_map[name].LoadState(n);
}
}
}
//------------------------------------------------------------------------
// Purpose: Function called when window size is changed to adjust UI
//------------------------------------------------------------------------
void Manager::SetUI()
{
oh.SetUI();
reply.SetUI();
textin.SetUI();
per.SetUI();
} | 29.156757 | 144 | 0.58908 | [
"object",
"vector"
] |
6eef41cec168ec2c9b1bcf9a4cfbda9b89f4669a | 4,248 | cpp | C++ | SPOJ/POSTERS - Election Posters.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 6 | 2018-11-26T02:38:07.000Z | 2021-07-28T00:16:41.000Z | SPOJ/POSTERS - Election Posters.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 1 | 2021-05-30T09:25:53.000Z | 2021-06-05T08:33:56.000Z | SPOJ/POSTERS - Election Posters.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 4 | 2020-04-16T07:15:01.000Z | 2020-12-04T06:26:07.000Z | /*POSTERS - Election Posters
#ad-hoc-1
A parliamentary election was being held in Byteland. Its enterprising and orderly citizens decided to limit the entire election campaign to a single dedicated wall, so as not to ruin the panorama with countless posters and billboards. Every politician was allowed to hang exactly one poster on the wall. All posters extend from top to bottom, but are hung at different points of the wall, and may be of different width. The wall is divided horizontally into sections, and a poster completely occupies two or more adjacent sections.
With time, some of the posters were covered (partially or completely) by those of other politicians. Knowing the location of all the posters and the order in which they were hung, determine how many posters have at least one visible section in the end.
Input
The input begins with the integer t, the number of test cases. Then t test cases follow.
Each test case begins with a line containing integer n - the number of posters (1 <= n <= 40000). Then n lines follow, the i-th (1 <= i <= n) containing exactly two integers li ri, denoting the numbers of the leftmost and rightmost sections covered by the i-th poster (1 <= li < ri <= 107). The input order corresponds to the order of hanging posters.
Output
For each test case output a line containing one integer - the number of posters with visible sections.
Example
Sample input:
1
5
1 4
2 6
8 10
3 4
7 10
Sample output:
4
An illustration of the sample input is given below.*/
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
#include <vector>
struct Poster {
int a;
int b;
};
int tree[1000000]; // This is not the tree, just the lazy propagation array
inline void push_down(int node, int lo, int hi)
{
if(tree[node] != 0)
{
if(lo != hi)
{
tree[2*node] = tree[2*node+1] = tree[node];
tree[node] = 0;
}
}
}
void range_update(int node, int lo, int hi, int i, int j, int val)
{
if (lo > hi || lo > j || hi < i)
return;
else if (lo >= i && hi <= j)
{
tree[node] = val;
}
else
{
push_down(node, lo, hi);
int mid = (lo + hi) / 2;
range_update(node*2, lo, mid, i, j, val);
range_update(node*2+1, mid+1, hi, i, j, val);
}
}
void query(int node, int lo, int hi, int i, int j, std::set<int>& output)
{
if (lo > hi || lo > j || hi < i)
return;
else if (tree[node] != 0 || lo == hi)
output.insert(tree[node]);
else
{
int mid = (lo + hi) / 2;
query(node*2, lo, mid, i, j, output);
query(node*2+1, mid+1, hi, i, j, output);
}
}
int main()
{
int tests;
std::scanf("%d", &tests);
while (tests--)
{
int n;
std::scanf("%d", &n);
std::vector<int> coord; // for coord compression
std::vector<Poster> vec (n);
// Input
for (int i = 0; i < n; ++i)
{
int l, r;
std::scanf("%d %d", &l, &r);
vec[i].a = l;
vec[i].b = r;
coord.push_back(l);
coord.push_back(r);
}
// Transform input vec with coord compression
std::sort(coord.begin(), coord.end());
int mx = 0;
for (auto& elem: vec)
{
elem.a = std::distance(std::begin(coord), std::lower_bound(coord.begin(), coord.end(), elem.a));
elem.b = std::distance(std::begin(coord), std::lower_bound(coord.begin(), coord.end(), elem.b));
if (elem.a > elem.b)
std::swap(elem.a, elem.b);
mx = std::max(mx, elem.b);
}
// Clear Segtree
std::memset(tree, 0, sizeof(int) * 1000000);
// Put each poster with coor [a, b] with color i+1
for (int i = 0; i < n; ++i)
{
range_update(1, 0, mx, vec[i].a, vec[i].b, i+1);
}
// Result
std::set<int> res {};
query(1, 0, mx, 0, mx, res);
res.erase(0);
std::printf("%d\n", res.size());
}
return 0;
}
| 28.32 | 531 | 0.558616 | [
"vector",
"transform"
] |
6ef51508084fc9c761455f671ab925ba6586da68 | 41,406 | cpp | C++ | src/newCompilerHelper.cpp | Fabio3rs/COFF-to-GTAScript-Helper | dc606372c48dd4f50ac822b77b71d5c0ea765544 | [
"MIT"
] | null | null | null | src/newCompilerHelper.cpp | Fabio3rs/COFF-to-GTAScript-Helper | dc606372c48dd4f50ac822b77b71d5c0ea765544 | [
"MIT"
] | null | null | null | src/newCompilerHelper.cpp | Fabio3rs/COFF-to-GTAScript-Helper | dc606372c48dd4f50ac822b77b71d5c0ea765544 | [
"MIT"
] | null | null | null | /*
Helper to convert compiled bytecode in COFF object to use with GTA3Script/CLEO Scripts in GTA San Andreas
Write by Fabio3rs - https://github.com/Fabio3rs
MIT License
Copyright (c) 2020 Fabio3rs
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.
*/
// http://brmodstudio.forumeiros.com
// http://brmodstudio.forumeiros.com
// http://brmodstudio.forumeiros.com
/*
Compile with:
g++ newCompilerHelper.cpp CText.cpp --std=c++17
Tested with MinGW objects on Windows
*/
#define _CRT_SECURE_NO_WARNINGS
#include "CText.h"
#include <iostream>
#include <fstream>
#include <memory>
#include <vector>
#include <string>
#include <map>
#include <utility>
#include <sstream>
#include <cctype>
#include <optional>
#include <cmath>
//// http://www.zedwood.com/article/cpp-str_replace-function
std::string& str_replace(const std::string &search, const std::string &replace, std::string &subject)
{
std::string buffer;
const int sealeng = search.length();
const int strleng = subject.length();
if (sealeng == 0)
return subject; //no change
for (int i = 0, j = 0; i<strleng; j = 0)
{
while (i + j<strleng && j<sealeng && subject[i + j] == search[j])
j++;
if (j == sealeng) //found 'search'
{
buffer.append(replace);
i += sealeng;
}
else
{
buffer.append(&subject[i++], 1);
}
}
subject = buffer;
return subject;
}
static inline void ltrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch)
{
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch)
{
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s)
{
ltrim(s);
rtrim(s);
}
std::string compileCMD = "F:/MinGW/bin/g++.exe -c %0 -fno-exceptions -IF:\\MinGW\\include -IF:\\MinGW\\i686-w64-mingw32\\include -IF:\\MinGW\\i686-w64-mingw32\\include\\c++ -IF:\\MinGW\\i686-w64-mingw32\\include\\c++\\i686-w64-mingw32 -IF:\\MinGW\\lib\\gcc\\i686-w64-mingw32\\4.8.3\\include -nostdlib -std=c++11 -shared -masm=intel -o %1";
std::string compileCMD2 = "F:/MinGW/bin/g++.exe -c new.cpp -fno-exceptions -IF:\\MinGW\\include -IF:\\MinGW\\i686-w64-mingw32\\include -IF:\\MinGW\\i686-w64-mingw32\\include\\c++ -IF:\\MinGW\\i686-w64-mingw32\\include\\c++\\i686-w64-mingw32 -IF:\\MinGW\\lib\\gcc\\i686-w64-mingw32\\4.8.3\\include -nostdlib -std=c++11 -shared -masm=intel -o testnew.o";
bool debugOn = false;
bool outputToGTA3SCFormat = false;
bool exportList = true, exportOtherFunctions = false;
int rellocOffset = 0;
std::vector<std::string> exports;
void executeCommand(const std::string &command)
{
system(command.c_str());
}
#pragma pack(push, 1)
union COFFNameUnion
{
char str[8];
struct
{
unsigned long zeroes;
unsigned long offset;
};
};
// COFF file structures, thanks to http://wiki.osdev.org/COFF
struct COFFHeader {
unsigned short f_magic; /* Magic number */
unsigned short f_nscns; /* Number of Sections */
long f_timdat; /* Time & date stamp */
long f_symptr; /* File pointer to Symbol Table */
long f_nsyms; /* Number of Symbols */
unsigned short f_opthdr; /* sizeof(Optional Header) */
unsigned short f_flags; /* Flags */
};
struct COFFOptionalHeader {
unsigned short magic; /* Magic Number */
unsigned short vstamp; /* Version stamp */
unsigned long tsize; /* Text size in bytes */
unsigned long dsize; /* Initialised data size */
unsigned long bsize; /* Uninitialised data size */
unsigned long entry; /* Entry point */
unsigned long text_start; /* Base of Text used for this file */
unsigned long data_start; /* Base of Data used for this file */
};
enum COFFSectionHeaderType { STYP_TEXT = 0x20, STYP_DATA = 0x40, STYP_BSS = 0x80};
long COFFSectionHeaderTypes = STYP_TEXT | STYP_DATA | STYP_BSS;
struct COFFSectionHeader {
COFFNameUnion s_name; /* Section Name */
long s_paddr; /* Physical Address */
long s_vaddr; /* Virtual Address */
long s_size; /* Section Size in Bytes */
long s_scnptr; /* File offset to the Section data */
long s_relptr; /* File offset to the Relocation table for this Section */
long s_lnnoptr; /* File offset to the Line Number table for this Section */
unsigned short s_nreloc; /* Number of Relocation table entries */
unsigned short s_nlnno; /* Number of Line Number table entries */
long s_flags; /* Flags for this section */
};
struct COFFRealocationsEntries {
long r_vaddr; /* Reference Address */
long r_symndx; /* Symbol index */
unsigned short r_type; /* Type of relocation */
//unsigned short offset; /* offset */
};
struct COFFLineNumberEntries {
union
{
long l_symndx; /* Symbol Index */
long l_paddr; /* Physical Address */
} l_addr;
unsigned short l_lnno; /* Line Number */
};
struct COFFSymbolTable
{
COFFNameUnion name;
long n_value; /* Value of Symbol */
short n_scnum; /* Section Number */
unsigned short n_type; /* Symbol Type */
char n_sclass; /* Storage Class */
char n_numaux; /* Auxiliary Count */
};
struct COFFSectionHeaderCPP
{
COFFSectionHeader rawSectionHeader;
std::unique_ptr<COFFRealocationsEntries[]> rawRealocationsEntries;
std::unique_ptr<COFFLineNumberEntries[]> rawLineNumberEntries;
std::unique_ptr<char[]> sectionData;
};
struct writtenSymbols
{
COFFSymbolTable *symbol;
int address;
std::streampos filePos;
};
#pragma pack(pop)
class COFFFile
{
public:
COFFHeader header;
COFFOptionalHeader optionalHeader;
std::unique_ptr<COFFSectionHeaderCPP[]> sectionsHeader;
std::unique_ptr<COFFSymbolTable[]> symbolTable;
std::map<long, std::string> stringData;
std::vector<writtenSymbols> wSymbols;
bool open;
COFFFile()
{
open = false;
}
int getNumSections() const
{
return header.f_nscns;
}
int getNumSymbols() const
{
return header.f_nsyms;
}
std::string getFullName(const COFFNameUnion &n) const
{
std::string result = "Fail to get name";
if (n.zeroes != 0)
{
int num = 8;
if (n.str[7] == 0)
num = strlen(n.str);
result = "";
result.insert(0, n.str, num);
}
else
{
auto off = stringData.find(n.offset);
if (off != stringData.end())
result = off->second;
}
return result;
}
std::string getSectionName(int id) const
{
if (getNumSections() <= id)
return "Fail to get name";
return getFullName(sectionsHeader[id].rawSectionHeader.s_name);
}
std::string getSymbolName(int id) const
{
if (getNumSymbols() <= id)
return "Fail to get name";
return getFullName(symbolTable[id].name);
}
COFFSymbolTable &getSymbolByName(const std::string &name)
{
for (int i = 0; i < getNumSymbols(); i++)
{
if (getFullName(symbolTable[i].name) == name)
{
return symbolTable[i];
}
}
throw std::runtime_error(std::string(__FILE__) + " " + std::to_string(__LINE__));
}
};
COFFFile openCOFFFile(const std::string &file)
{
COFFFile COFFfile;
std::fstream test(file, std::ios::in | std::ios::binary);
if (!test.is_open())
{
std::cout << "Fail to open the file" << std::endl;
return COFFfile;
}
COFFfile.open = true;
test.seekg(0, std::ios::beg);
test.read(reinterpret_cast<char*>(&COFFfile.header), sizeof(COFFfile.header));
//std::cout << header.f_opthdr << std::endl;
//std::cout << header.f_nscns << std::endl;
if (COFFfile.header.f_opthdr != 0)
{
test.read(reinterpret_cast<char*>(&COFFfile.optionalHeader), sizeof(COFFfile.optionalHeader));
}
COFFfile.sectionsHeader = std::make_unique<COFFSectionHeaderCPP[]>(COFFfile.header.f_nscns);
COFFfile.symbolTable = std::make_unique<COFFSymbolTable[]>(COFFfile.header.f_nsyms);
{
auto sectionsHeaderPointer = COFFfile.sectionsHeader.get();
for (int i = 0; i < COFFfile.header.f_nscns; i++)
{
auto §ionHeader = sectionsHeaderPointer[i];
test.read(reinterpret_cast<char*>(&(sectionHeader.rawSectionHeader)), sizeof(COFFSectionHeader));
}
for (int i = 0; i < COFFfile.header.f_nscns; i++)
{
auto §ionHeader = sectionsHeaderPointer[i];
/*std::cout << "Section name " << sectionHeader.rawSectionHeader.s_name << " Section size " << sectionHeader.rawSectionHeader.s_size
<< " lines num " << sectionHeader.rawSectionHeader.s_nlnno
<< " relocations num " << sectionHeader.rawSectionHeader.s_nreloc
<< " type " << (sectionHeader.rawSectionHeader.s_flags & COFFSectionHeaderTypes) << std::endl;*/
if (sectionHeader.rawSectionHeader.s_scnptr > 0 && sectionHeader.rawSectionHeader.s_size > 0)
{
sectionHeader.sectionData = std::make_unique<char[]>(sectionHeader.rawSectionHeader.s_size);
test.seekg(sectionHeader.rawSectionHeader.s_scnptr, std::ios::beg);
test.read(sectionHeader.sectionData.get(), sectionHeader.rawSectionHeader.s_size);
}
if (sectionHeader.rawSectionHeader.s_nreloc > 0)
{
sectionHeader.rawRealocationsEntries = std::make_unique<COFFRealocationsEntries[]>(sectionHeader.rawSectionHeader.s_nreloc);
test.seekg(sectionHeader.rawSectionHeader.s_relptr, std::ios::beg);
test.read(reinterpret_cast<char*>(sectionHeader.rawRealocationsEntries.get()), sizeof(COFFRealocationsEntries) * sectionHeader.rawSectionHeader.s_nreloc);
}
if (sectionHeader.rawSectionHeader.s_nlnno > 0)
{
sectionHeader.rawLineNumberEntries = std::make_unique<COFFLineNumberEntries[]>(sectionHeader.rawSectionHeader.s_nlnno);
test.seekg(sectionHeader.rawSectionHeader.s_lnnoptr, std::ios::beg);
test.read(reinterpret_cast<char*>(sectionHeader.rawLineNumberEntries.get()), sizeof(COFFLineNumberEntries) * sectionHeader.rawSectionHeader.s_nlnno);
}
}
}
// Read symbols table
test.seekg(COFFfile.header.f_symptr, std::ios::beg);
test.read(reinterpret_cast<char*>(COFFfile.symbolTable.get()), sizeof(COFFSymbolTable) * COFFfile.header.f_nsyms);
int32_t mem = 0;
test.read(reinterpret_cast<char*>(&mem), sizeof(mem));
std::unique_ptr<char[]> strings = std::make_unique<char[]>(mem);
const int memTest = (mem - 4);
{
memset(strings.get(), 0, 4);
test.read(strings.get() + 4, mem - 4);
char *s = strings.get();
for (int i = 0; i < memTest; i++)
{
if (i >= memTest)
{
break;
}
COFFfile.stringData[i] = &s[i];
int len = strlen(&s[i]);
i += len;
while (i < memTest)
{
if (s[i] == 0)
{
i++;
}
else
{
i--;
break;
}
}
}
}
for (int i = 0; i < COFFfile.header.f_nsyms; i++)
{
/*COFFSymbolTable &symbtable = COFFfile.symbolTable[i];
if (symbtable.name.zeroes != 0 && symbtable.name.str[0] > 0 && isprint(symbtable.name.str[0]))
{
std::cout << symbtable.name.str << std::endl;
}
else
{
if (symbtable.name.offset && symbtable.name.offset < memTest)
{
std::cout << "zeroes " << symbtable.name.zeroes << std::endl;
std::cout << "offset " << symbtable.name.offset << std::endl;
std::cout << " " << COFFfile.stringData[symbtable.name.offset] << std::endl;
}
}*/
}
return COFFfile;
}
void makeCall(std::vector<uint8_t> &data, int absoluteTargetAddress)
{
int32_t calc = data.size();
calc += 5;
calc = absoluteTargetAddress - calc;
data.push_back(0xE8);
uint8_t *calcPtr = reinterpret_cast<uint8_t*>(&calc);
data.insert(data.end(), calcPtr, calcPtr + sizeof(calc));
}
void makeExternalCall(std::vector<uint8_t> &data, uint32_t absoluteTargetAddress)
{
uint8_t asmData[] = {
0x68, 0x00, 0x00, 0x00, 0x00,
0xC3
};
*reinterpret_cast<uint32_t*>(&asmData[1]) = absoluteTargetAddress;
data.insert(data.end(), asmData, asmData + (sizeof(asmData) / sizeof(uint8_t)));
}
void makeExternalCallPushAddress(std::vector<uint8_t> &data, uint32_t absoluteTargetAddress)
{
uint8_t asmData[] = {
0x00, 0x00, 0x00, 0x00
};
*reinterpret_cast<uint32_t*>(&asmData[0]) = absoluteTargetAddress;
data.insert(data.end(), asmData, asmData + (sizeof(asmData) / sizeof(uint8_t)));
}
writtenSymbols getSymbolForReAlloc(const COFFFile &file, int symbolId)
{
writtenSymbols result{0, 0, 0};
if (file.getNumSymbols() > symbolId)
{
auto &symbol = file.symbolTable[symbolId];
for (auto &ws : file.wSymbols)
{
if (std::addressof(symbol) == ws.symbol)
return ws;
}
}
return result;
}
struct scriptSymbols
{
std::string name;
int pos;
int COFFid;
scriptSymbols()
{
pos = 0;
COFFid = -1;
}
};
std::vector<scriptSymbols> symbols;
scriptSymbols &getSymbolByName(const std::string &name)
{
for (int i = 0; i < symbols.size(); i++)
{
if (symbols[i].name == name)
{
return symbols[i];
}
}
throw std::runtime_error(std::string(__FILE__) + " " + std::to_string(__LINE__));
}
std::optional<scriptSymbols> symbolForIndex(int index)
{
for (auto &s : symbols)
{
if (s.pos == index)
{
return s;
}
}
return std::nullopt;
}
std::string outputStartHex()
{
if (outputToGTA3SCFormat)
{
return "DUMP";
}
return "HEX";
}
std::string outputEndHex()
{
if (outputToGTA3SCFormat)
{
return "ENDDUMP";
}
return "END";
}
std::string labelFormat(const std::string &label)
{
if (outputToGTA3SCFormat)
{
return label + ":";
}
return ":" + label;
}
bool mustExportThisSymbol(const std::string &symbolName)
{
if (symbolName.size() == 0)
return false;
if (symbolName == "_initCPPCode")
{
return true;
}
std::string s = symbolName;
if (s[0] == '_')
s[0] = ' ';
trim(s);
//std::cout << s << s.size() << std::endl;
auto it = std::find(exports.begin(), exports.end(), s);
if (it != exports.end())
{
//std::cout << "it true" << std::endl;
return true;
}
return false;
}
void vectorDataToFile(COFFFile &coff, std::fstream &fout, std::vector<uint8_t> &data)
{
int breakLineCount = 0;
// TODO: find .drectve section
bool DUMP = false, firstDUMP = false;
for (int i = 0; i < data.size(); i++, breakLineCount++)
{
auto &ch = data[i];
auto sn = symbolForIndex(i);
if (sn)
{
auto symbol = sn.value();
if (mustExportThisSymbol(symbol.name) && (symbol.COFFid == -1 || (symbol.COFFid >= 0 && coff.symbolTable[symbol.COFFid].n_type == 32)))
{
if (DUMP)
{
fout << std::endl;
fout << outputEndHex() << "\n";
}
fout << std::endl;
fout << labelFormat(symbol.name) << "\n";
fout << outputStartHex() << "\n";
breakLineCount = 0;
DUMP = true;
firstDUMP = true;
}
}
if (!firstDUMP)
{
fout << outputStartHex() << "\n";
firstDUMP = true;
DUMP = true;
}
fout << std::hex << (ch < 0x10 ? "0" : "") << (int)(ch) << " ";
if (breakLineCount >= 60)
{
fout << std::endl;
breakLineCount = 0;
}
}
}
void pushSymbolForSection(const COFFFile &file, int section, int value, int bytes)
{
for (int l = 0; l < file.getNumSymbols(); l++)
{
auto &symbol = file.symbolTable[l];
//std::cout << symbol.n_type << std::endl;
if ((symbol.n_scnum - 1) == section && /*symbol.n_type > 0 &&*/ symbol.n_value == value)
{
scriptSymbols ns;
ns.name = file.getFullName(symbol.name);
ns.pos = bytes;
ns.COFFid = l;
//std::cout << ns.name << std::endl;
//std::cout << bytes << std::endl;
//std::cout << value << std::endl;
//std::cout << l << std::endl;
symbols.push_back(std::move(ns));
}
}
}
void listSymbols(const COFFFile &file)
{
for (int l = 0; l < file.getNumSymbols(); l++)
{
auto &symbol = file.symbolTable[l];
{
std::cout << file.getFullName(symbol.name) << std::endl;
std::cout << l << std::endl;
}
}
}
struct reallocationTable
{
int32_t offset;
int32_t symbol;
int32_t type;
reallocationTable()
{
offset = symbol = type = 0;
}
reallocationTable(const COFFRealocationsEntries &entry)
{
offset = entry.r_vaddr;
symbol = entry.r_symndx;
type = entry.r_type;
}
};
struct reallocationTableToFile
{
int32_t offset;
int32_t symbol;
reallocationTableToFile()
{
offset = symbol = 0;
}
reallocationTableToFile(const reallocationTable &entry)
{
offset = entry.offset;
symbol = entry.symbol;
}
};
std::vector<reallocationTable> rellocations;
enum externalSymbolsType {textFunction, dataFunction};
struct externalObjectList
{
uint32_t address;
int type;
externalObjectList()
{
address = 0;
type = 0;
}
};
std::map<std::string, externalObjectList> externalObjects;
const std::map<std::string, externalObjectList> &getExternalObjectsList()
{
return externalObjects;
}
void parseDrective(const char *p, int size)
{
if (p && size > 0)
{
std::string str(p, p + size);
std::replace(str.begin(), str.end(), ' ', '\n');
std::replace(str.begin(), str.end(), ' ', '\n');
str_replace("-export:\"", "\n", str);
std::replace(str.begin(), str.end(), '"', '\n');
trim(str);
std::stringstream s(str);
std::string temp;
while (std::getline(s, temp))
{
trim(temp);
if (temp.size() == 0)
continue;
//std::cout << temp << temp.size() << std::endl;
exports.push_back(temp);
}
}
}
void loadSymbolList()
{
std::cout << "Tentando carregar SymbolList.txt..." << std::endl;
std::string test;
{
std::fstream symbolList("SymbolList.txt", std::ios::in | std::ios::binary);
if (symbolList.fail())
{
std::cout << "Falha ao abrir o arquivo SymbolList.txt" << std::endl << std::endl;
return;
}
symbolList.seekg(0, std::ios::end);
size_t size = symbolList.tellg();
symbolList.seekg(0, std::ios::beg);
test.insert(0, size, '\n');
symbolList.read(test.data(), size);
}
std::stringstream contents(std::move(test));
char line[1024];
while (contents.getline(line, sizeof(line)))
{
char funame[128], sect[64];
uint32_t addr;
int r = sscanf(line, "%s %s %x", funame, sect, &addr);
if (r == 3)
{
auto &nSymbol = externalObjects[funame];
nSymbol.address = addr;
nSymbol.type = externalSymbolsType::textFunction;
if (std::string(sect).find("data") != std::string::npos)
{
nSymbol.type = externalSymbolsType::dataFunction;
}
}
}
}
template<class T>
void printbits(T c)
{
for (int i = 0; i < (sizeof(T) * 8); i++)
{
const uint64_t b = pow(2, i);
std::cout << ((c & b) != 0);
}
}
void toCLEOSCM(COFFFile &COFFfile, const std::string &outFinalFile)
{
rellocations.clear();
symbols.clear();
exports.clear();
if (COFFfile.open)
{
std::fstream fout(outFinalFile, std::ios::out | std::ios::trunc);
if (fout.is_open())
{
std::vector<uint8_t> outputData;
{
externalObjectList nobj;
nobj.address = 0x00588BE0;
nobj.type = 0;
externalObjects["_showTextBox"] = nobj;
}
{
{
scriptSymbols ns;
ns.name = "getCodeTopAddress";
ns.pos = outputData.size();
symbols.push_back(ns);
}
uint8_t ab[] = { 0xE8u, 0x01u, 0x00u, 0x00u, 0x00u, 0xC3u, 0x8Bu, 0x04u, 0x24u, 0x83u, 0xE8u, 0x05u, 0xC3u };
outputData.insert(outputData.end(), ab, ab + (sizeof(ab) / sizeof(uint8_t)));
}
for (int i = 0; i < COFFfile.getNumSections(); i++)
{
auto §ion = COFFfile.sectionsHeader[i];
if (COFFfile.getSectionName(i) == ".drectve")
{
//std::cout << (section.rawSectionHeader.s_flags & (STYP_TEXT | STYP_DATA | STYP_BSS)) << std::endl << std::endl;
parseDrective(section.sectionData.get(), section.rawSectionHeader.s_size);
continue;
}
if (section.rawSectionHeader.s_nreloc > 0)
{
auto reloc = section.rawRealocationsEntries.get();
for (int i = 0; i < section.rawSectionHeader.s_nreloc; i++)
{
reallocationTable r = reloc[i];
r.offset += outputData.size();
//std::cout << reloc[i].offset << std::endl;
rellocations.push_back(r);
}
}
if (section.rawSectionHeader.s_flags & STYP_TEXT)
{
auto data = section.sectionData.get();
for (int j = 0; j < section.rawSectionHeader.s_size; j++)
{
uint8_t ubyte = static_cast<uint8_t>(data[j]);
pushSymbolForSection(COFFfile, i, j, outputData.size());
outputData.push_back(ubyte);
}
}
if (section.rawSectionHeader.s_flags & STYP_DATA)
{
auto data = section.sectionData.get();
for (int j = 0; j < section.rawSectionHeader.s_size; j++)
{
uint8_t ubyte = static_cast<uint8_t>(data[j]);
pushSymbolForSection(COFFfile, i, j, outputData.size());
outputData.push_back(ubyte);
}
}
if (section.rawSectionHeader.s_flags & STYP_BSS)
{
for (int j = 0; j < section.rawSectionHeader.s_size; j++)
{
pushSymbolForSection(COFFfile, i, j, outputData.size());
outputData.push_back(0x00);
}
}
}
for (int i = 0; i < COFFfile.getNumSymbols(); i++)
{
auto &symbol = COFFfile.symbolTable[i];
if (symbol.n_scnum == 0) {
auto objFullName = COFFfile.getFullName(symbol.name);
/*std::cout << objFullName << std::endl;
std::cout << "n_type " << symbol.n_type << std::endl;
std::cout << "n_value " << symbol.n_value << std::endl;
std::cout << "n_scnum " << symbol.n_scnum << std::endl;*/
auto &eobj = getExternalObjectsList();
auto it = eobj.find(objFullName);
if (it != eobj.end())
{
{
scriptSymbols ns;
ns.name = objFullName;
ns.pos = outputData.size();
ns.COFFid = i;
symbols.push_back(std::move(ns));
}
switch (it->second.type)
{
case 0:
makeExternalCall(outputData, it->second.address);
break;
case 1:
makeExternalCallPushAddress(outputData, it->second.address);
break;
case 2:
break;
default:
break;
}
}
else
{
std::cout << "Undefined external: " << COFFfile.getSymbolName(i) << std::endl;
}
}
}
int reallocationFunctionPos = 0;
{
scriptSymbols ns;
ns.name = "reallocationFunction";
ns.pos = outputData.size();
reallocationFunctionPos = ns.pos;
symbols.push_back(std::move(ns));
/*
#include <cstdint>
struct reallocationTable
{
int32_t offset;
int32_t symbol;
int32_t type;
};
extern "C" void volatile reallocationFunction(char *codeTop)
{
char *tablePos = codeTop;
tablePos += 0x10000;
reallocationTable *table = reinterpret_cast<reallocationTable*>(tablePos);
int tableSize = 1000;
for (int i = 0; i < tableSize; i++)
{
auto &tb = table[i];
int32_t **value = reinterpret_cast<int32_t**>(&codeTop[tb.offset]);
*value = reinterpret_cast<int32_t*>(&codeTop[tb.symbol]);
}
}
*/
int startPos = outputData.size();
uint8_t reallocationFunCode[] = {
/* 11 00000000*/ 0x55, //push ebp
/* 14 00000001*/ 0x89, 0xE5, //mov ebp, esp
/* 16 00000003*/ 0x83, 0xEC, 0x20, //sub esp, 32
/* 17 00000006*/ 0x8B, 0x45, 0x08, //mov eax, DWORD [ebp+8]
/* 18 00000009*/ 0x89, 0x45, 0xF8, //mov DWORD [ebp-8], eax
/* 19 0000000C*/ 0x81, 0x45, 0xF8, 0x00, 0x00, 0x01, 0x00, //add DWORD [ebp-8], 65536
/* 20 00000013*/ 0x8B, 0x45, 0xF8, //mov eax, DWORD [ebp-8]
/* 21 00000016*/ 0x89, 0x45, 0xF4, //mov DWORD [ebp-12], eax
/* 22 00000019*/ 0xC7, 0x45, 0xF0, 0xE8, 0x03, 0x00, 0x00, //mov DWORD [ebp-16], 1000
/* 23 00000020*/ 0xC7, 0x45, 0xFC, 0x00, 0x00, 0x00, 0x00, //mov DWORD [ebp-4], 0
/* 24 00000027*/ 0xEB, 0x37, //jmp L2
/* 26 00000029*/ 0x8B, 0x45, 0xFC, //mov eax, DWORD [ebp-4]
/* 27 0000002C*/ 0x8D, 0x14, 0xC5, 0x00, 0x00, 0x00, 0x00, //lea edx, [0+eax*8]
/* 28 00000033*/ 0x8B, 0x45, 0xF4, //mov eax, DWORD [ebp-12]
/* 29 00000036*/ 0x01, 0xD0, //add eax, edx
/* 30 00000038*/ 0x89, 0x45, 0xEC, //mov DWORD [ebp-20], eax
/* 31 0000003B*/ 0x8B, 0x45, 0xEC, //mov eax, DWORD [ebp-20]
/* 32 0000003E*/ 0x8B, 0x00, //mov eax, DWORD [eax]
/* 33 00000040*/ 0x89, 0xC2, //mov edx, eax
/* 34 00000042*/ 0x8B, 0x45, 0x08, //mov eax, DWORD [ebp+8]
/* 35 00000045*/ 0x01, 0xD0, //add eax, edx
/* 36 00000047*/ 0x89, 0x45, 0xE8, //mov DWORD [ebp-24], eax
/* 37 0000004A*/ 0x8B, 0x45, 0xEC, //mov eax, DWORD [ebp-20]
/* 38 0000004D*/ 0x8B, 0x40, 0x04, //mov eax, DWORD [eax+4]
/* 39 00000050*/ 0x89, 0xC2, //mov edx, eax
/* 40 00000052*/ 0x8B, 0x45, 0x08, //mov eax, DWORD [ebp+8]
/* 41 00000055*/ 0x01, 0xC2, //add edx, eax
/* 42 00000057*/ 0x8B, 0x45, 0xE8, //mov eax, DWORD [ebp-24]
/* 43 0000005A*/ 0x89, 0x10, //mov DWORD [eax], edx
/* 44 0000005C*/ 0x83, 0x45, 0xFC, 01, //add DWORD [ebp-4], 1
/* 46 00000060*/ 0x8B, 0x45, 0xFC, //mov eax, DWORD [ebp-4]
/* 47 00000063*/ 0x3B, 0x45, 0xF0, //cmp eax, DWORD [ebp-16]
/* 48 00000066*/ 0x7C, 0xC1, //jl L3
/* 49 00000068*/ 0xC9, //leave
/* 52 00000069*/ 0xC3 //ret
};
outputData.insert(outputData.end(), reallocationFunCode, reallocationFunCode + (sizeof(reallocationFunCode) / sizeof(uint8_t)));
int offsetPosInOutputData = startPos + 0xC + 3;
int numPosInOutputData = startPos + 0x19 + 3;
for (auto it = rellocations.begin(); it != rellocations.end(); )
{
if (it->type == 20)
{
int32_t off = it->offset;
int32_t symbol = it->symbol;
for (int i = 0; i < symbols.size(); i++)
{
auto &s = symbols[i];
if (s.COFFid >= 0 && symbol == s.COFFid)
{
int32_t target = s.pos;
//std::cout << COFFfile.getSymbolName(s.COFFid) << std::endl;
//std::cout << outputData[target] << std::endl;
//std::cout << off << std::endl;
target = target - (off + 4);
//std::cout << target << std::endl;
*reinterpret_cast<int32_t*>(std::addressof(outputData[it->offset])) = target;
break;
}
}
it = rellocations.erase(it);
}
else
{
auto &value = *reinterpret_cast<int32_t*>(std::addressof(outputData[it->offset]));
if (value > 0 && it->type == 6)
{
bool found = false;
for (int i = 0; i < COFFfile.getNumSymbols(); i++)
{
if (found)
break;
auto &symbol = COFFfile.symbolTable[i];
if (symbol.n_value == value)
{
for (int k = 0; k < symbols.size(); k++)
{
auto &s = symbols[k];
if (s.COFFid >= 0 && i == s.COFFid)
{
std::cout << "it symbol " << it->symbol << std::endl;
std::cout << "s.pos " << s.pos << std::endl;
/*std::cout << "COFFid " << i << std::endl;
std::cout << "it offset " << it->offset << std::endl;
std::cout << "name " << COFFfile.getSymbolName(i) << std::endl;
std::cout << "value " << value << std::endl;
std::cout << "symbol.n_numaux " << (int)symbol.n_numaux << std::endl;
std::cout << "symbol.n_sclass " << (int)symbol.n_sclass << std::endl;
std::cout << "symbol.n_scnum " << (int)symbol.n_scnum << std::endl;
std::cout << "symbol.n_type " << (int)symbol.n_type << std::endl;
std::cout << "symbol.n_value " << symbol.n_value << std::endl;
std::cout << "it section " << it->section << std::endl;*/
it->symbol = i;
it->type = 777;
value = s.pos;
//value = 0;
found = true;
break;
}
}
}
}
if (!found)
{
std::cout << "Symbol detect error " << it->offset << std::endl;
}
//value += 0x00400000;
}
else
{
//std::cout << "Other type? " << it->offset << " " << it->symbol << " " << it->type << " " << *reinterpret_cast<int32_t*>(std::addressof(outputData[it->offset])) << std::endl;
}
++it;
}
}
const int reallocationNum = rellocations.size();
const int reallocationOffset = outputData.size();
*reinterpret_cast<int32_t*>(&outputData[offsetPosInOutputData]) = reallocationOffset;
*reinterpret_cast<int32_t*>(&outputData[numPosInOutputData]) = reallocationNum;
{
for (auto &r : rellocations)
{
for (int i = 0; i < symbols.size(); i++)
{
auto &s = symbols[i];
if (s.COFFid >= 0 && s.COFFid == (r.symbol))
{
auto &symbol = COFFfile.symbolTable[s.COFFid];
if (r.type == 6)
{
//std::cout << COFFfile.getSymbolName(s.COFFid) << std::endl;
r.symbol = s.pos + *reinterpret_cast<int32_t*>(&outputData[r.offset]);
*reinterpret_cast<int32_t*>(&outputData[r.offset]) = r.symbol;
/*std::cout << "r.offset " << r.offset << std::endl;
std::cout << "r.symbol " << r.symbol << std::endl;
std::cout << "r.type " << r.type << std::endl;
std::cout << "*(int*)&outputData[r.offset] " << *(int*)&outputData[r.offset] << std::endl;*/
}
else
{
r.symbol = *reinterpret_cast<int32_t*>(&outputData[r.offset]);
}
}
}
}
uint8_t relocationTop[] = { 0x55, 0x89, 0xE5 };
uint8_t relocationMiddle[] = {
/* 16 00000003*/ 0x83, 0xEC, 0x10, //sub esp, 16
/* 17 00000006*/ 0xC7, 0x45, 0xFC, 0x30, 0x18, 0x20, 0x41, //mov DWORD [ebp-4], 1092622384
/* 18 0000000D*/ 0xC7, 0x45, 0xF8, 0x50, 0x31, 0x20, 0x51, //mov DWORD [ebp-8], 1361064272
/* 19 00000014*/ 0x8B, 0x55, 0xFC, //mov edx, DWORD [ebp-4]
/* 20 00000017*/ 0x8B, 0x45, 0x08, //mov eax, DWORD [ebp+8]
/* 21 0000001A*/ 0x01, 0xD0, //add eax, edx
/* 22 0000001C*/ 0x89, 0x45, 0xF4, //mov DWORD [ebp-12], eax
/* 23 0000001F*/ 0x8B, 0x55, 0xF8, //mov edx, DWORD [ebp-8]
/* 24 00000022*/ 0x8B, 0x45, 0x08, //mov eax, DWORD [ebp+8]
/* 25 00000025*/ 0x01, 0xC2, //add edx, eax
/* 26 00000027*/ 0x8B, 0x45, 0xF4, //mov eax, DWORD [ebp-12]
/* 27 0000002A*/ 0x89, 0x10 //mov DWORD [eax], edx
};
uint8_t relocationBtn[] = { 0xC9, 0xC3 };
/*outputData.insert(outputData.end(), relocationTop, relocationTop + (sizeof(relocationTop) / sizeof(uint8_t)));
for (auto &r : rellocations)
{
*reinterpret_cast<int32_t*>(std::addressof(relocationMiddle[3 + 3])) = r.offset;
*reinterpret_cast<int32_t*>(std::addressof(relocationMiddle[0xA + 3])) = r.symbol;
outputData.insert(outputData.end(), relocationMiddle, relocationMiddle + (sizeof(relocationMiddle) / sizeof(uint8_t)));
}
outputData.insert(outputData.end(), relocationBtn, relocationBtn + (sizeof(relocationBtn) / sizeof(uint8_t)));*/
}
if (reallocationNum > 0)
{
std::vector<reallocationTableToFile> rl;
rl.reserve(rellocations.size());
for (auto &r : rellocations)
{
rl.push_back(r);
}
uint8_t *r = reinterpret_cast<uint8_t*>(&rl[0]);
scriptSymbols ns;
ns.name = "relocationTable";
ns.pos = outputData.size();
symbols.push_back(std::move(ns));
outputData.insert(outputData.end(), r, r + (reallocationNum * sizeof(reallocationTableToFile)));
}
else
{
outputData.insert(outputData.end(), 12, 0u);
}
}
{
outputData.insert(outputData.end(), 8, 0x90);
scriptSymbols ns;
ns.name = "_initCPPCode";
ns.pos = outputData.size();
symbols.push_back(std::move(ns));
outputData.push_back(0x60); // pushad
outputData.push_back(0x9C); // pushfd
//outputData.push_back(0xCC);
makeCall(outputData, 0);
//outputData.push_back(0xCC);
outputData.push_back(0x50);
makeCall(outputData, reallocationFunctionPos);
uint8_t addesp4[] = { 0x83, 0xC4, 0x04 };
//outputData.push_back(0xCC);
outputData.insert(outputData.end(), addesp4, addesp4 + (sizeof(addesp4) / sizeof(uint8_t)));
try
{
auto &symbol = getSymbolByName(".ctors");
int num = *reinterpret_cast<int32_t*>(&outputData[symbol.pos]);
//std::cout << ".ctors: " << symbol.name << " " << symbol.COFFid << " " << symbol.pos << " " << num << std::endl;
bool callCreated = false;
for (int i = 0; i < symbols.size(); i++)
{
auto &s = symbols[i];
if (s.COFFid >= 0)
{
auto &symbol = COFFfile.symbolTable[s.COFFid];
if (symbol.n_value == num)
{
makeCall(outputData, s.pos);
callCreated = true;
break;
}
}
}
if (!callCreated)
{
std::cout << "Ctor found but not created the call, trying second method...\n";
for (int i = 0; i < symbols.size(); i++)
{
auto &s = symbols[i];
if (s.COFFid >= 0)
{
if (s.pos == num)
{
makeCall(outputData, s.pos);
callCreated = true;
break;
}
}
}
if (callCreated)
{
std::cout << "Call to ctor created\n";
}
else
{
std::cout << "Fail to search ctor function symbol\n";
}
}
}
catch (const std::exception &e)
{
std::cout << "Erro ao detectar o construtor\n" << e.what() << std::endl;
for (int i = 0; i < COFFfile.getNumSymbols(); i++)
{
std::cout << COFFfile.getSymbolName(i) << std::endl;
}
std::cout << "Talvez algo tenha dado errado, por favor avise no tópico: http://brmodstudio.forumeiros.com/t6959-" << std::endl;
std::cout << "Talvez algo tenha dado errado, por favor avise no tópico: http://brmodstudio.forumeiros.com/t6959-" << std::endl;
std::cout << "Talvez algo tenha dado errado, por favor avise no tópico: http://brmodstudio.forumeiros.com/t6959-" << std::endl;
}
outputData.push_back(0x9D); // popfd
outputData.push_back(0x61); // popad
outputData.push_back(0xC3); // InitCPPCode ret
}
if (rellocOffset > 0)
{
for (auto &r : rellocations)
{
*reinterpret_cast<int32_t*>(&outputData[r.offset]) = r.symbol + rellocOffset;
}
}
{
std::fstream rawFile(outFinalFile + ".raw", std::ios::out | std::ios::trunc | std::ios::binary);
rawFile.write(reinterpret_cast<const char*>(outputData.data()), outputData.size());
}
std::wcout << L"Bytes de código " << outputData.size() << std::endl;
vectorDataToFile(COFFfile, fout, outputData);
}
}
}
int main(int argc, char *argv[])
{
/*
TODO: read command line in argc/argv.
List/command to export some simbols to output file
Print usage
*/
loadSymbolList();
try {
CText Config("Config.txt");
compileCMD = Config[""]["compileCMD"];
compileCMD2 = Config[""]["compileCMD2"];
}
catch (const std::exception &e)
{
std::cout << e.what() << std::endl;
return 0;
}
bool what = true, doExit = false;
int wopt = 0;
int estagMenu = 0;
std::cout << "**** ESTE PROGRAMA ESTÁ EM FASE DE CRIAÇÃO E TESTES - USE POR SUA CONTA E RISCO ****" << std::endl;
std::cout << "**** ESTE PROGRAMA ESTÁ EM FASE DE CRIAÇÃO E TESTES - USE POR SUA CONTA E RISCO ****" << std::endl;
std::cout << "**** ESTE PROGRAMA ESTÁ EM FASE DE CRIAÇÃO E TESTES - USE POR SUA CONTA E RISCO ****" << std::endl;
std::cout << "*******************************************************************************************************************" << std::endl;
std::cout << "Em caso de duvida entre em contato pelo seguinte topico:" << std::endl;
std::cout << "http://brmodstudio.forumeiros.com/t4721-avancado-facilitador-de-conversao-de-c-para-assembly-para-usar-em-scripts-cleo-scm" << std::endl << std::endl;
std::cout << "http://brmodstudio.forumeiros.com/t6996-" << std::endl << std::endl;
std::cout << "Programa por Fabio Rossini Sluzala" << std::endl;
std::cout << "Obrigado a todas as pessoas que contribuiram para que essa ideia se tornasse possivel" << std::endl;
std::cout << "Brazilian Modding Studio" << std::endl;
std::cout << "*******************************************************************************************************************" << std::endl;
std::cout << std::endl;
std::string infile = "new.cpp", outCompilefile = "new.o", outFinalFile = "out.txt";
std::string optTemp;
do
{
switch (estagMenu)
{
case 0:
what = true;
do
{
std::wcout << L"Usando modo " << (outputToGTA3SCFormat? "GTA3Script" : "Sanny Builder") << "\n";
std::wcout << L"Opções:\n";
std::wcout << L" 1. Compilar source C/C++ e gerar código CLEO/SCM\n";
std::wcout << L" 2. Gerar código para CLEO/SCM de um objeto pronto\n";
std::wcout << L" 3. Usar sintaxe de Sanny Builder\n";
std::wcout << L" 4. Usar sintaxe de GTA3Script\n";
std::wcout << L" 5. Sair\n";
optTemp = "";
std::cin >> optTemp;
try
{
wopt = std::stoi(optTemp);
switch (wopt)
{
case 1:
++estagMenu;
what = false;
break;
case 2:
++estagMenu;
what = false;
break;
case 3:
outputToGTA3SCFormat = false;
break;
case 4:
outputToGTA3SCFormat = true;
break;
case 5:
what = false;
return 0;
break;
default:
std::wcout << L"Opção inválida, selecione uma opção de 1 a 3\n\n";
break;
}
}
catch (const std::exception &e)
{
std::cout << e.what() << std::endl;
}
} while (what);
break;
case 1:
{
what = true;
do
{
switch (wopt)
{
case 1:
{
std::wcout << L"Digite o nome do arquivo a ser compilado:\n";
optTemp = "";
std::cin >> optTemp;
if (optTemp.size() > 0)
{
infile = optTemp;
++estagMenu;
what = false;
}
}
break;
case 2:
{
std::wcout << L"Digite o nome do objeto (arquivo do tipo COFF) a ser convertido para uso em Scripts CLEO/SCM:\n";
optTemp = "";
std::cin >> optTemp;
if (optTemp.size() > 0)
{
outCompilefile = optTemp;
estagMenu += 2;
what = false;
}
}
break;
default:
std::wcout << L"Erro, opcao invalida\n";
estagMenu = 0;
what = false;
break;
}
} while (what);
break;
}
case 2:
{
what = true;
do
{
std::wcout << L"Digite o nome do arquivo intermediario (COFF object file):\n";
optTemp = "";
std::cin >> optTemp;
if (optTemp.size() > 0)
{
outCompilefile = optTemp;
++estagMenu;
what = false;
}
} while (what);
}
case 3:
{
what = true;
do
{
std::wcout << L"Digite o nome do arquivo de saída final:\n";
optTemp = "";
std::cin >> optTemp;
if (optTemp.size() > 0)
{
outFinalFile = optTemp;
++estagMenu;
what = false;
}
} while (what);
if (wopt == 1)
{
std::string commandToRun = multiRegister(compileCMD, infile, outCompilefile);
std::cout << "Rodando o seguinte comando...\n";
std::cout << commandToRun << std::endl;
executeCommand(commandToRun);
}
COFFFile COFFfile = openCOFFFile(outCompilefile);
toCLEOSCM(COFFfile, outFinalFile);
std::cout << "Comandos terminados, voltando ao inicio do menu...\n\n\n";
estagMenu = 0;
}
break;
}
} while (!doExit);
return 0;
}
| 26.356461 | 352 | 0.586582 | [
"object",
"vector"
] |
6efda739cb6795e9b762f9fbd36fd28a98d9c2ba | 8,584 | hpp | C++ | src/geometry/geometry_utils.hpp | lanl/phoebus | c570f42882c1c9e01e3bfe4b00b22e15a7a9992b | [
"BSD-3-Clause"
] | 3 | 2022-03-24T22:09:12.000Z | 2022-03-29T23:16:21.000Z | src/geometry/geometry_utils.hpp | lanl/phoebus | c570f42882c1c9e01e3bfe4b00b22e15a7a9992b | [
"BSD-3-Clause"
] | 8 | 2022-03-15T20:49:43.000Z | 2022-03-29T17:45:04.000Z | src/geometry/geometry_utils.hpp | lanl/phoebus | c570f42882c1c9e01e3bfe4b00b22e15a7a9992b | [
"BSD-3-Clause"
] | null | null | null | // © 2021. Triad National Security, LLC. All rights reserved. This
// program was produced under U.S. Government contract
// 89233218CNA000001 for Los Alamos National Laboratory (LANL), which
// is operated by Triad National Security, LLC for the U.S.
// Department of Energy/National Nuclear Security Administration. All
// rights in the program are reserved by Triad National Security, LLC,
// and the U.S. Department of Energy/National Nuclear Security
// Administration. The Government is granted for itself and others
// acting on its behalf a nonexclusive, paid-up, irrevocable worldwide
// license in this material to reproduce, prepare derivative works,
// distribute copies to the public, perform publicly and display
// publicly, and to permit others to do so.
#ifndef GEOMETRY_GEOMETRY_UTILS_HPP_
#define GEOMETRY_GEOMETRY_UTILS_HPP_
#include <array>
#include <cmath>
#include <limits>
#include <string>
#include <utility>
#include <vector>
// Parthenon includes
#include <kokkos_abstraction.hpp>
#include <parthenon/package.hpp>
#include <utils/error_checking.hpp>
using namespace parthenon::package::prelude;
// Phoebus includes
#include "phoebus_utils/cell_locations.hpp"
#include "phoebus_utils/linear_algebra.hpp"
#include "phoebus_utils/robust.hpp"
#include "phoebus_utils/variables.hpp"
namespace Geometry {
constexpr int NDSPACE = 3;
constexpr int NDFULL = NDSPACE + 1;
} // namespace Geometry
#define SPACELOOP(i) for (int i = 0; i < Geometry::NDSPACE; i++)
#define SPACETIMELOOP(mu) for (int mu = 0; mu < Geometry::NDFULL; mu++)
#define SPACELOOP2(i, j) SPACELOOP(i) SPACELOOP(j)
#define SPACETIMELOOP2(mu, nu) SPACETIMELOOP(mu) SPACETIMELOOP(nu)
#define SPACELOOP3(i, j, k) SPACELOOP(i) SPACELOOP(j) SPACELOOP(k)
#define SPACETIMELOOP3(mu, nu, sigma) \
SPACETIMELOOP(mu) SPACETIMELOOP(nu) SPACETIMELOOP(sigma)
namespace Geometry {
namespace Utils {
struct MeshBlockShape {
MeshBlockShape(ParameterInput *pin) {
ng = pin->GetOrAddInteger("parthenon/mesh", "nghost", 2);
int mesh_nx1 = pin->GetInteger("parthenon/mesh", "nx1");
int mesh_nx2 = pin->GetInteger("parthenon/mesh", "nx2");
int mesh_nx3 = pin->GetInteger("parthenon/mesh", "nx3");
ndim = (mesh_nx3 > 1 ? 3 : (mesh_nx2 > 1 ? 2 : 1));
nx1 = pin->GetOrAddInteger("parthenon/meshblock", "nx1", mesh_nx1) + 2 * ng;
nx2 = (ndim >= 2)
? pin->GetOrAddInteger("parthenon/meshblock", "nx2", mesh_nx2) + 2 * ng
: 1;
nx3 = (ndim >= 3)
? pin->GetOrAddInteger("parthenon/meshblock", "nx3", mesh_nx3) + 2 * ng
: 1;
}
int nx1, nx2, nx3, ndim, ng;
};
KOKKOS_INLINE_FUNCTION void
SetConnectionCoeffFromMetricDerivs(const Real dg[NDFULL][NDFULL][NDFULL],
Real Gamma[NDFULL][NDFULL][NDFULL]) {
SPACETIMELOOP3(a, b, c) {
Gamma[a][b][c] = 0.5 * (dg[b][a][c] + dg[c][a][b] - dg[b][c][a]);
}
}
template <typename System, typename... Args>
KOKKOS_INLINE_FUNCTION void SetConnectionCoeffByFD(const System &s,
Real Gamma[NDFULL][NDFULL][NDFULL],
Args... args) {
Real dg[NDFULL][NDFULL][NDFULL];
s.MetricDerivative(std::forward<Args>(args)..., dg);
SetConnectionCoeffFromMetricDerivs(dg, Gamma);
}
// TODO(JMM) Currently assumes static metric
template <typename System>
KOKKOS_INLINE_FUNCTION void SetGradLnAlphaByFD(const System &s, Real dx, Real X0, Real X1,
Real X2, Real X3, Real da[NDFULL]) {
Real EPS = std::pow(std::numeric_limits<Real>::epsilon(), 1.0 / 3.0);
LinearAlgebra::SetZero(da, NDFULL);
for (int d = 1; d < NDFULL; ++d) {
Real X1p = X1;
Real X1m = X1;
Real X2p = X2;
Real X2m = X2;
Real X3p = X3;
Real X3m = X3;
if (d == 1) {
dx = std::max(std::abs(X1), 1.0) * EPS;
X1p += dx;
X1m -= dx;
} else if (d == 2) {
dx = std::max(std::abs(X2), 1.0) * EPS;
X2p += dx;
X2m -= dx;
} else if (d == 3) {
dx = std::max(std::abs(X3), 1.0) * EPS;
X3p += dx;
X3m -= dx;
}
Real alpham = s.Lapse(X0, X1m, X2m, X3m);
Real alphap = s.Lapse(X0, X1p, X2p, X3p);
da[d] = robust::ratio(alphap - alpham, dx * (alpham + alphap));
}
}
KOKKOS_INLINE_FUNCTION
void Lower(const double Vcon[NDFULL], const double Gcov[NDFULL][NDFULL],
double Vcov[NDFULL]) {
SPACETIMELOOP(mu) {
Vcov[mu] = 0.;
SPACETIMELOOP(nu) { Vcov[mu] += Gcov[mu][nu] * Vcon[nu]; }
}
}
KOKKOS_INLINE_FUNCTION
void Raise(const double Vcov[NDFULL], const double Gcon[NDFULL][NDFULL],
double Vcon[NDFULL]) {
SPACETIMELOOP(mu) {
Vcon[mu] = 0.;
SPACETIMELOOP(nu) { Vcon[mu] += Gcon[mu][nu] * Vcov[nu]; }
}
}
KOKKOS_INLINE_FUNCTION
int KroneckerDelta(const int a, const int b) {
if (a == b) {
return 1;
} else {
return 0;
}
}
// TODO(JMM): Currently assumes static metric
template <typename System>
KOKKOS_INLINE_FUNCTION void SetMetricGradientByFD(const System &s, Real dx, Real X0,
Real X1, Real X2, Real X3,
Real dg[NDFULL][NDFULL][NDFULL]) {
Real EPS = std::pow(std::numeric_limits<Real>::epsilon(), 1.0 / 3.0);
LinearAlgebra::SetZero(dg, NDFULL, NDFULL, NDFULL);
Real gl[NDFULL][NDFULL];
Real gr[NDFULL][NDFULL];
for (int d = 1; d < NDFULL; ++d) {
Real X1L = X1;
Real X2L = X2;
Real X3L = X3;
Real X1R = X1;
Real X2R = X2;
Real X3R = X3;
if (d == 1) {
dx = std::max(std::abs(X1), 1.0) * EPS;
X1L -= dx;
X1R += dx;
}
if (d == 2) {
dx = std::max(std::abs(X2), 1.0) * EPS;
X2L -= dx;
X2R += dx;
}
if (d == 3) {
dx = std::max(std::abs(X3), 1.0) * EPS;
X3L -= dx;
X3R += dx;
}
s.SpacetimeMetric(X0, X1R, X2R, X3R, gr);
s.SpacetimeMetric(X0, X1L, X2L, X3L, gl);
SPACETIMELOOP(mu) {
SPACETIMELOOP(nu) {
dg[mu][nu][d] = robust::ratio(gr[mu][nu] - gl[mu][nu], 2 * dx);
}
}
}
}
KOKKOS_FORCEINLINE_FUNCTION
int Flatten2(int m, int n, int size) {
static constexpr int ind[4][4] = {
{0, 1, 3, 6}, {1, 2, 4, 7}, {3, 4, 5, 8}, {6, 7, 8, 9}};
PARTHENON_DEBUG_REQUIRE(0 <= m && 0 <= n && m < size && n < size, "bounds");
return ind[m][n];
}
template <int size>
KOKKOS_INLINE_FUNCTION int SymSize() {
return size * size - (size * (size - 1)) / 2;
}
} // namespace Utils
namespace impl {
template <typename Data, typename System>
void SetGeometryDefault(Data *rc, const System &system) {
std::vector<std::string> coord_names = {geometric_variables::cell_coords,
geometric_variables::node_coords};
PackIndexMap imap;
auto pack = rc->PackVariables(coord_names, imap);
PARTHENON_REQUIRE(imap["g.c.coord"].second >= 0, "g.c.coord exists");
PARTHENON_REQUIRE(imap["g.n.coord"].second >= 0, "g.n.coord exists");
PARTHENON_REQUIRE(imap["g.c.coord"].second - imap["g.c.coord"].first + 1 == 4,
"g.c.coord has correct shape");
PARTHENON_REQUIRE(imap["g.n.coord"].second - imap["g.n.coord"].first + 1 == 4,
"g.n.coord has correct shape");
int icoord_c = imap["g.c.coord"].first;
int icoord_n = imap["g.n.coord"].first;
auto lamb = KOKKOS_LAMBDA(const int b, const int k, const int j, const int i,
CellLocation loc) {
Real C[NDFULL];
int icoord = (loc == CellLocation::Cent) ? icoord_c : icoord_n;
system.Coords(loc, b, k, j, i, C);
SPACETIMELOOP(mu) pack(b, icoord + mu, k, j, i) = C[mu];
};
IndexRange ib = rc->GetBoundsI(IndexDomain::entire);
IndexRange jb = rc->GetBoundsJ(IndexDomain::entire);
IndexRange kb = rc->GetBoundsK(IndexDomain::entire);
parthenon::par_for(
DEFAULT_LOOP_PATTERN, "SetGeometry::Set Cached data, Cent", DevExecSpace(), 0,
pack.GetDim(5) - 1, kb.s, kb.e, jb.s, jb.e, ib.s, ib.e,
KOKKOS_LAMBDA(const int b, const int k, const int j, const int i) {
lamb(b, k, j, i, CellLocation::Cent);
});
parthenon::par_for(
DEFAULT_LOOP_PATTERN, "SetGeometry::Set Cached data, Corn", DevExecSpace(), 0,
pack.GetDim(5) - 1, kb.s, kb.e + 1, jb.s, jb.e + 1, ib.s, ib.e + 1,
KOKKOS_LAMBDA(const int b, const int k, const int j, const int i) {
lamb(b, k, j, i, CellLocation::Corn);
});
}
} // namespace impl
} // namespace Geometry
#endif // GEOMETRY_GEOMETRY_UTILS_HPP_
| 34.894309 | 90 | 0.609739 | [
"mesh",
"geometry",
"shape",
"vector"
] |
3e097b3e7b693127dc1fbc9eab82ce803702912f | 13,121 | cpp | C++ | test/diff/lcs_test.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/lcs_test.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/lcs_test.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2022 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "source/diff/lcs.h"
#include <string>
#include "gtest/gtest.h"
namespace spvtools {
namespace diff {
namespace {
using Sequence = std::vector<int>;
using LCS = LongestCommonSubsequence<Sequence>;
void VerifyMatch(const Sequence& src, const Sequence& dst,
size_t expected_match_count) {
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, expected_match_count);
size_t src_cur = 0;
size_t dst_cur = 0;
size_t matches_seen = 0;
while (src_cur < src.size() && dst_cur < dst.size()) {
if (src_match[src_cur] && dst_match[dst_cur]) {
EXPECT_EQ(src[src_cur], dst[dst_cur])
<< "Src: " << src_cur << " Dst: " << dst_cur;
++src_cur;
++dst_cur;
++matches_seen;
continue;
}
if (!src_match[src_cur]) {
++src_cur;
}
if (!dst_match[dst_cur]) {
++dst_cur;
}
}
EXPECT_EQ(matches_seen, expected_match_count);
}
TEST(LCSTest, EmptySequences) {
Sequence src, dst;
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, 0u);
EXPECT_TRUE(src_match.empty());
EXPECT_TRUE(dst_match.empty());
}
TEST(LCSTest, EmptySrc) {
Sequence src, dst = {1, 2, 3};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, 0u);
EXPECT_TRUE(src_match.empty());
EXPECT_EQ(dst_match, DiffMatch(3, false));
}
TEST(LCSTest, EmptyDst) {
Sequence src = {1, 2, 3}, dst;
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, 0u);
EXPECT_EQ(src_match, DiffMatch(3, false));
EXPECT_TRUE(dst_match.empty());
}
TEST(LCSTest, Identical) {
Sequence src = {1, 2, 3, 4, 5, 6}, dst = {1, 2, 3, 4, 5, 6};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, 6u);
EXPECT_EQ(src_match, DiffMatch(6, true));
EXPECT_EQ(dst_match, DiffMatch(6, true));
}
TEST(LCSTest, SrcPrefix) {
Sequence src = {1, 2, 3, 4}, dst = {1, 2, 3, 4, 5, 6};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
const DiffMatch src_expect = {true, true, true, true};
const DiffMatch dst_expect = {true, true, true, true, false, false};
EXPECT_EQ(match_count, 4u);
EXPECT_EQ(src_match, src_expect);
EXPECT_EQ(dst_match, dst_expect);
}
TEST(LCSTest, DstPrefix) {
Sequence src = {1, 2, 3, 4, 5, 6}, dst = {1, 2, 3, 4, 5};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
const DiffMatch src_expect = {true, true, true, true, true, false};
const DiffMatch dst_expect = {true, true, true, true, true};
EXPECT_EQ(match_count, 5u);
EXPECT_EQ(src_match, src_expect);
EXPECT_EQ(dst_match, dst_expect);
}
TEST(LCSTest, SrcSuffix) {
Sequence src = {3, 4, 5, 6}, dst = {1, 2, 3, 4, 5, 6};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
const DiffMatch src_expect = {true, true, true, true};
const DiffMatch dst_expect = {false, false, true, true, true, true};
EXPECT_EQ(match_count, 4u);
EXPECT_EQ(src_match, src_expect);
EXPECT_EQ(dst_match, dst_expect);
}
TEST(LCSTest, DstSuffix) {
Sequence src = {1, 2, 3, 4, 5, 6}, dst = {5, 6};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
const DiffMatch src_expect = {false, false, false, false, true, true};
const DiffMatch dst_expect = {true, true};
EXPECT_EQ(match_count, 2u);
EXPECT_EQ(src_match, src_expect);
EXPECT_EQ(dst_match, dst_expect);
}
TEST(LCSTest, None) {
Sequence src = {1, 3, 5, 7, 9}, dst = {2, 4, 6, 8, 10, 12};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
EXPECT_EQ(match_count, 0u);
EXPECT_EQ(src_match, DiffMatch(5, false));
EXPECT_EQ(dst_match, DiffMatch(6, false));
}
TEST(LCSTest, NonContiguous) {
Sequence src = {1, 2, 3, 4, 5, 6, 10}, dst = {2, 4, 5, 8, 9, 10, 12};
DiffMatch src_match, dst_match;
LCS lcs(src, dst);
size_t match_count =
lcs.Get<int>([](int s, int d) { return s == d; }, &src_match, &dst_match);
const DiffMatch src_expect = {false, true, false, true, true, false, true};
const DiffMatch dst_expect = {true, true, true, false, false, true, false};
EXPECT_EQ(match_count, 4u);
EXPECT_EQ(src_match, src_expect);
EXPECT_EQ(dst_match, dst_expect);
}
TEST(LCSTest, WithDuplicates) {
Sequence src = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4},
dst = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4};
VerifyMatch(src, dst, 6);
}
TEST(LCSTest, Large) {
const std::string src_str =
"GUJwrJSlkKJXxCVIAxlVgnUyOrdyRyFtlZwWMmFhYGfkFTNnhiBmClgHyrcXMVwfrRxNUfQk"
"qaoGvCbPZHAzXsaZpXHPfJxOMCUtRDmIQpfiXKbHQbhTfPqhxBDWvmTQAqwsWTLajZYtMUnf"
"hNNCfkuAXkZsaebwEbIZOxTDZsqSMUfCMoGeKJGVSNFgLTiBMbdvchHGfFRkHKcYCDjBfIcj"
"todPnvDjzQYWBcvIfVvyBzHikrwpDORaGEZLhmyztIFCLJOqeLhOzERYmVqzlsoUzruTXTXq"
"DLTxQRakOCMRrgRzCDTXfwwfDcKMBVnxRZemjcwcEsOVxwtwdBCWJycsDcZKlvrCvZaenKlv"
"vyByDQeLdxAyBnPkIMQlMQwqjUfRLybeoaOanlbFkpTPPZdHelQrIvucTHzMpWWQTbuANwvN"
"OVhCGGoIcGNDpfIsaBexlMMdHsxMGerTngmjpdPeQQJHfvKZkdYqAzrtDohqtDsaFMxQViVQ"
"YszDVgyoSHZdOXAvXkJidojLvGZOzhRajVPhWDwKuGqdaympELxHsrXAJYufdCPwJdGJfWqq"
"yvTWpcrFHOIuCEmNLnSCDsxQGRVDwyCykBJazhApfCnrOadnafvqfVuFqEXMSrYbHTfTnzbz"
"MhISyOtMUITaurCXvanCbuOXBhHyCjOhVbxnMvhlPmZBMQgEHCghtAJVMXGPNRtszVZlPxVl"
"QIPTBnPUPejlyZGPqeICyNngdQGkvKbIoWlTLBtVhMdBeUMozNlKQTIPYBeImVcMdLafuxUf"
"TIXysmcTrUTcspOSKBxhdhLwiRnREGFWJTfUKsgGOAQeYojXdrqsGjMJfiKalyoiqrgLnlij"
"CtOapoxDGVOOBalNYGzCtBlxbvaAzxipGnJpOEbmXcpeoIsAdxspKBzBDgoPVxnuRBUwmTSr"
"CRpWhxikgUYQVCwalLUIeBPRyhhsECGCXJmGDZSCIUaBwROkigzdeVPOXhgCGBEprWtNdYfL"
"tOUYJHQXxiIJgSGmWntezJFpNQoTPbRRYAGhtYvAechvBcYWocLkYFxsDAuszvQNLXdhmAHw"
"DErcjbtCdQllnKcDADVNWVezljjLrAuyGHetINMgAvJZwOEYakihYVUbZGCsHEufluLNyNHy"
"gqtSTSFFjBHiIqQejTPWybLdpWNwZrWvIWnlzUcGNQPEYHVPCbteWknjAnWrdTBeCbHUDBoK"
"aHvDStmpNRGIjvlumiZTbdZNAzUeSFnFChCsSExwXeEfDJfjyOoSBofHzJqJErvHLNyUJTjX"
"qmtgKPpMKohUPBMhtCteQFcNEpWrUVGbibMOpvBwdiWYXNissArpSasVJFgDzrqTyGkerTMX"
"gcrzFUGFZRhNdekaJeKYPogsofJaRsUQmIRyYdkrxKeMgLPpwOfSKJOqzXDoeHljTzhOwEVy"
"krOEnACFrWhufajsMitjOWdLOHHchQDddGPzxknEgdwmZepKDvRZGCuPqzeQkjOPqUBKpKLJ"
"eKieSsRXkaqxSPGajfvPKmwFWdLByEcLgvrmteazgFjmMGrLYqRRxzUOfOCokenqHVYstBHf"
"AwsWsqPTvqsRJUfGGTaYiylZMGbQqTzINhFHvdlRQvvYKBcuAHdBeKlHSxVrSsEKbcAvnIcf"
"xzdVDdwQPHMCHeZZRpGHWvKzgTGzSTbYTeOPyKvvYWmQToTpsjAtKUJUjcEHWhmdBLDTBMHJ"
"ivBXcLGtCsumNNVFyGbVviGmqHTdyBlkneibXBesKJGOUzOtIwXCPJggqBekSzNQYkALlItk"
"cbEhbdXAIKVHYpInLwxXalKZrkrpxtfuagqMGmRJnJbFQaEoYMoqPsxZpocddPXXPyvxVkaF"
"qdKISejWDhBImnEEOPDcyWTubbfVfwUztciaFJcsPLhgYVfhqlOfoNjKbmTFptFttYuyBrUI"
"zzmZypOqrjQHTGFwlHStpIwxPtMvtsEDpsmWIgwzYgwmdpbMOnfElZMYpVIcvzSWejeJcdUB"
"QUoBRUmGQVVWvEDseuozrDjgdXFScPwwsgaUPwSzScfBNrkpmEFDSZLKfNjMqvOmUtocUkbo"
"VGFEKgGLbNruwLgXHTloWDrnqymPVAtzjWPutonIsMDPeeCmTjYWAFXcyTAlBeiJTIRkZxiM"
"kLjMnAflSNJzmZkatXkYiPEMYSmzHbLKEizHbEjQOxBDzpRHiFjhedqiyMiUMvThjaRFmwll"
"aMGgwKBIKepwyoEdnuhtzJzboiNEAFKiqiWxxmkRFRoTiFWXLPAWLuzSCrajgkQhDxAQDqyM"
"VwZlhZicQLEDYYisEalesDWZAYzcvENuHUwRutIsGgsdoYwOZiURhcgdbTGWBNqhrFjvTQCj"
"VlTPNlRdRLaaqzUBBwbdtyXFkCBUYYMbmRrkFxfxbCqkgZNGyHPKLkOPnezfVTRmRQgCgHbx"
"wcZlInVOwmFePnSIbThMJosimzkhfuiqYEpwHQiemqsSDNNdbNhBLzbsPZBJZujSHJGtYKGb"
"HaAYGJZxBumsKUrATwPuqXFLfwNyImLQbchBKiJAYRZhkcrKCHXBEGYyBhBGvSqvabcRUrfq"
"AbPiMzjHAehGYjDEmxAnYLyoSFdeWVrfJUCuYZPluhXEBuyUpKaRXDKXeiCvGidpvATwMbcz"
"DZpzxrhTZYyrFORFQWTbPLCBjMKMhlRMFEiarDgGPttjmkrQVlujztMSkxXffXFNqLWOLThI"
"KBoyMHoFTEPCdUAZjLTifAdjjUehyDLEGKlRTFoLpjalziRSUjZfRYbNzhiHgTHowMMkKTwE"
"ZgnqiirMtnNpaBJqhcIVrWXPpcPWZfRpsPstHleFJDZYAsxYhOREVbFtebXTZRAIjGgWeoiN"
"qPLCCAVadqmUrjOcqIbdCTpcDRWuDVbHrZOQRPhqbyvOWwxAWJphjLiDgoAybcjzgfVktPlj"
"kNBCjelpuQfnYsiTgPpCNKYtOrxGaLEEtAuLdGdDsONHNhSn";
const std::string dst_str =
"KzitfifORCbGhfNEbnbObUdFLLaAsLOpMkOeKupjCoatzqfHBkNJfSgqSMYouswfNMnoQngK"
"jWwyPKmEnoZWyPBUdQRmKUNudUclueKXKQefUdXWUyyqtumzsFKznrLVLwfvPZpLChNYrrHK"
"AtpfOuVHiUKyeRCrktJAhkyFKmPWrASEMvBLNOzuGlvinZjvZUUXazNEkyMPiOLdqXvCIroC"
"MeWsvjHShlLhDwLZrVlpYBnDJmILcsNFDSoaLWOKNNkNGBgNBvVjPCJXAuKfsrKZhYcdEpxK"
"UihiRkYvMiLyOUvaqBMklLDwEhvQBfCXHSRoqsLsSCzLZQhIYMhBapvHaPbDoRrHoJXZsNXc"
"rxZYCrOMIzYcVPwDCFiHBFnPNTTeAeKEMGeVUeCaAeuWZmngyPWlQBcgWumSUIfbhjVYdnpV"
"hRSJXrIoFZubBXfNOMhilAkVPixrhILZKgDoFTvytPFPfBLMnbhSOBmLWCbJsLQxrCrMAlOw"
"RmfSQyGhrjhzYVqFSBHeoQBagFwyxIjcHFZngntpVHbSwqhwHeMnWSsISPljTxSNXfCxLebW"
"GhMdlphtJbdvhEcjNpwPCFqhdquxCyOxkjsDUPNgjpDcpIMhMwMclNhfESTrroJaoyeGQclV"
"gonnhuQRmXcBwcsWeLqjNngZOlyMyfeQBwnwMVJEvGqknDyzSApniRTPgJpFoDkJJhXQFuFB"
"VqhuEPMRGCeTDOSEFmXeIHOnDxaJacvnmORwVpmrRhGjDpUCkuODNPdZMdupYExDEDnDLdNF"
"iObKBaVWpGVMKdgNLgsNxcpypBPPKKoaajeSGPZQJWSOKrkLjiFexYVmUGxJnbTNsCXXLfZp"
"jfxQAEVYvqKehBzMsVHVGWmTshWFAoCNDkNppzzjHBZWckrzSTANICioCJSpLwPwQvtXVxst"
"nTRBAboPFREEUFazibpFesCsjzUOnECwoPCOFiwGORlIZVLpUkJyhYXCENmzTBLVigOFuCWO"
"IiXBYmiMtsxnUdoqSTTGyEFFrQsNAjcDdOKDtHwlANWoUVwiJCMCQFILdGqzEePuSXFbOEOz"
"dLlEnTJbKRSTfAFToOZNtDXTfFgvQiefAKbSUWUXFcpCjRYCBNXCCcLMjjuUDXErpiNsRuIx"
"mgHsrObTEXcnmjdqxTGhTjTeYizNnkrJRhNQIqDXmZMwArBccnixpcuiGOOexjgkpcEyGAnz"
"UbgiBfflTUyJfZeFFLrZVueFkSRosebnnwAnakIrywTGByhQKWvmNQJsWQezqLhHQzXnEpeD"
"rFRTSQSpVxPzSeEzfWYzfpcenxsUyzOMLxhNEhfcuprDtqubsXehuqKqZlLQeSclvoGjuKJK"
"XoWrazsgjXXnkWHdqFESZdMGDYldyYdbpSZcgBPgEKLWZHfBirNPLUadmajYkiEzmGuWGELB"
"WLiSrMdaGSbptKmgYVqMGcQaaATStiZYteGAPxSEBHuAzzjlRHYsrdDkaGNXmzRGoalJMiCC"
"GMtWSDMhgvRSEgKnywbRgnqWXFlwrhXbbvcgLGtWSuKQBiqIlWkfPMozOTWgVoLHavDJGRYI"
"YerrmZnTMtuuxmZALWakfzUbksTwoetqkOiRPGqGZepcVXHoZyOaaaijjZWQLlIhYwiQNbfc"
"KCwhhFaMQBoaCnOecJEdKzdsMPFEYQuJNPYiiNtsYxaWBRuWjlLqGokHMNtyTQfSJKbgGdol"
"fWlOZdupouQMfUWXIYHzyJHefMDnqxxasDxtgArvDqtwjDBaVEMACPkLFpiDOoKCHqkWVizh"
"lKqbOHpsPKkhjRQRNGYRYEfxtBjYvlCvHBNUwVuIwDJYMqHxEFtwdLqYWvjdOfQmNiviDfUq"
"pbucbNwjNQfMYgwUuPnQWIPOlqHcbjtuDXvTzLtkdBQanJbrmLSyFqSapZCSPMDOrxWVYzyO"
"lwDTTJFmKxoyfPunadkHcrcSQaQsAbrQtbhqwSTXGTPURYTCbNozjAVwbmcyVxIbZudBZWYm"
"rnSDyelGCRRWYtrUxvOVWlTLHHdYuAmVMGnGbHscbjmjmAzmYLaCxNNwhmMYdExKvySxuYpE"
"rVGwfqMngBCHnZodotNaNJZiNRFWubuPDfiywXPiyVWoQMeOlSuWmpilLTIFOvfpjmJTgrWa"
"dgoxYeyPyOaglOvZVGdFOBSeqEcGXBwjoeUAXqkpvOxEpSXhmklKZydTvRVYVvfQdRNNDkCT"
"dLNfcZCFQbZORdcDOhwotoyccrSbWvlqYMoiAYeEpDzZTvkamapzZMmCpEutZFCcHBWGIIkr"
"urwDNHrobaErPpclyEegLJDtkfUWSNWZosWSbBGAHIvJsFNUlJXbnkSVycLkOVQVcNcUtiBy"
"djLDIFsycbPBEWaMvCbntNtJlOeCttvXypGnHAQFnFSiXFWWqonWuVIKmVPpKXuJtFguXCWC"
"rNExYYvxLGEmuZJLJDjHgjlQyOzeieCpizJxkrdqKCgomyEkvsyVYSsLeyLvOZQrrgEJgRFK"
"CjYtoOfluNrLdRMTRkQXmAiMRFwloYECpXCReAMxOkNiwCtutsrqWoMHsrogRqPoUCueonvW"
"MTwmkAkajfGJkhnQidwpwIMEttQkzIMOPvvyWZHpqkMHWlNTeSKibfRfwDyxveKENZhtlPwP"
"dfAjwegjRcavtFnkkTNVYdCdCrgdUvzsIcqmUjwGmVvuuQvjVrWWIDBmAzQtiZPYvCOEWjce"
"rWzeqVKeiYTJBOedmQCVidOgUIEjfRnbGvUbctYxfRybJkdmeAkLZQMRMGPOnsPbFswXAoCK"
"IxWGwohoPpEJxslbqHFKSwknxTmrDCITRZWEDkGQeucPxHBdYkduwbYhKnoxCKhgjBFiFawC"
"QtgTDldTQmlOsBiGLquMjuecAbrUJJvNtXbFNGjWxaZPimSRXUJWgRbydpsczOqSFIeEtuKA"
"ZpRhmLtPdVNKdSDQZeeImUFmUwXApRTUNHItyvFyJtNtn";
Sequence src;
Sequence dst;
src.reserve(src_str.length());
dst.reserve(dst_str.length());
for (char c : src_str) {
src.push_back(c);
}
for (char c : dst_str) {
dst.push_back(c);
}
VerifyMatch(src, dst, 723);
}
} // namespace
} // namespace diff
} // namespace spvtools
| 39.760606 | 80 | 0.769454 | [
"vector"
] |
3e17eba811b4e9f9d409466d04f2ab2c2f3888d7 | 1,431 | cpp | C++ | Codechef/CVOTE.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | Codechef/CVOTE.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | Codechef/CVOTE.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define FORN(i,N) for (int i = 0; i < N; i++)
#define FORD(i,a,b) for (int i = a; i >= b; i--)
#define FOREACH(it,a) for ( it=a.begin() ; it != a.end(); it++ )
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
int main() {
map<string,string> chefToCountry;
map<string,int> chefVote;
map<string,int> countryVote;
int N, M;
char s[20];
char t[20];
scanf("%d %d",&N,&M);
while(N--) {
scanf("%s %s",s,t);
chefToCountry[(string)s] = (string)t;
}
while(M--) {
scanf("%s",s);
chefVote[(string)s]++;
countryVote[chefToCountry[(string)s]]++;
}
//printf("TEST");
int maxChef = 0;
int maxCountry = 0;
string maxChefStr = "";
string maxCountryStr = "";
map<string,int>::iterator it;
FOREACH(it,chefVote)
if((*it).second > maxChef) {
maxChef = (*it).second;
maxChefStr = (*it).first;
}
FOREACH(it,countryVote)
if((*it).second > maxCountry) {
maxCountry = (*it).second;
maxCountryStr = (*it).first;
}
printf("%s\n%s\n",maxCountryStr.c_str(),maxChefStr.c_str());
return 0;
}
| 21.358209 | 64 | 0.598882 | [
"vector"
] |
3e1a1f0de696a8e4066e08e30e8d9e4e488aca92 | 3,915 | cpp | C++ | Quoridor Game and Bot/kauts.cpp | kautsiitd/Games-and-BOTS | 58f345064b2834a8ec53074679ef42e159a55889 | [
"MIT"
] | 2 | 2017-09-16T23:12:43.000Z | 2021-01-26T16:25:58.000Z | Quoridor Game and Bot/kauts.cpp | kautsiitd/Games-and-BOTS | 58f345064b2834a8ec53074679ef42e159a55889 | [
"MIT"
] | null | null | null | Quoridor Game and Bot/kauts.cpp | kautsiitd/Games-and-BOTS | 58f345064b2834a8ec53074679ef42e159a55889 | [
"MIT"
] | 1 | 2015-12-28T22:34:47.000Z | 2015-12-28T22:34:47.000Z | #include "globals.h"
#define mp make_pair
using namespace std;
// global variables
//bool walls[N+1][M+1][2]; // walls are stored in zero index form [0] is horizontal walls and [1] is vertical walls
// opponent last move om(type) oro(row) oc(column)
// send answer in ans[3] (move,row,column)
// eval variables
int* que;
int* bfsdepth;
int eval(int playerno, int row,int col){
if ((playerno == 1 && row == N ) || (playerno == 2 && row == 1 ))
return 0;
int head = 0 , tail = 0;
for(int i = 0; i < N*M ; i++){
bfsdepth[i] = -1;
}
que[tail++] = (row-1) *M + (col-1);
bfsdepth[(row-1) *M + (col-1)] = 0;
while( head != tail ){
int cu_x = que[head]/M;
int cu_y = que[head]%M;// zero based positions
//top
if(cu_x-1>=0 && bfsdepth[(cu_x-1)*M + cu_y]==-1 && walls[cu_x][cu_y][0]==0 && walls[cu_x][cu_y+1][0]==0){
if(playerno ==2 && cu_x-1==0){
return bfsdepth[cu_x*M + cu_y] + 1;
}
bfsdepth[(cu_x-1)*M + cu_y]= bfsdepth[cu_x*M + cu_y] + 1;
que[tail++] = (cu_x-1)*M + cu_y;
}
//right
if(cu_y+1<M && bfsdepth[cu_x*M+cu_y+1]==-1 && walls[cu_x][cu_y+1][1]==0 && walls[cu_x+1][cu_y+1][1]==0){
bfsdepth[(cu_x)*M + cu_y +1 ]= bfsdepth[cu_x*M + cu_y] + 1;
que[tail++] = (cu_x)*M + cu_y + 1;
}
// down
if(cu_x+1<N && bfsdepth[(cu_x+1)*M + cu_y]== -1 && walls[cu_x+1][cu_y][0]==0 && walls[cu_x+1][cu_y+1][0]==0){
if(playerno ==1 && cu_x+1==N-1){
return bfsdepth[cu_x*M + cu_y] + 1;
}
bfsdepth[(cu_x+1)*M + cu_y]= bfsdepth[cu_x*M + cu_y] + 1;
que[tail++] = (cu_x+1)*M + cu_y;
}
//left
if(cu_y-1>=0 && bfsdepth[cu_x*M + cu_y-1]==-1 && walls[cu_x][cu_y][1]==0 && walls[cu_x+1][cu_y][1]==0){
bfsdepth[(cu_x)*M + cu_y -1 ]= bfsdepth[cu_x*M + cu_y] + 1;
que[tail++] = (cu_x)*M + cu_y - 1;
}
head++;
}
return (20000000);
}
bool terminal(int depth){
if(depth>4){
return 1;
}
return 0;
}
/*
int eval(int playereval,int cu_x, int cu_y){ // one based positions
cout << playereval << cu_x << cu_y << endl;
cout << "eval 3" << endl;
cu_y = cu_y -1;
cu_x = cu_x -1; // zero based positions
if ( (playereval == 2 && cu_x == 0) || (playereval == 1 && cu_x == N-1))
return 0;
for(int i=0; i<N; i++){
for (int j=0; j < M ; j++){
bfsdepth[i][j] = 0;
}
}
// bredth first search iterative
cout << "eval 3" << endl;
cout << "asdjfk" << endl;
que< vector<int> > fringe;
cout << "eval 3" << endl;
int depth=0;
vector<int> makep;
makep.push_back(cu_x);makep.push_back(cu_y);makep.push_back(depth);
fringe.push(makep);makep.clear();
cout << "eval 4" << endl;
while(!fringe.empty()){
cu_x=fringe.front()[0];
cu_y=fringe.front()[1];
depth=fringe.front()[2];
bfsdepth[cu_x][cu_y]=1;
if(cu_x+1<N && bfsdepth[cu_x+1][cu_y]==0 && walls[cu_x+1][cu_y][0]==0 && walls[cu_x+1][cu_y+1][0]==0){
if(playereval==1 && cu_x+1==N-1){
return fringe.front()[2]+1;
}
makep.push_back(cu_x+1);makep.push_back(cu_y);makep.push_back(depth+1);
fringe.push(makep);makep.clear();
bfsdepth[cu_x+1][cu_y]=1;
}
if(cu_x-1>=0 && bfsdepth[cu_x-1][cu_y]==0 && walls[cu_x][cu_y][0]==0 && walls[cu_x][cu_y+1][0]==0){
if(playereval==2 && cu_x-1==0){
return fringe.front()[2]+1;
}
makep.push_back(cu_x-1);makep.push_back(cu_y);makep.push_back(depth+1);
fringe.push(makep);makep.clear();
bfsdepth[cu_x-1][cu_y]=1;
}
if(cu_y+1<M && bfsdepth[cu_x][cu_y+1]==0 && walls[cu_x][cu_y+1][1]==0 && walls[cu_x+1][cu_y+1][1]==0){
makep.push_back(cu_x);makep.push_back(cu_y+1);makep.push_back(depth+1);
fringe.push(makep);makep.clear();
bfsdepth[cu_x][cu_y+1]=1;
}
if(cu_y-1>=0 && bfsdepth[cu_x][cu_y-1]==0 && walls[cu_x][cu_y][1]==0 && walls[cu_x+1][cu_y][1]==0){
makep.push_back(cu_x);makep.push_back(cu_y-1);makep.push_back(depth+1);
fringe.push(makep);makep.clear();
bfsdepth[cu_x][cu_y-1]=1;
}
fringe.pop();
}
return numeric_limits<int>::max();
}
*/
| 30.826772 | 119 | 0.57931 | [
"vector"
] |
3e1b45fdc76e36f28e465dcb53e5d4d100029ce1 | 9,731 | cc | C++ | vision/locate_cameras.cc | cornell-cup/cs-reminibot | 411d1ed4b4f67f07f3608cb6ddb7f0b8d7a22b24 | [
"Apache-2.0"
] | 5 | 2020-09-05T18:57:33.000Z | 2022-03-15T00:14:57.000Z | vision/locate_cameras.cc | cornell-cup/cs-reminibot | 411d1ed4b4f67f07f3608cb6ddb7f0b8d7a22b24 | [
"Apache-2.0"
] | 33 | 2019-11-07T22:42:13.000Z | 2022-02-05T17:54:50.000Z | vision/locate_cameras.cc | cornell-cup/cs-reminibot | 411d1ed4b4f67f07f3608cb6ddb7f0b8d7a22b24 | [
"Apache-2.0"
] | 10 | 2019-09-28T16:44:10.000Z | 2022-03-12T20:23:50.000Z | /*Specifications:
This is Step 2 in initializing the vision system. Compile the locate_cameras.cc
file by the following command
g++ -std=c++11 locate_cameras.cc (PATH TO)/cs-reminibot/vision
`pkg-config --libs --cflags opencv` -l apriltag -o locate_cameras.o
(Here --cflags are what you got while installing the opencv system)
Once you have the locate_cameras.o file, you run
./locate_camera.x 0.calib
Once the camera window opens up, make sure to have the april tags placed within the frame
all side by side in the following order: ID 0 (top left), ID 1 (top right), ID 2 (bottom left)
and ID 3 (bottom right). This makes the center of the tags the origin of the coordinate system.
(You will see a bunch of values being printed in the terminal)
Colored lines will appear around the tags. Once done, you can stop the command.
*/
#include <apriltag/apriltag.h>
#include <apriltag/tag36h11.h>
#include <apriltag/tag36artoolkit.h>
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace cv;
using std::vector;
#define TAG_SIZE 6.5f
int main(int argc, char** argv) {
// Display usage
if (argc < 2) {
printf("Usage: %s [cameras...]\n", argv[0]);
return -1;
}
// Parse arguments
vector<VideoCapture> devices;
vector<int> device_ids;
vector<Mat> device_camera_matrix;
vector<Mat> device_dist_coeffs;
for (int i = 1; i < argc; i++) {
int id = atoi(argv[i]);
VideoCapture device(id);
if (!device.isOpened()) {
std::cerr << "Failed to open video capture device " << id << std::endl;
continue;
}
std::ifstream fin;
fin.open(argv[i]);
if (fin.fail()) {
std::cerr << "Failed to open file " << argv[i] << std::endl;
continue;
}
Mat camera_matrix, dist_coeffs;
std::string line;
// TODO Error checking
while (std::getline(fin, line)) {
std::stringstream line_stream(line);
std::string key, equals;
line_stream >> key >> equals;
if (key == "camera_matrix") {
vector<double> data;
for (int i = 0; i < 9; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
camera_matrix = Mat(data, true).reshape(1, 3);
}
else if (key == "dist_coeffs") {
vector<double> data;
for (int i = 0; i < 5; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
dist_coeffs = Mat(data, true).reshape(1, 1);
}
else {
std::cerr << "Unrecognized key '" << key << "' in file " << argv[i] << std::endl;
}
}
if (camera_matrix.rows != 3 || camera_matrix.cols != 3) {
std::cerr << "Error reading camera_matrix in file " << argv[i] << std::endl;
continue;
}
if (dist_coeffs.rows != 1 || dist_coeffs.cols != 5) {
std::cerr << "Error reading dist_coeffs in file " << argv[i] << std::endl;
continue;
}
device.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
device.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
device.set(CV_CAP_PROP_FPS, 30);
devices.push_back(device);
device_ids.push_back(id);
device_camera_matrix.push_back(camera_matrix);
device_dist_coeffs.push_back(dist_coeffs);
}
// Initialize detector
apriltag_family_t* tf = tag36h11_create();
tf->black_border = 1;
apriltag_detector_t* td = apriltag_detector_create();
apriltag_detector_add_family(td, tf);
td->quad_decimate = 1.0;
td->quad_sigma = 0.0;
td->nthreads = 4;
td->debug = 0;
td->refine_edges = 1;
td->refine_decode = 0;
td->refine_pose = 0;
int key = 0;
Mat frame, gray;
while (key != 27) { // Quit on escape keypress
for (size_t i = 0; i < devices.size(); i++) {
if (!devices[i].isOpened()) {
continue;
}
devices[i] >> frame;
cvtColor(frame, gray, COLOR_BGR2GRAY);
image_u8_t im = {
.width = gray.cols,
.height = gray.rows,
.stride = gray.cols,
.buf = gray.data
};
zarray_t* detections = apriltag_detector_detect(td, &im);
vector<Point2f> img_points(16);
vector<Point3f> obj_points(16);
Mat rvec(3, 1, CV_64FC1);
Mat tvec(3, 1, CV_64FC1);
for (int j = 0; j < zarray_size(detections); j++) {
// Get the ith detection
apriltag_detection_t *det;
zarray_get(detections, j, &det);
if ((det -> id) <= 3) {
int id = det -> id;
// Draw onto the frame
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[1][0], det->p[1][1]),
Scalar(0, 0xff, 0), 2);
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0, 0, 0xff), 2);
line(frame, Point(det->p[1][0], det->p[1][1]),
Point(det->p[2][0], det->p[2][1]),
Scalar(0xff, 0, 0), 2);
line(frame, Point(det->p[2][0], det->p[2][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0xff, 0, 0), 2);
// Compute transformation using PnP
img_points[0 + 4*id] = Point2f(det->p[0][0], det->p[0][1]);
img_points[1 + 4*id] = Point2f(det->p[1][0], det->p[1][1]);
img_points[2 + 4*id] = Point2f(det->p[2][0], det->p[2][1]);
img_points[3 + 4*id] = Point2f(det->p[3][0], det->p[3][1]);
int a = (det->id % 2) * 2 - 1;
int b = -((det->id / 2) * 2 - 1);
obj_points[0 + 4*id] = Point3f(-0.5f * TAG_SIZE + a * 8.5f * 0.5f, -0.5f * TAG_SIZE + b * 11.0f * 0.5f, 0.f);
obj_points[1 + 4*id] = Point3f( 0.5f * TAG_SIZE + a * 8.5f * 0.5f, -0.5f * TAG_SIZE + b * 11.0f * 0.5f, 0.f);
obj_points[2 + 4*id] = Point3f( 0.5f * TAG_SIZE + a * 8.5f * 0.5f, 0.5f * TAG_SIZE + b * 11.0f * 0.5f, 0.f);
obj_points[3 + 4*id] = Point3f(-0.5f * TAG_SIZE + a * 8.5f * 0.5f, 0.5f * TAG_SIZE + b * 11.0f * 0.5f, 0.f);
}
}
solvePnP(obj_points, img_points, device_camera_matrix[i],
device_dist_coeffs[i], rvec, tvec);
Matx33d r;
Rodrigues(rvec,r);
// Construct the origin to camera matrix
vector<double> data;
data.push_back(r(0,0));
data.push_back(r(0,1));
data.push_back(r(0,2));
data.push_back(tvec.at<double>(0));
data.push_back(r(1,0));
data.push_back(r(1,1));
data.push_back(r(1,2));
data.push_back(tvec.at<double>(1));
data.push_back(r(2,0));
data.push_back(r(2,1));
data.push_back(r(2,2));
data.push_back(tvec.at<double>(2));
data.push_back(0);
data.push_back(0);
data.push_back(0);
data.push_back(1);
Mat origin2cam = Mat(data,true).reshape(1,4);
Mat cam2origin = origin2cam.inv();
// DEBUG Generate the location of the camera
vector<double> data2;
data2.push_back(0);
data2.push_back(0);
data2.push_back(0);
data2.push_back(1);
Mat genout = Mat(data2,true).reshape(1,4);
Mat camcoords = cam2origin * genout;
printf("%zu :: filler :: % 3.3f % 3.3f % 3.3f\n", i,
camcoords.at<double>(0,0), camcoords.at<double>(1,0), camcoords.at<double>(2,0));
// if (key == 'w') {
printf("written to camera %zu\n",i);
std::ofstream fout;
fout.open(std::to_string(device_ids[i]) + ".calib", std::ofstream::out);
fout << "camera_matrix =";
for (int r = 0; r < device_camera_matrix[i].rows; r++) {
for (int c = 0; c < device_camera_matrix[i].cols; c++) {
fout << " " << device_camera_matrix[i].at<double>(r, c);
}
}
fout << std::endl;
fout << "dist_coeffs =";
for (int r = 0; r < device_dist_coeffs[i].rows; r++) {
for (int c = 0; c < device_dist_coeffs[i].cols; c++) {
fout << " " << device_dist_coeffs[i].at<double>(r, c);
}
}
fout << std::endl;
fout << "transform_matrix =";
for (int r = 0; r < cam2origin.rows; r++) {
for (int c = 0; c < cam2origin.cols; c++) {
fout << " " << cam2origin.at<double>(r, c);
}
}
fout << std::endl;
fout.close();
// }
zarray_destroy(detections);
imshow(std::to_string(i), frame);
}
key = waitKey(16);
}
}
| 36.582707 | 129 | 0.480526 | [
"vector"
] |
4a49726a46332bed12e20b3e6572079d89a15f9d | 6,768 | cpp | C++ | third_party/libunwindstack/tests/MapInfoTest.cpp | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 716 | 2017-09-22T11:50:40.000Z | 2020-03-14T21:52:22.000Z | third_party/libunwindstack/tests/MapInfoTest.cpp | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 132 | 2017-09-24T11:48:18.000Z | 2020-03-17T17:39:45.000Z | third_party/libunwindstack/tests/MapInfoTest.cpp | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 49 | 2017-09-23T10:23:59.000Z | 2020-03-14T09:27:49.000Z | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <sys/mman.h>
#include <thread>
#include <gtest/gtest.h>
#include <unwindstack/MapInfo.h>
#include <unwindstack/Maps.h>
#include "ElfFake.h"
namespace unwindstack {
TEST(MapInfoTest, maps_constructor_const_char) {
auto prev_map = MapInfo::Create(0, 0, 0, 0, "");
auto map_info = MapInfo::Create(prev_map, 1, 2, 3, 4, "map");
EXPECT_EQ(prev_map.get(), map_info->prev_map().get());
EXPECT_EQ(1UL, map_info->start());
EXPECT_EQ(2UL, map_info->end());
EXPECT_EQ(3UL, map_info->offset());
EXPECT_EQ(4UL, map_info->flags());
EXPECT_EQ("map", map_info->name());
EXPECT_EQ(UINT64_MAX, map_info->load_bias());
EXPECT_EQ(0UL, map_info->object_offset());
EXPECT_TRUE(map_info->object().get() == nullptr);
}
TEST(MapInfoTest, maps_constructor_string) {
std::string name("string_map");
auto prev_map = MapInfo::Create(0, 0, 0, 0, "");
auto map_info = MapInfo::Create(prev_map, 1, 2, 3, 4, name);
EXPECT_EQ(prev_map, map_info->prev_map());
EXPECT_EQ(1UL, map_info->start());
EXPECT_EQ(2UL, map_info->end());
EXPECT_EQ(3UL, map_info->offset());
EXPECT_EQ(4UL, map_info->flags());
EXPECT_EQ(UINT64_MAX, map_info->load_bias());
EXPECT_EQ(0UL, map_info->object_offset());
EXPECT_TRUE(map_info->object().get() == nullptr);
}
TEST(MapInfoTest, real_map_check) {
auto map1 = MapInfo::Create(0, 0x1000, 0, PROT_READ, "fake.so");
auto map2 = MapInfo::Create(map1, 0, 0, 0, 0, "");
auto map3 = MapInfo::Create(map2, 0x1000, 0x2000, 0x1000, PROT_READ | PROT_EXEC, "fake.so");
EXPECT_EQ(nullptr, map1->prev_map());
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(map2, map1->next_map());
EXPECT_EQ(map3, map1->GetNextRealMap());
EXPECT_EQ(map1, map2->prev_map());
EXPECT_EQ(nullptr, map2->GetPrevRealMap());
EXPECT_EQ(map3, map2->next_map());
EXPECT_EQ(nullptr, map2->GetNextRealMap());
EXPECT_EQ(map2, map3->prev_map());
EXPECT_EQ(map1, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->next_map());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
// Verify that if the middle map is not blank, then the Get{Next,Prev}RealMap
// functions return nullptrs.
map2->set_offset(1);
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(nullptr, map1->GetNextRealMap());
EXPECT_EQ(nullptr, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
map2->set_offset(0);
EXPECT_EQ(map3, map1->GetNextRealMap());
map2->set_flags(1);
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(nullptr, map1->GetNextRealMap());
EXPECT_EQ(nullptr, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
map2->set_flags(0);
EXPECT_EQ(map3, map1->GetNextRealMap());
map2->set_name("something");
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(nullptr, map1->GetNextRealMap());
EXPECT_EQ(nullptr, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
map2->set_name("");
EXPECT_EQ(map3, map1->GetNextRealMap());
// Verify that if the Get{Next,Prev}RealMap names must match.
map1->set_name("another");
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(nullptr, map1->GetNextRealMap());
EXPECT_EQ(nullptr, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
map1->set_name("fake.so");
EXPECT_EQ(map3, map1->GetNextRealMap());
map3->set_name("another");
EXPECT_EQ(nullptr, map1->GetPrevRealMap());
EXPECT_EQ(nullptr, map1->GetNextRealMap());
EXPECT_EQ(nullptr, map3->GetPrevRealMap());
EXPECT_EQ(nullptr, map3->GetNextRealMap());
map3->set_name("fake.so");
EXPECT_EQ(map3, map1->GetNextRealMap());
}
TEST(MapInfoTest, get_function_name) {
ElfFake* elf = new ElfFake(nullptr);
ElfInterfaceFake* interface = new ElfInterfaceFake(nullptr);
elf->FakeSetInterface(interface);
interface->FakePushFunctionData(FunctionData("function", 1000));
auto map_info = MapInfo::Create(1, 2, 3, 4, "");
map_info->set_object(elf);
SharedString name;
uint64_t offset;
ASSERT_TRUE(map_info->GetFunctionName(1000, &name, &offset));
EXPECT_EQ("function", name);
EXPECT_EQ(1000UL, offset);
}
TEST(MapInfoTest, multiple_thread_get_object_fields) {
auto map_info = MapInfo::Create(0, 0, 0, 0, "");
static constexpr size_t kNumConcurrentThreads = 100;
MapInfo::ObjectFields* object_fields[kNumConcurrentThreads];
std::atomic_bool wait;
wait = true;
// Create all of the threads and have them do the call at the same time
// to make it likely that a race will occur.
std::vector<std::thread*> threads;
for (size_t i = 0; i < kNumConcurrentThreads; i++) {
std::thread* thread = new std::thread([i, &wait, &map_info, &object_fields]() {
while (wait)
;
object_fields[i] = &map_info->GetObjectFields();
});
threads.push_back(thread);
}
// Set them all going and wait for the threads to finish.
wait = false;
for (auto thread : threads) {
thread->join();
delete thread;
}
// Now verify that all of elf fields are exactly the same and valid.
MapInfo::ObjectFields* expected_object_fields = &map_info->GetObjectFields();
ASSERT_TRUE(expected_object_fields != nullptr);
for (size_t i = 0; i < kNumConcurrentThreads; i++) {
EXPECT_EQ(expected_object_fields, object_fields[i]) << "Thread " << i << " mismatched.";
}
}
TEST(MapInfoTest, object_file_not_readable) {
auto map_info_readable = MapInfo::Create(0, 0x1000, 0, PROT_READ, "fake.so");
map_info_readable->set_memory_backed_object(true);
ASSERT_TRUE(map_info_readable->ObjectFileNotReadable());
auto map_info_no_name = MapInfo::Create(0, 0x1000, 0, PROT_READ, "");
map_info_no_name->set_memory_backed_object(true);
ASSERT_FALSE(map_info_no_name->ObjectFileNotReadable());
auto map_info_bracket = MapInfo::Create(0, 0x2000, 0, PROT_READ, "[vdso]");
map_info_bracket->set_memory_backed_object(true);
ASSERT_FALSE(map_info_bracket->ObjectFileNotReadable());
auto map_info_memfd = MapInfo::Create(0, 0x3000, 0, PROT_READ, "/memfd:jit-cache");
map_info_memfd->set_memory_backed_object(true);
ASSERT_FALSE(map_info_memfd->ObjectFileNotReadable());
}
} // namespace unwindstack
| 34.707692 | 94 | 0.712323 | [
"object",
"vector"
] |
4a4ae37d1a5e37915d810652215b1a6a9061fbbc | 13,069 | cc | C++ | sling/myelin/generator/elementwise.cc | anders-sandholm/sling | f3ab461cf378b31ad202cfa4892a007b85cf08af | [
"Apache-2.0"
] | 1 | 2021-06-16T13:02:01.000Z | 2021-06-16T13:02:01.000Z | sling/myelin/generator/elementwise.cc | anders-sandholm/sling | f3ab461cf378b31ad202cfa4892a007b85cf08af | [
"Apache-2.0"
] | null | null | null | sling/myelin/generator/elementwise.cc | anders-sandholm/sling | f3ab461cf378b31ad202cfa4892a007b85cf08af | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google 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 "sling/myelin/generator/elementwise.h"
#define __ masm->
namespace sling {
namespace myelin {
using namespace jit;
ElementwiseIndexGenerator::ElementwiseIndexGenerator(
const Step *step, MacroAssembler *masm) : IndexGenerator(masm) {
// Get size from first output.
CHECK_GE(step->outdegree(), 1);
type_ = step->output(0)->type();
shape_ = step->output(0)->shape();
// Allocate locators for all inputs and outputs.
input_.resize(step->indegree());
for (int i = 0; i < step->indegree(); ++i) {
CHECK(step->input(i)->type() == type_);
CHECK(InitializeLocator(step->input(i), &input_[i]));
}
output_.resize(step->outdegree());
for (int i = 0; i < step->outdegree(); ++i) {
CHECK(step->output(i)->type() == type_);
CHECK(step->output(i)->shape() == step->output(0)->shape());
CHECK(InitializeLocator(step->output(i), &output_[i]));
}
}
ElementwiseIndexGenerator::~ElementwiseIndexGenerator() {
for (auto *i : iterators_) delete i;
}
bool ElementwiseIndexGenerator::InitializeLocator(Tensor *var, Locator *loc) {
// Set variable for locator.
loc->var = var;
// Determine iterator type for variable.
if (var->elements() == 1) {
// Variable only has one element; use a scalar/const iterator.
loc->iterator = NewIterator(var->IsConstant() ? CONST : SCALAR);
} else if (var->shape() == shape_) {
// Variable has same shape as output; use simple iterator.
loc->iterator = NewIterator(SIMPLE);
} else if (var->rank() <= shape_.rank()) {
// Find common suffix between variable and output.
int n = 1;
int d1 = var->rank() - 1;
int d2 = shape_.rank() - 1;
while (d1 >= 0) {
int n1 = var->dim(d1);
int n2 = shape_.dim(d2);
if (n1 != n2) break;
n *= n1;
d1--;
d2--;
}
if (n == var->elements()) {
if (var->elements() == shape_.elements()) {
// The variable shape prefix is a one vector so use a simple iterator.
loc->iterator = NewIterator(SIMPLE);
} else {
// Variable shape is a suffix of the output shape; use a repeated
// iterator.
DCHECK(shape_.elements() % n == 0);
loc->iterator = NewIterator(REPEAT);
loc->iterator->size = n;
}
} else if (d1 >= 0 && d2 >= 0 && var->dim(d1) == 1 &&
var->elements() * shape_.dim(d2) == shape_.elements()) {
// Create broadcast iterator over one dimension.
loc->iterator = NewIterator(BROADCAST);
loc->iterator->size = n;
loc->iterator->broadcast = shape_.dim(d2);
} else {
LOG(WARNING) << "Unsupported broadcast: " << var->name()
<< " input: " << var->shape().ToString()
<< " output: " << shape_.ToString();
return false;
}
} else {
return false;
}
return true;
}
void ElementwiseIndexGenerator::Initialize(size_t vecsize) {
vecsize_ = vecsize;
single_ = shape_.elements() * element_size() == vecsize_;
}
bool ElementwiseIndexGenerator::AllocateRegisters() {
// Allocate temp vars.
if (!IndexGenerator::AllocateRegisters()) return false;
// Allocate register for output offset.
Registers &rr = masm_->rr();
if (!single_) {
offset_ = rr.try_alloc();
if (!offset_.is_valid()) return false;
}
// Allocate registers for locators.
for (auto &loc : input_) {
if (!AllocateLocatorRegisters(&loc)) return false;
}
for (auto &loc : output_) {
if (!AllocateLocatorRegisters(&loc)) return false;
}
// Try to allocate extra base registers as an optimization.
if (!single_) {
for (auto &loc : input_) {
if (loc.base.is_valid()) continue;
if (loc.iterator->type == SIMPLE || loc.iterator->type == REPEAT) {
loc.base = rr.try_alloc();
}
}
for (auto &loc : output_) {
if (loc.base.is_valid()) continue;
if (loc.iterator->type == SIMPLE) {
loc.base = rr.try_alloc();
}
}
}
return true;
}
bool ElementwiseIndexGenerator::AllocateLocatorRegisters(Locator *loc) {
Registers &rr = masm_->rr();
switch (loc->iterator->type) {
case SIMPLE:
case SCALAR:
// Allocate base register for non-instance variables.
if (loc->var->offset() == -1 || loc->var->ref()) {
loc->base = rr.try_alloc();
if (!loc->base.is_valid()) return false;
}
break;
case CONST:
// Constants use pc-relative addressing, so no extra registers are needed.
break;
case REPEAT:
// Allocate base register for non-instance variables.
if (loc->var->offset() == -1 || loc->var->ref()) {
loc->base = rr.try_alloc();
if (!loc->base.is_valid()) return false;
}
// Allocate index register.
loc->iterator->offset = rr.try_alloc();
if (!loc->iterator->offset.is_valid()) return false;
break;
case BROADCAST:
// Allocate block, index, and broadcast registers.
loc->iterator->block = rr.try_alloc();
if (!loc->iterator->block.is_valid()) return false;
loc->iterator->offset = rr.try_alloc();
if (!loc->iterator->offset.is_valid()) return false;
loc->iterator->repeat = rr.try_alloc();
if (!loc->iterator->repeat.is_valid()) return false;
break;
default:
return false;
};
return true;
}
void ElementwiseIndexGenerator::BeginLoop() {
// Load tensor addresses and initialize index registers.
MacroAssembler *masm = masm_;
for (auto &loc : input_) {
if (loc.base.is_valid()) {
__ LoadTensorAddress(loc.base, loc.var);
}
if (loc.iterator->block.is_valid()) {
__ LoadTensorAddress(loc.iterator->block, loc.var);
}
if (!single_ && loc.iterator->offset.is_valid()) {
__ xorq(loc.iterator->offset, loc.iterator->offset);
}
if (loc.iterator->repeat.is_valid()) {
__ xorq(loc.iterator->repeat, loc.iterator->repeat);
}
}
for (auto &loc : output_) {
if (loc.base.is_valid()) {
__ LoadTensorAddress(loc.base, loc.var);
}
}
// Generate loop start, unless there is only one iteration.
if (!single_) {
__ xorq(offset_, offset_);
__ bind(&begin_);
}
}
void ElementwiseIndexGenerator::EndLoop() {
MacroAssembler *masm = masm_;
if (!single_) {
// Move to next output element.
__ addq(offset_, Immediate(vecsize_));
// Update iterators.
for (Iterator *it : iterators_) {
if (it->type == REPEAT) {
size_t repeat_size = element_size() * it->size;
if ((repeat_size & (repeat_size - 1)) == 0) {
// The repeat block size is a power of two, so the index can be
// computed using masking.
__ movq(it->offset, offset_);
__ andq(it->offset, Immediate(repeat_size - 1));
} else {
// Increment offset and reset at end of repeat.
Label l;
__ addq(it->offset, Immediate(vecsize_));
__ cmpq(it->offset, Immediate(repeat_size));
__ j(less, &l);
__ xorq(it->offset, it->offset);
__ bind(&l);
}
} else if (it->type == BROADCAST) {
size_t block_size = element_size() * it->size;
Label l;
// Move to next inner element block.
__ addq(it->offset, Immediate(vecsize_));
__ cmpq(it->offset, Immediate(block_size));
__ j(less, &l);
// Next repetition of block.
__ xorq(it->offset, it->offset); // at end of block, reset index
__ incq(it->repeat); // increment block repeat
__ cmpq(it->repeat, Immediate(it->broadcast));
__ j(less, &l);
// Move to next block.
__ xorq(it->repeat, it->repeat); // move to next block
__ addq(it->block, Immediate(block_size));
__ bind(&l);
}
}
// Check if we have reached the end of the output.
size_t size = element_size() * shape_.elements();
__ cmpq(offset_, Immediate(size));
__ j(less, &begin_);
}
}
Operand ElementwiseIndexGenerator::addr(Express::Var *var) {
if (var->type == Express::NUMBER) {
// System-defined constant.
switch (type_) {
case DT_FLOAT: {
float number = Express::NumericFlt32(var->id);
int repeat = vecsize_ / sizeof(float);
return masm_->GetConstant(number, repeat)->address();
}
case DT_DOUBLE: {
double number = Express::NumericFlt64(var->id);
int repeat = vecsize_ / sizeof(double);
return masm_->GetConstant(number, repeat)->address();
}
case DT_INT8: {
int8 number = Express::NumericFlt32(var->id);
int repeat = vecsize_ / sizeof(int8);
return masm_->GetConstant(number, repeat)->address();
}
case DT_INT16: {
int16 number = Express::NumericFlt32(var->id);
int repeat = vecsize_ / sizeof(int16);
return masm_->GetConstant(number, repeat)->address();
}
case DT_INT32: {
int32 number = Express::NumericFlt32(var->id);
int repeat = vecsize_ / sizeof(int32);
return masm_->GetConstant(number, repeat)->address();
}
case DT_INT64: {
int64 number = Express::NumericFlt32(var->id);
int repeat = vecsize_ / sizeof(int64);
return masm_->GetConstant(number, repeat)->address();
}
default:
LOG(FATAL) << "Unsupported constant type";
return Operand(rbp);
}
} else {
// Get locator.
CHECK(Valid(var));
Locator *loc = GetLocator(var);
// Return operand for accessing variable.
switch (loc->iterator->type) {
case SIMPLE:
if (single_) {
// Single iteration.
if (loc->base.is_valid()) {
// Index single element using base register.
return Operand(loc->base);
} else {
// Index single element using offset in instance.
return Operand(masm_->instance(), loc->var->offset());
}
} else {
// Multiple iterations.
if (loc->base.is_valid()) {
// Index element using base register and index.
return Operand(loc->base, offset_);
} else {
// Index element using offset in instance and index.
return Operand(masm_->instance(), offset_, times_1,
loc->var->offset());
}
}
case SCALAR:
if (loc->base.is_valid()) {
// Index scalar using base register.
return Operand(loc->base);
} else {
// Index scalar using offset in instance.
return Operand(masm_->instance(), loc->var->offset());
}
case CONST: {
// Scalar constant in code block, vectorized if needed.
DCHECK(loc->var->IsConstant());
int size = loc->var->element_size();
int repeat = vecsize_ / size;
DCHECK_EQ(repeat * size, vecsize_);
return masm_->GetData(loc->var->data(), size, repeat)->address();
}
case REPEAT:
if (single_) {
// Single iteration.
if (loc->base.is_valid()) {
// Index single element using base register.
return Operand(loc->base);
} else {
// Index single element using offset in instance.
return Operand(masm_->instance(), loc->var->offset());
}
} else {
// Multiple iterations.
if (loc->base.is_valid()) {
// Index element using base register and index.
return Operand(loc->base, loc->iterator->offset);
} else {
// Index element using offset in instance and index.
return Operand(masm_->instance(), loc->iterator->offset, times_1,
loc->var->offset());
}
}
case BROADCAST:
// Return block base plus block offset.
return Operand(loc->iterator->block, loc->iterator->offset);
default:
LOG(FATAL) << "Unsupported iterator type";
return Operand(rbp);
}
}
}
const void *ElementwiseIndexGenerator::data(Express::Var *var) {
DCHECK_EQ(var->type, Express::CONST);
Locator *loc = GetLocator(var);
DCHECK(loc->var->IsConstant());
return loc->var->data();
}
bool ElementwiseIndexGenerator::Valid(Express::Var *var) const {
if (var->type == Express::OUTPUT) {
return var->id >= 0 && var->id < output_.size();
} else {
return var->id >= 0 && var->id < input_.size();
}
}
} // namespace myelin
} // namespace sling
| 32.591022 | 80 | 0.590328 | [
"shape",
"vector"
] |
4a535ee82b38a272fb538efdcd44b6eb40432ca4 | 10,060 | cpp | C++ | src/components/input/mipalsainput.cpp | xchbx/fox | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 2 | 2019-04-12T10:26:43.000Z | 2019-06-21T15:20:11.000Z | src/components/input/mipalsainput.cpp | xchbx/NetCamera | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 1 | 2019-08-06T16:57:49.000Z | 2019-08-06T16:57:49.000Z | src/components/input/mipalsainput.cpp | xchbx/NetCamera | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 1 | 2020-12-31T08:52:03.000Z | 2020-12-31T08:52:03.000Z | /*
This file is a part of EMIPLIB, the EDM Media over IP Library.
Copyright (C) 2006-2017 Hasselt University - Expertise Centre for
Digital Media (EDM) (http://www.edm.uhasselt.be)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "mipconfig.h"
#ifdef MIPCONFIG_SUPPORT_ALSA
#include "mipalsainput.h"
#include "miprawaudiomessage.h"
#include "mipsystemmessage.h"
#include "mipstreambuffer.h"
#include <iostream>
#include "mipdebug.h"
using namespace jthread;
using namespace std;
#define MIPALSAINPUT_ERRSTR_DEVICEALREADYOPEN "Device already opened"
#define MIPALSAINPUT_ERRSTR_DEVICENOTOPEN "Device is not opened"
#define MIPALSAINPUT_ERRSTR_CANTOPENDEVICE "Error opening device"
#define MIPALSAINPUT_ERRSTR_CANTGETHWPARAMS "Error retrieving device hardware parameters"
#define MIPALSAINPUT_ERRSTR_CANTSETINTERLEAVEDMODE "Can't set device to interleaved mode"
#define MIPALSAINPUT_ERRSTR_FLOATNOTSUPPORTED "Floating point format is not supported by this device"
#define MIPALSAINPUT_ERRSTR_S16NOTSUPPORTED "Signed 16 bit format is not supported by this device"
#define MIPALSAINPUT_ERRSTR_UNSUPPORTEDSAMPLINGRATE "The requested sampling rate is not supported"
#define MIPALSAINPUT_ERRSTR_UNSUPPORTEDCHANNELS "The requested number of channels is not supported"
#define MIPALSAINPUT_ERRSTR_CANTSETHWPARAMS "Error setting hardware parameters"
#define MIPALSAINPUT_ERRSTR_CANTSTARTBACKGROUNDTHREAD "Can't start the background thread"
#define MIPALSAINPUT_ERRSTR_THREADSTOPPED "Background thread stopped"
#define MIPALSAINPUT_ERRSTR_INCOMPATIBLECHANNELS "Incompatible number of channels"
#define MIPALSAINPUT_ERRSTR_INCOMPATIBLESAMPLINGRATE "Incompatible sampling rate"
#define MIPALSAINPUT_ERRSTR_CANTINITSIGWAIT "Unable to initialize signal waiter"
#define MIPALSAINPUT_ERRSTR_BADMESSAGE "Bad message, expecting a WAITTIME message"
MIPAlsaInput::MIPAlsaInput() : MIPComponent("MIPAlsaInput")
{
int status;
m_pDevice = 0;
if ((status = m_stopMutex.Init()) < 0)
{
std::cerr << "Error: can't initialize ALSA output thread mutex (JMutex error code " << status << ")" << std::endl;
exit(-1);
}
m_pBuffer = nullptr;
m_pMsg = nullptr;
}
MIPAlsaInput::~MIPAlsaInput()
{
close();
}
bool MIPAlsaInput::open(int sampRate, int channels, MIPTime blockTime, bool floatSamples, const string device)
{
if (m_pDevice != 0)
{
setErrorString(MIPALSAINPUT_ERRSTR_DEVICEALREADYOPEN);
return false;
}
if (!m_sigWait.isInit())
{
if (!m_sigWait.init())
{
setErrorString(MIPALSAINPUT_ERRSTR_CANTINITSIGWAIT);
return false;
}
m_sigWait.clearSignalBuffers();
}
int status;
m_floatSamples = floatSamples;
if ((status = snd_pcm_open(&m_pDevice, device.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0)
{
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_CANTOPENDEVICE);
return false;
}
snd_pcm_hw_params_malloc(&m_pHwParameters);
if ((status = snd_pcm_hw_params_any(m_pDevice,m_pHwParameters)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_CANTGETHWPARAMS);
return false;
}
if ((status = snd_pcm_hw_params_set_access(m_pDevice, m_pHwParameters, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_CANTSETINTERLEAVEDMODE);
return false;
}
if (floatSamples)
{
if ((status = snd_pcm_hw_params_set_format(m_pDevice, m_pHwParameters, SND_PCM_FORMAT_FLOAT)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_FLOATNOTSUPPORTED);
return false;
}
}
else
{
if ((status = snd_pcm_hw_params_set_format(m_pDevice, m_pHwParameters, SND_PCM_FORMAT_S16)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_S16NOTSUPPORTED);
return false;
}
}
// For some reason this does not work well on my soundcard at home
//if ((status = snd_pcm_hw_params_set_rate(m_pDevice, m_pHwParameters, sampRate, 0)) < 0)
unsigned int rate = sampRate;
if ((status = snd_pcm_hw_params_set_rate_near(m_pDevice, m_pHwParameters, &rate, 0)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_UNSUPPORTEDSAMPLINGRATE);
return false;
}
if (rate != (unsigned int)sampRate)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_UNSUPPORTEDSAMPLINGRATE);
return false;
}
if ((status = snd_pcm_hw_params_set_channels(m_pDevice, m_pHwParameters, channels)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(MIPALSAINPUT_ERRSTR_UNSUPPORTEDCHANNELS);
return false;
}
m_blockFrames = ((size_t)((blockTime.getValue() * ((real_t)sampRate)) + 0.5));
m_blockSize = m_blockFrames * ((size_t)channels);
if (floatSamples)
m_blockSize *= sizeof(float);
else
m_blockSize *= sizeof(int16_t);
snd_pcm_uframes_t minVal, maxVal;
minVal = m_blockFrames;
maxVal = m_blockFrames*10;
snd_pcm_hw_params_set_buffer_size_minmax(m_pDevice, m_pHwParameters, &minVal, &maxVal);
//cout << "minVal = " << minVal << " maxVal = " << maxVal << endl;
if ((status = snd_pcm_hw_params(m_pDevice, m_pHwParameters)) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
setErrorString(std::string(MIPALSAINPUT_ERRSTR_CANTSETHWPARAMS)+std::string(": ")+std::string(snd_strerror(status)));
return false;
}
m_pBuffer = new MIPStreamBuffer(m_blockSize);
m_channels = channels;
m_sampRate = sampRate;
if (floatSamples)
{
m_floatFrames.resize(m_blockFrames*m_channels*10);
m_pMsg = new MIPRawFloatAudioMessage(sampRate, channels, m_blockFrames, &m_floatFrames[0], false);
}
else
{
m_s16Frames.resize(m_blockFrames*m_channels*10);
m_pMsg = new MIPRaw16bitAudioMessage(sampRate, channels, m_blockFrames, true, MIPRaw16bitAudioMessage::Native,
&m_s16Frames[0], false);
}
m_stopLoop = false;
if ((status = JThread::Start()) < 0)
{
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
delete m_pBuffer;
m_pBuffer = nullptr;
delete m_pMsg;
m_pMsg = nullptr;
setErrorString(MIPALSAINPUT_ERRSTR_CANTSTARTBACKGROUNDTHREAD);
return false;
}
return true;
}
bool MIPAlsaInput::close()
{
if (m_pDevice == 0)
{
setErrorString(MIPALSAINPUT_ERRSTR_DEVICENOTOPEN);
return false;
}
MIPTime starttime = MIPTime::getCurrentTime();
m_stopMutex.Lock();
m_stopLoop = true;
m_stopMutex.Unlock();
while (JThread::IsRunning() && (MIPTime::getCurrentTime().getValue()-starttime.getValue()) < 5.0)
{
MIPTime::wait(MIPTime(0.010));
m_sigWait.signal();
}
if (JThread::IsRunning())
JThread::Kill();
snd_pcm_hw_params_free(m_pHwParameters);
snd_pcm_reset(m_pDevice);
snd_pcm_close(m_pDevice);
m_pDevice = 0;
m_sigWait.clearSignalBuffers();
delete m_pBuffer;
m_pBuffer = nullptr;
delete m_pMsg;
m_pMsg = nullptr;
return true;
}
bool MIPAlsaInput::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
if (m_pDevice == 0)
{
setErrorString(MIPALSAINPUT_ERRSTR_DEVICENOTOPEN);
return false;
}
if (!JThread::IsRunning())
{
setErrorString(MIPALSAINPUT_ERRSTR_THREADSTOPPED);
return false;
}
if (!(pMsg->getMessageType() == MIPMESSAGE_TYPE_SYSTEM && pMsg->getMessageSubtype() == MIPSYSTEMMESSAGE_TYPE_WAITTIME))
{
setErrorString(MIPALSAINPUT_ERRSTR_BADMESSAGE);
return false;
}
m_sigWait.clearSignalBuffers();
if (m_pBuffer->getAmountBuffered() < m_blockSize)
m_sigWait.waitForSignal();
void *pTgt = (m_floatSamples)?((void *)&m_floatFrames[0]):((void *)&m_s16Frames[0]);
m_pBuffer->read(pTgt, m_blockSize);
m_gotMsg = false;
return true;
}
bool MIPAlsaInput::pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg)
{
if (m_pDevice == 0)
{
setErrorString(MIPALSAINPUT_ERRSTR_DEVICENOTOPEN);
return false;
}
if (m_gotMsg)
{
m_gotMsg = false;
*pMsg = 0;
}
else
{
m_gotMsg = true;
*pMsg = m_pMsg;
}
return true;
}
void *MIPAlsaInput::Thread()
{
#ifdef MIPDEBUG
std::cout << "MIPAlsaInput::Thread started" << std::endl;
#endif // MIPDEBUG
JThread::ThreadStarted();
vector<uint8_t> block(m_blockSize);
bool done;
m_stopMutex.Lock();
done = m_stopLoop;
m_stopMutex.Unlock();
while (!done)
{
int r = 0;
MIPTime t = MIPTime::getCurrentTime();
if ((r = snd_pcm_readi(m_pDevice, &block[0], m_blockFrames)) >= 0)
{
MIPTime dt = MIPTime::getCurrentTime();
dt -= t;
if (m_pBuffer->getAmountBuffered() > m_blockSize) // try not to build up delay
m_pBuffer->clear();
m_pBuffer->write(&block[0], m_blockSize);
m_sigWait.signal();
}
else
{
cerr << "Error reading data, trying to recover: " << snd_strerror(r) << endl;
snd_pcm_recover(m_pDevice, r, 0);
}
m_stopMutex.Lock();
done = m_stopLoop;
m_stopMutex.Unlock();
}
#ifdef MIPDEBUG
std::cout << "MIPAlsaInput::Thread stopped" << std::endl;
#endif // MIPDEBUG
return 0;
}
#endif // MIPCONFIG_SUPPORT_ALSA
| 26.266319 | 120 | 0.741054 | [
"vector"
] |
4a55590dc3285fca917b4412b718b5e7ae1b3618 | 6,549 | cpp | C++ | src/paintown-engine/network/paintown_network.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | 1 | 2021-06-16T15:25:47.000Z | 2021-06-16T15:25:47.000Z | src/paintown-engine/network/paintown_network.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | src/paintown-engine/network/paintown_network.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | #include "network.h"
#include "util/system.h"
#include <vector>
#include <string>
#include <string.h>
/* FIXME: these things should come from util/network/network.h */
#ifdef HAVE_NETWORKING
#ifdef WII
#include <network.h>
#elif defined(WINDOWS)
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
#else
#ifndef htonl
#define htonl(x) x
#endif
#ifndef htons
#define htons(x) x
#endif
#ifndef ntohl
#define ntohl(x) x
#endif
#ifndef ntohs
#define ntohs(x) x
#endif
#endif
using std::string;
using std::vector;
namespace Network{
/* just some random number I picked out of thin air */
const unsigned int MagicId = 0x0dff2110;
static int messageSize(Message const & message){
return message.size();
}
static int messageSize(Message* const & message){
return message->size();
}
static uint8_t * messageDump(const Message & message, uint8_t * buffer){
return message.dump(buffer);
}
static uint8_t * messageDump(Message* const & message, uint8_t * buffer){
return message->dump(buffer);
}
template <typename M>
static int totalSize(const vector<M> & messages){
int size = 0;
for (typename vector<M>::const_iterator it = messages.begin(); it != messages.end(); it++){
// size += messageSize<M>(*it);
size += messageSize(*it);
}
return size;
}
template <class M>
static void dump(const std::vector<M> & messages, uint8_t * buffer ){
for (typename vector<M>::const_iterator it = messages.begin(); it != messages.end(); it++ ){
buffer = messageDump(*it, buffer);
}
}
template <class M>
static void doSendAllMessages(const vector<M> & messages, Socket socket){
#ifdef HAVE_NETWORKING
int length = totalSize<M>(messages);
uint8_t * data = new uint8_t[length];
dump<M>(messages, data);
// Compress::testCompression((unsigned char *) data, length);
sendBytes(socket, data, length);
delete[] data;
#endif
}
void sendAllMessages(const vector<Message> & messages, Socket socket){
doSendAllMessages<Message>(messages, socket);
}
void sendAllMessages(const vector<Message*> & messages, Socket socket){
doSendAllMessages<Message*>(messages, socket);
}
void Message::send(Socket socket) const {
/*
send16( socket, id );
sendBytes( socket, data, DATA_SIZE );
if ( path != "" ){
send16( socket, path.length() + 1 );
sendStr( socket, path );
} else {
send16( socket, -1 );
}
*/
#ifdef HAVE_NETWORKING
uint8_t * buffer = new uint8_t[size()];
dump(buffer);
sendBytes(socket, buffer, size());
delete[] buffer;
#endif
}
Message::Message():
id((uint32_t) -1),
timestamp(0),
readFrom(0){
memset(data, 0, sizeof(data));
position = data;
}
Message::Message(const Message & m):
timestamp(m.timestamp),
readFrom(m.readFrom){
memcpy(data, m.data, sizeof(data));
position = data;
position += m.position - m.data;
path = m.path;
id = m.id;
}
Message & Message::operator=( const Message & m ){
memcpy(data, m.data, sizeof(data));
position = data;
position += m.position - m.data;
path = m.path;
id = m.id;
timestamp = m.timestamp;
readFrom = m.readFrom;
return *this;
}
Message::Message(Socket socket){
#ifdef HAVE_NETWORKING
position = data;
id = read32(socket);
readBytes(socket, data, DATA_SIZE);
int str = read16(socket);
if (str != -1){
/* cap strings at 1024 bytes */
char buf[1024];
str = (signed)(sizeof(buf) - 1) < str ? (signed)(sizeof(buf) - 1) : str;
readBytes(socket, (uint8_t *) buf, str);
buf[str] = 0;
/* this is a string copy, not an assignment to a temporary pointer */
this->path = buf;
}
timestamp = System::currentMilliseconds();
readFrom = socket;
#endif
}
/* copies data into buffer and increments buffer by the number of bits
* in Size
*/
template<class Size> static void mcopy(uint8_t *& buffer, Size data){
memcpy(buffer, &data, sizeof(data));
buffer += sizeof(data);
}
uint8_t * Message::dump(uint8_t * buffer) const {
mcopy<uint32_t>(buffer, htonl(id));
// *(uint32_t *) buffer = htonl(id);
// Global::debug(1, "network") << "Dumped id " << id << " as " << htonl(id) << std::endl;
// buffer += sizeof(id);
memcpy(buffer, data, DATA_SIZE);
buffer += DATA_SIZE;
if (path != ""){
// *(uint16_t *) buffer = htons(path.length() + 1);
// buffer += sizeof(uint16_t);
mcopy<uint16_t>(buffer, htons(path.length() + 1));
memcpy(buffer, path.c_str(), path.length() + 1);
buffer += path.length() + 1;
} else {
// *(uint16_t *) buffer = htons((uint16_t) -1);
// buffer += sizeof(uint16_t);
mcopy<uint16_t>(buffer, htons((uint16_t) -1));
}
return buffer;
}
void Message::reset(){
position = data;
}
Message & Message::operator<<(int x){
if (position > data + DATA_SIZE - sizeof(uint16_t)){
throw NetworkException("Tried to set too much data");
}
// *(int16_t *) position = htons(x);
// position += sizeof(int16_t);
mcopy<int16_t>(position, htons(x));
return *this;
}
Message & Message::operator<<(unsigned int x){
if (position > data + DATA_SIZE - sizeof(uint32_t)){
throw NetworkException("Tried to set too much data");
}
mcopy<int32_t>(position, htonl(x));
/*
int32_t use = htonl(x);
memcpy(position, &use, sizeof(use));
*/
// *(int32_t *) position = htonl(x);
return *this;
}
Message & Message::operator>>(int & x){
if (position > data + DATA_SIZE - sizeof(uint16_t)){
throw NetworkException("Tried to read too much data");
}
/*
x = ntohs(*(int16_t *) position);
position += sizeof(int16_t);
*/
int16_t out;
memcpy(&out, position, sizeof(out));
position += sizeof(out);
x = ntohs(out);
return *this;
}
Message & Message::operator>>(unsigned int & x){
if (position > data + DATA_SIZE - sizeof(uint32_t)){
throw NetworkException("Tried to read too much data");
}
/*
x = htonl(*(int32_t *) position);
position += sizeof(int32_t);
*/
int32_t out;
memcpy(&out, position, sizeof(out));
position += sizeof(out);
x = ntohl(out);
return *this;
}
Message & Message::operator>>(std::string & out){
out = path;
return *this;
}
Message & Message::operator<<(string p){
path = p;
return *this;
}
int Message::size() const {
return sizeof(id) + DATA_SIZE +
(path != "" ? sizeof(uint16_t) + path.length() + 1 : sizeof(uint16_t));
}
}
| 24.345725 | 96 | 0.621622 | [
"vector"
] |
4a575e532de0907bb1108d75be1c921cf8d244af | 3,220 | cpp | C++ | src/yamlcast/iarchive_test.cpp | unnonouno/yamlcast | cff7cc2c66f15850e3c97343d87fa546593ccfe0 | [
"MIT"
] | 2 | 2015-09-27T22:05:41.000Z | 2015-10-28T05:34:05.000Z | src/yamlcast/iarchive_test.cpp | unnonouno/yamlcast | cff7cc2c66f15850e3c97343d87fa546593ccfe0 | [
"MIT"
] | null | null | null | src/yamlcast/iarchive_test.cpp | unnonouno/yamlcast | cff7cc2c66f15850e3c97343d87fa546593ccfe0 | [
"MIT"
] | null | null | null | #include <map>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "exception.hpp"
#include "iarchive.hpp"
using std::map;
using std::string;
using std::vector;
namespace yamlcast {
template <typename T>
void deserialize(const string& str, T& v) {
document::ptr yaml = document::parse_string(str);
v = yaml_cast<T>(*yaml);
}
template <typename T>
void test_eq(const string& str, const T& expect) {
T v;
deserialize(str, v);
EXPECT_EQ(expect, v);
}
TEST(iarchive, bool) {
test_eq<bool>("true", true);
test_eq<bool>("false", false);
}
TEST(iarchive, invalid_bool) {
bool v;
EXPECT_THROW(deserialize("[]", v), yaml_bad_cast);
EXPECT_THROW(deserialize("10", v), yaml_invalid_scalar);
}
TEST(iarchive, int) {
test_eq<int>("10", 10);
}
TEST(iarchive, invalid_int) {
int v;
EXPECT_THROW(deserialize("[]", v), yaml_bad_cast);
EXPECT_THROW(deserialize("true", v), yaml_invalid_scalar);
}
TEST(iarchive, double) {
test_eq<double>("1.5", 1.5);
}
TEST(iarchive, invalid_double) {
double v;
EXPECT_THROW(deserialize("{}", v), yaml_bad_cast);
EXPECT_THROW(deserialize("true", v), yaml_invalid_scalar);
}
TEST(iarchive, string) {
test_eq<string>("\"hello\"", "hello");
}
TEST(iarchive, invalid_string) {
double v;
EXPECT_THROW(deserialize("{}", v), yaml_bad_cast);
}
TEST(iarchive, vector) {
vector<int> v;
v.push_back(0);
v.push_back(1);
test_eq<vector<int> >("[0, 1]", v);
}
TEST(iarchive, map) {
map<string, int> m;
m["hello"] = 1;
m["goodbye"] = 2;
test_eq<map<string, int> >("{hello: 1, goodbye: 2}", m);
}
struct Struct {
int age;
int nam;
string name;
vector<string> tags;
template <typename Ar>
void serialize(Ar& ar) {
ar & MEMBER(age) & MEMBER(nam) & MEMBER(name) & MEMBER(tags);
}
};
TEST(iarchive, object) {
Struct s;
deserialize("{age: 10, nam: 1, name: \"taro\", tags: [\"saitama\"]}", s);
EXPECT_EQ(10, s.age);
EXPECT_EQ("taro", s.name);
ASSERT_EQ(1u, s.tags.size());
EXPECT_EQ("saitama", s.tags[0]);
}
TEST(iarchive, not_found) {
Struct s;
try {
deserialize("{age: 10, nam: 1, tags: [\"saitama\"]}", s);
FAIL();
} catch(const yaml_not_found& e) {
EXPECT_EQ("name", e.get_key());
}
}
struct OptionalStruct {
pfi::data::optional<int> n;
pfi::data::optional<int> m;
template <typename Ar>
void serialize(Ar& ar) {
ar & MEMBER(n) & MEMBER(m);
}
};
TEST(iarchive, optional) {
OptionalStruct s;
s.m = 100;
deserialize("{n: 10}", s);
EXPECT_TRUE(s.n);
EXPECT_EQ(10, s.n);
EXPECT_FALSE(s.m);
}
struct Empty {
int n;
template <typename Ar>
void serialize(Ar& ar) {
ar & MEMBER(n);
}
};
TEST(iarchive, ignore_non_scalar_key) {
Empty e;
deserialize("{[aa]: 1, n: 10}", e);
EXPECT_EQ(10, e.n);
}
struct Any {
yamlcast::node::ptr arg;
template <typename Ar>
void serialize(Ar& ar) {
ar & MEMBER(arg);
}
};
TEST(iarchive, node) {
Any a;
document::ptr yaml = document::parse_string("{arg: {x: 10, y: 20}}");
a = yaml_cast<Any>(*yaml);
EXPECT_EQ(YAML_MAPPING_NODE, a.arg->type());
std::map<std::string, int> m;
from_yaml(*a.arg, m);
EXPECT_EQ(10, m["x"]);
EXPECT_EQ(20, m["y"]);
}
} // namespace yamlcast
| 18.941176 | 75 | 0.629503 | [
"object",
"vector"
] |
4a5c9831dc7bf70018714c76b7270c8d517233f2 | 178,835 | cpp | C++ | source/game/vehicles/TransportComponents.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/vehicles/TransportComponents.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/vehicles/TransportComponents.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "TransportComponents.h"
#include "Transport.h"
#include "Vehicle_RigidBody.h"
#include "../anim/Anim.h"
#include "Attachments.h"
#include "../ContentMask.h"
#include "../IK.h"
#include "VehicleIK.h"
#include "../../framework/CVarSystem.h"
#include "VehicleSuspension.h"
#include "VehicleControl.h"
#include "../Player.h"
#include "../client/ClientMoveable.h"
#include "../physics/Physics_JetPack.h"
#include "../../decllib/DeclSurfaceType.h"
#include "../script/Script_Helper.h"
#include "../script/Script_ScriptObject.h"
#include "../effects/TireTread.h"
const float minParticleCreationSpeed = 64.f;
idCVar g_disableTransportDebris( "g_disableTransportDebris", "0", CVAR_GAME | CVAR_BOOL, "" );
idCVar g_maxTransportDebrisExtraHigh( "g_maxTransportDebrisExtraHigh", "8", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "The maximum number of pieces of extra high priority (really large) debris. -1 means no limit." );
idCVar g_maxTransportDebrisHigh( "g_maxTransportDebrisHigh", "8", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "The maximum number of pieces of high priority (large) debris. -1 means no limit." );
idCVar g_maxTransportDebrisMedium( "g_maxTransportDebrisMedium", "8", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "The maximum number of pieces of medium priority (middling) debris. -1 means no limit." );
idCVar g_maxTransportDebrisLow( "g_maxTransportDebrisLow", "8", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "The maximum number of pieces of low priority (small) debris. -1 means no limit." );
idCVar g_transportDebrisExtraHighCutoff("g_transportDebrisExtraHighCutoff", "8192", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Beyond this distance from the viewpoint extra high priority debris will not be spawned. -1 means no limit." );
idCVar g_transportDebrisHighCutoff( "g_transportDebrisHighCutoff", "4096", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Beyond this distance from the viewpoint high priority debris will not be spawned. -1 means no limit." );
idCVar g_transportDebrisMediumCutoff( "g_transportDebrisMediumCutoff", "2048", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Beyond this distance from the viewpoint medium priority debris will not be spawned. -1 means no limit." );
idCVar g_transportDebrisLowCutoff( "g_transportDebrisLowCutoff", "1024", CVAR_GAME | CVAR_INTEGER | CVAR_ARCHIVE, "Beyond this distance from the viewpoint low priority debris will not be spawned. -1 means no limit." );
sdVehicleDriveObject::debrisList_t sdVehicleDriveObject::extraHighDebris;
sdVehicleDriveObject::debrisList_t sdVehicleDriveObject::highDebris;
sdVehicleDriveObject::debrisList_t sdVehicleDriveObject::mediumDebris;
sdVehicleDriveObject::debrisList_t sdVehicleDriveObject::lowDebris;
/*
===============================================================================
sdVehicleDriveObject
===============================================================================
*/
ABSTRACT_DECLARATION( idClass, sdVehicleDriveObject )
END_CLASS
/*
================
sdVehicleDriveObject::sdVehicleDriveObject
================
*/
sdVehicleDriveObject::sdVehicleDriveObject( void ) {
hidden = false;
scriptObject = NULL;
}
/*
================
sdVehicleDriveObject::~sdVehicleDriveObject
================
*/
sdVehicleDriveObject::~sdVehicleDriveObject( void ) {
if ( scriptObject ) {
gameLocal.program->FreeScriptObject( scriptObject );
}
}
/*
================
sdVehicleDriveObject::PostInit
================
*/
void sdVehicleDriveObject::PostInit( void ) {
sdTransport* parent = GetParent();
assert( parent );
if ( GoesInPartList() ) {
parent->AddActiveDriveObject( this );
}
}
/*
================
sdVehicleDriveObject::Hide
================
*/
void sdVehicleDriveObject::Hide( void ) {
if ( hidden ) {
return;
}
hidden = true;
sdTransport* parent = GetParent();
assert( parent );
if ( GoesInPartList() ) {
parent->RemoveActiveDriveObject( this );
if ( IsType( sdVehicleRigidBodyWheel::Type ) ) {
parent->RemoveCriticalDrivePart();
}
}
}
/*
================
sdVehicleDriveObject::Show
================
*/
void sdVehicleDriveObject::Show( void ) {
if ( !hidden ) {
return;
}
hidden = false;
sdTransport* parent = GetParent();
assert( parent );
if ( GoesInPartList() ) {
parent->AddActiveDriveObject( this );
if ( IsType( sdVehicleRigidBodyWheel::Type ) ) {
parent->AddCriticalDrivePart();
}
}
}
/*
================
sdVehicleDriveObject::CanAddDebris
================
*/
bool sdVehicleDriveObject::CanAddDebris( debrisPriority_t priority, const idVec3& origin ) {
debrisList_t* list = &highDebris;
int limit = g_maxTransportDebrisHigh.GetInteger();
float distanceLimit = g_transportDebrisHighCutoff.GetFloat();
if ( priority == PRIORITY_MEDIUM ) {
list = &mediumDebris;
limit = g_maxTransportDebrisMedium.GetInteger();
distanceLimit = g_transportDebrisMediumCutoff.GetFloat();
} else if ( priority == PRIORITY_LOW ) {
list = &lowDebris;
limit = g_maxTransportDebrisLow.GetInteger();
distanceLimit = g_transportDebrisLowCutoff.GetFloat();
} else if ( priority == PRIORITY_EXTRA_HIGH ) {
list = &extraHighDebris;
limit = g_maxTransportDebrisExtraHigh.GetInteger();
distanceLimit = g_transportDebrisExtraHighCutoff.GetFloat();
}
// clean out NULLs
for ( int i = 0; i < list->Num(); i++ ) {
if ( !(*list)[ i ].IsValid() ) {
list->RemoveIndexFast( i );
i--;
continue;
}
}
// don't let it exceed the limit
if ( limit != -1 && list->Num() >= limit ) {
return false;
}
idPlayer* player = gameLocal.GetLocalViewPlayer();
if ( distanceLimit != -1 && player != NULL ) {
float distance = ( player->GetViewPos() - origin ).Length();
if ( distance > distanceLimit ) {
return false;
}
}
return true;
}
/*
================
sdVehicleDriveObject::AddDebris
================
*/
void sdVehicleDriveObject::AddDebris( rvClientMoveable* debris, debrisPriority_t priority ) {
debrisList_t* list = &highDebris;
int limit = g_maxTransportDebrisHigh.GetInteger();
if ( priority == PRIORITY_MEDIUM ) {
list = &mediumDebris;
limit = g_maxTransportDebrisMedium.GetInteger();
} else if ( priority == PRIORITY_LOW ) {
list = &lowDebris;
limit = g_maxTransportDebrisLow.GetInteger();
} else if ( priority == PRIORITY_EXTRA_HIGH ) {
list = &extraHighDebris;
limit = g_maxTransportDebrisExtraHigh.GetInteger();
}
// -1 means no limit
if ( limit == -1 ) {
return;
}
rvClientEntityPtr< rvClientMoveable >* entry = list->Alloc();
if ( entry != NULL ) {
entry->operator=( debris );
}
}
/*
===============================================================================
sdVehiclePart
===============================================================================
*/
extern const idEventDef EV_GetAngles;
extern const idEventDef EV_GetHealth;
extern const idEventDef EV_GetOrigin;
const idEventDef EV_VehiclePart_GetParent( "getParent", 'e', DOC_TEXT( "Returns the vehicle this part belongs to." ), 0, "This will never return $null$." );
const idEventDef EV_VehiclePart_GetJoint( "getJoint", 's', DOC_TEXT( "Returns the name of the joint this part is associated with." ), 0, "An empty string will be returned if the lookup fails." );
ABSTRACT_DECLARATION( sdVehicleDriveObject, sdVehiclePart )
EVENT( EV_GetHealth, sdVehiclePart::Event_GetHealth )
EVENT( EV_GetOrigin, sdVehiclePart::Event_GetOrigin )
EVENT( EV_GetAngles, sdVehiclePart::Event_GetAngles )
EVENT( EV_VehiclePart_GetParent, sdVehiclePart::Event_GetParent )
EVENT( EV_VehiclePart_GetJoint, sdVehiclePart::Event_GetJoint )
END_CLASS
/*
================
sdVehiclePart::sdVehiclePart
================
*/
sdVehiclePart::sdVehiclePart( void ) {
bodyId = -1;
waterEffects = NULL;
scriptObject = NULL;
reattachTime = 0;
}
/*
================
sdVehiclePart::AddSurface
================
*/
void sdVehiclePart::AddSurface( const char* surfaceName ) {
int id = GetParent()->FindSurfaceId( surfaceName );
if ( id != -1 ) {
surfaces.Alloc() = id;
} else {
gameLocal.Warning( "sdVehiclePart::AddSurface Invalid Surface '%s'", surfaceName );
}
}
/*
================
sdVehiclePart::Detach
================
*/
void sdVehiclePart::Detach( bool createDebris, bool decay ) {
if ( IsHidden() ) {
return;
}
Hide();
if ( !noAutoHide ) {
HideSurfaces();
}
idPhysics* physics = GetParent()->GetPhysics();
if( bodyId != -1 ) {
oldcontents = physics->GetContents( bodyId );
oldclipmask = physics->GetClipMask( bodyId );
physics->SetContents( 0, bodyId );
physics->SetClipMask( 0, bodyId );
}
if ( createDebris && brokenPart ) {
if ( decay == false && physics->InWater() < 1.0f ) {
CreateExplosionDebris();
} else {
CreateDecayDebris();
}
}
}
/*
================
sdVehiclePart::CreateExplosionDebris
================
*/
void sdVehiclePart::CreateExplosionDebris( void ) {
if ( g_disableTransportDebris.GetBool() ) {
return;
}
sdTransport* transport = GetParent();
idPhysics* parentPhysics = transport->GetPhysics();
idVec3 org;
idMat3 axis;
GetWorldOrigin( org );
GetWorldAxis( axis );
// make sure we can have another part of this priority
debrisPriority_t priority = ( debrisPriority_t )brokenPart->dict.GetInt( "priority" );
if ( !CanAddDebris( priority, org ) ) {
return;
}
if ( transport->GetMasterDestroyedPart() != NULL ) {
parentPhysics = transport->GetMasterDestroyedPart()->GetPhysics();
}
const idVec3& vel = parentPhysics->GetLinearVelocity();
const idVec3& aVel = parentPhysics->GetAngularVelocity();
rvClientMoveable* cent = gameLocal.SpawnClientMoveable( brokenPart->GetName(), 5000, org, axis, vec3_origin, vec3_origin );
AddDebris( cent, priority );
if ( cent != NULL ) {
gameLocal.PlayEffect( brokenPart->dict, colorWhite.ToVec3(), "fx_explode", NULL, cent->GetPhysics()->GetOrigin(), cent->GetPhysics()->GetAxis(), false );
if ( flipMaster ) {
transport->SetMasterDestroyedPart( cent );
}
//
const idVec3& centCOM = cent->GetPhysics()->GetCenterOfMass();
const idVec3& parentCOM = parentPhysics->GetCenterOfMass();
const idVec3& parentOrg = parentPhysics->GetOrigin();
const idMat3& parentAxis = parentPhysics->GetAxis();
idVec3 radiusVector = ( centCOM*axis + org ) - ( parentCOM * parentAxis + parentOrg );
// calculate the actual linear velocity of this point
idVec3 myVelocity = vel + aVel.Cross( radiusVector );
cent->GetPhysics()->SetLinearVelocity( myVelocity );
//
cent->GetPhysics()->SetContents( 0, 0 );
cent->GetPhysics()->SetClipMask( CONTENTS_SOLID | CONTENTS_BODY, 0 );
if ( flipPower != 0.0f ) {
idBounds bounds = cent->GetPhysics()->GetBounds();
// choose a random point in its bounds to apply an upwards impulse
idVec3 size = bounds.Size();
idVec3 point;
// pick whether it should flip forwards or backwards based on the velocity
if ( myVelocity * axis[ 0 ] >= 0.0f ) {
point.x = 0.0f;
} else {
point.x = size.x;
}
point.y = size.y * gameLocal.random.RandomFloat();
point.z = size.z * gameLocal.random.RandomFloat();
point += bounds[ 0 ];
point *= axis;
point += org;
const idVec3& gravityNormal = -cent->GetPhysics()->GetGravityNormal();
idVec3 flipDirection = -gravityNormal;
float flipAmount = -flipDirection * cent->GetPhysics()->GetGravity();
if ( parentPhysics != transport->GetPhysics() ) {
// this is a slaved part
flipDirection = radiusVector;
flipDirection -= ( flipDirection*gravityNormal )*gravityNormal;
flipDirection.Normalize();
}
float scaleByVel = idMath::ClampFloat( 0.75f, 1.0f, myVelocity.Length() / 500.0f );
// calculate the impulse to apply
idVec3 impulse = scaleByVel * flipPower * MS2SEC( gameLocal.msec ) * cent->GetPhysics()->GetMass() * flipDirection * flipAmount;
cent->GetPhysics()->ApplyImpulse( 0, point, impulse );
}
}
}
/*
================
sdVehiclePart::CreateDecayDebris
================
*/
void sdVehiclePart::CreateDecayDebris( void ) {
if ( g_disableTransportDebris.GetBool() ) {
return;
}
sdTransport* transport = GetParent();
idVec3 org;
idMat3 axis;
GetWorldOrigin( org );
GetWorldAxis( axis );
// make sure we can have another part of this priority
debrisPriority_t priority = ( debrisPriority_t )brokenPart->dict.GetInt( "priority" );
if ( !CanAddDebris( priority, org ) ) {
return;
}
idVec3 velMax = brokenPart->dict.GetVector( "decay_velocity_max", "300 0 0" );
idVec3 aVelMax = brokenPart->dict.GetVector( "decay_angular_velocity_max", "0.5 1 2" );
idVec3 vel, aVel;
float random = gameLocal.random.RandomFloat();
for( int i = 0; i < 3; i++ ) {
// jrad - disable damage-based motion for now...
vel[ i ] = random * ( velMax[ i ] /*+ damageAmount * -damageDirection[ i ] */ );
aVel[ i ] = random * aVelMax[ i ];
}
vel *= axis;
vel += transport->GetPhysics()->GetLinearVelocity();
aVel += transport->GetPhysics()->GetAngularVelocity();
vel *= transport->GetRenderEntity()->axis;
aVel *= transport->GetRenderEntity()->axis;
rvClientMoveable* cent = gameLocal.SpawnClientMoveable( brokenPart->GetName(), 5000, org, axis, vel, aVel, 1 );
AddDebris( cent, priority );
if ( cent != NULL ) {
gameLocal.PlayEffect( brokenPart->dict, colorWhite.ToVec3(), "fx_decay", NULL, cent->GetPhysics()->GetOrigin(), cent->GetPhysics()->GetAxis(), false );
cent->GetPhysics()->SetContents( 0 );
cent->GetPhysics()->SetClipMask( CONTENTS_SOLID | CONTENTS_BODY );
}
}
/*
================
sdVehiclePart::Reattach
================
*/
void sdVehiclePart::Reattach( void ) {
if ( !IsHidden() ) {
return;
}
Show();
ShowSurfaces();
idPhysics* physics = GetParent()->GetPhysics();
if( bodyId != -1 ) {
physics->SetContents( oldcontents, bodyId );
physics->SetClipMask( oldclipmask, bodyId );
}
physics->Activate();
reattachTime = gameLocal.time;
}
/*
================
sdVehiclePart::Repair
================
*/
int sdVehiclePart::Repair( int repair ) {
if ( health >= maxHealth ) {
return 0;
}
int heal = maxHealth - health;
if( repair > heal ) {
repair = heal;
}
health += repair;
return repair;
}
/*
================
sdVehiclePart::HideSurfaces
================
*/
void sdVehiclePart::HideSurfaces( void ) {
bool surfacesChanged = false;
idRenderModel* renderModel = GetParent()->GetRenderEntity()->hModel;
for ( int i = 0; i < surfaces.Num(); i++ ) {
GetParent()->GetRenderEntity()->hideSurfaceMask.Set( surfaces[ i ] );
surfacesChanged = true;
}
// remove bound things in that bounds
idBounds partBounds;
idVec3 origin;
idMat3 axis;
GetWorldOrigin( origin );
GetWorldAxis( axis );
GetBounds( partBounds );
partBounds.RotateSelf( axis );
partBounds.TranslateSelf( origin );
GetParent()->RemoveBinds( &partBounds, true );
if ( GetParent()->GetModelDefHandle() != -1 ) {
gameRenderWorld->RemoveDecals( GetParent()->GetModelDefHandle() );
}
if ( surfacesChanged ) {
GetParent()->BecomeActive( TH_UPDATEVISUALS );
}
}
/*
================
sdVehiclePart::ShowSurfaces
================
*/
void sdVehiclePart::ShowSurfaces( void ) {
bool surfacesChanged = false;
for ( int i = 0; i < surfaces.Num(); i++ ) {
GetParent()->GetRenderEntity()->hideSurfaceMask.Clear( surfaces[ i ] );
surfacesChanged = true;
}
if ( surfacesChanged ) {
GetParent()->BecomeActive( TH_UPDATEVISUALS );
}
}
/*
================
sdVehiclePart::Damage
================
*/
void sdVehiclePart::Damage( int damage, idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const trace_t* collision ) {
if ( gameLocal.isClient ) {
return;
}
if ( IsHidden() ) {
return;
}
health -= damage;
if ( health < -1 ) {
health = -1;
}
sdTransport* transport = GetParent();
if ( health <= 0 || transport->GetHealth() <= 0 ) {
Detach( true, false );
OnKilled();
transport->GetPhysics()->Activate();
}
}
/*
================
sdVehiclePart::Decay
This makes a part fall off, instead of blowing it off like Damage will.
================
*/
void sdVehiclePart::Decay( void ) {
if ( gameLocal.isClient ) {
return;
}
if ( IsHidden() ) {
return;
}
// destroy it instantly
health = -1;
sdTransport* transport = GetParent();
//HideSurfaces(); ?!? detach calls this already
Detach( true, true );
OnKilled();
transport->GetPhysics()->Activate();
}
/*
================
sdVehiclePart::~sdVehiclePart
================
*/
sdVehiclePart::~sdVehiclePart() {
delete waterEffects;
}
/*
================
sdVehiclePart::GetBounds
================
*/
void sdVehiclePart::GetBounds( idBounds& bounds ) {
if( !GetParent() || bodyId == -1 ) {
bounds = partBounds;
return;
}
bounds = GetParent()->GetPhysics()->GetBounds( bodyId );
}
/*
================
sdVehiclePart::GetWorldOrigin
================
*/
void sdVehiclePart::GetWorldOrigin( idVec3& vec ) {
if( !GetParent() || bodyId == -1 ) {
vec = GetParent()->GetPhysics()->GetOrigin();
return;
}
vec = GetParent()->GetPhysics()->GetOrigin( bodyId );
}
/*
================
sdVehiclePart::GetWorldAxis
================
*/
void sdVehiclePart::GetWorldAxis( idMat3& axis ) {
if( !GetParent() || bodyId == -1 ) {
axis = GetParent()->GetPhysics()->GetAxis();
return;
}
axis = GetParent()->GetPhysics()->GetAxis( bodyId );
}
/*
================
sdVehiclePart::Init
================
*/
void sdVehiclePart::Init( const sdDeclVehiclePart& part ) {
name = part.data.GetString( "name" );
maxHealth = health = part.data.GetInt( "health" );
brokenPart = gameLocal.declEntityDefType[ part.data.GetString( "def_brokenPart" ) ];
damageInfo.damageScale = part.data.GetFloat( "damageScale", "1.0" );
damageInfo.collisionScale = part.data.GetFloat( "collisionScale", "1.0" );
damageInfo.collisionMinSpeed = part.data.GetFloat( "collisionMinSpeed", "256.0" );
damageInfo.collisionMaxSpeed = part.data.GetFloat( "collisionMaxSpeed", "1024.0" );
noAutoHide = part.data.GetBool( "noAutoHide", "0" );
flipPower = part.data.GetFloat( "flip_power", "5" );
flipMaster = part.data.GetBool( "flip_master" );
const idKeyValue* kv = NULL;
while ( kv = part.data.MatchPrefix( "surface", kv ) ) {
AddSurface( kv->GetValue() );
}
partBounds.Clear();
if ( brokenPart ) {
renderEntity_t renderEnt;
gameEdit->ParseSpawnArgsToRenderEntity( brokenPart->dict, renderEnt );
if ( renderEnt.hModel ) {
partBounds = renderEnt.hModel->Bounds();
}
}
waterEffects = sdWaterEffects::SetupFromSpawnArgs( part.data );
if ( waterEffects ) {
waterEffects->SetMaxVelocity( 300.0f );
}
}
/*
================
sdVehiclePart::CheckWater
================
*/
void sdVehiclePart::CheckWater( const idVec3& waterBodyOrg, const idMat3& waterBodyAxis, idCollisionModel* waterBodyModel ) {
if ( waterEffects ) {
idVec3 temp;
idMat3 temp2;
GetWorldOrigin( temp );
GetWorldAxis( temp2 );
waterEffects->SetOrigin( temp );
waterEffects->SetAxis( temp2 );
waterEffects->SetVelocity( GetParent()->GetPhysics()->GetLinearVelocity() );
waterEffects->CheckWater( GetParent(), waterBodyOrg, waterBodyAxis, waterBodyModel );
}
}
/*
================
sdVehiclePart::CalcSurfaceBounds
================
*/
idBounds sdVehiclePart::CalcSurfaceBounds( jointHandle_t joint ) {
idBounds res;
//res[0] = idVec3(-20,-20,-20);
//res[1] = idVec3(20,20,20);
res.Clear();
if ( !GetParent() ) {
return res;
}
for ( int i = 0; i < surfaces.Num(); i++ ) {
idBounds b;
GetParent()->GetAnimator()->GetMeshBounds( joint, surfaces[ i ], gameLocal.time, b, true );
res.AddBounds( b );
}
return res;
}
/*
================
sdVehiclePart::Event_GetHealth
================
*/
void sdVehiclePart::Event_GetHealth( void ) {
sdProgram::ReturnFloat( health );
}
/*
================
sdVehiclePart::Event_GetOrigin
================
*/
void sdVehiclePart::Event_GetOrigin( void ) {
idVec3 temp;
GetWorldOrigin( temp );
sdProgram::ReturnVector( temp );
}
/*
================
sdVehiclePart::Event_GetAngles
================
*/
void sdVehiclePart::Event_GetAngles( void ) {
idMat3 temp;
GetWorldAxis( temp );
idAngles ang = temp.ToAngles();
sdProgram::ReturnVector( idVec3( ang[0], ang[1], ang[2] ) );
}
/*
================
sdVehiclePart::Event_GetParent
================
*/
void sdVehiclePart::Event_GetParent( void ) {
sdProgram::ReturnEntity( GetParent() );
}
/*
================
sdVehiclePart::Event_GetJoint
================
*/
void sdVehiclePart::Event_GetJoint( void ) {
if ( !GetParent() ) {
sdProgram::ReturnString("");
return;
}
if ( !GetParent()->GetAnimator() ) {
sdProgram::ReturnString("");
return;
}
sdProgram::ReturnString( GetParent()->GetAnimator()->GetJointName( GetJoint() ) );
}
/*
===============================================================================
sdVehiclePartSimple
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehiclePartSimple )
END_CLASS
/*
============
sdVehiclePart::ShouldDisplayDebugInfo
============
*/
bool sdVehiclePartSimple::ShouldDisplayDebugInfo() const {
return true;
// idPlayer* player = gameLocal.GetLocalPlayer();
// return ( player && parent == player->GetProxyEntity() );
}
/*
================
sdVehiclePartSimple::Init
================
*/
void sdVehiclePartSimple::Init( const sdDeclVehiclePart& part, sdTransport* _parent ) {
parent = _parent;
sdVehiclePart::Init( part );
joint = _parent->GetAnimator()->GetJointHandle( part.data.GetString( "joint" ) );
if ( joint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePartSimple::Init Invalid Joint Name '%s'", part.data.GetString( "joint" ) );
}
partBounds = CalcSurfaceBounds( joint );
}
/*
================
sdVehiclePartSimple::GetWorldAxis
================
*/
void sdVehiclePartSimple::GetWorldAxis( idMat3& axis ) {
parent->GetWorldAxis( joint, axis );
}
/*
================
sdVehiclePartSimple::GetWorldOrigin
================
*/
void sdVehiclePartSimple::GetWorldOrigin( idVec3& vec ) {
parent->GetWorldOrigin( joint, vec );
}
/*
================
sdVehiclePartSimple::GetWorldPhysicsAxis
================
*/
void sdVehiclePartSimple::GetWorldPhysicsAxis( idMat3& axis ) {
GetWorldAxis( axis );
// transform this to be relative to the physics. can't use the render info as physics input!
const idMat3& physicsAxis = parent->GetPhysics()->GetAxis();
const idMat3& renderAxis = parent->GetRenderEntity()->axis;
axis = physicsAxis * renderAxis.TransposeMultiply( axis );
}
/*
================
sdVehiclePartSimple::GetWorldPhysicsOrigin
================
*/
void sdVehiclePartSimple::GetWorldPhysicsOrigin( idVec3& vec ) {
GetWorldOrigin( vec );
// transform this to be relative to the physics. can't use the render info as physics input!
const idVec3& physicsOrigin = parent->GetPhysics()->GetOrigin();
const idVec3& renderOrigin = parent->GetRenderEntity()->origin;
const idMat3& physicsAxis = parent->GetPhysics()->GetAxis();
const idMat3& renderAxis = parent->GetRenderEntity()->axis;
vec = physicsAxis * renderAxis.TransposeMultiply( vec - renderOrigin ) + physicsOrigin;
}
/*
============
sdVehicleRigidBodyPart::ShouldDisplayDebugInfo
============
*/
bool sdVehicleRigidBodyPart::ShouldDisplayDebugInfo() const {
idPlayer* player = gameLocal.GetLocalPlayer();
return ( player && parent == player->GetProxyEntity() );
}
/*
===============================================================================
sdVehiclePartScripted
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePartSimple, sdVehiclePartScripted )
END_CLASS
/*
================
sdVehiclePartScripted::Init
================
*/
void sdVehiclePartScripted::Init( const sdDeclVehiclePart& part, sdTransport* _parent ) {
sdVehiclePartSimple::Init( part, _parent );
onKilled = NULL;
onPostDamage = NULL;
if ( !scriptObject ) {
const char *name = part.data.GetString( "scriptObject" );
if ( *name ) {
scriptObject = gameLocal.program->AllocScriptObject( this, name );
}
}
if ( scriptObject ) {
onKilled = scriptObject->GetFunction( "OnKilled" );
onPostDamage = scriptObject->GetFunction( "OnPostDamage" );
}
}
/*
================
sdVehiclePartScripted::OnKilled
================
*/
void sdVehiclePartScripted::OnKilled( void ) {
if ( onKilled ) {
sdScriptHelper helper;
scriptObject->CallNonBlockingScriptEvent( onKilled, helper );
}
}
/*
================
sdVehiclePartScripted::Damage
================
*/
void sdVehiclePartScripted::Damage( int damage, idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const trace_t* collision ) {
int oldHealth = health;
sdVehiclePartSimple::Damage( damage, inflictor, attacker, dir, collision );
if ( onPostDamage ) {
sdScriptHelper helper;
helper.Push( attacker ? attacker->GetScriptObject() : NULL );
helper.Push( oldHealth );
helper.Push( health );
scriptObject->CallNonBlockingScriptEvent( onPostDamage, helper );
}
}
/*
===============================================================================
sdVehicleRigidBodyPartSimple
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehicleRigidBodyPartSimple )
END_CLASS
/*
================
sdVehicleRigidBodyPartSimple::Init
================
*/
void sdVehicleRigidBodyPartSimple::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
parent = _parent;
sdVehiclePart::Init( part );
joint = _parent->GetAnimator()->GetJointHandle( part.data.GetString( "joint" ) );
if ( joint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePartSimple::Init Invalid Joint Name '%s'", part.data.GetString( "joint" ) );
}
partBounds = CalcSurfaceBounds( joint );
}
/*
================
sdVehicleRigidBodyPartSimple::GetParent
================
*/
sdTransport* sdVehicleRigidBodyPartSimple::GetParent( void ) const {
return parent;
}
/*
================
sdVehicleRigidBodyPartSimple::GetWorldOrigin
================
*/
void sdVehicleRigidBodyPartSimple::GetWorldOrigin( idVec3& vec ) {
sdTransport* transport = GetParent();
if( !transport ) {
vec.Zero();
return;
}
transport->GetWorldOrigin( joint, vec );
}
/*
================
sdVehicleRigidBodyPartSimple::GetWorldPhysicsOrigin
================
*/
void sdVehicleRigidBodyPartSimple::GetWorldPhysicsOrigin( idVec3& vec ) {
GetWorldOrigin( vec );
// transform this to be relative to the physics. can't use the render info as physics input!
const idVec3& physicsOrigin = parent->GetPhysics()->GetOrigin();
const idVec3& renderOrigin = parent->GetRenderEntity()->origin;
const idMat3& physicsAxis = parent->GetPhysics()->GetAxis();
const idMat3& renderAxis = parent->GetRenderEntity()->axis;
vec = physicsAxis * renderAxis.TransposeMultiply( vec - renderOrigin ) + physicsOrigin;
}
/*
===============================================================================
sdVehicleRigidBodyPart
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehicleRigidBodyPart )
END_CLASS
/*
================
sdVehicleRigidBodyPart::Init
================
*/
void sdVehicleRigidBodyPart::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
parent = _parent;
sdVehiclePart::Init( part );
idClipModel* cm = NULL;
const char* clipModelName = part.data.GetString( "cm_model" );
if ( *clipModelName ) {
idTraceModel trm;
if ( !gameLocal.clip.LoadTraceModel( clipModelName, trm ) ) {
gameLocal.Error( "sdVehicleRigidBodyPart::Init Could not convert '%s' to a trace model", clipModelName );
}
cm = new idClipModel( trm, false );
} else {
idTraceModel trm;
idVec3 mins = part.data.GetVector( "mins" );
idVec3 maxs = part.data.GetVector( "maxs" );
idBounds bounds( mins, maxs );
if ( bounds.GetVolume() < 0.0f ) {
gameLocal.Warning( "sdVehicleRigidBodyPart::Init Invalid mins/maxs: Volume is negative!" );
// fix the bounds so the volume isn't negative
bounds.Clear();
bounds.AddPoint( mins );
bounds.AddPoint( maxs );
}
const char* typeName = part.data.GetString( "type", "box" );
if ( !idStr::Icmp( typeName, "box" ) ) {
trm.SetupBox( bounds );
} else if ( !idStr::Icmp( typeName, "cylinder" ) ) {
trm.SetupCylinder( bounds, part.data.GetInt( "sides" ), part.data.GetFloat( "angleOffset" ), part.data.GetInt( "option" ) );
} else if ( !idStr::Icmp( typeName, "frustum" ) ) {
trm.SetupFrustum( bounds, part.data.GetFloat( "topOffset" ) );
} else {
gameLocal.Error( "sdVehicleRigidBodyPart::Init Invalid Rigid Body Part Type '%s'", typeName );
}
cm = new idClipModel( trm, false );
}
sdPhysics_RigidBodyMultiple& rigidBody = *_parent->GetRBPhysics();
int index = rigidBody.GetNumClipModels();
bodyId = index;
rigidBody.SetClipModel( cm, 1.f, bodyId );
rigidBody.SetContactFriction( bodyId, part.data.GetVector( "contactFriction" ) );
rigidBody.SetMass( part.data.GetFloat( "mass", "1" ), bodyId );
rigidBody.SetBodyOffset( bodyId, part.data.GetVector( "offset" ) );
rigidBody.SetBodyBuoyancy( bodyId, part.data.GetFloat( "buoyancy", "0.01" ) );
rigidBody.SetBodyWaterDrag( bodyId, part.data.GetFloat( "waterDrag", "0" ) );
if ( part.data.GetBool( "noCollision" ) ) {
rigidBody.SetClipMask( 0, bodyId );
rigidBody.SetContents( 0, bodyId );
} else {
rigidBody.SetClipMask( MASK_VEHICLESOLID | CONTENTS_MONSTER, bodyId );
rigidBody.SetContents( CONTENTS_PLAYERCLIP | CONTENTS_IKCLIP | CONTENTS_VEHICLECLIP | CONTENTS_FLYERHIVECLIP, bodyId );
}
joint = _parent->GetAnimator()->GetJointHandle( part.data.GetString( "joint" ) );
partBounds = CalcSurfaceBounds( joint );
}
/*
================
sdVehicleRigidBodyPart::GetParent
================
*/
sdTransport* sdVehicleRigidBodyPart::GetParent( void ) const {
return parent;
}
/*
================
sdVehicleRigidBodyPart::sdVehicleRigidBodyPart
================
*/
void sdVehicleRigidBodyPart::GetWorldOrigin( idVec3& vec ) {
parent->GetRBPhysics()->GetBodyOrigin( vec, bodyId );
}
/*
============
sdVehicleRigidBodyPartSimple::ShouldDisplayDebugInfo
============
*/
bool sdVehicleRigidBodyPartSimple::ShouldDisplayDebugInfo() const {
idPlayer* player = gameLocal.GetLocalPlayer();
return ( player && parent == player->GetProxyEntity() );
}
/*
===============================================================================
sdVehicleRigidBodyWheel
===============================================================================
*/
CLASS_DECLARATION( sdVehicleRigidBodyPart, sdVehicleRigidBodyWheel )
END_CLASS
/*
================
sdVehicleRigidBodyWheel::sdVehicleRigidBodyWheel
================
*/
sdVehicleRigidBodyWheel::sdVehicleRigidBodyWheel( void ) {
frictionAxes.Identity();
currentFriction.Zero();
wheelModel = NULL;
suspension = NULL;
wheelOffset = 0;
totalWheels = -1;
memset( &groundTrace, 0, sizeof( groundTrace ) );
wheelFractionMemory.SetNum( MAX_WHEEL_MEMORY );
for ( int i = 0; i < MAX_WHEEL_MEMORY; i++ ) {
wheelFractionMemory[ i ] = 1.0f;
}
currentMemoryFrame = 0;
currentMemoryIndex = 0;
suspensionInterface.Init( this );
}
/*
================
sdVehicleRigidBodyWheel::~sdVehicleRigidBodyWheel
================
*/
sdVehicleRigidBodyWheel::~sdVehicleRigidBodyWheel( void ) {
gameLocal.clip.DeleteClipModel( wheelModel );
delete suspension;
}
/*
================
sdVehicleRigidBodyWheel::Init
================
*/
void sdVehicleRigidBodyWheel::TrackWheelInit( const sdDeclVehiclePart& track, int index, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPartSimple::Init( track, _parent );
name = track.data.GetString( va( "wheel_joint_%i", index + 1 ) );
health = maxHealth = -1;
brokenPart = NULL;
partBounds.Clear();
joint = _parent->GetAnimator()->GetJointHandle( name.c_str() );
if ( joint == INVALID_JOINT ) {
gameLocal.Error( "sdVehicleRigidBodyWheel::TrackWheelInit Invalid Joint Name '%s'", name.c_str() );
}
partBounds = CalcSurfaceBounds( joint );
CommonInit( track );
sdVehicleSuspension_Vertical* verticalSuspension = new sdVehicleSuspension_Vertical();
suspension = verticalSuspension;
if ( verticalSuspension != NULL ) {
verticalSuspension->Init( &suspensionInterface, track.data.GetString( va( "wheel_suspension_%i", index + 1 ) ) );
}
traceIndex = track.data.GetInt( va( "wheel_trace_index_%i", index + 1 ), "-1" );
wheelFlags.partOfTrack = true;
}
/*
================
sdVehicleRigidBodyWheel::Init
================
*/
void sdVehicleRigidBodyWheel::Init( const sdDeclVehiclePart& wheel, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPartSimple::Init( wheel, _parent );
CommonInit( wheel );
const sdDeclStringMap* suspensionInfoDecl = gameLocal.declStringMapType[ wheel.data.GetString( "suspension" ) ];
if ( suspensionInfoDecl != NULL ) {
suspension = sdVehicleSuspension::GetSuspension( suspensionInfoDecl->GetDict().GetString( "type" ) );
if ( suspension != NULL ) {
suspension->Init( &suspensionInterface, suspensionInfoDecl->GetDict() );
}
}
traceIndex = wheel.data.GetInt( "trace_index", "-1" );
wheelFlags.partOfTrack = false;
}
/*
================
sdVehicleRigidBodyWheel::CommonInit
================
*/
void sdVehicleRigidBodyWheel::CommonInit( const sdDeclVehiclePart& part ) {
if ( part.data.GetBool( "turn" ) ) {
wheelFlags.hasSteering = true;
wheelFlags.inverseSteering = false;
} else if ( part.data.GetBool( "inverseturn" ) ) {
wheelFlags.hasSteering = true;
wheelFlags.inverseSteering = true;
} else {
wheelFlags.hasSteering = false;
wheelFlags.inverseSteering = false;
}
wheelFlags.noPhysics = part.data.GetBool( "noPhysics" );
wheelFlags.hasDrive = part.data.GetBool( "drive" );
wheelFlags.noRotation = part.data.GetBool( "noRotation" );
wheelFlags.slowsOnLeft = part.data.GetBool( "slowOnLeft" );
wheelFlags.slowsOnRight = part.data.GetBool( "slowOnRight" );
angle = 0.f;
steerAngle = 0.f;
idealSteerAngle = 0.f;
state.moving = false;
state.changed = true;
state.steeringChanged = false;
state.grounded = false;
state.suspensionDisabled = false;
radius = part.data.GetFloat( "radius" );
rotationspeed = 0.f;
normalFriction = part.data.GetVector( "contactFriction" );
currentFriction = normalFriction;
steerScale = part.data.GetFloat( "steerScale", "1" );
suspensionInfo.velocityScale = part.data.GetFloat( "suspensionVelocityScale", "1" );
suspensionInfo.kCompress = part.data.GetFloat( "suspensionKCompress" );
suspensionInfo.upTrace = part.data.GetFloat( "suspensionUpTrace" );
suspensionInfo.downTrace = part.data.GetFloat( "suspensionDownTrace" );
suspensionInfo.totalDist = suspensionInfo.upTrace + suspensionInfo.downTrace;
suspensionInfo.damping = part.data.GetFloat( "suspensionDamping" );
suspensionInfo.base = part.data.GetFloat( "suspensionBase" );
suspensionInfo.range = part.data.GetFloat( "suspensionRange" );
suspensionInfo.maxRestVelocity = part.data.GetFloat( "suspensionMaxRestVelocity", "5" );
suspensionInfo.aggressiveDampening = part.data.GetBool( "aggressiveDampening" );
suspensionInfo.slowScale = part.data.GetFloat( "slowScale", "0" );
suspensionInfo.slowScaleSpeed = part.data.GetFloat( "slowScaleSpeed", "400" );
suspensionInfo.hardStopScale = 1.0f / Max( 1.0f, part.data.GetFloat( "hardStopFrames", "4" ) );
suspensionInfo.alternateSuspensionModel = part.data.GetBool( "alternateSuspensionModel" );
wheelSpinForceThreshold = part.data.GetFloat( "wheelSpinForceThreshhold" );
wheelSkidVelocityThreshold = part.data.GetFloat( "wheelSkidVelocityThreshold", "150" );
state.setSteering = part.data.GetBool( "control_steering" );
brakingForce = part.data.GetFloat( "brakingForce", "500000" );
handBrakeSlipScale = part.data.GetFloat( "handBrakeSlipScale", "1" );
maxSlip = part.data.GetFloat( "maxSlip", "100000" );
wheelFlags.hasHandBrake = part.data.GetBool( "hasHandBrake" );
traction.AssureSize( gameLocal.declSurfaceTypeType.Num() );
int i;
for ( i = 0; i < gameLocal.declSurfaceTypeType.Num(); i++ ) {
traction[ i ] = part.data.GetFloat( va( "traction_%s", gameLocal.declSurfaceTypeType[ i ]->GetName() ), "1" );
}
static idVec3 rightWheelWinding[ 4 ] = {
idVec3( 1.0f, 0.f, 0.0f ),
idVec3( -1.0f, 0.f, 0.0f ),
idVec3( -1.0f, 1.f, 0.0f ),
idVec3( 1.0f, 1.f, 0.0f )
};
static idVec3 leftWheelWinding[ 4 ] = {
idVec3( 1.0f, -1.f, 0.0f ),
idVec3( -1.0f, -1.f, 0.0f ),
idVec3( -1.0f, 0.f, 0.0f ),
idVec3( 1.0f, 0.f, 0.0f )
};
parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, baseOrg, baseAxes );
baseOrgOffset = part.data.GetVector( "base_org_offset" );
if ( part.data.GetBool( "localRotation" ) ) {
rotationAxis = baseAxes[ 0 ];
} else {
rotationAxis.Set( 0.f, -1.f, 0.f );
}
wheelFlags.isLeftWheel = baseOrg[ 1 ] < 0;
wheelFlags.isFrontWheel = baseOrg[ 0 ] > 0;
idVec3* wheelWinding = IsLeftWheel() ? leftWheelWinding : rightWheelWinding;
idVec3 verts[ 4 ];
float footprint = part.data.GetFloat( "footprint" );
if ( footprint < idMath::FLT_EPSILON ) {
gameLocal.Error( "sdVehicleRigidBodyWheel::CommonInit \"footprint\" too small: %.6f in vscript: %s", footprint, parent->GetVehicleScript()->GetName() );
}
for ( i = 0; i < 4; i++ ) {
verts[ i ] = wheelWinding[ i ] * footprint;
}
idTraceModel trm;
trm.SetupPolygon( verts, 4 );
wheelModel = new idClipModel( trm, false );
idIK* ik = parent->GetIK();
if ( ik && ik->IsType( sdIK_WheeledVehicle::Type ) ) {
sdIK_WheeledVehicle* wheelIK = reinterpret_cast< sdIK_WheeledVehicle* >( ik );
wheelIK->AddWheel( *this );
}
treadId = 0;
parent->InitEffectList( dustEffects, "fx_wheeldust", numSurfaceTypesAtSpawn );
parent->InitEffectList( spinEffects, "fx_wheelspin", numSurfaceTypesAtSpawn );
parent->InitEffectList( skidEffects, "fx_skid", numSurfaceTypesAtSpawn );
stroggTread = parent->spawnArgs.GetBool( "stroggTread" );
}
/*
================
sdVehicleRigidBodyWheel::GetLinearSpeed
================
*/
float sdVehicleRigidBodyWheel::GetLinearSpeed( void ) {
idVec3 temp;
parent->GetRBPhysics()->GetPointVelocity( groundTrace.c.point, temp );
temp -= ( temp * groundTrace.c.normal ) * groundTrace.c.normal;
return temp * ( frictionAxes * parent->GetRBPhysics()->GetAxis()[ 0 ] );
}
idCVar cm_drawTraces( "cm_drawTraces", "0", CVAR_GAME | CVAR_BOOL, "draw polygon and edge normals" );
idCVar g_skipVehicleFrictionFeedback( "g_skipVehicleFrictionFeedback", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "ignore the effects of surface friction" );
idCVar g_debugVehicleFrictionFeedback( "g_debugVehicleFrictionFeedback", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about wheeled surface friction feedback" );
idCVar g_debugVehicleDriveForces( "g_debugVehicleDriveForces", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about wheeled drive forces" );
idCVar g_debugVehicleWheelForces( "g_debugVehicleWheelForces", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about wheel forces" );
idCVar g_vehicleWheelTracesPerFrame( "g_vehicleWheelTracesPerFrame", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_CHEAT, "What fraction of the wheels are updated per frame" );
struct cm_logger_t {
};
/*
================
sdVehicleRigidBodyWheel::UpdateSuspension
================
*/
void sdVehicleRigidBodyWheel::UpdateSuspension( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
if ( totalWheels == -1 ) {
idIK* ik = parent->GetIK();
if ( ik && ik->IsType( sdIK_WheeledVehicle::Type ) ) {
sdIK_WheeledVehicle* wheelIK = reinterpret_cast< sdIK_WheeledVehicle* >( ik );
totalWheels = wheelIK->GetNumWheels();
}
// auto-assign for 4 wheeled vehicles
if ( traceIndex == -1 && totalWheels == 4 ) {
if ( wheelFlags.isLeftWheel ) {
if ( wheelFlags.isFrontWheel ) {
traceIndex = 0;
} else {
traceIndex = 3;
}
}
if ( !wheelFlags.isLeftWheel ) {
if ( wheelFlags.isFrontWheel ) {
traceIndex = 2;
} else {
traceIndex = 1;
}
}
}
}
if( HasSteering() ) {
idealSteerAngle = input.GetSteerAngle();
if( HasInverseSteering() ) {
idealSteerAngle = -idealSteerAngle;
}
idealSteerAngle *= steerScale;
} else {
idealSteerAngle = 0.f;
}
if ( idealSteerAngle != steerAngle ) {
steerAngle = idealSteerAngle;
if ( state.setSteering ) {
parent->SetSteerVisualAngle( steerAngle );
}
state.steeringChanged = true;
idAngles::YawToMat3( -steerAngle, frictionAxes );
}
if ( !input.GetBraking() && !input.GetHandBraking() && HasDrive() ) {
physics.Activate();
}
if ( !parent->GetPhysics()->IsAtRest() ) {
idVec3 org = parent->GetPhysics()->GetOrigin();
idMat3 axis = parent->GetPhysics()->GetAxis();
org = org + ( ( baseOrg + baseOrgOffset ) * axis );
idVec3 start = org + ( axis[ 2 ] * suspensionInfo.upTrace );
idVec3 end = org - ( axis[ 2 ] * suspensionInfo.downTrace );
bool doTraceThisFrame = false;
if ( traceIndex != -1 && g_vehicleWheelTracesPerFrame.GetFloat() < 1.0f ) {
// find out if this wheel is to be updated this frame
assert( totalWheels != -1 );
int numPerFrame = Max( 1, ( int )( g_vehicleWheelTracesPerFrame.GetFloat() * totalWheels ) );
if ( parent->GetAORPhysicsLOD() >= 2 ) {
numPerFrame = 1;
}
const int wheelToUpdate = ( gameLocal.framenum * numPerFrame );
const int nextWheelToUpdate = wheelToUpdate + numPerFrame;
for ( int i = wheelToUpdate; i < nextWheelToUpdate; i++ ) {
if ( i % totalWheels == traceIndex ) {
doTraceThisFrame = true;
break;
}
}
} else {
doTraceThisFrame = true;
}
if ( !doTraceThisFrame ) {
// check if the previous frame is in the memory bank
int prevFrameWrap = ( gameLocal.framenum - 1 ) / MAX_WHEEL_MEMORY;
int prevFrameIndex = ( gameLocal.framenum - 1 ) % MAX_WHEEL_MEMORY;
int curFrameWrap = currentMemoryFrame / MAX_WHEEL_MEMORY;
if ( prevFrameWrap < curFrameWrap - 1 ) {
// too far in the past
doTraceThisFrame = true;
} else if ( prevFrameWrap == curFrameWrap - 1 ) {
// in the previous wrap - check that the index
// is greater than the current one
if ( prevFrameIndex <= currentMemoryIndex ) {
// too far in the past
doTraceThisFrame = true;
}
} else {
// in the current wrap - check that its before this one
if ( gameLocal.framenum - 1 > currentMemoryFrame ) {
// WTF? Future?
doTraceThisFrame = true;
}
}
}
if ( doTraceThisFrame ) {
memset( &groundTrace, 0, sizeof( groundTrace ) );
if ( parent->GetAORPhysicsLOD() == 0 ) {
physics.GetTraceCollection().Translation( CLIP_DEBUG_PARMS groundTrace, start, end, wheelModel, axis, MASK_VEHICLESOLID | CONTENTS_MONSTER );
} else {
// cheaper point trace
physics.GetTraceCollection().Translation( CLIP_DEBUG_PARMS groundTrace, start, end, NULL, mat3_identity, MASK_VEHICLESOLID | CONTENTS_MONSTER );
}
if( g_debugVehicleWheelForces.GetBool() && ShouldDisplayDebugInfo() ) {
gameRenderWorld->DebugArrow( colorGreen, start, groundTrace.endpos, 10 );
gameRenderWorld->DebugArrow( colorRed, groundTrace.endpos, end, 10 );
if ( parent->GetAORPhysicsLOD() == 0 ) {
wheelModel->Draw( groundTrace.endpos, axis );
}
}
// store the fraction in the memory bank
currentMemoryFrame = gameLocal.framenum;
currentMemoryIndex = gameLocal.framenum % MAX_WHEEL_MEMORY;
wheelFractionMemory[ currentMemoryIndex ] = groundTrace.fraction;
} else {
// get the fraction from the previous frame
int prevFrameIndex = ( gameLocal.framenum - 1 ) % MAX_WHEEL_MEMORY;
float prevFraction = wheelFractionMemory[ prevFrameIndex ];
// fake it to seem like it did a trace this frame
idVec3 newEnd = Lerp( start, end, prevFraction );
if ( prevFraction < 1.0f ) {
idVec3 vel;
physics.GetPointVelocity( newEnd, vel );
float suspensionDelta = ( vel * axis[ 2 ] )*MS2SEC( gameLocal.msec );
newEnd -= axis[ 2 ] * suspensionDelta * 0.5f;
}
// calculate the new fraction
groundTrace.fraction = ( ( newEnd - start )*axis[ 2 ] ) / ( ( end - start )*axis[ 2 ] );
groundTrace.endpos = newEnd;
// store the fraction in the memory bank
currentMemoryFrame = gameLocal.framenum;
currentMemoryIndex = gameLocal.framenum % MAX_WHEEL_MEMORY;
wheelFractionMemory[ currentMemoryIndex ] = groundTrace.fraction;
}
groundTrace.c.point = groundTrace.endpos;
groundTrace.c.selfId = -1;
wheelOffset = suspensionInfo.upTrace + radius - ( suspensionInfo.totalDist * groundTrace.fraction );
state.rested = true;
state.spinning = false;
state.skidding = false;
if ( groundTrace.fraction != 1.0f ) {
CalcForces( suspensionForce, suspensionVelocity );
if ( idMath::Fabs( suspensionVelocity ) > suspensionInfo.maxRestVelocity ) {
state.rested = false;
parent->GetPhysics()->Activate();
} else {
suspensionVelocity = 0.f;
}
}
state.grounded = groundTrace.fraction != 1.f;
if ( suspension ) {
suspension->Update();
}
} else {
state.rested = true;
}
currentFriction = normalFriction;
UpdateFriction( input );
}
/*
================
sdVehicleRigidBodyWheel::UpdateMotor
================
*/
void sdVehicleRigidBodyWheel::UpdateMotor( const sdVehicleInput& input, float inputMotorForce ) {
if ( parent->IsFrozen() ) {
state.skidding = false;
state.spinning = false;
state.moving = false;
state.rested = true;
return;
}
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
motorForce = 0.f;
motorSpeed = 0.f;
if ( !input.GetBraking() && !input.GetHandBraking() ) {
if( HasDrive() ) {
motorForce = idMath::Fabs( inputMotorForce );
motorSpeed = GetInputSpeed( input );
// adjust wheel velocity for better steering because there are no differentials between the wheels
if(( steerAngle < 0.0f && SlowsOnLeft()) ||
( steerAngle > 0.0f && SlowsOnRight() )) {
motorSpeed *= 0.5f;
}
}
}
bool braking = input.GetBraking();
bool handBraking = wheelFlags.hasHandBrake && input.GetHandBraking();
if ( braking || handBraking ) {
motorForce = brakingForce;
motorSpeed = 0.0f;
if ( !( handBraking && !braking ) ) {
float scale = ( idMath::Sqrt( 1.0f - groundTrace.c.normal.z ) )*5.0f;
motorForce *= scale + 1.5f;
}
}
if ( !parent->GetPhysics()->IsAtRest() ) {
if ( groundTrace.fraction != 1.0f ) {
if( !( braking || handBraking ) && groundTrace.c.surfaceType ) {
if( motorForce > 0.0f && ( motorForce / traction[ groundTrace.c.surfaceType->Index() ] > wheelSpinForceThreshold )) {
state.spinning = true;
}
}
UpdateSkidding();
}
}
}
/*
================
sdVehicleRigidBodyWheel::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyWheel::UpdatePrePhysics( const sdVehicleInput& input ) {
if ( wheelFlags.noPhysics || state.suspensionDisabled ) {
return;
}
UpdateSuspension( input );
UpdateMotor( input, input.GetForce() );
if ( !parent->GetPhysics()->IsAtRest() ) {
if( g_debugVehicleDriveForces.GetBool() && ShouldDisplayDebugInfo() ) {
idVec3 org = parent->GetPhysics()->GetOrigin();
idMat3 axis = parent->GetPhysics()->GetAxis();
org = org + ( ( baseOrg + baseOrgOffset ) * axis );
gameRenderWorld->DrawText( va( "motor sp: %.2f\nmotor f: %.2f\n", motorSpeed, motorForce ), org, 0.25f, colorGreen, axis, 0 );
}
}
if ( !state.skidding && treadId ) {
tireTreadManager->StopSkid( treadId );
treadId = 0;
}
}
/*
================
sdVehicleRigidBodyWheel::UpdateFriction
================
*/
void sdVehicleRigidBodyWheel::UpdateFriction( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
idVec3 wheelOrigin = groundTrace.c.point;
idMat3 worldFrictionAxes = frictionAxes * physics.GetAxis();
// vary the lateral friction with the lateral slip
idVec3 contactWRTground;
physics.GetPointVelocity( wheelOrigin, contactWRTground );
idVec3 carWRTground = physics.GetLinearVelocity();
float lateralSlip = ( contactWRTground - carWRTground ) * worldFrictionAxes[ 1 ];
idVec3 slidingFriction = normalFriction * 0.8f; // assume kinetic friction is 80% of static friction
// make it much more sensitive to slip when handbraking
if ( wheelFlags.hasHandBrake && input.GetHandBraking() ) {
lateralSlip *= handBrakeSlipScale;
slidingFriction *= 0.5f;
}
float slideFactor = ( idMath::Fabs( lateralSlip ) ) / maxSlip;
slideFactor = idMath::ClampFloat( 0.0f, 1.0f, slideFactor );
currentFriction = Lerp( normalFriction, slidingFriction, slideFactor );
}
/*
================
sdVehicleRigidBodyWheel::UpdateSkidding
================
*/
void sdVehicleRigidBodyWheel::UpdateSkidding() {
idBounds bb;
GetBounds( bb );
if ( bb.IsCleared() ) {
return;
}
//
// get info about the parent
//
idPhysics* physics = GetParent()->GetPhysics();
const idVec3& origin = physics->GetOrigin();
const idMat3& axis = physics->GetAxis();
idMat3 axisTranspose = physics->GetAxis().Transpose();
const idVec3& velocity = physics->GetLinearVelocity();
const idVec3& angVel = physics->GetAngularVelocity();
const idVec3& com = physics->GetCenterOfMass() * axis + origin;
//
// get info about self
//
idVec3 delta = ( groundTrace.c.point - com ) * axisTranspose;
idVec3 pointVelocity = velocity + angVel.Cross( delta );
float slipVelocity = idMath::Fabs( pointVelocity * axis[ 1 ] );
if ( slipVelocity > wheelSkidVelocityThreshold ) {
state.skidding = true;
if ( gameLocal.isNewFrame ) {
if ( treadId == 0 ) {
treadId = tireTreadManager->StartSkid( stroggTread );
}
if ( treadId != 0 ) {
idVec3 point;
GetWorldOrigin( point );
idMat3 wheelaxis;
GetWorldAxis( wheelaxis );
point += wheelaxis[2] * (bb[0][2] * 0.8f);
if ( !tireTreadManager->AddSkidPoint( treadId, point/*groundTrace.c.point*/, pointVelocity, groundTrace.c.normal, groundTrace.c.surfaceType ) ) {
treadId = 0;
}
}
}
// gameRenderWorld->DebugArrow( colorYellow, com, com + velocity*0.2f, 8 );
// gameRenderWorld->DebugArrow( colorRed, com, com + delta * axis, 8 );
// gameRenderWorld->DebugArrow( colorGreen, groundTrace.c.point, groundTrace.c.point + slipVelocity*axis[ 1 ]*0.2f, 8 );
} else {
if ( treadId != 0 && gameLocal.isNewFrame ) {
tireTreadManager->StopSkid( treadId );
treadId = 0;
}
}
}
/*
================
sdVehicleRigidBodyWheel::UpdatePostPhysics
================
*/
void sdVehicleRigidBodyWheel::UpdatePostPhysics( const sdVehicleInput& input ) {
if ( !wheelFlags.noRotation ) {
UpdateRotation( input );
}
if ( gameLocal.isNewFrame ) {
UpdateParticles( input );
}
}
idCVar g_skipVehicleTurnFeedback( "g_skipVehicleTurnFeedback", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "skip turn ducking effects on wheeled suspensions" );
idCVar g_skipVehicleAccelFeedback( "g_skipVehicleAccelFeedback", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "skip acceleration effects on wheeled suspensions" );
idCVar g_debugVehicleFeedback( "g_debugVehicleFeedback", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about wheeled suspension feedback" );
/*
================
sdVehicleRigidBodyWheel::CalcForces
================
*/
void sdVehicleRigidBodyWheel::CalcForces( float& maxForce, float& velocity ) {
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
idVec3 vel;
physics.GetPointVelocity( groundTrace.endpos, vel );
float compressionScale = idMath::ClampFloat( 0.0f, 1.0f, 1.0f - ( physics.GetLinearVelocity().Length() / suspensionInfo.slowScaleSpeed ) );
compressionScale = 1.0f + compressionScale*suspensionInfo.slowScale;
float springLength = groundTrace.fraction * suspensionInfo.totalDist;
float loss = suspensionInfo.totalDist - suspensionInfo.range;
springLength -= loss;
float springForce = 0.0f;
float invTimeStep = 1.0f / MS2SEC( gameLocal.msec );
float shockVelocity = vel * physics.GetAxis()[ 2 ];
// scale down the spring force allowed to be applied after reattaching wheels
float raiseUpFactor = 1.0f;
if ( reattachTime != 0 ) {
raiseUpFactor = idMath::ClampFloat( 0.0f, 1.0f, ( gameLocal.time - reattachTime ) / 1000.0f );
}
if ( springLength < 0.f && raiseUpFactor >= 1.0f ) {
// hard-stop
velocity = Min( suspensionInfo.range * -0.1f, springLength ) * ( invTimeStep * suspensionInfo.hardStopScale );
springForce = idMath::INFINITY * 0.5f;;
} else {
if ( !suspensionInfo.alternateSuspensionModel ) {
// regular
float compression = idMath::Sqrt( Max( 0.0f, ( suspensionInfo.range - springLength ) / suspensionInfo.range ) ) * suspensionInfo.range;
if ( !suspensionInfo.aggressiveDampening ) {
springForce = ( compression * compression * suspensionInfo.kCompress * compressionScale ) + suspensionInfo.base;
float s = 1.f - ( springLength / suspensionInfo.range );
s = s * s;
s = ( s * suspensionInfo.velocityScale * ( 1.0f / ( 3.0f * ( compressionScale - 1.0f ) +1.0f ) ) ) + 1.f;
float scale = s / ( float )gameLocal.msec;
velocity = -( compression - ( shockVelocity * suspensionInfo.damping * compressionScale ) ) * scale;
} else {
// the "agressive dampening" version does it differently
springForce = ( compression * compression * suspensionInfo.kCompress * compressionScale ) + suspensionInfo.base;
springForce -= shockVelocity * suspensionInfo.damping * compressionScale;
velocity = 0.0f;
}
} else {
float compression = suspensionInfo.range - springLength;
springForce = compression * suspensionInfo.kCompress - suspensionInfo.damping * shockVelocity;
// velocity needs to be the velocity this should be moving at. we can predict this, roughly
velocity = shockVelocity - MS2SEC( gameLocal.msec ) * springForce / ( parent->GetPhysics()->GetMass() / totalWheels );
velocity /= compressionScale;
springForce = springForce * compressionScale;
}
springForce *= raiseUpFactor;
}
if ( springForce < 0.0f ) {
springForce = 0.0f;
}
if( g_debugVehicleWheelForces.GetBool() && ShouldDisplayDebugInfo() ) {
idVec3 org = parent->GetPhysics()->GetOrigin();
idMat3 axis = parent->GetPhysics()->GetAxis();
org = org + ( ( baseOrg + baseOrgOffset ) * axis );
gameRenderWorld->DrawText( va( "velocity: %.2f\nmaxForce: %.2f", velocity, maxForce ), org, 0.25f, colorGreen, axis );
}
maxForce = springForce;
}
/*
================
sdVehicleRigidBodyWheel::EvaluateContacts
================
*/
int sdVehicleRigidBodyWheel::EvaluateContacts( contactInfo_t* list, contactInfoExt_t* listExt, int max ) {
if ( IsHidden() || max < 1 || state.suspensionDisabled ) {
return 0;
}
if ( state.grounded ) {
listExt[ 0 ].contactForceMax = suspensionForce;
listExt[ 0 ].contactForceVelocity = suspensionVelocity;
listExt[ 0 ].contactFriction = currentFriction;
listExt[ 0 ].frictionAxes = frictionAxes;
listExt[ 0 ].motorForce = motorForce;
if ( groundTrace.c.surfaceType ) {
listExt[ 0 ].motorForce *= traction[ groundTrace.c.surfaceType->Index() ];
}
if ( groundTrace.fraction < 1.0f ) {
// smoothly scale down the force applied, based on the slope of the surface
// so shallow slopes keep much of the force, but steep slopes rapidly lose traction
float temp = idMath::ClampFloat( 0.0f, 1.0f, groundTrace.c.normal.z );
float normalScaleDown = -0.5f*idMath::Cos( temp*temp*temp*idMath::PI ) + 0.5f;
if ( normalScaleDown < 0.00001f ) {
normalScaleDown = 0.0f;
}
listExt[ 0 ].motorForce *= normalScaleDown;
listExt[ 0 ].contactForceMax *= normalScaleDown;
}
listExt[ 0 ].motorDirection = frictionAxes[ 0 ];
listExt[ 0 ].motorSpeed = motorSpeed;
listExt[ 0 ].rested = state.rested;
list[ 0 ] = groundTrace.c;
return 1;
}
return 0;
}
/*
================
sdVehicleRigidBodyWheel::GetBaseWorldOrg
================
*/
idVec3 sdVehicleRigidBodyWheel::GetBaseWorldOrg( void ) const {
return parent->GetRenderEntity()->origin + ( baseOrg * parent->GetRenderEntity()->axis );
}
/*
================
sdVehicleRigidBodyWheel::GetInputSpeed
================
*/
float sdVehicleRigidBodyWheel::GetInputSpeed( const sdVehicleInput& input ) {
return ( IsLeftWheel() ? input.GetLeftSpeed() : input.GetRightSpeed() );
}
/*
================
sdVehicleRigidBodyWheel::UpdateRotation
================
*/
void sdVehicleRigidBodyWheel::UpdateRotation( float speed ) {
rotationspeed = speed;
angle += 360 * ( rotationspeed * MS2SEC( gameLocal.msec ) / ( 2 * idMath::PI * radius ) );
state.changed |= ( rotationspeed != 0 ) || ( state.steeringChanged );
state.steeringChanged = false;
state.moving = idMath::Fabs( speed ) > minParticleCreationSpeed;
}
/*
================
sdVehicleRigidBodyWheel::UpdateRotation
================
*/
void sdVehicleRigidBodyWheel::UpdateRotation( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
float oldangle = angle;
float s = 0.f;
if ( state.grounded ) {
if( !physics.IsAtRest() && !( input.GetHandBraking() && wheelFlags.hasHandBrake ) ) {
float vel = GetLinearSpeed();
s = vel;
if ( groundTrace.c.surfaceType ) {
s /= traction[ groundTrace.c.surfaceType->Index() ];
}
if ( fabs( s ) < 0.5f ) {
s = 0.f;
}
}
} else {
if ( !physics.InWater() ) {
float speed = GetInputSpeed( input );
if ( HasDrive() && speed ) {
s = speed;
} else {
float timeStep = MS2SEC( gameLocal.msec );
float rotationSlowingFactor;
if ( !physics.HasGroundContacts() ) {
rotationSlowingFactor = 0.2f;
} else if ( gameLocal.msec > 0 ) {
rotationSlowingFactor = 0.2f / timeStep;
} else {
rotationSlowingFactor = 0.0f;
}
s = rotationspeed - ( MS2SEC( gameLocal.msec ) * rotationspeed * rotationSlowingFactor );
if ( idMath::Fabs( s ) < 10.f ) {
s = 0.f;
}
}
}
}
UpdateRotation( s );
}
/*
================
sdVehicleRigidBodyWheel::UpdateParticles
================
*/
void sdVehicleRigidBodyWheel::UpdateParticles( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple& physics = *parent->GetRBPhysics();
int surfaceTypeIndex = -1;
if ( groundTrace.fraction < 1.0f ) {
surfaceTypeIndex = 0;
}
if ( groundTrace.c.surfaceType ) {
surfaceTypeIndex = groundTrace.c.surfaceType->Index() + 1;
}
if ( surfaceTypeIndex != -1 ) {
if ( state.grounded && state.moving ) {
renderEffect_t& renderEffect = dustEffects[ surfaceTypeIndex ].GetRenderEffect();
renderEffect.origin = groundTrace.c.point;
float vel = idMath::Fabs( rotationspeed );
renderEffect.attenuation = vel > 1000.0f ? 1.0f : 0.5f * ( 2 / Square( 1000.0f ) ) * Square( vel );
renderEffect.gravity = gameLocal.GetGravity();
dustEffects[ surfaceTypeIndex ].Start( gameLocal.time );
dustEffects[ surfaceTypeIndex ].GetNode().AddToEnd( activeEffects );
} else {
dustEffects[ surfaceTypeIndex ].Stop();
dustEffects[ surfaceTypeIndex ].GetNode().Remove();
}
if( state.grounded && state.spinning ) {
renderEffect_t& renderEffect = spinEffects[ surfaceTypeIndex ].GetRenderEffect();
renderEffect.origin = groundTrace.c.point;
renderEffect.gravity = gameLocal.GetGravity();
spinEffects[ surfaceTypeIndex ].Start( gameLocal.time );
spinEffects[ surfaceTypeIndex ].GetNode().AddToEnd( activeEffects );
} else {
spinEffects[ surfaceTypeIndex ].Stop();
spinEffects[ surfaceTypeIndex ].GetNode().Remove();
}
if( state.grounded && state.skidding ) {
renderEffect_t& renderEffect = skidEffects[ surfaceTypeIndex ].GetRenderEffect();
renderEffect.origin = groundTrace.c.point;
renderEffect.gravity = gameLocal.GetGravity();
skidEffects[ surfaceTypeIndex ].Start( gameLocal.time );
skidEffects[ surfaceTypeIndex ].GetNode().AddToEnd( activeEffects );
} else {
skidEffects[ surfaceTypeIndex ].Stop();
skidEffects[ surfaceTypeIndex ].GetNode().Remove();
}
}
sdEffect* effect = activeEffects.Next();
for( ; effect != NULL; effect = effect->GetNode().Next() ) {
effect->Update();
// stop playing any effects for surfaces we're no longer on
if ( ( surfaceTypeIndex == -1 ) || ( effect != &dustEffects[ surfaceTypeIndex ]
&& effect != &spinEffects[ surfaceTypeIndex ]
&& effect != &skidEffects[ surfaceTypeIndex ] ) ) {
effect->Stop();
}
}
}
/*
================
sdVehicleRigidBodyWheel::CreateDecayDebris
================
*/
void sdVehicleRigidBodyWheel::CreateDecayDebris( void ) {
if ( g_disableTransportDebris.GetBool() ) {
return;
}
sdTransport* transport = GetParent();
idVec3 org;
idMat3 axis;
GetWorldOrigin( org );
GetWorldAxis( axis );
// make sure we can have another part of this priority
debrisPriority_t priority = ( debrisPriority_t )brokenPart->dict.GetInt( "priority" );
if ( !CanAddDebris( priority, org ) ) {
return;
}
float velMin = brokenPart->dict.GetFloat( "decay_wheel_velocity_min", "50" );
float velMax = brokenPart->dict.GetFloat( "decay_wheel_velocity_max", "80" );
float avelMin = brokenPart->dict.GetFloat( "decay_wheel_angular_velocity_min", "30" );
float avelMax = brokenPart->dict.GetFloat( "decay_wheel_angular_velocity_max", "50" );
// get some axes of the transport
idVec3 forward = transport->GetPhysics()->GetAxis()[0];
idVec3 left = transport->GetPhysics()->GetAxis()[1];
// get the difference between this and the transport's origin
idVec3 difference = org - transport->GetPhysics()->GetOrigin();
// vary the falling-off velocity a bit
float velocity = (gameLocal.random.RandomFloat() * (velMax - velMin)) + velMin;
idVec3 vel = left * velocity;
// make an angular velocity about the forwards vector that will cause the wheels to topple over
float angVelocity = (gameLocal.random.RandomFloat() * (avelMax - avelMin)) + avelMin;
idVec3 aVel = forward * angVelocity;
// use the dot product to determine what direction its in
if (difference * left < 0.0f) {
vel *= -1.f;
aVel *= -1.f;
}
vel += transport->GetPhysics()->GetLinearVelocity();
aVel += transport->GetPhysics()->GetAngularVelocity();
rvClientMoveable* cent = gameLocal.SpawnClientMoveable( brokenPart->GetName(), 5000, org, axis, vel, aVel, 1 );
if ( cent != NULL ) {
cent->GetPhysics()->SetContents( 0 );
cent->GetPhysics()->SetClipMask( CONTENTS_SOLID | CONTENTS_BODY );
}
}
/*
================
sdVehicleRigidBodyWheel::CheckWater
================
*/
void sdVehicleRigidBodyWheel::CheckWater( const idVec3& waterBodyOrg, const idMat3& waterBodyAxis, idCollisionModel* waterBodyModel ) {
if ( waterEffects ) {
idVec3 mountOrg;
idMat3 mountAxis;
parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, mountOrg, mountAxis );
waterEffects->SetOrigin( mountOrg * parent->GetRenderEntity()->axis + parent->GetRenderEntity()->origin );
waterEffects->SetAxis( parent->GetRenderEntity()->axis );
waterEffects->SetMaxVelocity( 200.0f );
waterEffects->SetVelocity( idVec3( idMath::Abs( rotationspeed ), 0.0f, 0.0f ) );
waterEffects->CheckWater( parent, waterBodyOrg, waterBodyAxis, waterBodyModel );
}
}
/*
================
sdVehicleRigidBodyWheel::UpdateSuspensionIK
================
*/
bool sdVehicleRigidBodyWheel::UpdateSuspensionIK( void ) {
if ( suspension != NULL ) {
return suspension->UpdateIKJoints( parent->GetAnimator() );
}
return false;
}
/*
================
sdVehicleRigidBodyWheel::ClearSuspensionIK
================
*/
void sdVehicleRigidBodyWheel::ClearSuspensionIK( void ) {
if ( suspension != NULL ) {
suspension->ClearIKJoints( parent->GetAnimator() );
}
}
/*
===============================================================================
sdVehicleTrack
===============================================================================
*/
CLASS_DECLARATION( sdVehicleDriveObject, sdVehicleTrack )
END_CLASS
/*
================
sdVehicleTrack::~sdVehicleTrack
================
*/
sdVehicleTrack::~sdVehicleTrack( void ) {
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
delete wheels[ i ];
}
}
/*
================
sdVehicleTrack::Init
================
*/
void sdVehicleTrack::Init( const sdDeclVehiclePart& track, sdTransport_RB* _parent ) {
spawnPart = &track;
parent = _parent;
joint = parent->GetAnimator()->GetJointHandle( track.data.GetString( "joint" ) );
direction = track.data.GetVector( "direction" );
shaderParmIndex = track.data.GetInt( "shaderParmIndex" );
name = track.data.GetString( "name" );
idVec3 origin;
parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, origin );
leftTrack = origin[ 1 ] > 0;
parent->GetRenderEntity()->shaderParms[ shaderParmIndex ] = 0;
}
/*
================
sdVehicleTrack::GetParent
================
*/
sdTransport* sdVehicleTrack::GetParent( void ) const {
return parent;
}
/*
================
sdVehicleTrack::GetInputSpeed
================
*/
float sdVehicleTrack::GetInputSpeed( const sdVehicleInput& input ) const {
return ( IsLeftTrack() ? input.GetLeftSpeed() : input.GetRightSpeed() );
}
/*
================
sdVehicleTrack::UpdatePrePhysics
================
*/
void sdVehicleTrack::UpdatePrePhysics( const sdVehicleInput& input ) {
int numOnGround = 0;
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
wheels[ i ]->UpdateSuspension( input );
if ( wheels[ i ]->IsGrounded() ) {
numOnGround++;
}
}
float inputMotorForce = input.GetForce();
float maxInputMotorForce = inputMotorForce * 2.0f;
int idealNumOnGround = wheels.Num() - 2;
if ( numOnGround > 0 && numOnGround < idealNumOnGround ) {
// compensate for having some wheels off the ground
float fullForce = inputMotorForce * idealNumOnGround;
inputMotorForce = fullForce / numOnGround;
if ( inputMotorForce > maxInputMotorForce ) {
inputMotorForce = maxInputMotorForce;
}
}
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
wheels[ i ]->UpdateMotor( input, inputMotorForce );
}
}
/*
================
sdVehicleTrack::UpdatePostPhysics
================
*/
void sdVehicleTrack::UpdatePostPhysics( const sdVehicleInput& input ) {
int i;
for ( i = 1; i < wheels.Num() - 1; i++ ) {
wheels[ i ]->UpdatePostPhysics( input );
}
bool grounded = false;
float speed;
for ( i = 0; i < wheels.Num(); i++ ) {
if ( wheels[ i ]->IsGrounded() ) {
grounded = true;
break;
}
}
if ( grounded ) {
idVec3 pos;
parent->GetWorldOrigin( joint, pos );
idVec3 velocity;
speed = parent->GetRBPhysics()->GetPointVelocity( pos, velocity ) * ( direction * parent->GetPhysics()->GetAxis() );
} else {
speed = GetInputSpeed( input );
}
if ( idMath::Fabs( speed ) < 0.5f ) {
speed = 0.f;
}
parent->GetRenderEntity()->shaderParms[ shaderParmIndex ] += speed;
for ( i = 0; i < wheels.Num(); i++ ) {
wheels[ i ]->UpdateRotation( speed );
}
}
/*
================
sdVehicleTrack::EvaluateContacts
================
*/
int sdVehicleTrack::EvaluateContacts( contactInfo_t* list, contactInfoExt_t* listExt, int max ) {
int num = 0;
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
num += wheels[ i ]->EvaluateContacts( list + num, listExt + num, max - num );
}
return num;
}
/*
================
sdVehicleTrack::CheckWater
================
*/
void sdVehicleTrack::CheckWater( const idVec3& waterBodyOrg, const idMat3& waterBodyAxis, idCollisionModel* waterBodyModel ) {
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
wheels[ i ]->CheckWater( waterBodyOrg, waterBodyAxis, waterBodyModel );
}
}
/*
================
sdVehicleTrack::GetSurfaceType
================
*/
const sdDeclSurfaceType* sdVehicleTrack::GetSurfaceType( void ) const {
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
const sdDeclSurfaceType* surface = wheels[ i ]->GetSurfaceType();
if ( surface != NULL ) {
return surface;
}
}
return NULL;
}
/*
================
sdVehicleTrack::PostInit
================
*/
void sdVehicleTrack::PostInit( void ) {
sdVehicleDriveObject::PostInit();
int numWheels = spawnPart->data.GetInt( "num_true_wheels" ) + 2;
if ( numWheels > TRACK_MAX_WHEELS ) {
gameLocal.Error( "sdVehicleTrack::PostInit - number of wheels exceeds TRACK_MAX_WHEELS" );
}
wheels.SetNum( numWheels );
// get the start wheel
sdVehicleDriveObject* object = parent->GetDriveObject( spawnPart->data.GetString( "start_wheel" ) );
if ( object == NULL ) {
gameLocal.Error( "sdVehicleTrack::PostInit - no start_wheel" );
}
wheels[ 0 ] = reinterpret_cast< sdVehicleRigidBodyWheel* >( object );
if ( wheels[ 0 ] == NULL ) {
gameLocal.Error( "sdVehicleTrack::PostInit - start_wheel is not a sdVehicleRigidBodyWheel" );
}
// get the end wheel
object = parent->GetDriveObject( spawnPart->data.GetString( "end_wheel" ) );
if ( object == NULL ) {
gameLocal.Error( "sdVehicleTrack::PostInit - no end_wheel" );
}
wheels[ numWheels - 1 ] = reinterpret_cast< sdVehicleRigidBodyWheel* >( object );
if ( wheels[ numWheels - 1 ] == NULL ) {
gameLocal.Error( "sdVehicleTrack::PostInit - end_wheel is not a sdVehicleRigidBodyWheel" );
}
// create the other wheels
for ( int i = 1; i < numWheels - 1; i++ ) {
sdVehicleRigidBodyWheel* part = new sdVehicleRigidBodyWheel;
part->SetIndex( -1 );
part->TrackWheelInit( *spawnPart, i, parent );
wheels[ i ] = part;
}
for ( int i = 1; i < numWheels - 1; i++ ) {
wheels[ i ]->PostInit();
}
}
/*
================
sdVehicleTrack::UpdateSuspensionIK
================
*/
bool sdVehicleTrack::UpdateSuspensionIK( void ) {
bool changed = false;
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
changed |= wheels[ i ]->UpdateSuspensionIK();
}
return changed;
}
/*
================
sdVehicleTrack::ClearSuspensionIK
================
*/
void sdVehicleTrack::ClearSuspensionIK( void ) {
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
wheels[ i ]->ClearSuspensionIK();
}
}
/*
================
sdVehicleTrack::IsGrounded
================
*/
bool sdVehicleTrack::IsGrounded( void ) const {
int numGrounded = 0;
for ( int i = 1; i < wheels.Num() - 1; i++ ) {
if ( wheels[ i ]->IsGrounded() ) {
numGrounded++;
}
}
return numGrounded >= 1;
}
/*
===============================================================================
sdVehicleThruster
===============================================================================
*/
const idEventDef EV_Thruster_SetThrust( "setThrust", '\0', DOC_TEXT( "Controls the thrust multiplier used by this thruster." ), 1, NULL, "f", "scale", "Scale factor to set." );
CLASS_DECLARATION( sdVehicleDriveObject, sdVehicleThruster )
EVENT( EV_Thruster_SetThrust, sdVehicleThruster::Event_SetThrust )
END_CLASS
/*
================
sdVehicleThruster::sdVehicleThruster
================
*/
void sdVehicleThruster::Init( const sdDeclVehiclePart& thruster, sdTransport_RB* _parent ) {
parent = _parent;
direction = thruster.data.GetVector( "direction" );
fixedDirection = thruster.data.GetVector( "direction_fixed" );
origin = thruster.data.GetVector( "origin" );
reverseScale = thruster.data.GetFloat( "reverse_scale", "1" );
float force = thruster.data.GetFloat( "force" );
direction *= force;
fixedDirection *= force;
name = thruster.data.GetString( "name" );
needWater = thruster.data.GetBool( "need_water" );
inWater = false;
thrustScale = 0.f;
}
/*
================
sdVehicleThruster::GetParent
================
*/
sdTransport* sdVehicleThruster::GetParent( void ) const {
return parent;
}
/*
================
sdVehicleThruster::CalcPos
================
*/
void sdVehicleThruster::CalcPos( idVec3& pos ) {
pos = parent->GetPhysics()->GetOrigin() + ( origin * parent->GetPhysics()->GetAxis() );
}
/*
================
sdVehicleThruster::SetThrust
================
*/
void sdVehicleThruster::SetThrust( float thrust ) {
thrustScale = thrust;
}
/*
================
sdVehicleThruster::Event_SetThrust
================
*/
void sdVehicleThruster::Event_SetThrust( float thrust ) {
SetThrust( thrust );
}
/*
================
sdVehicleThruster::UpdatePrePhysics
================
*/
void sdVehicleThruster::UpdatePrePhysics( const sdVehicleInput& input ) {
bool reallyInWater = inWater || parent->GetRBPhysics()->InWater();
if ( needWater ) {
if ( !reallyInWater ) {
return;
}
} else {
if ( reallyInWater ) {
return;
}
}
if ( thrustScale != 0.f ) {
float height = parent->GetPhysics()->GetOrigin()[ 2 ];
float forceScale = 1.0f;
if ( height > gameLocal.flightCeilingLower ) {
if ( height > gameLocal.flightCeilingUpper ) {
forceScale = 0.f;
} else {
forceScale = ( 1.f - ( height - gameLocal.flightCeilingLower ) / ( gameLocal.flightCeilingUpper - gameLocal.flightCeilingLower ) );
}
}
if ( thrustScale < 0.f ) {
thrustScale *= reverseScale;
}
idVec3 pos;
CalcPos( pos );
idVec3 dir = parent->GetPhysics()->GetAxis() * ( ( direction * thrustScale ) + ( fixedDirection * idMath::Fabs( thrustScale ) ) );
parent->GetPhysics()->AddForce( 0, pos, dir * forceScale );
}
}
/*
================
sdVehicleThruster::CheckWater
================
*/
void sdVehicleThruster::CheckWater( const idVec3& waterBodyOrg, const idMat3& waterBodyAxis, idCollisionModel* waterBodyModel ) {
if ( !needWater ) {
return;
}
idVec3 pos;
CalcPos( pos );
pos -= waterBodyOrg;
pos *= waterBodyAxis.Transpose();
inWater = waterBodyModel->GetBounds().ContainsPoint( pos );
}
/*
===============================================================================
sdVehicleAirBrake
===============================================================================
*/
CLASS_DECLARATION( sdVehicleDriveObject, sdVehicleAirBrake )
END_CLASS
/*
================
sdVehicleAirBrake::sdVehicleThruster
================
*/
void sdVehicleAirBrake::Init( const sdDeclVehiclePart& airBrake, sdTransport_RB* _parent ) {
parent = _parent;
enabled = false;
factor = airBrake.data.GetFloat( "factor" );
maxSpeed = airBrake.data.GetFloat( "max_speed" );
name = airBrake.data.GetString( "name" );
}
/*
================
sdVehicleAirBrake::UpdatePrePhysics
================
*/
void sdVehicleAirBrake::UpdatePrePhysics( const sdVehicleInput& input ) {
if ( !enabled ) {
return;
}
const idMat3& ownerAxis = parent->GetPhysics()->GetAxis();
idVec3 forward = ownerAxis[ 0 ];
forward.z = 0.f;
float speed = parent->GetPhysics()->GetLinearVelocity() * forward;
if ( speed > 0.f ) {
idVec3 vel = speed * forward;
idVec3 impulse = ( -vel * factor );
impulse.Truncate( maxSpeed );
impulse *= parent->GetPhysics()->GetMass();
idVec3 com = parent->GetPhysics()->GetOrigin() + ( parent->GetPhysics()->GetCenterOfMass() * ownerAxis );
parent->GetPhysics()->ApplyImpulse( 0, com, impulse );
}
}
/*
===============================================================================
sdVehicleRigidBodyRotor
===============================================================================
*/
CLASS_DECLARATION( sdVehicleRigidBodyPartSimple, sdVehicleRigidBodyRotor )
END_CLASS
/*
================
sdVehicleRigidBodyRotor::sdVehicleRigidBodyRotor
================
*/
sdVehicleRigidBodyRotor::sdVehicleRigidBodyRotor( void ) {
}
/*
================
sdVehicleRigidBodyRotor::~sdVehicleRigidBodyRotor
================
*/
sdVehicleRigidBodyRotor::~sdVehicleRigidBodyRotor( void ) {
}
/*
================
sdVehicleRigidBodyRotor::Init
================
*/
void sdVehicleRigidBodyRotor::Init( const sdDeclVehiclePart& rotor, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPartSimple::Init( rotor, _parent );
liftCoefficient = rotor.data.GetFloat( "lift" );
const char* typeName = rotor.data.GetString( "rotortype", "main" );
if ( !idStr::Icmp( typeName, "main" ) ) {
type = RT_MAIN;
} else if ( !idStr::Icmp( typeName, "tail" ) ) {
type = RT_TAIL;
} else {
gameLocal.Error( "sdVehicleRigidBodyRotor::Init Invalid Rotor Type '%s'", typeName );
}
maxPitchDeflect = rotor.data.GetFloat( "maxPitchDeflect" );
maxYawDeflect = rotor.data.GetFloat( "maxYawDeflect" );
advanced.cyclicBankRate = rotor.data.GetFloat( "cyclicBankRate" ) * 0.033f;
advanced.cyclicPitchRate = rotor.data.GetFloat( "cyclicPitchRate" ) * 0.033f;
oldPitch = 0.f;
oldYaw = 0.f;
int count = rotor.data.GetInt( "num_blades" );
for ( int i = 0; i < count; i++ ) {
rotorJoint_t& j = animJoints.Alloc();
const char* bladeJointName = rotor.data.GetString( va( "blade%i_joint", i + 1 ) );
j.joint = _parent->GetAnimator()->GetJointHandle( bladeJointName );
if ( j.joint == INVALID_JOINT ) {
gameLocal.Warning( "sdVehicleRigidBodyRotor::Init Invalid Joint '%s'", bladeJointName );
j.jointAxes.Identity();
} else {
_parent->GetAnimator()->GetJointTransform( j.joint, gameLocal.time, j.jointAxes );
}
j.speedScale = rotor.data.GetFloat( va( "blade%i_speedScale", i + 1 ) );
j.isYaw = rotor.data.GetInt( va("blade%i_yaw", i+1 ) ) != 0;
j.angle = 0.f;
}
speed = 0;
sideScale = rotor.data.GetFloat( "force_side_scale", "1" );
zOffset = rotor.data.GetFloat( "z_offset", "0" );
}
/*
================
sdVehicleRigidBodyRotor::UpdatePrePhysics_Main
================
*/
void sdVehicleRigidBodyRotor::UpdatePrePhysics_Main( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple* physics = parent->GetRBPhysics();
const idMat3& bodyaxis = physics->GetAxis();
idVec3 bodyorg = physics->GetOrigin() + ( physics->GetMainCenterOfMass() * bodyaxis ); // + physics->GetBodyOffset( bodyId );
bool alive = parent->GetHealth() > 0;
idVec3 rotorAxis = bodyaxis[ 2 ];
bool deathThroes = parent->InDeathThroes();
bool careening = parent->IsCareening() && !deathThroes;
const idVec3& angVelocity = physics->GetAngularVelocity();
const idAngles bodyangles = bodyaxis.ToAngles();
bool drowned = physics->InWater() > 0.5f;
bool simpleControls = input.GetPlayer() != NULL && !input.GetPlayer()->GetUserInfo().advancedFlightControls;
idMat3 rotateAxes;
idAngles::YawToMat3( -( bodyangles.yaw ), rotateAxes );
rotorAxis *= rotateAxes;
Swap( rotorAxis[ 0 ], rotorAxis[ 2 ] );
idAngles angles = rotorAxis.ToAngles();
angles.pitch = idMath::AngleNormalize180( angles.pitch );
if ( angles.pitch < 0.f ) {
angles.pitch += maxPitchDeflect;
if ( angles.pitch > 0.f ) {
angles.pitch = 0.f;
}
} else {
angles.pitch -= maxPitchDeflect;
if ( angles.pitch < 0.f ) {
angles.pitch = 0.f;
}
}
angles.yaw = idMath::AngleNormalize180( angles.yaw );
if ( angles.yaw < 0.f ) {
angles.yaw += maxYawDeflect;
if ( angles.yaw > 0.f ) {
angles.yaw = 0.f;
}
} else {
angles.yaw -= maxYawDeflect;
if ( angles.yaw < 0.f ) {
angles.yaw = 0.f;
}
}
rotorAxis = angles.ToForward();
Swap( rotorAxis[ 0 ], rotorAxis[ 2 ] );
rotorAxis *= rotateAxes.Transpose();
rotorAxis[ 0 ] *= sideScale;
rotorAxis[ 0 ] = idMath::ClampFloat( -1.f, 1.f, rotorAxis[ 0 ] );
rotorAxis[ 1 ] *= sideScale;
rotorAxis[ 1 ] = idMath::ClampFloat( -1.f, 1.f, rotorAxis[ 1 ] );
// gameRenderWorld->DebugLine( colorYellow, worldOrg, worldOrg + ( rotorAxis * 32 ) );
const sdVehicleControlBase* control = parent->GetVehicleControl();
bool deadZone = ( angles.pitch == 0 ) && ( angles.yaw == 0 ) && ( !control || physics->HasGroundContacts() );
float deadZoneFraction = 1.0f - ( control != NULL ? control->GetDeadZoneFraction() : 0.0f );
deadZoneFraction = idMath::ClampFloat( 0.0f, 1.0f, deadZoneFraction );
deadZoneFraction = idMath::Sqrt( deadZoneFraction );
if ( alive ) {
float inputRoll = 0.0f;
float inputPitch = 0.0f;
if ( !deadZone ) {
if ( input.GetPlayer() && !input.GetUserCmd().buttons.btn.tophat ) {
inputRoll = input.GetRoll();
inputPitch = input.GetPitch();
}
}
inputRoll = idMath::ClampFloat( -2.f, 2.f, inputRoll );
inputPitch = idMath::ClampFloat( -2.f, 2.f, inputPitch );
advanced.cyclicBank = ( inputRoll / 180.f ) * advanced.cyclicBankRate;
advanced.cyclicPitch = ( inputPitch / 180.f ) * advanced.cyclicPitchRate;
if ( deathThroes ) {
advanced.cyclicPitch = 45.0f;
}
if ( control && careening ) {
advanced.cyclicBank = control->GetCareeningRollAmount();
advanced.cyclicPitch = control->GetCareeningPitchAmount();
}
bodyorg += advanced.cyclicPitch * bodyaxis[ 0 ];
bodyorg += advanced.cyclicBank * bodyaxis[ 1 ];
}
float frac;
if ( control ) {
int start = control->GetLandingChangeTime();
int length = control->GetLandingChangeEndTime() - start;
frac = length ? idMath::ClampFloat( 0.f, 1.f, ( gameLocal.time - start ) / static_cast< float >( length ) ) : 1.f;
frac = Square( frac );
} else {
frac = 1.f;
}
if ( control && careening ) {
frac = control->GetCareeningLiftScale();
}
if ( !control || control->IsLanding() && !( careening && !deathThroes ) ) {
speed = GetTopGoalSpeed() * ( 1.f - frac );
} else {
speed = GetTopGoalSpeed() * frac;
}
float lift = 1.f;
const float liftSpeedFrac = 0.90f;
float speedFrac = speed / GetTopGoalSpeed();
if ( speedFrac > liftSpeedFrac ) {
lift += input.GetCollective();
if ( control && careening ) {
lift += control->GetCareeningCollectiveAmount();
}
lift *= speed * liftCoefficient;
float height = physics->GetOrigin()[ 2 ];
if ( height > gameLocal.flightCeilingLower ) {
if ( height > gameLocal.flightCeilingUpper ) {
lift = 0.f;
} else {
lift *= ( 1.f - ( height - gameLocal.flightCeilingLower ) / ( gameLocal.flightCeilingUpper - gameLocal.flightCeilingLower ) );
}
}
if ( drowned ) {
lift = 0.0f;
}
idVec3 force = rotorAxis * lift;
physics->AddForce( bodyId, bodyorg, force );
parent->GetRenderEntity()->shaderParms[ SHADERPARM_ALPHA ] = ( speedFrac - liftSpeedFrac ) / ( 1.f - liftSpeedFrac );
} else {
parent->GetRenderEntity()->shaderParms[ SHADERPARM_ALPHA ] = 0.0f;
}
if ( drowned ) {
// try to resist all movement
const idVec3& linearVelocity = physics->GetLinearVelocity();
idVec3 stoppingAcceleration = -0.05f * linearVelocity / MS2SEC( gameLocal.msec );
physics->AddForce( stoppingAcceleration * physics->GetMass( -1 ) );
const idVec3& angularVelocity = physics->GetAngularVelocity();
idVec3 stoppingAlpha = -0.05f * angularVelocity / MS2SEC( gameLocal.msec );
physics->AddTorque( stoppingAlpha * physics->GetInertiaTensor( -1 ) );
}
}
const float goalSpeedTail = 1000.f;
/*
================
sdVehicleRigidBodyRotor::UpdatePrePhysics_Tail
================
*/
void sdVehicleRigidBodyRotor::UpdatePrePhysics_Tail( const sdVehicleInput& input ) {
sdPhysics_RigidBodyMultiple* physics = parent->GetRBPhysics();
if ( physics->InWater() > 0.5f ) {
return;
}
const idMat3& bodyaxis = physics->GetAxis();
idVec3 bodyorg;
idVec3 rotorAxis = bodyaxis[ 1 ];
const idVec3 comWorld = physics->GetOrigin() + ( physics->GetCenterOfMass() * bodyaxis );
GetWorldPhysicsOrigin( bodyorg );
bodyorg += bodyaxis[ 2 ] * zOffset;
bool simpleControls = input.GetPlayer() != NULL && !input.GetPlayer()->GetUserInfo().advancedFlightControls;
if ( !simpleControls ) {
// advanced controls fly the vehicle in local space
float arm = ( bodyorg - comWorld ).Length();
rotorAxis.Set( 0.0f, 1.0f, 0.0f );
bodyorg.Set( -arm, 0.0f, 0.0f );
}
const sdVehicleControlBase* control = parent->GetVehicleControl();
float frac;
if ( control ) {
int start = control->GetLandingChangeTime();
int length = control->GetLandingChangeEndTime() - start;
frac = length ? idMath::ClampFloat( 0.f, 1.f, ( gameLocal.time - start ) / static_cast< float >( length ) ) : 1.f;
frac = Square( frac );
} else {
frac = 1.f;
}
if ( !control || control->IsLanding() ) {
speed = goalSpeedTail * ( 1.f - frac );
} else {
speed = goalSpeedTail * frac;
}
bool deathThroes = parent->InDeathThroes();
bool careening = parent->IsCareening() && !deathThroes;
if ( deathThroes || careening ) {
frac = 1.0f;
speed = goalSpeedTail;
}
if ( input.GetPlayer() || ( ( deathThroes || careening ) && !physics->HasGroundContacts() ) ) {
float lift = -0.5f * input.GetYaw();
if ( deathThroes ) {
lift -= 1.0f;
} else if ( control && careening ) {
lift = control->GetCareeningYawAmount();
}
if( lift ) {
lift *= speed / goalSpeedTail;
idVec3 force = rotorAxis * lift * liftCoefficient;
if ( !simpleControls ) {
// use a torque to turn
// without adverse sideways movement
float torqueMag = force.y * bodyorg.x;
const idMat3& itt = physics->GetInertiaTensor();
// find the moment in the z axis
float zMoment = idVec3( 0.0f, 0.0f, 1.0f ) * (itt * idVec3( 0.0f, 0.0f, 1.0f ));
// calculate the torque to do a clean rotation about the vehicle's z axis
idVec3 alpha( 0.0f, 0.0f, torqueMag / zMoment );
idVec3 cleanTorque = itt * alpha;
physics->AddTorque( ( cleanTorque ) * bodyaxis );
} else {
// calculate the effect the force WOULD have if we applied it right now
idVec3 torque = ( bodyorg - comWorld ).Cross( force );
const idMat3 worldIT = bodyaxis.Transpose() * physics->GetInertiaTensor() * bodyaxis;
const idMat3 worldInvIT = worldIT.Inverse();
idVec3 alpha = worldInvIT * torque;
// find the alpha with only yaw (wrt world)
float desiredAlphaMagnitude = alpha.LengthFast();
if ( alpha.z < 0.0f ) {
desiredAlphaMagnitude = -desiredAlphaMagnitude;
}
alpha.Set( 0.0f, 0.0f, desiredAlphaMagnitude );
// calculate the torque needed
torque = worldIT * alpha;
// calculate the effect this will have
idVec3 torqueAlpha = worldInvIT * torque;
physics->AddTorque( torque );
}
}
}
}
/*
================
sdVehicleRigidBodyRotor::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyRotor::UpdatePrePhysics( const sdVehicleInput& input ) {
switch( type ) {
case RT_MAIN:
UpdatePrePhysics_Main( input );
break;
case RT_TAIL:
UpdatePrePhysics_Tail( input );
break;
}
}
/*
================
sdVehicleRigidBodyRotor::UpdatePostPhysics_Main
================
*/
void sdVehicleRigidBodyRotor::UpdatePostPhysics_Main( const sdVehicleInput& input ) {
if ( speed > 0.5f ) {
int i;
for ( i = 0; i < animJoints.Num(); i++ ) {
rotorJoint_t& joint = animJoints[ i ];
joint.angle += speed * MS2SEC( gameLocal.msec ) * joint.speedScale;
idMat3 rotation;
idAngles::YawToMat3( joint.angle, rotation );
parent->GetAnimator()->SetJointAxis( joint.joint, JOINTMOD_WORLD_OVERRIDE, joint.jointAxes * rotation );
}
}
}
/*
================
sdVehicleRigidBodyRotor::UpdatePostPhysics_Tail
================
*/
void sdVehicleRigidBodyRotor::UpdatePostPhysics_Tail( const sdVehicleInput& input ) {
if( speed > 0.5f ) {
int i;
for ( i = 0; i < animJoints.Num(); i++ ) {
rotorJoint_t& joint = animJoints[ i ];
joint.angle += speed * MS2SEC( gameLocal.msec ) * joint.speedScale;
idMat3 rotation;
if ( joint.isYaw ) {
idAngles::YawToMat3( joint.angle, rotation );
} else {
idAngles::PitchToMat3( joint.angle, rotation );
}
parent->GetAnimator()->SetJointAxis( joint.joint, JOINTMOD_WORLD_OVERRIDE, joint.jointAxes * rotation );
}
}
}
/*
================
sdVehicleRigidBodyRotor::UpdatePostPhysics
================
*/
void sdVehicleRigidBodyRotor::UpdatePostPhysics( const sdVehicleInput& input ) {
switch( type ) {
case RT_MAIN:
UpdatePostPhysics_Main( input );
break;
case RT_TAIL:
UpdatePostPhysics_Tail( input );
break;
}
}
/*
================
sdVehicleRigidBodyRotor::GetTopGoalSpeed
================
*/
float sdVehicleRigidBodyRotor::GetTopGoalSpeed( void ) const {
sdPhysics_RigidBodyMultiple* physics = parent->GetRBPhysics();
return ( physics->GetMainMass() * -physics->GetGravity()[ 2 ] ) / liftCoefficient;
}
/*
================
sdVehicleRigidBodyRotor::ResetCollective
================
*/
void sdVehicleRigidBodyRotor::ResetCollective( void ) {
advanced.collective = 0.f;
}
/*
===============================================================================
sdVehicleRigidBodyHoverPad
===============================================================================
*/
CLASS_DECLARATION( sdVehicleRigidBodyPartSimple, sdVehicleRigidBodyHoverPad )
END_CLASS
/*
================
sdVehicleRigidBodyHoverPad::sdVehicleRigidBodyHoverPad
================
*/
sdVehicleRigidBodyHoverPad::sdVehicleRigidBodyHoverPad( void ) {
}
/*
================
sdVehicleRigidBodyHoverPad::~sdVehicleRigidBodyHoverPad
================
*/
sdVehicleRigidBodyHoverPad::~sdVehicleRigidBodyHoverPad( void ) {
}
/*
================
sdVehicleRigidBodyHoverPad::Init
================
*/
void sdVehicleRigidBodyHoverPad::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPartSimple::Init( part, _parent );
traceDir = part.data.GetVector( "direction", "0 0 -1" );
traceDir.Normalize();
minAngles = part.data.GetAngles( "min_angles", "-10 -10 -10" );
maxAngles = part.data.GetAngles( "max_angles", "10 10 10" );
maxTraceLength = part.data.GetFloat( "distance", "64" );
shaderParmIndex = part.data.GetInt( "shaderParmIndex", "0" );
adaptSpeed = part.data.GetFloat( "adaption_speed", "0.005" );
_parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, baseOrg, baseAxes );
idMat3 ident; ident.Identity();
currentAxes = ident.ToQuat();
// Setup the lighting effect
renderEffect_t &effect = engineEffect.GetRenderEffect();
effect.declEffect = gameLocal.FindEffect( _parent->spawnArgs.GetString( "fx_hoverpad" ) );
effect.axis = mat3_identity;
effect.attenuation = 1.f;
effect.hasEndOrigin = true;
effect.loop = false;
effect.shaderParms[SHADERPARM_RED] = 1.0f;
effect.shaderParms[SHADERPARM_GREEN] = 1.0f;
effect.shaderParms[SHADERPARM_BLUE] = 1.0f;
effect.shaderParms[SHADERPARM_ALPHA] = 1.0f;
effect.shaderParms[SHADERPARM_BRIGHTNESS] = 1.0f;
nextBeamTime = gameLocal.time + 2000 + gameLocal.random.RandomInt( 1000 );
beamTargetInfo = gameLocal.declTargetInfoType[ _parent->spawnArgs.GetString( "ti_lightning" ) ];
lastVelocity.Zero();
}
idCVar g_debugVehicleHoverPads( "g_debugVehicleHoverPads", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about hoverpads" );
void sdVehicleRigidBodyHoverPad::UpdatePostPhysics( const sdVehicleInput& input ) {
if ( !input.GetPlayer() || parent->GetPhysics()->GetAxis()[ 2 ].z < 0.f ) {
return;
}
if ( !gameLocal.DoClientSideStuff() ) {
return;
}
idMat3 axis;
idVec3 origin;
GetWorldAxis( axis );
GetWorldOrigin( origin );
idMat3 ownerAxis = parent->GetPhysics()->GetAxis();
idVec3 velocity = parent->GetPhysics()->GetLinearVelocity();
idVec3 acceleration = ( velocity - lastVelocity ) / MS2SEC( gameLocal.msec );
lastVelocity = velocity;
// tilt things based on velocity & acceleration
idVec3 forward = ownerAxis[0];
idVec3 right = ownerAxis[1];
idVec3 up = ownerAxis[2];
float forwardAccel = acceleration * forward;
float rightAccel = acceleration * right;
float forwardVel = velocity * forward;
float rightVel = velocity * right;
// want to rotate the joint on its axis to look like its tilting with the speed
idAngles target( 0.0f, 0.0f, 0.0f );
target.pitch = 0.05f * ( forwardAccel * 0.1f + forwardVel * 0.1f );
target.roll = -0.05f * ( rightAccel * 0.1f + rightVel * 0.1f );
// create a rotation about the offset axis
float rotSpeed = parent->GetPhysics()->GetAngularVelocity() * up;
idVec3 rotAxis = baseOrg;
rotAxis.Normalize();
idRotation rotationRot( vec3_zero, rotAxis, rotSpeed * 15.0f );
idMat3 rotationMat = rotationRot.ToMat3();
idMat3 translationMat = target.ToMat3();
idMat3 totalMat = rotationMat * translationMat;
target = totalMat.ToAngles();
target.Clamp( minAngles, maxAngles );
// Lerp with the current rotations
// this is a semi hack, you have to do an slerp to be totally correct, but we just do a linear lerp + renormalize
// this causes or rotation speeds to be non uniform but who cares... the rotations are still correct
float lerp = ( gameLocal.msec * adaptSpeed );
currentAxes = target.ToQuat() * lerp + currentAxes * ( 1.0f - lerp );
currentAxes.Normalize();
currentAxes.FixDenormals( 0.00001f );
// Add the local joint transform on top of this
idMat3 mat = baseAxes * currentAxes.ToMat3();
parent->GetAnimator()->SetJointAxis( joint, JOINTMOD_WORLD_OVERRIDE, mat );
// Enable disable engine shader effect on model
if ( parent->GetEngine().GetState() ) {
parent->GetRenderEntity()->shaderParms[shaderParmIndex] = 1.0f;
} else {
parent->GetRenderEntity()->shaderParms[shaderParmIndex] = 0.0f;
}
// Lightning bolts from engines
// (visuals only no physics here)
//
if ( gameLocal.time > nextBeamTime ) {
idMat3 parentAxis = parent->GetRBPhysics()->GetAxis();
idVec3 tempTraceDir = traceDir * axis;
idVec3 end = origin + ( tempTraceDir * maxTraceLength );
idEntity *entList[ 100 ];
bool foundAttractor = false;
int numFound = gameLocal.EntitiesWithinRadius( origin, 256.0f, entList, 100 );
engineEffect.Stop(); // stop old bolt
for ( int i = 0; i < numFound; i++ ) {
if ( entList[ i ] != parent && beamTargetInfo->FilterEntity( entList[ i ] ) ) {
idPhysics* entPhysics = entList[ i ]->GetPhysics();
idVec3 end = entPhysics->GetOrigin() + entPhysics->GetBounds().GetCenter();
engineEffect.GetRenderEffect().endOrigin = end;
// If it is to far or going up don't bother
idVec3 diff = end - origin;
if ( ( diff.z < 0.f ) && ( diff.LengthSqr() < Square( 1000.f ) ) ) {
engineEffect.Start( gameLocal.time );
nextBeamTime = gameLocal.time + 100 + gameLocal.random.RandomInt( 250 ); //Make the lightning a bit more "explosive"
foundAttractor = true;
break;
}
}
}
if ( !foundAttractor ) {
// Random vector in negative z cone
idVec3 dir = gameLocal.random.RandomVectorInCone( 80.f );
dir.z = -dir.z;
end = origin + dir * 256.f;
trace_t beamTrace;
memset( &beamTrace, 0, sizeof( beamTrace ) );
gameLocal.clip.TracePoint( CLIP_DEBUG_PARMS beamTrace, origin, end, MASK_VEHICLESOLID, parent );
// If it hit anything then spawn a beam towards that
if ( beamTrace.fraction < 1.f ) {
engineEffect.GetRenderEffect().endOrigin = beamTrace.endpos;
engineEffect.Start( gameLocal.time );
}
nextBeamTime = gameLocal.time + 1000 + gameLocal.random.RandomInt( 2500 );
}
}
engineEffect.GetRenderEffect().origin = origin;
engineEffect.GetRenderEffect().suppressSurfaceInViewID = parent->GetRenderEntity()->suppressSurfaceInViewID;
engineEffect.GetRenderEffect().suppressLightsInViewID = parent->GetRenderEntity()->suppressSurfaceInViewID;
engineEffect.Update();
}
/*
================
sdVehicleRigidBodyHoverPad::EvaluateContacts
================
*/
int sdVehicleRigidBodyHoverPad::EvaluateContacts( contactInfo_t* list, contactInfoExt_t* listExt, int max ) {
return 0;
}
/*
===============================================================================
sdVehicleSuspensionPoint
===============================================================================
*/
CLASS_DECLARATION( sdVehicleDriveObject, sdVehicleSuspensionPoint )
END_CLASS
/*
================
sdVehicleSuspensionPoint::sdVehicleSuspensionPoint
================
*/
sdVehicleSuspensionPoint::sdVehicleSuspensionPoint( void ) {
suspension = NULL;
offset = 0;
suspensionInterface.Init( this );
}
/*
================
sdVehicleSuspensionPoint::~sdVehicleSuspensionPoint
================
*/
sdVehicleSuspensionPoint::~sdVehicleSuspensionPoint( void ) {
delete suspension;
}
/*
================
sdVehicleSuspensionPoint::Init
================
*/
void sdVehicleSuspensionPoint::Init( const sdDeclVehiclePart& point, sdTransport_RB* _parent ) {
parent = _parent;
state.grounded = false;
state.rested = true;
suspensionInfo.velocityScale= point.data.GetFloat( "suspensionVelocityScale", "1" );
suspensionInfo.kCompress = point.data.GetFloat( "suspensionKCompress" );
suspensionInfo.damping = point.data.GetFloat( "suspensionDamping" );
radius = point.data.GetFloat( "radius" );
joint = _parent->GetAnimator()->GetJointHandle( point.data.GetString( "joint" ) );
startJoint = _parent->GetAnimator()->GetJointHandle( point.data.GetString( "startJoint" ) );
if ( joint == INVALID_JOINT ) {
gameLocal.Error( "sdVehicleSuspensionPoint::Init Invalid Joint Name '%s'", point.data.GetString( "joint" ) );
}
if ( startJoint == INVALID_JOINT ) {
gameLocal.Error( "sdVehicleSuspensionPoint::Init Invalid Joint Name '%s'", point.data.GetString( "startJoint" ) );
}
_parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, baseOrg );
_parent->GetAnimator()->GetJointTransform( startJoint, gameLocal.time, baseStartOrg );
suspensionInfo.totalDist = ( baseOrg - baseStartOrg ).Length();
const sdDeclStringMap* suspenionInfo = gameLocal.declStringMapType[ point.data.GetString( "suspension" ) ];
if ( suspenionInfo ) {
gameLocal.CacheDictionaryMedia( suspenionInfo->GetDict() );
suspension = sdVehicleSuspension::GetSuspension( suspenionInfo->GetDict().GetString( "type" ) );
if ( suspension ) {
suspension->Init( &suspensionInterface, suspenionInfo->GetDict() );
}
}
frictionAxes.Identity();
contactFriction = point.data.GetVector( "contactFriction", "0 0 0" );
aggressiveDampening = point.data.GetBool( "aggressiveDampening" );
}
/*
================
sdVehicleSuspensionPoint::GetParent
================
*/
sdTransport* sdVehicleSuspensionPoint::GetParent( void ) const {
return parent;
}
/*
================
sdVehicleSuspensionPoint::UpdatePrePhysics
================
*/
void sdVehicleSuspensionPoint::UpdatePrePhysics( const sdVehicleInput& input ) {
idVec3 org;
idVec3 startOrg;
idMat3 axis = mat3_identity;
if ( !parent->GetPhysics()->IsAtRest() ) {
const renderEntity_t& renderEntity = *parent->GetRenderEntity();
org = renderEntity.origin + ( baseOrg * renderEntity.axis );
startOrg = renderEntity.origin + ( baseStartOrg * renderEntity.axis );
idVec3 start = startOrg;
idVec3 end = org;
memset( &groundTrace, 0, sizeof( groundTrace ) );
gameLocal.clip.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end, MASK_VEHICLESOLID | CONTENTS_MONSTER, parent );
groundTrace.c.selfId = -1;
offset = radius - ( 1.0f - groundTrace.fraction ) * suspensionInfo.totalDist;
state.rested = true;
if ( groundTrace.fraction != 1.0f ) {
groundTrace.c.selfId = -1;
groundTrace.c.normal = start - end;
groundTrace.c.normal.Normalize();
CalcForces( suspensionForce, suspensionVelocity, -groundTrace.c.normal );
if ( suspensionVelocity < -5.f ) {
state.rested = false;
parent->GetPhysics()->Activate();
} else {
suspensionVelocity = 0.f;
}
}
state.grounded = groundTrace.fraction != 1.f;
if ( suspension ) {
suspension->Update();
}
frictionAxes = axis;
} else {
state.rested = true;
}
}
/*
================
sdVehicleSuspensionPoint::EvaluateContacts
================
*/
int sdVehicleSuspensionPoint::EvaluateContacts( contactInfo_t* list, contactInfoExt_t* listExt, int max ) {
if ( IsHidden() || max < 1 ) {
return 0;
}
if ( state.grounded ) {
listExt[ 0 ].contactForceMax = suspensionForce;
listExt[ 0 ].contactForceVelocity = suspensionVelocity;
listExt[ 0 ].contactFriction = contactFriction;
listExt[ 0 ].frictionAxes = frictionAxes;
listExt[ 0 ].motorForce = 0.0f;
listExt[ 0 ].motorDirection.Zero();
listExt[ 0 ].motorSpeed = 0.0f;
listExt[ 0 ].rested = state.rested;
list[ 0 ] = groundTrace.c;
return 1;
}
return 0;
}
/*
================
sdVehicleSuspensionPoint::CalcForces
================
*/
void sdVehicleSuspensionPoint::CalcForces( float& maxForce, float& velocity, const idVec3& traceDir ) {
idVec3 v;
parent->GetRBPhysics()->GetPointVelocity( groundTrace.endpos, v );
float dampingForce = suspensionInfo.damping * idMath::Fabs( v * -traceDir );
float compression = suspensionInfo.totalDist - suspensionInfo.totalDist * groundTrace.fraction;
state.grounded = true;
maxForce = compression * suspensionInfo.kCompress;
if ( groundTrace.fraction < 0.5f ) { // TODO: Make this configurable
maxForce *= 2.f;
}
if ( !aggressiveDampening ) {
velocity = dampingForce - ( compression * suspensionInfo.velocityScale );
} else {
velocity = 0.0f;
}
}
/*
================
sdVehicleSuspensionPoint::UpdateSuspensionIK
================
*/
bool sdVehicleSuspensionPoint::UpdateSuspensionIK( void ) {
if ( suspension != NULL ) {
return suspension->UpdateIKJoints( parent->GetAnimator() );
}
return false;
}
/*
================
sdVehicleSuspensionPoint::ClearSuspensionIK
================
*/
void sdVehicleSuspensionPoint::ClearSuspensionIK( void ) {
if ( suspension != NULL ) {
suspension->ClearIKJoints( parent->GetAnimator() );
}
}
/*
===============================================================================
sdVehicleRigidBodyVtol
===============================================================================
*/
CLASS_DECLARATION( sdVehicleRigidBodyPartSimple, sdVehicleRigidBodyVtol )
END_CLASS
/*
================
sdVehicleRigidBodyVtol::sdVehicleRigidBodyVtol
================
*/
sdVehicleRigidBodyVtol::sdVehicleRigidBodyVtol( void ) {
}
/*
================
sdVehicleRigidBodyVtol::~sdVehicleRigidBodyVtol
================
*/
sdVehicleRigidBodyVtol::~sdVehicleRigidBodyVtol( void ) {
}
/*
================
sdVehicleRigidBodyVtol::Init
================
*/
void sdVehicleRigidBodyVtol::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPartSimple::Init( part, _parent );
shoulderAnglesBounds = part.data.GetVec2( "shoulderBounds", "-10 10" );
elbowAnglesBounds = part.data.GetVec2( "elbowBounds", "-10 10" );
shoulderAxis = part.data.GetInt( "shoulderAxis", "1" ); // Which major axis to rotate along
elbowAxis = part.data.GetInt( "elbowAxis", "0" );
shoulderAngleScale = part.data.GetInt( "shoulderAngleScale", "1" );
elbowAngleScale = part.data.GetInt( "elbowAngleScale", "1" );
elbowJoint = _parent->GetAnimator()->GetJointHandle( part.data.GetString( "elbowJoint" ) );
if ( elbowJoint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePart_AF::Init '%s' can't find VTOL joint '%s'", name.c_str(), part.data.GetString( "elbowJoint" ) );
}
effectJoint = _parent->GetAnimator()->GetJointHandle( part.data.GetString( "effectJoint" ) );
if ( effectJoint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePart_AF::Init '%s' can't find VTOL joint '%s'", name.c_str(), part.data.GetString( "elbowJoint" ) );
}
idVec3 shoulderBaseOrg; idVec3 elbowBaseOrg;
// Extract initial joint positions
_parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, shoulderBaseOrg, shoulderBaseAxes );
_parent->GetAnimator()->GetJointTransform( elbowJoint, gameLocal.time, elbowBaseOrg, elbowBaseAxes );
// Setup the engine effect
renderEffect_t &effect = engineEffect.GetRenderEffect();
effect.declEffect = gameLocal.FindEffect( _parent->spawnArgs.GetString( part.data.GetString( "effect", "fx_vtol" ) ) );
effect.axis = mat3_identity;
effect.attenuation = 1.f;
effect.hasEndOrigin = false;
effect.loop = true;
effect.shaderParms[SHADERPARM_RED] = 1.0f;
effect.shaderParms[SHADERPARM_GREEN] = 1.0f;
effect.shaderParms[SHADERPARM_BLUE] = 1.0f;
effect.shaderParms[SHADERPARM_ALPHA] = 1.0f;
effect.shaderParms[SHADERPARM_BRIGHTNESS] = 1.0f;
_parent->GetAnimator()->GetJointTransform( effectJoint, gameLocal.time, engineEffect.GetRenderEffect().origin, engineEffect.GetRenderEffect().axis );
//engineEffect.Start( gameLocal.time );
oldShoulderAngle = 0.f;
oldElbowAngle = 0.f;
/*
shaderParmIndex = part.data.GetInt( "shaderParmIndex", "0" );
adaptSpeed = part.data.GetFloat( "adaption_speed", "0.005" );
velocityInfluence = part.data.GetFloat( "linear_velocity_influence", "0.3" );
angVelocityInfluence = part.data.GetFloat( "angular_velocity_influence", "-0.3" );
noiseFreq = part.data.GetFloat( "random_motion_freq", "0.001" );
noisePhase = part.data.GetFloat( "random_motion_amplitude", "3" );
restFraction = part.data.GetFloat( "restFraction", "0.9" );
minAngles.Set( minAnglesValues.x, minAnglesValues.y, minAnglesValues.z );
maxAngles.Set( maxAnglesValues.x, maxAnglesValues.y, maxAnglesValues.z );
traceDir.Normalize();
groundNormal = idVec3( 0.0f, 0.0f, 1.0f );
_parent->GetAnimator()->GetJointTransform( joint, gameLocal.time, baseOrg, baseAxes );
idMat3 ident; ident.Identity();
currentAxes = ident.ToQuat();
noisePhase = gameLocal.random.CRandomFloat() * 4000.0f;
//Dir is the direction the pads should "point to" when the vehicle is rotating along it's z-axis
//(so it can turn on the spot (velocity == 0)) and still look cool
//This gives directions on the rotation circle (like the arms of a swastika)
angularDir.Cross( baseOrg, idVec3( 0, 0, 1 ) );
angularDir.Normalize();
// Setup the lighting effect
renderEffect_t &effect = engineEffect.GetRenderEffect();
effect.declEffect = gameLocal.declEffectsType.Find( _parent->spawnArgs.GetString( "fx_hoverpad" ) );
effect.axis = mat3_identity;
effect.attenuation = 1.f;
effect.hasEndOrigin = true;
effect.loop = false;
effect.shaderParms[SHADERPARM_RED] = 1.0f;
effect.shaderParms[SHADERPARM_GREEN] = 1.0f;
effect.shaderParms[SHADERPARM_BLUE] = 1.0f;
effect.shaderParms[SHADERPARM_ALPHA] = 1.0f;
effect.shaderParms[SHADERPARM_BRIGHTNESS] = 1.0f;
nextBeamTime = gameLocal.time + 2000 + gameLocal.random.RandomInt( 1000 );
beamTargetInfo = (const sdDeclTargetInfo *)gameLocal.declTargetInfoType.Find( _parent->spawnArgs.GetString( "ti_lightning" ) );*/
}
/*
================
sdVehicleRigidBodyHoverPad::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyVtol::UpdatePrePhysics( const sdVehicleInput& input ) {
// We just want to do some animation
}
void sdVehicleRigidBodyVtol::UpdatePostPhysics( const sdVehicleInput& input ) {
const idMat3 &modelAxis = parent->GetRenderEntity()->axis;
const idVec3 &modelOrg = parent->GetRenderEntity()->origin;
float shoulderAngle = RAD2DEG( idMath::ACos( modelAxis[0] * idVec3(0,0,1) ) ) - 90.0f;
float elbowAngle = RAD2DEG( idMath::ACos( modelAxis[1] * idVec3(0,0,1) ) ) - 90.0;
// "Shoulder"
idVec3 axis = vec3_origin;
axis[ shoulderAxis ] = 1.0f;
shoulderAngle *= shoulderAngleScale;
if( shoulderAngle < shoulderAnglesBounds.x ) {
shoulderAngle = shoulderAnglesBounds.x;
} else if ( shoulderAngle > shoulderAnglesBounds.y ) {
shoulderAngle = shoulderAnglesBounds.y;
}
if ( idMath::Fabs( oldShoulderAngle - shoulderAngle ) > 0.1f ) {
oldShoulderAngle = shoulderAngle;
idRotation rot( vec3_origin, axis, shoulderAngle );
idMat3 mat = shoulderBaseAxes * rot.ToMat3();
parent->GetAnimator()->SetJointAxis( joint, JOINTMOD_WORLD_OVERRIDE, mat );
}
// "Elbow"
axis = vec3_origin;
axis[ elbowAxis ] = 1.0f;
elbowAngle *= elbowAngleScale;
if( elbowAngle < elbowAnglesBounds.x ) {
elbowAngle = elbowAnglesBounds.x;
} else if ( elbowAngle > elbowAnglesBounds.y ) {
elbowAngle = elbowAnglesBounds.y;
}
if ( idMath::Fabs( oldElbowAngle - elbowAngle ) > 0.1f ) {
elbowAngle = elbowAngle;
idRotation rot = idRotation( vec3_origin, axis, elbowAngle );
parent->GetAnimator()->SetJointAxis( elbowJoint, JOINTMOD_LOCAL, rot.ToMat3() );
}
if ( parent->GetEngine().GetState() ) {
idMat3 effectAxis;
idVec3 effectOrg;
parent->GetAnimator()->GetJointTransform( effectJoint, gameLocal.time, effectOrg, effectAxis );
engineEffect.GetRenderEffect().axis = effectAxis * modelAxis;
engineEffect.GetRenderEffect().origin = effectOrg * modelAxis + modelOrg;
engineEffect.Start( gameLocal.time );
engineEffect.Update();
} else {
engineEffect.Stop();
}
}
/*
===============================================================================
sdVehicleRigidBodyAntiGrav
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePartSimple, sdVehicleRigidBodyAntiGrav )
END_CLASS
/*
================
sdVehicleRigidBodyAntiGrav::sdVehicleRigidBodyAntiGrav
================
*/
sdVehicleRigidBodyAntiGrav::sdVehicleRigidBodyAntiGrav( void ) {
clientParent = NULL;
oldVelocity.Zero();
}
/*
================
sdVehicleRigidBodyAntiGrav::~sdVehicleRigidBodyAntiGrav
================
*/
sdVehicleRigidBodyAntiGrav::~sdVehicleRigidBodyAntiGrav( void ) {
}
/*
================
sdVehicleRigidBodyAntiGrav::Init
================
*/
void sdVehicleRigidBodyAntiGrav::Init( const sdDeclVehiclePart& part, sdTransport* _parent ) {
sdVehiclePartSimple::Init( part, _parent );
rotAxis = part.data.GetInt( "rotAxis", "1" );
tailUpAxis = part.data.GetInt( "tailUpAxis", "0" );
tailSideAxis = part.data.GetInt( "tailSideAxis", "2" );
{
renderEffect_t &effect = engineMainEffect.GetRenderEffect();
effect.declEffect = gameLocal.FindEffect( _parent->spawnArgs.GetString( part.data.GetString( "effect", "fx_engine" ) ) );
effect.axis = mat3_identity;
effect.attenuation = 1.f;
effect.hasEndOrigin = false;
effect.loop = true;
effect.shaderParms[SHADERPARM_RED] = 1.0f;
effect.shaderParms[SHADERPARM_GREEN] = 1.0f;
effect.shaderParms[SHADERPARM_BLUE] = 1.0f;
effect.shaderParms[SHADERPARM_ALPHA] = 1.0f;
effect.shaderParms[SHADERPARM_BRIGHTNESS] = 1.0f;
}
{
renderEffect_t &effect = engineBoostEffect.GetRenderEffect();
effect.declEffect = gameLocal.FindEffect( _parent->spawnArgs.GetString( part.data.GetString( "effect_boost", "fx_engine_boost" ) ) );
effect.axis = mat3_identity;
effect.attenuation = 1.f;
effect.hasEndOrigin = false;
effect.loop = true;
effect.shaderParms[SHADERPARM_RED] = 1.0f;
effect.shaderParms[SHADERPARM_GREEN] = 1.0f;
effect.shaderParms[SHADERPARM_BLUE] = 1.0f;
effect.shaderParms[SHADERPARM_ALPHA] = 1.0f;
effect.shaderParms[SHADERPARM_BRIGHTNESS] = 1.0f;
}
oldAngle = 0.0f;
fanRotation = 0.f;
targetAngle = 0.f;
fanJointName = part.data.GetString( "fanJoint" );
tailJointName = part.data.GetString( "tailJoint" );
SetupJoints( _parent->GetAnimator() );
lastGroundEffectsTime = 0;
fanSpeedMultiplier = parent->spawnArgs.GetFloat( "fan_speed_multiplier", "0.9" );
fanSpeedOffset = parent->spawnArgs.GetFloat( "fan_speed_offset", "500" );
fanSpeedMax = parent->spawnArgs.GetFloat( "fan_pitch_max", "800" );
fanSpeedRampRate = parent->spawnArgs.GetFloat( "fan_ramp_rate", "0.1" );
lastFanSpeed = fanSpeedOffset;
}
/*
================
sdVehicleRigidBodyAntiGrav::SetupJoints
================
*/
void sdVehicleRigidBodyAntiGrav::SetupJoints( idAnimator* targetAnimator ) {
fanJoint = targetAnimator->GetJointHandle( fanJointName );
if ( fanJoint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePart_AF::Init '%s' can't find AntiGrav joint '%s'", name.c_str(), fanJointName.c_str() );
}
tailJoint = targetAnimator->GetJointHandle( tailJointName );
if ( tailJoint == INVALID_JOINT ) {
gameLocal.Error( "sdVehiclePart_AF::Init '%s' can't find AntiGrav joint '%s'", name.c_str(), tailJointName.c_str() );
}
idVec3 baseOrg;
// Extract initial joint positions
targetAnimator->GetJointTransform( joint, gameLocal.time, baseOrg, baseAxes );
// Setup the engine effect
targetAnimator->GetJointTransform( joint, gameLocal.time, engineMainEffect.GetRenderEffect().origin, engineMainEffect.GetRenderEffect().axis );
targetAnimator->GetJointTransform( joint, gameLocal.time, engineBoostEffect.GetRenderEffect().origin, engineBoostEffect.GetRenderEffect().axis );
}
/*
================
sdVehicleRigidBodyAntiGrav::SetClientParent
================
*/
void sdVehicleRigidBodyAntiGrav::SetClientParent( rvClientEntity* p ) {
clientParent = p;
if ( p ) {
SetupJoints( p->GetAnimator() );
}
}
/*
================
sdVehicleRigidBodyAntiGrav::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyAntiGrav::UpdatePrePhysics( const sdVehicleInput& input ) {
// We just want to do some animation
}
/*
================
sdVehicleRigidBodyAntiGrav::UpdatePostPhysics
================
*/
void sdVehicleRigidBodyAntiGrav::UpdatePostPhysics( const sdVehicleInput& input ) {
idPlayer* player = parent->GetPositionManager().FindDriver();
sdPhysics_JetPack* jetpackPhysics = parent->GetPhysics()->Cast< sdPhysics_JetPack >();
idAnimator* targetAnimator;
idVec3 modelOrg;
idMat3 modelAxis;
if ( clientParent ) {
modelOrg = clientParent->GetOrigin();
modelAxis = clientParent->GetAxis();
targetAnimator = clientParent->GetAnimator();
} else {
modelOrg = parent->GetPhysics()->GetOrigin();
modelAxis = parent->GetRenderEntity()->axis;
targetAnimator = parent->GetAnimator();
}
idVec3 velocity, localVelocity;// = parent->GetPhysics()->GetLinearVelocity() * modelAxis.Transpose();
if ( jetpackPhysics ) {
localVelocity = jetpackPhysics->GetFanForce() * modelAxis.Transpose();
} else {
localVelocity.Zero();
}
// zero out lateral velocities, as not represented in fan movement
velocity = localVelocity;
velocity.y = 0.f;
// remove jittery small velocities
if ( fabsf( velocity.x ) < 0.0001f ) {
velocity.x = 0.f;
}
if ( fabsf( velocity.z ) < 0.0001f ) {
velocity.z = 0.f;
}
// If we are not really going up just blend towards the forward pose
//if ( velocity.z < 0.001f ) {
// velocity = idVec3( velocity.x + 100.0f, velocity.y, 0 );
//}
oldVelocity.FixDenormals();
idVec3 targetVelocity = velocity * 0.9f + oldVelocity * 0.1f;
targetVelocity.FixDenormals();
float blendSpeed = 0.4f;
if ( targetVelocity.Length() < 0.01f && (!jetpackPhysics || jetpackPhysics->OnGround()) ) {
targetAngle = 0;//15;
blendSpeed = 0.05f;
}
float angle = targetAngle * blendSpeed + oldAngle * (1.f - blendSpeed);
if ( idMath::Fabs( angle ) < idMath::FLT_EPSILON ) {
angle = 0.0f;
}
idRotation rot( vec3_origin, baseAxes[rotAxis], angle );
targetAnimator->SetJointAxis( joint, JOINTMOD_WORLD_OVERRIDE, rot.ToMat3() );
oldAngle = angle;
if ( !targetVelocity.Compare( oldVelocity, 0.00001f ) )
{
// Engine hubs
idVec3 dir = targetVelocity ;
dir.y = 0.0f; // Ignore strafing :)
dir.Normalize();
targetAngle = RAD2DEG( idMath::ACos( dir * idVec3( 1, 0, 0 ) ) );
// Tail stabilizers
dir = targetVelocity;
dir.Normalize();
idVec3 angles;
angles.Zero();
angles[tailUpAxis] = dir.z * 2.0f;
angles[tailSideAxis] = dir.y * 5.0f;
targetAnimator->SetJointAxis( tailJoint, JOINTMOD_LOCAL, idAngles( angles ).ToMat3() );
oldVelocity = targetVelocity;
}
if ( player ) {
const idVec3& upAxis = parent->GetPhysics()->GetAxis()[ 2 ];
float absSpeedKPH = ( localVelocity - ( localVelocity*upAxis )*upAxis ).Length();
float idealNewSpeed = ( absSpeedKPH * fanSpeedMultiplier ) + fanSpeedOffset;
if ( idealNewSpeed > fanSpeedMax ) {
idealNewSpeed = fanSpeedMax;
}
float speed = Lerp( lastFanSpeed, idealNewSpeed, fanSpeedRampRate );
lastFanSpeed = speed;
if ( jetpackPhysics ) {
speed += jetpackPhysics->GetBoost() * 1000.f;
}
// HACK - right fan spin in opposite direction
if ( fanJointName[ 0 ] == 'r' ) {
speed = -speed;
}
fanRotation += MS2SEC( gameLocal.msec ) * speed;
idAngles rot( 0.0f, 0.0f, fanRotation );
targetAnimator->SetJointAxis( fanJoint, JOINTMOD_LOCAL_OVERRIDE, rot.ToMat3() );
}
if ( !clientParent ) {
UpdateEffect();
}
}
/*
================
sdVehicleRigidBodyAntiGrav::UpdateEffect
================
*/
void sdVehicleRigidBodyAntiGrav::UpdateEffect() {
idAnimator* targetAnimator;
idVec3 modelOrg;
idMat3 modelAxis;
if ( clientParent ) {
modelOrg = clientParent->GetOrigin();
modelAxis = clientParent->GetAxis();
targetAnimator = clientParent->GetAnimator();
} else {
modelOrg = parent->GetPhysics()->GetOrigin();
modelAxis = parent->GetRenderEntity()->axis;
targetAnimator = parent->GetAnimator();
}
if ( parent->GetPositionManager().FindDriver() ) {
idMat3 mountAxis;
idVec3 mountOrg;
targetAnimator->GetJointTransform( fanJoint, gameLocal.time, mountOrg, mountAxis );
bool boost = false;
sdPhysics_JetPack* jetpackPhysics = parent->GetPhysics()->Cast< sdPhysics_JetPack >();
if ( jetpackPhysics ) {
boost = jetpackPhysics->GetBoost() > 0.5f;
}
engineBoostEffect.GetRenderEffect().axis = ( mountAxis * modelAxis )[ 0 ].ToMat3();
engineBoostEffect.GetRenderEffect().origin = mountOrg * modelAxis + modelOrg;
engineMainEffect.GetRenderEffect().axis = ( mountAxis * modelAxis )[ 0 ].ToMat3();
engineMainEffect.GetRenderEffect().origin = mountOrg * modelAxis + modelOrg;
engineMainEffect.Start( gameLocal.time );
engineMainEffect.Update();
if ( boost ) {
engineBoostEffect.Start( gameLocal.time );
} else {
engineBoostEffect.Stop();
}
engineBoostEffect.Update();
if ( boost ) {
idMat3 orient = mountAxis * modelAxis;
idVec3 dist(-800.f, 0.f, 0.f);
dist = orient * dist;
idVec3 traceOrg = mountOrg * modelAxis + modelOrg;
idVec3 traceEnd = traceOrg + dist;
trace_t traceObject;
gameLocal.clip.TracePoint( CLIP_DEBUG_PARMS traceObject, traceOrg, traceEnd, MASK_SOLID | CONTENTS_WATER | MASK_OPAQUE, parent );
traceEnd = traceObject.endpos;
if ( gameLocal.time >= ( lastGroundEffectsTime + 100 )
&& traceObject.fraction < 1.0f ) {
const char* surfaceTypeName = NULL;
if ( traceObject.c.surfaceType ) {
surfaceTypeName = traceObject.c.surfaceType->GetName();
}
parent->PlayEffect( "fx_groundeffect", colorWhite.ToVec3(), surfaceTypeName, traceObject.endpos, traceObject.c.normal.ToMat3(), 0 );
lastGroundEffectsTime = gameLocal.time;
}
}
} else {
engineMainEffect.Stop();
engineBoostEffect.Stop();
}
}
/*
===============================================================================
sdVehicleRigidBodyPseudoHover
===============================================================================
*/
idCVar g_debugVehiclePseudoHover( "g_debugVehiclePseudoHover", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about the pseudoHover component" );
#define MASK_PSEUDOHOVERCLIP (CONTENTS_SOLID | CONTENTS_VEHICLECLIP | CONTENTS_WATER | CONTENTS_MONSTER)
CLASS_DECLARATION( sdVehiclePart, sdVehicleRigidBodyPseudoHover )
END_CLASS
/*
================
sdVehicleRigidBodyPseudoHover::sdVehicleRigidBodyPseudoHover
================
*/
sdVehicleRigidBodyPseudoHover::sdVehicleRigidBodyPseudoHover( void ) {
}
/*
================
sdVehicleRigidBodyPseudoHover::~sdVehicleRigidBodyPseudoHover
================
*/
sdVehicleRigidBodyPseudoHover::~sdVehicleRigidBodyPseudoHover( void ) {
gameLocal.clip.DeleteClipModel( mainClipModel );
}
/*
================
sdVehicleRigidBodyPseudoHover::Init
================
*/
#define SIGNEDPOWER( a, b ) ( idMath::Sign( a ) * idMath::Pow( idMath::Fabs( a ), b ) )
void sdVehicleRigidBodyPseudoHover::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehiclePart::Init( part );
oldDriver = NULL;
parent = _parent;
grounded = false;
parkMode = false;
lockedPark = false;
hoverHeight = part.data.GetFloat( "height", "60" );
parkHeight = part.data.GetFloat( "height_park", "30" );
repulsionSpeedCoeff = part.data.GetFloat( "repulsion_speed_coeff" );
repulsionSpeedHeight = part.data.GetFloat( "repulsion_speed_height" );
repulsionSpeedMax = part.data.GetFloat( "repulsion_speed_max" );
yawCoeff = part.data.GetFloat( "yaw_coeff" );
fwdCoeff = part.data.GetFloat( "fwd_coeff" );
fwdSpeedDampCoeff = part.data.GetFloat( "fwd_speed_damping_coeff" );
fwdSpeedDampPower = part.data.GetFloat( "fwd_speed_damping_pow" );
fwdSpeedDampMax = part.data.GetFloat( "fwd_speed_damping_max" );
frontCastPos = part.data.GetFloat( "front_cast" );
backCastPos = part.data.GetFloat( "back_cast" );
castOffset = part.data.GetFloat( "cast_offset" );
maxSlope = part.data.GetFloat( "max_slope" );
slopeDropoff = part.data.GetFloat( "slope_dropoff" );
parkTime = part.data.GetFloat( "park_time", "0.25" );
effectJoint = parent->GetAnimator()->GetJointHandle( parent->spawnArgs.GetString( "joint_park_fx", "origin" ) );
lastFrictionScale = 1.0f;
startParkTime = 0;
endParkTime = gameLocal.time;
evalState.surfaceNormal.Set( 0.0f, 0.0f, 1.0f );
//
// TWTODO: Take these from the vscript
//
castStarts.Append( idVec3( frontCastPos, -80.0f, castOffset ) );
castStarts.Append( idVec3( frontCastPos, 80.0f, castOffset ) );
castStarts.Append( idVec3( backCastPos, -80.0f, castOffset ) );
castStarts.Append( idVec3( backCastPos, 80.0f, castOffset ) );
castDirections.Append( idVec3( 128.0f, -64.0f, 0.0f ) );
castDirections.Append( idVec3( 128.0f, 64.0f, 0.0f ) );
castDirections.Append( idVec3( -64.0f, -64.0f, 0.0f ) );
castDirections.Append( idVec3( -64.0f, 64.0f, 0.0f ) );
mainClipModel = NULL;
targetVelocity.Zero();
targetQuat.Set( 1.0f, 0.0f, 0.0f, 0.0f );
lastParkEffectTime = 0;
lastUnparkEffectTime = 0;
chosenParkAxis.Identity();
chosenParkOrigin.Zero();
}
/*
================
sdVehicleRigidBodyPseudoHover::RepulsionForCast
================
*/
void sdVehicleRigidBodyPseudoHover::DoRepulsionForCast( const idVec3& start, const idVec3& end, float desiredFraction, const trace_t& trace, float& height, int numForces ) {
idVec3 traceDir = end - start;
float fullLength = traceDir.Normalize();
float traceLength = trace.fraction * fullLength;
float idealLength = desiredFraction * fullLength;
if ( trace.c.normal.z < 0.2f ) {
// HACK - make it pretend like a trace went straight down the full distance if it touched
// a too-steep slope
const_cast< idVec3& >( trace.c.normal ) = evalState.axis[ 2 ];
traceLength = idealLength;
}
//
// Calculate the repulsion
//
float reachingTime = 0.5f;
if ( trace.fraction < 0.2f ) {
reachingTime = 0.3f;
}
if ( trace.fraction < 0.1f ) {
reachingTime = 0.15f;
}
if ( trace.fraction < 1.0f ) {
float delta = idealLength - traceLength;
float futureDistMoved = evalState.linVelocity * traceDir * reachingTime * 0.5f;
float repulseAccel = 2 * ( delta + futureDistMoved ) / ( reachingTime*reachingTime );
idVec3 hoverAccel = -repulseAccel*traceDir - evalState.gravity;
// TODO: Use the hover force generated to create a torque and use that to re-orient the vehicle
// Will need to make the surface angle matching etc code take that into account!
evalState.hoverForce += hoverAccel * evalState.mass / numForces;
evalState.surfaceNormal += ( 1.0f - trace.fraction ) * trace.c.normal;
}
height += trace.fraction;
}
/*
================
sdVehicleRigidBodyPseudoHover::DoRepulsors
================
*/
void sdVehicleRigidBodyPseudoHover::DoRepulsors() {
const idVec3& upVector = evalState.axis[ 2 ];
//
// We want to cast out a bit forwards so that we don't tend to
// bottom out when the slope of the surface changes
//
idVec3 forwardLeading = evalState.linVelocity * 0.3f;
if ( startParkTime != 0 ) {
forwardLeading.Zero();
} else {
forwardLeading -= ( upVector*forwardLeading ) * upVector;
float fwdLeadLength = forwardLeading.Length();
if ( fwdLeadLength > 200.0f ) {
forwardLeading = forwardLeading * ( 200.0f / fwdLeadLength );
}
}
idVec3 traceDirection = -upVector;
traceDirection.Normalize();
evalState.hoverForce.Zero();
float mainTraceLength = hoverHeight;
if ( startParkTime != 0 ) {
mainTraceLength = hoverHeight * 3.0f;
}
float extraTraceLength = hoverHeight * 3.0f;
evalState.surfaceNormal.Zero();
float realHeight = 0.0f;
//
// Main body
//
if ( g_debugVehiclePseudoHover.GetBool() ) {
mainClipModel->Draw( evalState.origin, evalState.axis );
}
memset( &groundTrace, 0, sizeof( groundTrace ) );
idVec3 start = evalState.origin + 0.3f * castOffset * upVector;
idVec3 end = start + mainTraceLength * traceDirection;
end += forwardLeading;
evalState.clipLocale.Translation( CLIP_DEBUG_PARMS groundTrace, start, end, mainClipModel, evalState.axis, MASK_PSEUDOHOVERCLIP );
if ( groundTrace.c.normal.z < 0.2f ) {
idVec3 end = start + idVec3( 0.0f, 0.0f, -1.0f ) * extraTraceLength;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end, MASK_PSEUDOHOVERCLIP );
}
DoRepulsionForCast( start, end, hoverHeight / mainTraceLength, groundTrace, realHeight, 2 );
realHeight = 0.0f;
if ( g_debugVehiclePseudoHover.GetBool() ) {
mainClipModel->Draw( groundTrace.endpos, evalState.axis );
}
//
// Do a bunch of other position casts
int numCasts = castStarts.Num() < castDirections.Num() ? castStarts.Num() : castDirections.Num();
for ( int i = 0; i < numCasts; i++ ) {
trace_t currentTrace;
idVec3 castStart = evalState.origin + castStarts[ i ] * evalState.axis;
idVec3 castEnd = castStart + extraTraceLength * traceDirection;
castEnd += forwardLeading;
castEnd += castDirections[ i ] * evalState.axis;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS currentTrace, castStart, castEnd, MASK_PSEUDOHOVERCLIP );
if ( currentTrace.c.normal.z < 0.2f ) {
idVec3 castEnd = castStart + idVec3( 0.0f, 0.0f, -1.0f ) * extraTraceLength;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS currentTrace, castStart, castEnd, MASK_PSEUDOHOVERCLIP );
}
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorRed, castStart, currentTrace.endpos, 4 );
}
DoRepulsionForCast( castStart, castEnd, hoverHeight / extraTraceLength, currentTrace, realHeight, numCasts + 1 );
}
// Calculate the estimates of the normal & height
realHeight = realHeight * extraTraceLength / numCasts;
float normalLength = evalState.surfaceNormal.Normalize();
if ( normalLength < idMath::FLT_EPSILON ) {
evalState.surfaceNormal.Set( 0.0f, 0.0f, 1.0f );
}
// Don't let the generated up velocity exceed 300ups
float currentUpVel = evalState.linVelocity * evalState.axis[ 2 ];
float upForce = evalState.hoverForce*evalState.axis[ 2 ];
if ( idMath::Fabs( upForce ) > idMath::FLT_EPSILON ) {
float futureVel = currentUpVel + evalState.timeStep * upForce / evalState.mass ;
float clampedFutureVel = idMath::ClampFloat( -300.0f, 300.0f, futureVel );
float newUpForce = evalState.mass * ( clampedFutureVel - currentUpVel ) / evalState.timeStep;
if ( realHeight > hoverHeight && newUpForce > 0.0f ) {
// scale the up force down to prevent it getting ridiculously high up
float scale = Lerp( 1.0f, 0.3f, ( realHeight - hoverHeight ) / hoverHeight * 2.0f );
scale = idMath::ClampFloat( 0.3f, 1.0f, scale );
newUpForce *= scale;
}
evalState.hoverForce *= newUpForce / upForce;
}
//
// Up vector based velocity dampening
//
grounded = false;
if ( realHeight < repulsionSpeedHeight ) {
// calculate the acceleration required to put a stop to this vertical velocity
const idVec3 estFutureVelocity = evalState.linVelocity + evalState.hoverForce*( evalState.timeStep / evalState.mass );
const float upVelocity = ( estFutureVelocity ) * evalState.surfaceNormal;
float coefficient = repulsionSpeedCoeff;
if ( upVelocity > 0.0f ) {
coefficient *= 0.5f;
}
const float neededUpAccel = -upVelocity / evalState.timeStep;
float upAccel = idMath::ClampFloat( -repulsionSpeedMax, repulsionSpeedMax, neededUpAccel * coefficient );
evalState.hoverForce += evalState.mass * upAccel*evalState.surfaceNormal;
grounded = true;
}
}
/*
================
sdVehicleRigidBodyPseudoHover::CalculateSurfaceAxis
================
*/
void sdVehicleRigidBodyPseudoHover::CalculateSurfaceAxis() {
if ( evalState.surfaceNormal == vec3_origin ) {
evalState.surfaceNormal.Set( 0.0f, 0.0f, 1.0f );
}
idVec3 surfaceRight = evalState.surfaceNormal.Cross( evalState.axis[ 0 ] );
surfaceRight.Normalize();
idVec3 surfaceForward = surfaceRight.Cross( evalState.surfaceNormal );
surfaceForward.Normalize();
// construct the surface matrix
idMat3 surfaceAxis( surfaceForward, surfaceRight, evalState.surfaceNormal );
// slerp the surface axis with the old one to add some dampening
evalState.surfaceQuat = surfaceAxis.ToQuat();
evalState.surfaceAxis = evalState.surfaceQuat.ToMat3();
}
/*
================
sdVehicleRigidBodyPseudoHover::CalculateDrivingForce
================
*/
void sdVehicleRigidBodyPseudoHover::CalculateDrivingForce( const sdVehicleInput& input ) {
if ( parkMode ) {
evalState.drivingForce.Zero();
return;
}
const idVec3& upVector = evalState.axis[ 2 ];
const idVec3& surfaceUp = evalState.surfaceAxis[ 2 ];
// "go forwards" impetus
idVec3 fwdAccel( input.GetForward(), -input.GetCollective(), 0.0f );
fwdAccel.Normalize();
idVec3 inputAccel = fwdAccel * fwdCoeff * input.GetForce();
// HACK: these should really go in the vscript or the def file.
float targetSpeed = 380.0f;
if ( input.GetForce() > 1.0f ) {
targetSpeed = 605.0f;
}
float currentSpeed = evalState.linVelocity * ( fwdAccel * evalState.axis );
float maxDelta = fwdCoeff * input.GetForce();
float speedDelta = targetSpeed - currentSpeed;
if ( speedDelta > 0.0f ) {
speedDelta = Lerp( speedDelta, maxDelta, ( speedDelta / targetSpeed ) * 0.15f + 0.85f );
if ( speedDelta > maxDelta ) {
speedDelta = maxDelta;
}
} else {
speedDelta = 0.0f;
}
inputAccel = speedDelta * fwdAccel;
// figure out what that means in terms of a velocity delta
idVec3 vDelta = inputAccel * evalState.timeStep;
// figure out what force is needed to get that sort of vDelta, considering the hovering forces
idVec3 neededForce = evalState.surfaceAxis*inputAccel*evalState.mass - evalState.hoverForce;
neededForce -= ( neededForce*surfaceUp )*surfaceUp;
evalState.drivingForce = neededForce;
//
// Figure out if the slope is too steep, and ramp the force down
//
float angleBetween = idMath::ACos( idVec3( 0.0f, 0.0f, 1.0f ) * surfaceUp ) * idMath::M_RAD2DEG;
if ( angleBetween > maxSlope) {
// calculate the direction vectors directly up and tangential to the slope
idVec3 slopeRight = surfaceUp.Cross( idVec3( 0.0f, 0.0f, 1.0f ) );
idVec3 slopeForward = slopeRight.Cross( surfaceUp );
slopeRight.Normalize();
slopeForward.Normalize();
// ramp down the force
float accelScale = 1.0f - ( angleBetween - maxSlope ) * slopeDropoff;
if ( accelScale < 0.0f ) {
accelScale = 0.0f;
}
// HACK: Drop off the force quicker when boosting
if ( input.GetForce() > 1.0f ) {
accelScale *= accelScale;
}
if ( angleBetween > maxSlope * 2.0f ) {
// way beyond the max slope, zero all force up the slope
accelScale = 0.0f;
}
// remove the component up the slope
float upSlopeComponent = evalState.drivingForce * slopeForward;
if ( upSlopeComponent > 0.0f ) {
evalState.drivingForce = evalState.drivingForce - slopeForward * upSlopeComponent * ( 1.f - accelScale );
}
float hoverUpSlopeComponent = evalState.hoverForce * slopeForward;
if ( hoverUpSlopeComponent > 0.0f ) {
evalState.hoverForce = evalState.hoverForce - slopeForward * hoverUpSlopeComponent * ( 1.f - accelScale );
}
// remove the component into the slope
float intoSlopeComponent = evalState.drivingForce * surfaceUp;
if ( intoSlopeComponent > 0.0f ) {
evalState.drivingForce = evalState.drivingForce - surfaceUp * intoSlopeComponent * ( 1.f - accelScale );
}
float hoverIntoSlopeComponent = evalState.hoverForce * slopeForward;
if ( hoverIntoSlopeComponent > 0.0f ) {
evalState.hoverForce = evalState.hoverForce - slopeForward * hoverIntoSlopeComponent * ( 1.f - accelScale );
}
}
}
/*
================
sdVehicleRigidBodyPseudoHover::CalculateFrictionForce
================
*/
void sdVehicleRigidBodyPseudoHover::CalculateFrictionForce( const sdVehicleInput& input ) {
const idVec3& upVector = evalState.axis[ 2 ];
const idVec3& surfaceUp = evalState.surfaceAxis[ 2 ];
// calculate the future velocity that will be created by the forces that are applied
idVec3 futureVelocity = evalState.linVelocity
+ ( evalState.hoverForce + evalState.drivingForce ) * evalState.timeStep / evalState.mass
/*+ evalState.gravity * evalState.timeStep*/;
// project it to the plane
futureVelocity -= ( futureVelocity * surfaceUp ) * surfaceUp;
float futureSpeed = futureVelocity.Normalize();
// apply friction to it
float futureVelDamp = -fwdSpeedDampCoeff * SIGNEDPOWER( futureSpeed, fwdSpeedDampPower );
futureVelDamp = idMath::ClampFloat( -fwdSpeedDampMax, fwdSpeedDampMax, futureVelDamp );
if ( fabs( input.GetForce() ) > 0.0f ) {
futureVelDamp /= input.GetForce();
} else {
futureVelDamp = 0.0f;
}
// if the speed is quite small or the player is giving no input
// then increase the magnitude of the friction
// TODO: Move these tuning parameters to vscript defined thingies
float frictionScaleCutoff = 128.0f;
float frictionScaleMax = 15.0f;
float frictionScalePower = 0.5f;
float frictionScale = 0.8f;
float parkTimeRemaining = parkTime;
if ( startParkTime != 0 ) {
parkTimeRemaining = parkTime - MS2SEC( gameLocal.time - startParkTime );
} else if ( endParkTime != 0 ) {
parkTimeRemaining = MS2SEC( gameLocal.time - endParkTime );
}
parkTimeRemaining /= parkTime;
parkTimeRemaining = idMath::ClampFloat( 0.0f, 1.0f, parkTimeRemaining );
float parkScale = parkTimeRemaining;
if ( parkTimeRemaining < 1.0f || ( input.GetForward() == 0.0f && input.GetCollective() == 0.0f ) ) {
if ( futureSpeed < frictionScaleCutoff ) {
frictionScale = ( frictionScaleCutoff - futureSpeed ) / frictionScaleCutoff;
frictionScale = idMath::Pow( frictionScale, frictionScalePower );
frictionScale = frictionScale * frictionScaleMax + 1.0f;
} else {
// its going too fast to be acted on by the really strong power
// hack a different friction that will slow it down to the friction cutoff over time
lastFrictionScale = 1.0f;
// calculate the acceleration needed to nullify the velocity
futureVelDamp = -( futureSpeed / evalState.timeStep ) / 5.0f;
}
} else {
// the player is applying input, so snap to zero friction scale
lastFrictionScale = 1.0f;
}
// blend the friction scale with the last frame's one
frictionScale = lastFrictionScale * 0.7f + frictionScale * 0.3f;
frictionScale *= parkScale;
lastFrictionScale = frictionScale;
// apply the friction
evalState.frictionForce = futureVelDamp * evalState.mass * frictionScale * futureVelocity;
}
/*
================
sdVehicleRigidBodyPseudoHover::CalculateTilting
================
*/
void sdVehicleRigidBodyPseudoHover::CalculateTilting( const sdVehicleInput& input ) {
evalState.surfaceMatchingQuat = evalState.surfaceQuat;
if ( startParkTime == 0 ) {
idVec3 inputMove( -input.GetForward(), -( input.GetCollective() + 2.0f*input.GetSteerAngle() ) * 0.5f, 0.0f );
inputMove *= 2.5f * input.GetForce();
// modify the surface quat using the movement keys
idRotation pitchRotation( vec3_origin, evalState.axis[ 1 ], inputMove.x );
idRotation yawRotation( vec3_origin, evalState.axis[ 0 ], inputMove.y );
evalState.surfaceMatchingQuat *= pitchRotation.ToQuat();
evalState.surfaceMatchingQuat *= yawRotation.ToQuat();
}
targetQuat = evalState.surfaceMatchingQuat;
}
/*
================
sdVehicleRigidBodyPseudoHover::CalculateYaw
================
*/
void sdVehicleRigidBodyPseudoHover::CalculateYaw( const sdVehicleInput& input ) {
// calculate the desired angular velocity for the yaw
float yawVel = -yawCoeff * input.GetSteerAngle() * input.GetForce() * 0.04f;
if ( input.GetForward() < 0.0f ) {
yawVel = -yawVel;
}
evalState.steeringAngVel = evalState.axis[ 2 ] * yawVel;
// ramp the steering based on park mode
float parkTimeRemaining = 1.0f;
if ( startParkTime != 0 ) {
parkTimeRemaining = parkTime - MS2SEC( gameLocal.time - startParkTime );
} else if ( endParkTime != 0 ) {
parkTimeRemaining = MS2SEC( gameLocal.time - endParkTime );
}
parkTimeRemaining /= parkTime;
parkTimeRemaining = idMath::ClampFloat( 0.0f, 1.0f, parkTimeRemaining );
evalState.steeringAngVel *= parkTimeRemaining;
float rotation = RAD2DEG( -yawVel * parkTimeRemaining * evalState.timeStep * 3.0f );
idRotation rot( vec3_origin, evalState.axis[ 2 ], rotation );
idQuat rotQuat = rot.ToQuat();
targetQuat = targetQuat * rotQuat;
}
/*
================
sdVehicleRigidBodyPseudoHover::ChooseParkPosition
================
*/
void sdVehicleRigidBodyPseudoHover::ChooseParkPosition() {
// The method here: - Cast down from all the corners of the bounds, & the main bounds
// - Use those to estimate an angle to park at
// - Cast the bounds down using the average normal to find the ground
// - Find a position offset above the ground to park at
grounded = false;
// do the downward casts
float midHeight = ( mainBounds[ 0 ].z + mainBounds[ 1 ].z ) * 0.5f;
idVec3 castOffset = midHeight * evalState.axis[ 2 ];
const idVec3& upVector = evalState.axis[ 2 ];
idVec3 traceVector( 0.0f, 0.0f, -1024.0f );
idVec3 start = evalState.origin;
idVec3 end = start + traceVector;
memset( &groundTrace, 0, sizeof( groundTrace ) );
evalState.clipLocale.Translation( CLIP_DEBUG_PARMS groundTrace, start, end, mainClipModel, evalState.axis, MASK_PSEUDOHOVERCLIP );
grounded |= groundTrace.fraction < 1.0f;
idVec3 mainBodyEndPoint = groundTrace.endpos;
idVec3 mainBodyNormal = groundTrace.c.normal;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugBounds( colorGreen, mainBounds, evalState.origin, evalState.axis, 10000 );
}
// front
memset( &groundTrace, 0, sizeof( groundTrace ) );
start = evalState.origin + mainBounds[ 1 ].x * evalState.axis[ 0 ] + castOffset;
end = start + traceVector;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end , MASK_PSEUDOHOVERCLIP );
grounded |= groundTrace.fraction < 1.0f;
idVec3 frontEndPoint = groundTrace.endpos;
idVec3 frontNormal = groundTrace.c.normal;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorGreen, start, frontEndPoint, 4, 10000 );
}
// back
memset( &groundTrace, 0, sizeof( groundTrace ) );
start = evalState.origin + mainBounds[ 0 ].x * evalState.axis[ 0 ] + castOffset;
end = start + traceVector;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end , MASK_PSEUDOHOVERCLIP );
grounded |= groundTrace.fraction < 1.0f;
idVec3 backEndPoint = groundTrace.endpos;
idVec3 backNormal = groundTrace.c.normal;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorGreen, start, backEndPoint, 4, 10000 );
}
// left
memset( &groundTrace, 0, sizeof( groundTrace ) );
start = evalState.origin + mainBounds[ 1 ].y * evalState.axis[ 1 ] + castOffset;
end = start + traceVector;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end , MASK_PSEUDOHOVERCLIP );
grounded |= groundTrace.fraction < 1.0f;
idVec3 leftEndPoint = groundTrace.endpos;
idVec3 leftNormal = groundTrace.c.normal;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorGreen, start, leftEndPoint, 4, 10000 );
}
// right
memset( &groundTrace, 0, sizeof( groundTrace ) );
start = evalState.origin + mainBounds[ 0 ].y * evalState.axis[ 1 ] + castOffset;
end = start + traceVector;
evalState.clipLocale.TracePoint( CLIP_DEBUG_PARMS groundTrace, start, end , MASK_PSEUDOHOVERCLIP );
grounded |= groundTrace.fraction < 1.0f;
idVec3 rightEndPoint = groundTrace.endpos;
idVec3 rightNormal = groundTrace.c.normal;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorGreen, start, rightEndPoint, 4, 10000 );
}
if ( !grounded ) {
evalState.surfaceNormal = vec3_origin;
return;
}
//
// Use the info gleaned to estimate a surface normal
//
// Calculate the pitch angle of the surface
idVec3 frontBack = frontEndPoint - backEndPoint;
idVec3 frontBackDir = frontBack;
frontBackDir.Normalize();
float pitchAngle = idMath::ACos( idVec3( 0.0f, 0.0f, 1.0f ) * frontBackDir ) * idMath::M_RAD2DEG - 90.0f;
// Calculate the roll angle of the surface
idVec3 leftRight = rightEndPoint - leftEndPoint;
idVec3 leftRightDir = leftRight;
leftRightDir.Normalize();
float rollAngle = idMath::ACos( idVec3( 0.0f, 0.0f, 1.0f ) * leftRightDir ) * idMath::M_RAD2DEG - 90.0f;
float yawAngle = evalState.axis.ToAngles().yaw;
idAngles newAngles( pitchAngle, yawAngle, rollAngle );
idMat3 chosenAxis = newAngles.ToMat3();
chosenParkAxis = chosenAxis;
// now cast the main body down with that normal as its
start = evalState.origin;
end = start - 1024.0f * chosenParkAxis[ 2 ];
memset( &groundTrace, 0, sizeof( groundTrace ) );
evalState.clipLocale.Translation( CLIP_DEBUG_PARMS groundTrace, start, end, mainClipModel, chosenAxis, MASK_PSEUDOHOVERCLIP );
chosenParkOrigin = groundTrace.endpos + chosenParkAxis[ 2 ] * parkHeight;
foundPark = true;
if ( g_debugVehiclePseudoHover.GetBool() ) {
gameRenderWorld->DebugArrow( colorRed, chosenParkOrigin, chosenParkOrigin + chosenAxis[ 0 ] * 128.0f, 4, 10000 );
gameRenderWorld->DebugArrow( colorGreen, chosenParkOrigin, chosenParkOrigin + chosenAxis[ 1 ] * 128.0f, 4, 10000 );
gameRenderWorld->DebugArrow( colorBlue, chosenParkOrigin, chosenParkOrigin + chosenAxis[ 2 ] * 128.0f, 4, 10000 );
}
}
/*
================
sdVehicleRigidBodyPseudoHover::DoParkRepulsors
================
*/
void sdVehicleRigidBodyPseudoHover::DoParkRepulsors() {
//
// Park mode hovering
//
float timeRemaining = parkTime - MS2SEC( gameLocal.time - startParkTime );
if ( timeRemaining < evalState.timeStep ) {
timeRemaining = evalState.timeStep;
}
if ( !foundPark ) {
chosenParkAxis = evalState.axis;
chosenParkOrigin = evalState.origin;
}
evalState.surfaceNormal = chosenParkAxis[ 2 ];
idVec3 distToMove = chosenParkOrigin - evalState.origin;
assert( chosenParkAxis[ 2 ] != vec3_origin );
if ( chosenParkAxis[ 2 ] == vec3_origin ) {
return;
}
float distToMoveLength = distToMove.Length();
if ( distToMoveLength < 25.0f ) {
lockedPark = true;
}
if ( distToMoveLength > 512.0f ) {
lockedPark = false;
}
idVec3 neededAcceleration;
if ( distToMoveLength < 10.0f ) {
// close enough! just figure out how to cancel out our existing velocity
neededAcceleration = -0.2f * evalState.linVelocity / evalState.timeStep;
} else {
// figure out a velocity to reach that point in the time remaining
idVec3 neededVelocity = distToMove / timeRemaining;
float neededVelocityLength = neededVelocity.Length();
if ( neededVelocityLength > 100.0f ) {
neededVelocity *= 100.0f / neededVelocityLength;
}
// figure out what acceleration is needed to get to that velocity in the next frame
idVec3 vDelta = neededVelocity - evalState.linVelocity;
neededAcceleration = vDelta / evalState.timeStep;
}
// make sure nothing ridiculous is happening with the acceleration
float accelLength = neededAcceleration.Length();
if ( accelLength > 500.0f ) {
neededAcceleration *= 500.0f / accelLength;
}
neededAcceleration -= evalState.gravity;
evalState.hoverForce = neededAcceleration * evalState.mass;
}
/*
================
sdVehicleRigidBodyPseudoHover::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyPseudoHover::UpdatePrePhysics( const sdVehicleInput& input ) {
evalState.physics = parent->GetPhysics()->Cast< sdPhysics_RigidBodyMultiple >();
if ( evalState.physics == NULL ) {
return;
}
if ( mainClipModel == NULL ) {
mainBounds.Clear();
for ( int i = 0; i < evalState.physics->GetNumClipModels(); i++ ) {
int contents = evalState.physics->GetContents( i );
if ( contents && contents != MASK_HURTZONE ) {
idBounds bounds = evalState.physics->GetBounds( i );
bounds.TranslateSelf( evalState.physics->GetBodyOffset( i ) );
mainBounds.AddBounds( bounds );
}
}
mainClipModel = new idClipModel( idTraceModel( mainBounds ), false );
}
evalState.timeStep = MS2SEC( gameLocal.msec );
evalState.driver = parent->GetPositionManager().FindDriver();
// get the set of clip models to trace against
idBounds localeBounds = mainBounds;
localeBounds[ 0 ].z -= hoverHeight;
evalState.clipLocale.Update( localeBounds, evalState.physics->GetOrigin(), evalState.physics->GetAxis(),
evalState.physics->GetLinearVelocity(), evalState.physics->GetAngularVelocity(),
MASK_PSEUDOHOVERCLIP, parent );
evalState.clipLocale.RemoveEntitiesOfCollection( "vehicles" );
evalState.clipLocale.RemoveEntitiesOfCollection( "deployables" );
// see if its too steep to go into siege mode
bool wantsHandBrake = input.GetHandBraking();
if ( wantsHandBrake ) {
float angleBetween = idMath::ACos( idVec3( 0.0f, 0.0f, 1.0f ) * evalState.surfaceNormal ) * idMath::M_RAD2DEG;
if ( angleBetween > maxSlope ) {
wantsHandBrake = false;
parent->GetVehicleControl()->CancelSiegeMode();
}
}
if ( parkMode && ( !wantsHandBrake || !grounded ) && !parent->IsEMPed() ) {
parkMode = false;
foundPark = false;
lockedPark = false;
startParkTime = 0;
endParkTime = gameLocal.time;
if ( gameLocal.time - lastUnparkEffectTime > 500 ) {
parent->PlayEffect( "fx_park_disengage", colorWhite.ToVec3(), NULL, effectJoint );
if ( oldDriver != NULL ) {
parent->StartSound( "snd_park_disengage", SND_VEHICLE_MISC, SND_VEHICLE_MISC, 0, NULL );
}
lastUnparkEffectTime = gameLocal.time;
}
} else if ( ( parent->IsEMPed() || wantsHandBrake ) && !parkMode && grounded ) {
parkMode = true;
foundPark = false;
lockedPark = false;
startParkTime = gameLocal.time;
lastParkUpdateTime = 0;
endParkTime = 0;
if ( gameLocal.time - lastParkEffectTime > 500 ) {
parent->PlayEffect( "fx_park_engage", colorWhite.ToVec3(), NULL, effectJoint );
if ( evalState.driver != NULL ) {
parent->StartSound( "snd_park_engage", SND_VEHICLE_MISC, SND_VEHICLE_MISC, 0, NULL );
}
lastParkEffectTime = gameLocal.time;
}
}
oldDriver = evalState.driver;
// inform the vehicle control if we've finished parking or not
sdVehicleControlBase* control = parent->GetVehicleControl();
if ( control != NULL ) {
control->SetSiegeMode( lockedPark );
}
//
// Harvest data
//
evalState.origin = evalState.physics->GetOrigin();
evalState.axis = evalState.physics->GetAxis();
evalState.mass = evalState.physics->GetMass( -1 );
evalState.gravity = evalState.physics->GetGravity();
evalState.linVelocity = evalState.physics->GetLinearVelocity() + evalState.gravity * evalState.timeStep;
evalState.angVelocity = evalState.physics->GetAngularVelocity();
evalState.inertiaTensor = evalState.physics->GetInertiaTensor();
//
// Handle park updating
//
if ( !gameLocal.isClient ) {
// HACK: seek new parking places when in contact with an MCP
if ( parkMode && lockedPark ) {
for ( int i = 0; i < evalState.physics->GetNumContacts(); i++ ) {
const contactInfo_t& contact = evalState.physics->GetContact( i );
idEntity* contactEnt = gameLocal.entities[ contact.entityNum ];
if ( contactEnt != NULL && contactEnt->Cast< sdTransport >() != NULL ) {
if ( !contactEnt->IsCollisionPushable() ) {
lockedPark = false;
foundPark = false;
}
}
}
}
// try picking a place to park
if ( parkMode && ( !foundPark || gameLocal.time > lastParkUpdateTime + 750 ) && !lockedPark ) {
foundPark = false;
ChooseParkPosition();
lastParkUpdateTime = gameLocal.time;
}
} else {
// clients do a simplified form of what the server does, just so they can
// predict the initial park location and start the process - otherwise they'll
// continually override what the server tells them to do
if ( parkMode && !foundPark && gameLocal.isNewFrame ) {
ChooseParkPosition();
}
}
//
// Hovering
//
if ( !parkMode ) {
DoRepulsors();
} else if ( !lockedPark ) {
DoParkRepulsors();
}
if ( !lockedPark ) {
CalculateSurfaceAxis();
CalculateDrivingForce( input );
CalculateFrictionForce( input );
CalculateTilting( input );
CalculateYaw( input );
idVec3 force = evalState.drivingForce + evalState.frictionForce + evalState.hoverForce;
targetVelocity = evalState.linVelocity + evalState.timeStep * force / evalState.mass;
evalState.physics->Activate();
}
}
/*
================
sdVehicleRigidBodyPseudoHover::UpdatePostPhysics
================
*/
void sdVehicleRigidBodyPseudoHover::UpdatePostPhysics( const sdVehicleInput& input ) {
}
/*
================
sdVehicleRigidBodyPseudoHover::AddCustomConstraints
================
*/
const float CONTACT_LCP_EPSILON = 1e-8f;
int sdVehicleRigidBodyPseudoHover::AddCustomConstraints( constraintInfo_t* list, int max ) {
if ( !grounded ) {
return 0;
}
idPhysics* parentPhysics = parent->GetPhysics();
idVec3 targVel = vec3_origin;
idVec3 targAngVel = vec3_origin;
idQuat toQuat;
float angVelDamp = 0.05f;
if ( !lockedPark ) {
targVel = targetVelocity;
toQuat = targetQuat;
} else {
idVec3 delta = 0.2f * ( chosenParkOrigin - parentPhysics->GetOrigin() );
delta /= MS2SEC( gameLocal.msec );
delta *= 0.5f;
targVel = delta;
toQuat = chosenParkAxis.ToQuat();
angVelDamp = 0.1f;
}
idQuat fromQuat = parentPhysics->GetAxis().ToQuat();
idQuat diffQuat = toQuat.Inverse() * fromQuat;
targAngVel = ( diffQuat.ToAngularVelocity() - parentPhysics->GetAngularVelocity() * angVelDamp ) / MS2SEC( gameLocal.msec );
//
// LINEAR VELOCITY
//
idVec3 comWorld = parentPhysics->GetCenterOfMass() * parentPhysics->GetAxis() + parentPhysics->GetOrigin();
// add the position matching constraints
constraintInfo_t& vx = list[ 0 ];
constraintInfo_t& vy = list[ 1 ];
constraintInfo_t& vz = list[ 2 ];
vx.j.SubVec3( 0 ).Set( 1.0f, 0.0f, 0.0f );
vy.j.SubVec3( 0 ).Set( 0.0f, 1.0f, 0.0f );
vz.j.SubVec3( 0 ).Set( 0.0f, 0.0f, 1.0f );
vx.j.SubVec3( 1 ).Zero();
vy.j.SubVec3( 1 ).Zero();
vz.j.SubVec3( 1 ).Zero();
vx.boxIndex = vy.boxIndex = vz.boxIndex = -1;
vx.error = vy.error = vz.error = CONTACT_LCP_EPSILON;
vx.pos = vy.pos = vz.pos = comWorld;
vx.lm = vy.lm = vz.lm = 0.0f;
vx.c = -targVel.x;
vy.c = -targVel.y;
vz.c = -targVel.z;
// calculate the force needed to make it in one frame
idVec3 force = ( targVel - parentPhysics->GetLinearVelocity() ) / MS2SEC( gameLocal.msec );
// limit the max acceleration
float forceLength = force.Normalize();
if ( forceLength > 4000.0f ) {
forceLength = 4000.0f;
}
force = force * forceLength;
force -= parentPhysics->GetGravity();
force *= parentPhysics->GetMass();
if ( force.x < 0.0f ) {
vx.lo = force.x;
vx.hi = 0.0f;
} else {
vx.hi = force.x;
vx.lo = 0.0f;
}
if ( force.y < 0.0f ) {
vy.lo = force.y;
vy.hi = 0.0f;
} else {
vy.hi = force.y;
vy.lo = 0.0f;
}
if ( force.z < 0.0f ) {
vz.lo = force.z;
vz.hi = 0.0f;
} else {
vz.hi = force.z;
vz.lo = 0.0f;
}
//
// ANGULAR VELOCITY
//
constraintInfo_t& wx = list[ 3 ];
constraintInfo_t& wy = list[ 4 ];
constraintInfo_t& wz = list[ 5 ];
wx.j.SubVec3( 0 ).Zero();
wy.j.SubVec3( 0 ).Zero();
wz.j.SubVec3( 0 ).Zero();
wx.j.SubVec3( 1 ).Set( 1.0f, 0.0f, 0.0f );
wy.j.SubVec3( 1 ).Set( 0.0f, 1.0f, 0.0f );
wz.j.SubVec3( 1 ).Set( 0.0f, 0.0f, 1.0f );
wx.boxIndex = wy.boxIndex = wz.boxIndex = -1;
wx.error = wy.error = wz.error = CONTACT_LCP_EPSILON;
wx.pos = wy.pos = wz.pos = comWorld;
wx.lm = wy.lm = wz.lm = 0.0f;
wx.c = -targAngVel.x;
wy.c = -targAngVel.y;
wz.c = -targAngVel.z;
// calculate the alpha needed to achieve the desired angular movements
idVec3 alpha = ( targAngVel - parentPhysics->GetAngularVelocity() ) / MS2SEC( gameLocal.msec );
// limit the max acceleration
float alphaLength = alpha.Normalize();
if ( alphaLength > 400.0f ) {
alphaLength = 400.0f;
}
alpha = alpha * alphaLength;
alpha *= parentPhysics->GetInertiaTensor();
if ( alpha.x < 0.0f ) {
wx.lo = alpha.x;
wx.hi = 0.0f;
} else {
wx.hi = alpha.x;
wx.lo = 0.0f;
}
if ( alpha.y < 0.0f ) {
wy.lo = alpha.y;
wy.hi = 0.0f;
} else {
wy.hi = alpha.y;
wy.lo = 0.0f;
}
if ( alpha.z < 0.0f ) {
wz.lo = alpha.z;
wz.hi = 0.0f;
} else {
wz.hi = alpha.z;
wz.lo = 0.0f;
}
return 6;
}
/*
================
sdVehicleRigidBodyPseudoHover::CreateNetworkStructure
================
*/
sdEntityStateNetworkData* sdVehicleRigidBodyPseudoHover::CreateNetworkStructure( networkStateMode_t mode ) const {
if ( mode == NSM_BROADCAST ) {
return new sdPseudoHoverBroadcastData;
}
if ( mode == NSM_VISIBLE ) {
return new sdPseudoHoverNetworkData;
}
return NULL;
}
/*
================
sdVehicleRigidBodyPseudoHover::CheckNetworkStateChanges
================
*/
bool sdVehicleRigidBodyPseudoHover::CheckNetworkStateChanges( networkStateMode_t mode, const sdEntityStateNetworkData& baseState ) const {
if ( mode == NSM_BROADCAST ) {
NET_GET_BASE( sdPseudoHoverBroadcastData );
NET_CHECK_FIELD( parkMode, parkMode );
NET_CHECK_FIELD( foundPark, foundPark );
NET_CHECK_FIELD( lockedPark, lockedPark );
NET_CHECK_FIELD( startParkTime, startParkTime );
NET_CHECK_FIELD( endParkTime, endParkTime );
NET_CHECK_FIELD( lastParkUpdateTime, lastParkUpdateTime );
NET_CHECK_FIELD( chosenParkOrigin, chosenParkOrigin );
NET_CHECK_FIELD( chosenParkAxis, chosenParkAxis );
return false;
}
if ( mode == NSM_VISIBLE ) {
NET_GET_BASE( sdPseudoHoverNetworkData );
NET_CHECK_FIELD( lastFrictionScale, lastFrictionScale );
return false;
}
return false;
}
/*
================
sdVehicleRigidBodyPseudoHover::WriteNetworkState
================
*/
void sdVehicleRigidBodyPseudoHover::WriteNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, idBitMsg& msg ) const {
if ( mode == NSM_BROADCAST ) {
NET_GET_STATES( sdPseudoHoverBroadcastData );
newData.parkMode = parkMode;
newData.foundPark = foundPark;
newData.lockedPark = lockedPark;
newData.startParkTime = startParkTime;
newData.endParkTime = endParkTime;
newData.lastParkUpdateTime = lastParkUpdateTime;
newData.chosenParkOrigin = chosenParkOrigin;
newData.chosenParkAxis = chosenParkAxis;
msg.WriteBool( newData.parkMode );
msg.WriteBool( newData.foundPark );
msg.WriteBool( newData.lockedPark );
msg.WriteDeltaLong( baseData.startParkTime, newData.startParkTime );
msg.WriteDeltaLong( baseData.endParkTime, newData.endParkTime );
msg.WriteDeltaLong( baseData.lastParkUpdateTime, newData.lastParkUpdateTime );
msg.WriteDeltaVector( baseData.chosenParkOrigin, newData.chosenParkOrigin );
msg.WriteDeltaCQuat( baseData.chosenParkAxis.ToCQuat(), newData.chosenParkAxis.ToCQuat() );
return;
}
if ( mode == NSM_VISIBLE ) {
NET_GET_STATES( sdPseudoHoverNetworkData );
newData.lastFrictionScale = lastFrictionScale;
msg.WriteDeltaFloat( baseData.lastFrictionScale, newData.lastFrictionScale );
return;
}
}
/*
================
sdVehicleRigidBodyPseudoHover::ReadNetworkState
================
*/
void sdVehicleRigidBodyPseudoHover::ReadNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, const idBitMsg& msg ) const {
if ( mode == NSM_VISIBLE ) {
NET_GET_STATES( sdPseudoHoverNetworkData );
newData.lastFrictionScale = msg.ReadDeltaFloat( baseData.lastFrictionScale );
return;
}
if ( mode == NSM_BROADCAST ) {
NET_GET_STATES( sdPseudoHoverBroadcastData );
newData.parkMode = msg.ReadBool();
newData.foundPark = msg.ReadBool();
newData.lockedPark = msg.ReadBool();
newData.startParkTime = msg.ReadDeltaLong( baseData.startParkTime );
newData.endParkTime = msg.ReadDeltaLong( baseData.endParkTime );
newData.lastParkUpdateTime = msg.ReadDeltaLong( baseData.lastParkUpdateTime );
newData.chosenParkOrigin = msg.ReadDeltaVector( baseData.chosenParkOrigin );
idCQuat readQuat = msg.ReadDeltaCQuat( baseData.chosenParkAxis.ToCQuat() );
newData.chosenParkAxis = readQuat.ToMat3();
return;
}
}
/*
================
sdVehicleRigidBodyPseudoHover::ApplyNetworkState
================
*/
void sdVehicleRigidBodyPseudoHover::ApplyNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& newState ) {
if ( mode == NSM_VISIBLE ) {
NET_GET_NEW( sdPseudoHoverNetworkData );
lastFrictionScale = newData.lastFrictionScale;
return;
}
if ( mode == NSM_BROADCAST ) {
NET_GET_NEW( sdPseudoHoverBroadcastData );
parkMode = newData.parkMode;
foundPark = newData.foundPark;
lockedPark = newData.lockedPark;
startParkTime = newData.startParkTime;
endParkTime = newData.endParkTime;
lastParkUpdateTime = newData.lastParkUpdateTime;
chosenParkOrigin = newData.chosenParkOrigin;
chosenParkAxis = newData.chosenParkAxis;
return;
}
}
/*
================
sdPseudoHoverNetworkData::MakeDefault
================
*/
void sdPseudoHoverNetworkData::MakeDefault( void ) {
lastFrictionScale = 1.0f;
}
/*
================
sdPseudoHoverNetworkData::Write
================
*/
void sdPseudoHoverNetworkData::Write( idFile* file ) const {
file->WriteFloat( lastFrictionScale );
}
/*
================
sdPseudoHoverNetworkData::Read
================
*/
void sdPseudoHoverNetworkData::Read( idFile* file ) {
file->ReadFloat( lastFrictionScale );
}
/*
================
sdPseudoHoverBroadcastData::MakeDefault
================
*/
void sdPseudoHoverBroadcastData::MakeDefault( void ) {
parkMode = false;
foundPark = false;
lockedPark = false;
startParkTime = 0;
endParkTime = gameLocal.time;
lastParkUpdateTime = 0;
chosenParkOrigin.Zero();
chosenParkAxis.Identity();
}
/*
================
sdPseudoHoverBroadcastData::Write
================
*/
void sdPseudoHoverBroadcastData::Write( idFile* file ) const {
file->WriteBool( parkMode );
file->WriteBool( foundPark );
file->WriteBool( lockedPark );
file->WriteInt( startParkTime );
file->WriteInt( endParkTime );
file->WriteInt( lastParkUpdateTime );
file->WriteVec3( chosenParkOrigin );
file->WriteMat3( chosenParkAxis );
}
/*
================
sdPseudoHoverBroadcastData::Read
================
*/
void sdPseudoHoverBroadcastData::Read( idFile* file ) {
file->ReadBool( parkMode );
file->ReadBool( foundPark );
file->ReadBool( lockedPark );
file->ReadInt( startParkTime );
file->ReadInt( endParkTime );
file->ReadInt( lastParkUpdateTime );
file->ReadVec3( chosenParkOrigin );
file->ReadMat3( chosenParkAxis );
}
/*
===============================================================================
sdVehicleRigidBodyDragPlane
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehicleRigidBodyDragPlane )
END_CLASS
/*
================
sdVehicleRigidBodyDragPlane::sdVehicleRigidBodyDragPlane
================
*/
sdVehicleRigidBodyDragPlane::sdVehicleRigidBodyDragPlane( void ) {
}
/*
================
sdVehicleRigidBodyDragPlane::~sdVehicleRigidBodyDragPlane
================
*/
sdVehicleRigidBodyDragPlane::~sdVehicleRigidBodyDragPlane( void ) {
}
/*
================
sdVehicleRigidBodyDragPlane::Init
================
*/
void sdVehicleRigidBodyDragPlane::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehiclePart::Init( part );
parent = _parent;
coefficient = part.data.GetFloat( "coefficient" );
maxForce = part.data.GetFloat( "max_force" );
minForce = part.data.GetFloat( "min_force" );
origin = part.data.GetVector( "origin" );
normal = part.data.GetVector( "normal" );
normal.Normalize();
doubleSided = part.data.GetBool( "double_sided" );
useAngleScale = part.data.GetBool( "use_angle_scale" );
}
/*
================
sdVehicleRigidBodyDragPlane::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyDragPlane::UpdatePrePhysics( const sdVehicleInput& input ) {
idPhysics* physics = parent->GetPhysics();
idVec3 parentOrigin = physics->GetOrigin();
idVec3 velocity = physics->GetLinearVelocity();
idMat3 axis = physics->GetAxis();
idVec3 worldNormal = normal * axis;
idVec3 worldOrigin = parentOrigin + ( origin * axis );
idVec3 dragForce = vec3_zero;
// calculate the component of the velocity in the normal direction
float normalVel = velocity * worldNormal;
// only velocity INTO the surface is considered relevant
if ( !doubleSided && normalVel < 0.0f ) {
return;
}
float angleScale = 1.0f;
if ( useAngleScale ) {
// simulate the plane only being in contact for some of the time (ie, boat rising out of the water)
idAngles angles = axis.ToAngles();
angleScale = 7.5f - fabs( angles.pitch );
angleScale = idMath::ClampFloat( 0.0f, 7.5f, angleScale ) / 7.5f;
const idVec3& gravity = physics->GetGravityNormal();
if ( axis[ 2 ] * gravity < -0.7f ) {
idVec3 temp = velocity - ( ( velocity * gravity ) * gravity );
if ( temp.LengthSqr() > Square( 10.f ) ) {
// do a HORRIBLE HACK to keep the rear end of the boat out of the water
const idBounds& bounds = parent->GetPhysics()->GetBounds();
float rearDist = bounds[ 0 ].x;
idVec3 rear( rearDist, 0.0f, 24.0f );
idVec3 worldRear = parentOrigin + rear * axis;
// check if it is in the water
int cont = gameLocal.clip.Contents( CLIP_DEBUG_PARMS worldRear, NULL, mat3_identity, CONTENTS_WATER, parent );
if ( cont ) {
// find the top of the water
// TWTODO (Post-E3): Calculate this without using a trace!
trace_t trace;
idVec3 traceStart = worldRear;
traceStart.z = parentOrigin.z + 24.0f;
gameLocal.clip.TracePoint( CLIP_DEBUG_PARMS trace, traceStart, worldRear, CONTENTS_WATER, parent );
idVec3 waterSurfacePoint = trace.endpos;
// End TWTODO
//gameRenderWorld->DebugArrow( colorRed, worldRear, waterSurfacePoint, 2.0f );
float dropDist = trace.endpos.z - worldRear.z;
// figure out what velocity it needs to push itself out of the water enough
float timeStep = MS2SEC( gameLocal.msec );
float pushOutVel = 0.5f * dropDist / timeStep;
if ( pushOutVel > velocity.z ) {
// ok so its not scaling it by the force, but it just wants a slight nudge up
float accelToPushOut = 0.5f * ( pushOutVel - velocity.z ) / timeStep;
parent->GetPhysics()->AddForce( 0, worldRear, idVec3( 0.0f, 0.0f, accelToPushOut ) );
}
}
}
}
}
// calculate the amount of drag caused by this
float drag = coefficient * normalVel * normalVel;
if ( drag > maxForce ) {
drag = maxForce;
} else if ( drag <= minForce ) {
return;
}
// calculate the drag force
dragForce = -drag * angleScale * worldNormal;
// apply the drag force
parent->GetPhysics()->AddForce( 0, worldOrigin, dragForce );
// gameRenderWorld->DebugLine( colorGreen, worldOrigin, worldOrigin + dragForce * 0.0001f );
}
/*
================
sdVehicleRigidBodyDragPlane::UpdatePostPhysics
================
*/
void sdVehicleRigidBodyDragPlane::UpdatePostPhysics( const sdVehicleInput& input ) {
}
/*
===============================================================================
sdVehicleRigidBodyRudder
===============================================================================
*/
CLASS_DECLARATION( sdVehicleRigidBodyDragPlane, sdVehicleRigidBodyRudder )
END_CLASS
/*
================
sdVehicleRigidBodyRudder::Init
================
*/
void sdVehicleRigidBodyRudder::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehicleRigidBodyDragPlane::Init( part, _parent );
}
/*
================
sdVehicleRigidBodyRudder::UpdatePrePhysics
================
*/
void sdVehicleRigidBodyRudder::UpdatePrePhysics( const sdVehicleInput& input ) {
float oldCoefficient = coefficient;
idVec3 oldOrigin = origin;
float right = input.GetRight();
if ( right != 0.f ) {
origin.y += right * -600.0f;
coefficient *= fabs( right );
normal.x = 1.0f;
normal.y = 0.0f;
normal.z = 0.0f;
sdVehicleRigidBodyDragPlane::UpdatePrePhysics( input );
}
coefficient = oldCoefficient;
origin = oldOrigin;
}
/*
===============================================================================
sdVehicleRigidBodyHurtZone
===============================================================================
*/
idCVar g_debugVehicleHurtZones( "g_debugVehicleHurtZones", "0", CVAR_GAME | CVAR_BOOL | CVAR_CHEAT, "show info about the hurtZone component" );
CLASS_DECLARATION( sdVehiclePart, sdVehicleRigidBodyHurtZone )
END_CLASS
/*
================
sdVehicleRigidBodyHurtZone::Init
================
*/
void sdVehicleRigidBodyHurtZone::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehicleRigidBodyPart::Init( part, _parent );
maxHealth = health = -1.0f;
sdPhysics_RigidBodyMultiple& rigidBody = *_parent->GetRBPhysics();
rigidBody.SetContactFriction( bodyId, vec3_origin );
rigidBody.SetMass( 1.0f, bodyId );
rigidBody.SetBodyBuoyancy( bodyId, 0.0f );
rigidBody.SetClipMask( MASK_HURTZONE, bodyId );
rigidBody.SetContents( MASK_HURTZONE, bodyId );
}
/*
===============================================================================
sdVehicleAntiRoll
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehicleAntiRoll )
END_CLASS
/*
================
sdVehicleAntiRoll::sdVehicleAntiRoll
================
*/
sdVehicleAntiRoll::sdVehicleAntiRoll( void ) {
}
/*
================
sdVehicleAntiRoll::~sdVehicleAntiRoll
================
*/
sdVehicleAntiRoll::~sdVehicleAntiRoll( void ) {
}
/*
================
sdVehicleAntiRoll::Init
================
*/
void sdVehicleAntiRoll::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehiclePart::Init( part );
parent = _parent;
currentStrength = 0.0f;
active = false;
startAngle = part.data.GetFloat( "angle_start", "15" );
endAngle = part.data.GetFloat( "angle_end", "45" );
strength = part.data.GetFloat( "strength", "1" );
needsGround = part.data.GetBool( "needs_ground", "1" );
if ( endAngle <= startAngle + 0.1f ) {
endAngle = startAngle + 0.1f;
}
}
/*
================
sdVehicleAntiRoll::UpdatePrePhysics
================
*/
void sdVehicleAntiRoll::UpdatePrePhysics( const sdVehicleInput& input ) {
assert( parent != NULL );
active = false;
if ( parent->GetPositionManager().FindDriver() == NULL ) {
return;
}
// use the ground contacts & water level to figure out if we should apply
// cos flipping whilst in the air is kinda cool! ;)
sdPhysics_RigidBodyMultiple* parentPhysics = parent->GetRBPhysics();
if ( !needsGround || parentPhysics->HasGroundContacts() || parentPhysics->InWater() ) {
idAngles myAngles = parentPhysics->GetAxis().ToAngles();
myAngles.Normalize180();
idAngles levelAngles( myAngles.pitch, myAngles.yaw, 0.0f );
idMat3 levelAxis = levelAngles.ToMat3();
// find the angle from the vertical
idVec3 currentUp = parentPhysics->GetAxis()[ 2 ];
float angleBetween = idMath::Fabs( idMath::ACos( levelAxis[ 2 ] * currentUp ) ) * idMath::M_RAD2DEG;
if ( angleBetween < startAngle ) {
return;
}
active = true;
if ( angleBetween > endAngle ) {
angleBetween = endAngle;
}
currentStrength = strength * ( angleBetween - startAngle ) / ( endAngle - startAngle );
}
}
/*
================
sdVehicleAntiRoll::UpdatePostPhysics
================
*/
void sdVehicleAntiRoll::UpdatePostPhysics( const sdVehicleInput& input ) {
}
/*
================
sdVehicleAntiRoll::AddCustomConstraints
================
*/
int sdVehicleAntiRoll::AddCustomConstraints( constraintInfo_t* list, int max ) {
if ( !active ) {
return 0;
}
//
// LIMIT ROLLING
// unidirectional rotation constraint away from current direction we exceed allowed in
//
idPhysics* parentPhysics = parent->GetPhysics();
const idMat3& axis = parentPhysics->GetAxis();
idVec3 comWorld = parentPhysics->GetCenterOfMass() * axis + parentPhysics->GetOrigin();
idAngles angles = axis.ToAngles();
angles.Normalize180();
// figure out the velocity needed to get back to the allowed roll range
idAngles clampedAngles = angles;
clampedAngles.roll = idMath::ClampFloat( -endAngle, endAngle, clampedAngles.roll );
float angVelDamp = 0.05f;
idAngles diffAngles = clampedAngles - angles;
diffAngles.Normalize180();
// clamp the diff angles so that it doesn't try to achieve something totally insane
diffAngles.roll = idMath::ClampFloat( -5.0f, 5.0f, diffAngles.roll );
float rollVelocity = parentPhysics->GetAngularVelocity() * axis[ 0 ];
float neededVelocity = DEG2RAD( diffAngles.roll / MS2SEC( gameLocal.msec ) );
float targetRollVel = neededVelocity - rollVelocity * angVelDamp;
// figure out angular impulse needed
float rollImpulse = currentStrength * ( targetRollVel - rollVelocity ) / MS2SEC( gameLocal.msec );
rollImpulse *= ( parentPhysics->GetInertiaTensor() * axis[ 0 ] ) * axis[ 0 ];
if ( idMath::Fabs( rollImpulse ) < idMath::FLT_EPSILON ) {
return 0;
}
// set up the constraint
constraintInfo_t& wx = list[ 0 ];
wx.j.SubVec3( 0 ).Zero();
wx.j.SubVec3( 1 ) = parentPhysics->GetAxis()[ 0 ];
wx.boxIndex = -1;
wx.error = CONTACT_LCP_EPSILON;
wx.pos = comWorld;
wx.lm = 0.0f;
wx.c = -targetRollVel;
if ( rollImpulse < 0.0f ) {
wx.lo = rollImpulse;
wx.hi = 0.0f;
} else {
wx.hi = rollImpulse;
wx.lo = 0.0f;
}
return 1;
}
/*
===============================================================================
sdVehicleAntiPitch
===============================================================================
*/
CLASS_DECLARATION( sdVehiclePart, sdVehicleAntiPitch )
END_CLASS
/*
================
sdVehicleAntiPitch::sdVehicleAntiPitch
================
*/
sdVehicleAntiPitch::sdVehicleAntiPitch( void ) {
}
/*
================
sdVehicleAntiPitch::~sdVehicleAntiPitch
================
*/
sdVehicleAntiPitch::~sdVehicleAntiPitch( void ) {
}
/*
================
sdVehicleAntiPitch::Init
================
*/
void sdVehicleAntiPitch::Init( const sdDeclVehiclePart& part, sdTransport_RB* _parent ) {
sdVehiclePart::Init( part );
parent = _parent;
currentStrength = 0.0f;
active = false;
startAngle = part.data.GetFloat( "angle_start", "15" );
endAngle = part.data.GetFloat( "angle_end", "45" );
strength = part.data.GetFloat( "strength", "1" );
needsGround = part.data.GetBool( "needs_ground", "1" );
if ( endAngle <= startAngle + 0.1f ) {
endAngle = startAngle + 0.1f;
}
}
/*
================
sdVehicleAntiPitch::UpdatePrePhysics
================
*/
void sdVehicleAntiPitch::UpdatePrePhysics( const sdVehicleInput& input ) {
assert( parent != NULL );
active = false;
if ( parent->GetPositionManager().FindDriver() == NULL ) {
return;
}
// use the ground contacts & water level to figure out if we should apply
// cos flipping whilst in the air is kinda cool! ;)
sdPhysics_RigidBodyMultiple* parentPhysics = parent->GetRBPhysics();
if ( !needsGround || parentPhysics->HasGroundContacts() || parentPhysics->InWater() ) {
idAngles myAngles = parentPhysics->GetAxis().ToAngles();
myAngles.Normalize180();
idAngles levelAngles( 0.0f, myAngles.yaw, myAngles.roll );
idMat3 levelAxis = levelAngles.ToMat3();
// find the angle from the vertical
idVec3 currentUp = parentPhysics->GetAxis()[ 2 ];
float angleBetween = idMath::Fabs( idMath::ACos( levelAxis[ 2 ] * currentUp ) ) * idMath::M_RAD2DEG;
if ( angleBetween < startAngle ) {
return;
}
active = true;
if ( angleBetween > endAngle ) {
angleBetween = endAngle;
}
currentStrength = strength * ( angleBetween - startAngle ) / ( endAngle - startAngle );
}
}
/*
================
sdVehicleAntiPitch::UpdatePostPhysics
================
*/
void sdVehicleAntiPitch::UpdatePostPhysics( const sdVehicleInput& input ) {
}
/*
================
sdVehicleAntiPitch::AddCustomConstraints
================
*/
int sdVehicleAntiPitch::AddCustomConstraints( constraintInfo_t* list, int max ) {
if ( !active ) {
return 0;
}
//
// LIMIT PITCHING
// unidirectional rotation constraint away from current direction we exceed allowed in
//
idPhysics* parentPhysics = parent->GetPhysics();
const idMat3& axis = parentPhysics->GetAxis();
idVec3 comWorld = parentPhysics->GetCenterOfMass() * axis + parentPhysics->GetOrigin();
idAngles angles = axis.ToAngles();
angles.Normalize180();
// figure out the velocity needed to get back to the allowed roll range
idAngles clampedAngles = angles;
clampedAngles.pitch = idMath::ClampFloat( -endAngle, endAngle, clampedAngles.pitch );
float angVelDamp = 0.05f;
idAngles diffAngles = clampedAngles - angles;
diffAngles.Normalize180();
// clamp the diff angles so that it doesn't try to achieve something totally insane
diffAngles.pitch = idMath::ClampFloat( -5.0f, 5.0f, diffAngles.pitch );
float pitchVelocity = parentPhysics->GetAngularVelocity() * axis[ 1 ];
float neededVelocity = DEG2RAD( diffAngles.pitch / MS2SEC( gameLocal.msec ) );
float targetPitchVel = neededVelocity - pitchVelocity * angVelDamp;
// figure out angular impulse needed
float pitchImpulse = currentStrength * ( targetPitchVel - pitchVelocity ) / MS2SEC( gameLocal.msec );
pitchImpulse *= ( parentPhysics->GetInertiaTensor() * axis[ 1 ] ) * axis[ 1 ];
if ( idMath::Fabs( pitchImpulse ) < idMath::FLT_EPSILON ) {
return 0;
}
// set up the constraint
constraintInfo_t& wx = list[ 0 ];
wx.j.SubVec3( 0 ).Zero();
wx.j.SubVec3( 1 ) = parentPhysics->GetAxis()[ 1 ];
wx.boxIndex = -1;
wx.error = CONTACT_LCP_EPSILON;
wx.pos = comWorld;
wx.lm = 0.0f;
wx.c = -targetPitchVel;
if ( pitchImpulse < 0.0f ) {
wx.lo = pitchImpulse;
wx.hi = 0.0f;
} else {
wx.hi = pitchImpulse;
wx.lo = 0.0f;
}
return 1;
}
| 30.659181 | 237 | 0.649817 | [
"render",
"object",
"vector",
"model",
"transform"
] |
4a5d005a10609fb8055d8b2e23cfda7a1e6766fa | 176 | hpp | C++ | redist/deps/flif/src/transform/factory.hpp | FrostyLeaves/spot | 703150893da7b586be772e716dab41687b85bc5b | [
"Zlib"
] | 71 | 2015-01-08T06:52:45.000Z | 2018-01-11T00:41:43.000Z | redist/deps/flif/src/transform/factory.hpp | FrostyLeaves/spot | 703150893da7b586be772e716dab41687b85bc5b | [
"Zlib"
] | 11 | 2015-02-12T10:04:50.000Z | 2017-02-19T19:48:49.000Z | redist/deps/flif/src/transform/factory.hpp | FrostyLeaves/spot | 703150893da7b586be772e716dab41687b85bc5b | [
"Zlib"
] | 26 | 2015-02-28T03:24:31.000Z | 2017-12-29T09:43:32.000Z | #ifndef FLIF_FACTORY_HPP
#define FLIF_FACTORY_HPP
#include "transform.hpp"
#include <string>
template <typename IO>
Transform<IO> *create_transform(std::string desc);
#endif | 17.6 | 50 | 0.789773 | [
"transform"
] |
4a5d206496e517dd6367e76134f972f3a20c5b79 | 53,080 | cpp | C++ | src/VStarCatalogue.cpp | GernotMaier/Eventdisplay | b244d65856ddc26ea8ef88af53d2b247e8d5936c | [
"BSD-3-Clause"
] | 11 | 2019-12-10T13:34:46.000Z | 2021-08-24T15:39:35.000Z | src/VStarCatalogue.cpp | Eventdisplay/Eventdisplay | 01ef380cf53a44f95351960a297a2d4f271a4160 | [
"BSD-3-Clause"
] | 53 | 2019-11-19T13:14:36.000Z | 2022-02-16T14:22:27.000Z | src/VStarCatalogue.cpp | pivosb/Eventdisplay | 6b299a1d3f77ddb641f98a511a37a5045ddd6b47 | [
"BSD-3-Clause"
] | 3 | 2020-05-07T13:52:46.000Z | 2021-06-25T09:49:21.000Z | /*! \class VStarCatalogue
* \brief bright star catalogue
*/
#include "VStarCatalogue.h"
ClassImp( VStarCatalogue )
VStarCatalogue::VStarCatalogue()
{
fDebug = false;
fCatalogue = "Hipparcos_MAG8_1997.dat";
fCatalogueVersion = 0;
setTelescopePointing();
}
VStarCatalogue::~VStarCatalogue()
{
for( unsigned int i = 0; i < fStars.size(); i++ )
{
if( fStars[i] )
{
delete fStars[i];
}
}
for( unsigned int i = 0; i < fStarsinFOV.size(); i++ )
{
if( fStarsinFOV[i] )
{
delete fStarsinFOV[i];
}
}
}
bool VStarCatalogue::init( double MJD )
{
return init( MJD, fCatalogue );
}
bool VStarCatalogue::init( double iMJD, string iCatalogue )
{
fCatalogue = iCatalogue;
if( !readCatalogue() )
{
return false;
}
double dec, ra;
double i_b, i_l;
for( unsigned int i = 0; i < fStars.size(); i++ )
{
dec = fStars[i]->fDec2000 * TMath::Pi() / 180.;
ra = fStars[i]->fRA2000 * TMath::Pi() / 180.;
// calculate galac coordinates
VAstronometry::vlaEqgal( ra, dec, &i_l, &i_b );
fStars[i]->fRunGalLong1958 = i_l * 180. / TMath::Pi();
// apply precesssion
VAstronometry::vlaPreces( 2451545.0 - 2400000.5, iMJD, &ra, &dec );
// calculate ra/dec for current epoch
fStars[i]->fDecCurrentEpoch = dec * 180. / TMath::Pi();
fStars[i]->fRACurrentEpoch = ra * 180. / TMath::Pi();
fStars[i]->fRunGalLat1958 = i_b * 180. / TMath::Pi();
}
return true;
}
/*
*/
bool VStarCatalogue::readVERITASsourcesfromDB( string iofile )
{
char c_query[1000];
stringstream iTempS;
iTempS << getDBServer() << "/VERITAS";
//std::cout<<"VStarCatalogue::readVERITASsourcesfromDB "<<std::endl;
VDB_Connection my_connection( iTempS.str().c_str(), "readonly", "" ) ;
if( !my_connection.Get_Connection_Status() )
{
cout << "VStarCatalogue: failed to connect to database server" << endl;
return false;
}
sprintf( c_query, "select * from tblObserving_Sources " );
if( !my_connection.make_query( c_query ) )
{
return false;
}
TSQLResult* db_res = my_connection.Get_QueryResult();
int fNRows = db_res->GetRowCount();
unsigned int zID = 0;
double ra = 0.;
double dec = 0.;
for( int i = 0; i < fNRows; i++ )
{
TSQLRow* db_row = db_res->Next();
if( db_row->GetField( 0 ) && db_row->GetField( 1 ) && db_row->GetField( 2 ) )
{
VStar* i_Star = new VStar();
i_Star->fStarID = zID;
i_Star->fStarName = db_row->GetField( 0 );
// don't read the dark spots
if( i_Star->fStarName.substr( 0, 5 ) == "DARK_" )
{
continue;
}
// don't read bright stars
if( i_Star->fStarName.substr( 0, 3 ) == "BSC" )
{
continue;
}
// don't read different Crab pointings
if( i_Star->fStarName.substr( 0, 4 ) == "Crab" && i_Star->fStarName.size() > 4 )
{
continue;
}
// don't read zenith runs
if( i_Star->fStarName == "ZENITH" )
{
continue;
}
ra = atof( db_row->GetField( 1 ) ) * 180. / TMath::Pi();
dec = atof( db_row->GetField( 2 ) ) * 180. / TMath::Pi();
i_Star->fRA2000 = ra;
i_Star->fDec2000 = dec;
i_Star->fBrightness_V = -9999.;
i_Star->fBrightness_B = -9999.;
i_Star->fMajorDiameter = 0.;
i_Star->fMajorDiameter_68 = 0.;
cout << "ID " << i_Star->fRA2000 << " " << i_Star->fDec2000 << endl;
fStars.push_back( i_Star );
zID++;
}
}
if( my_connection.Get_Connection_Status() )
{
my_connection.Close_Connection(); // just so it get close as soon as possible. Before the end of the function.
}
// write sources into a text file
if( iofile.size() > 0 )
{
ofstream os;
os.open( iofile.c_str() );
if( !os )
{
cout << "error opening file for VERITAS sources: " << iofile << endl;
return false;
}
os << "* V 4" << endl;
for( unsigned int i = 0; i < fStars.size(); i++ )
{
if( fStars[i]->fStarName.substr( 0, 2 ) == "SS" )
{
continue;
}
if( fStars[i]->fStarName.substr( 0, 3 ) == "GRB" )
{
continue;
}
os << fStars[i]->fRA2000 << "\t" << fStars[i]->fDec2000 << "\t" << fStars[i]->fStarName << endl;
}
os.close();
}
return true;
}
/*!
attention: very dependend on format of text file
iV < 3: Brightstarcatalogue
iV == 3: tevcat
iV == 4: HMX catalogue
*/
bool VStarCatalogue::readCatalogue()
{
//////////////////////////////////////
// READ VERITAS object catalogue from DB
if( fCatalogue == "VERITASDB" )
{
return readVERITASsourcesfromDB( "" );
}
//////////////////////////////////////
//////////////////////////////////////
// READ catalogue from an ascii file
//////////////////////////////////////
ifstream is;
is.open( fCatalogue.c_str(), ifstream::in );
if( !is )
{
// try ENVDISPDATA
string itemp = "";
if( gSystem->Getenv( "VERITAS_EVNDISP_AUX_DIR" ) )
{
itemp = gSystem->Getenv( "VERITAS_EVNDISP_AUX_DIR" );
}
if( itemp.size() > 0 )
{
fCatalogue = itemp + "/AstroData/Catalogues/" + fCatalogue;
is.open( fCatalogue.c_str(), ifstream::in );
}
if( !is )
{
cout << "VStarCatalogue::readCatalogue error: file not found, " << fCatalogue << endl;
return false;
}
}
string iLine;
string iLine_sub;
string iT1;
string iT2;
string iT3;
cout << "\treading star catalogue: " << fCatalogue << endl;
int zid = 0;
// catalogue version
fCatalogueVersion = 0;
while( getline( is, iLine ) )
{
// hard maximum number of sources of 150,000 to avoid memory leaks
if( zid > 150000 )
{
cout << "VStarCatalogue::init: too many objects in catalogue, possible memory leak..." << endl;
return false;
}
if( iLine.size() < 2 )
{
continue;
}
// skip the commend lines
if( iLine.substr( 0, 1 ) == "#" )
{
continue;
}
// read catalogue version
// (note: this defines the expected layout of the ascii file)
if( iLine.substr( 0, 1 ) == "*" )
{
istringstream is_stream( iLine );
is_stream >> iT1;
is_stream >> iT1;
is_stream >> iT1;
fCatalogueVersion = atoi( iT1.c_str() );
continue;
}
////////////////////////////////////////////
// this is the text line to be worked with
iLine_sub = iLine;
////////////////////////////////////////////
// check number of text blocks available
if( !checkTextBlocks( iLine_sub, fCatalogueVersion ) )
{
if( fDebug )
{
cout << "Skipping following line in catalogue (version " << fCatalogueVersion << ")" << endl;
cout << iLine_sub << endl;
}
continue;
}
// start a new star
VStar* i_Star = new VStar();
i_Star->fQualityFlag = 0;
if( fCatalogueVersion == 3 )
{
i_Star->fStarName = iLine.substr( 0, 20 );
iLine_sub = iLine.substr( 23, iLine.size() );
}
if( fCatalogueVersion == 11 )
{
i_Star = readCommaSeparatedLine_Fermi( iLine_sub, zid, i_Star );
}
else if( fCatalogueVersion == 13 )
{
i_Star = readCommaSeparatedLine_Fermi_Catalogue( iLine_sub, zid, i_Star );
}
else if( fCatalogueVersion == 14 )
{
i_Star = readCommaSeparatedLine_FAVA( iLine_sub, zid, i_Star );
}
else if( fCatalogueVersion == 15 )
{
i_Star = readCommaSeparatedLine_Fermi2nd_Catalogue( iLine_sub, zid, i_Star );
}
else
{
istringstream is_stream( iLine_sub );
i_Star->fVariability = false;
// star ID
if( fCatalogueVersion < 2 )
{
is_stream >> iT1;
i_Star->fStarID = ( unsigned int )atoi( iT1.c_str() );
i_Star->fStarName = iT1;
}
else if( fCatalogueVersion == 3 || fCatalogueVersion == 4 || fCatalogueVersion == 6 )
{
i_Star->fStarID = ( unsigned int )zid;
}
else
{
i_Star->fStarID = ( unsigned int )zid;
}
if( fCatalogueVersion == 5 || fCatalogueVersion == 9 )
{
is_stream >> iT1;
// RA2000
i_Star->fRA2000 = atof( iT1.c_str() );
is_stream >> iT1;
// Dec2000
i_Star->fDec2000 = atof( iT1.c_str() );
}
else if( fCatalogueVersion < 10 || fCatalogueVersion == 12 )
{
// RA2000
is_stream >> iT1;
// make sure that entry exists
if( (is_stream>>std::ws).eof() )
{
zid++;
continue;
}
is_stream >> iT2;
if( (is_stream>>std::ws).eof() )
{
zid++;
continue;
}
if( fCatalogueVersion != 6 && fCatalogueVersion != 7 )
{
is_stream >> iT3;
}
else
{
iT3 = "0";
}
i_Star->fRA2000 = 15.*( atof( iT1.c_str() ) + atof( iT2.c_str() ) / 60. + atof( iT3.c_str() ) / 3600. );
// dec2000
is_stream >> iT1;
is_stream >> iT2;
if( fCatalogueVersion != 6 && fCatalogueVersion != 7 )
{
is_stream >> iT3;
}
else
{
iT3 = "0";
}
if( iT1.find( "-", 0 ) != string::npos )
{
i_Star->fDec2000 = atof( iT1.c_str() ) - atof( iT2.c_str() ) / 60. - atof( iT3.c_str() ) / 3600.;
}
else
{
i_Star->fDec2000 = atof( iT1.c_str() ) + atof( iT2.c_str() ) / 60. + atof( iT3.c_str() ) / 3600.;
}
}
i_Star->fBrightness_V = 9999;
i_Star->fBrightness_B = 9999;
i_Star->fMajorDiameter = 0.;
i_Star->fMajorDiameter_68 = 0.;
// objet name
if( fCatalogueVersion == 4 )
{
i_Star->fStarName = iLine.substr( 24, iLine.size() );
}
else if( fCatalogueVersion == 8 )
{
i_Star->fStarName = iLine.substr( 24, 16 );
i_Star->fStarName = "1RXS" + i_Star->fStarName;
i_Star->fMajorDiameter = atof( iLine.substr( 40, 4 ).c_str() );
i_Star->fMajorDiameter /= 3600.; // arcsec -> deg
}
else if( fCatalogueVersion == 5 )
{
i_Star->fStarName = is_stream.str().substr( is_stream.tellg(), is_stream.str().size() ).c_str();
i_Star->fStarName = VUtilities::remove_leading_spaces( i_Star->fStarName );
}
else if( fCatalogueVersion == 6 || fCatalogueVersion == 7 )
{
i_Star->fStarName = iLine.substr( 15, 11 );
if( fCatalogueVersion == 7 )
{
i_Star->fStarName = "3EG " + i_Star->fStarName;
}
i_Star->fMajorDiameter = atof( iLine.substr( 27, 5 ).c_str() );
// arcmin -> deg
if( fCatalogueVersion == 6 )
{
i_Star->fMajorDiameter /= 60.;
}
}
else if( fCatalogueVersion == 9 )
{
i_Star->fStarName = iLine.substr( is_stream.tellg(), iLine.size() );
}
else if( fCatalogueVersion == 12 )
{
is_stream >> i_Star->fStarName;
}
else if( fCatalogueVersion < 3 )
{
// brightness
is_stream >> i_Star->fBrightness_V;
is_stream >> i_Star->fBrightness_B;
// here check for B = 9999
if( TMath::Abs( i_Star->fBrightness_B - 9999. ) > 1. )
{
i_Star->fBrightness_B += i_Star->fBrightness_V;
}
else
{
i_Star->fBrightness_B = 9999;
}
}
// Hipparcos catalogue
if( fCatalogueVersion == 10 )
{
is_stream >> iT1;
i_Star->fRA2000 = atof( iT1.c_str() );
is_stream >> iT1;
i_Star->fDec2000 = atof( iT1.c_str() );
is_stream >> iT1;
i_Star->fStarID = atoi( iT1.c_str() );
i_Star->fStarName = "HIP" + iT1;
is_stream >> iT1;
i_Star->fBrightness_V = atof( iT1.c_str() );
is_stream >> iT1;
i_Star->fBrightness_B = i_Star->fBrightness_V + atof( iT1.c_str() );
}
}
fStars.push_back( i_Star );
zid++;
}
is.close();
return true;
}
VStar* VStarCatalogue::readCommaSeparatedLine_FAVA( string iLine, int zid, VStar* i_Star )
{
string iT1;
string iT2;
string iT3;
i_Star->fStarID = zid;
i_Star->fBrightness_V = 9999.;
i_Star->fBrightness_B = 9999.;
if( iLine.size() == 0 )
{
return i_Star;
}
string iTemp = iLine;
// star name
i_Star->fStarName = iTemp.substr( 0, iTemp.find( "," ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ra, dec
istringstream is_stream( iTemp );
is_stream >> iT1;
is_stream >> iT2;
is_stream >> iT3;
cout << "RA " << zid << " " << iT1.c_str() << " " << iT2.c_str() << " " << iT3.c_str() << endl;
i_Star->fRA2000 = 15.*( atof( iT1.c_str() ) + atof( iT2.c_str() ) / 60. + atof( iT3.c_str() ) / 3600. );
// dec2000
is_stream >> iT1;
is_stream >> iT1;
is_stream >> iT2;
is_stream >> iT3;
cout << "Dec " << zid << " " << iT1.c_str() << " " << iT2.c_str() << " " << iT3.c_str() << endl;
if( iT1.find( "-", 0 ) != string::npos )
{
i_Star->fDec2000 = atof( iT1.c_str() ) - atof( iT2.c_str() ) / 60. - atof( iT3.c_str() ) / 3600.;
}
else
{
i_Star->fDec2000 = atof( iT1.c_str() ) + atof( iT2.c_str() ) / 60. + atof( iT3.c_str() ) / 3600.;
}
return i_Star;
}
/*
2nd Fermi catalogue
*/
VStar* VStarCatalogue::readCommaSeparatedLine_Fermi2nd_Catalogue( string iLine, int zid, VStar* i_Star )
{
i_Star->fStarID = zid;
i_Star->fBrightness_V = 9999.;
i_Star->fBrightness_B = 9999.;
if( iLine.size() == 0 )
{
return i_Star;
}
string iTemp = iLine;
// star name
i_Star->fStarName = iTemp.substr( 0, iTemp.find( "," ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ra, dec
i_Star->fRA2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fDec2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
// galactic latitude/longitude are calculated from ra, dec
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ignore 68% values on position
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMajorDiameter_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMinorDiameter_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fPositionAngle_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 95% confidence radius
i_Star->fMajorDiameter = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMinorDiameter = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fPositionAngle = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// significance
i_Star->fSignificance = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
for( unsigned int i = 0; i < 4; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// spectral index
i_Star->fSpectralIndex = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fSpectralIndexError = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 1 GeV to 100 GeV flux
i_Star->fFluxEnergyMin.push_back( 1. );
i_Star->fFluxEnergyMax.push_back( 1.e2 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// spectral type
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fSpectrumType = iTemp.substr( 0, iTemp.find( "," ) );
for( unsigned int i = 0; i < 18; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// cutoff energy
i_Star->fCutOff_MeV = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fCutOffError_MeV = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 6; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// 100 MeV to 300 MeV
i_Star->fFluxEnergyMin.push_back( 0.1 );
i_Star->fFluxEnergyMax.push_back( 0.3 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 300 MeV to 1 GeV
i_Star->fFluxEnergyMin.push_back( 0.3 );
i_Star->fFluxEnergyMax.push_back( 1.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 1 GeV to 3 GeV
i_Star->fFluxEnergyMin.push_back( 1.0 );
i_Star->fFluxEnergyMax.push_back( 3.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 3 GeV to 10 GeV
i_Star->fFluxEnergyMin.push_back( 3.0 );
i_Star->fFluxEnergyMax.push_back( 10.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 10 GeV to 100 GeV
i_Star->fFluxEnergyMin.push_back( 10.0 );
i_Star->fFluxEnergyMax.push_back( 100.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 113; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// Other names
for( unsigned int i = 0; i < 72; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 )
{
if( iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
for( unsigned int i = 0; i < 26; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// classification
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 && iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fType = iTemp.substr( 0, iTemp.find( "," ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 5; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
for( unsigned int i = 0; i < 22; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 )
{
if( iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fAssociations.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
i_Star->fQualityFlag = atoi( iTemp.substr( iTemp.rfind( "," ) + 1, iTemp.size() ).c_str() );
return i_Star;
}
VStar* VStarCatalogue::readCommaSeparatedLine_Fermi_Catalogue( string iLine, int zid, VStar* i_Star )
{
i_Star->fStarID = zid;
i_Star->fBrightness_V = 9999.;
i_Star->fBrightness_B = 9999.;
if( iLine.size() == 0 )
{
return i_Star;
}
string iTemp = iLine;
// star name
i_Star->fStarName = iTemp.substr( 0, iTemp.find( "," ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ra, dec
i_Star->fRA2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fDec2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
// galactic latitude/longitude are calculated from ra, dec
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ignore 68% values on position
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMajorDiameter_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMinorDiameter_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fPositionAngle_68 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 95% confidence radius
i_Star->fMajorDiameter = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fMinorDiameter = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fPositionAngle = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// significance
i_Star->fSignificance = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
for( unsigned int i = 0; i < 4; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// spectral index
i_Star->fSpectralIndex = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fSpectralIndexError = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 1 GeV to 100 GeV flux
i_Star->fFluxEnergyMin.push_back( 1. );
i_Star->fFluxEnergyMax.push_back( 1.e2 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 6; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// 100 MeV to 300 MeV
i_Star->fFluxEnergyMin.push_back( 0.1 );
i_Star->fFluxEnergyMax.push_back( 0.3 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 300 MeV to 1 GeV
i_Star->fFluxEnergyMin.push_back( 0.3 );
i_Star->fFluxEnergyMax.push_back( 1.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 1 GeV to 3 GeV
i_Star->fFluxEnergyMin.push_back( 1.0 );
i_Star->fFluxEnergyMax.push_back( 3.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 3 GeV to 10 GeV
i_Star->fFluxEnergyMin.push_back( 3.0 );
i_Star->fFluxEnergyMax.push_back( 10.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 10 GeV to 100 GeV
i_Star->fFluxEnergyMin.push_back( 10.0 );
i_Star->fFluxEnergyMax.push_back( 100.0 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 28; i++ )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
// Other names
for( unsigned int i = 0; i < 72; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 )
{
if( iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
// classification
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 && iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fType = iTemp.substr( 0, iTemp.find( "," ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
for( unsigned int i = 0; i < 5; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
for( unsigned int i = 0; i < 22; i++ )
{
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 1 )
{
if( iTemp.substr( 0, iTemp.find( "," ) ) != " " )
{
i_Star->fAssociations.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
}
i_Star->fQualityFlag = atoi( iTemp.substr( iTemp.rfind( "," ) + 1, iTemp.size() ).c_str() );
return i_Star;
}
VStar* VStarCatalogue::readCommaSeparatedLine_Fermi( string iLine, int zid, VStar* i_Star )
{
i_Star->fStarID = zid;
i_Star->fBrightness_V = 9999.;
i_Star->fBrightness_B = 9999.;
if( iLine.size() == 0 )
{
return i_Star;
}
string iTemp = iLine;
// star name
i_Star->fStarName = iTemp.substr( 0, iTemp.find( "," ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// ra, dec
i_Star->fRA2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fDec2000 = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
// galactic latitude/longitude are calculated from ra, dec
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 95% confiduence radius
i_Star->fMajorDiameter = atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() );
// ignore likelihood test
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 100 MeV to 1 GeV flux
i_Star->fFluxEnergyMin.push_back( 1.e-2 );
i_Star->fFluxEnergyMax.push_back( 1. );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// 1 GeV to 100 GeV flux
i_Star->fFluxEnergyMin.push_back( 1. );
i_Star->fFluxEnergyMax.push_back( 1.e2 );
i_Star->fFlux.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
i_Star->fFluxError.push_back( atof( iTemp.substr( 0, iTemp.find( "," ) ).c_str() ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
// Variability
if( iTemp.substr( 0, iTemp.find( "," ) ) == "F" )
{
i_Star->fVariability = false;
}
else
{
i_Star->fVariability = true;
}
// Other names
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fOtherNames.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fAssociations.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
if( iTemp.substr( 0, iTemp.find( "," ) ).size() > 0 )
{
i_Star->fAssociations.push_back( iTemp.substr( 0, iTemp.find( "," ) ) );
iTemp = iTemp.substr( iTemp.find( "," ) + 1, iTemp.size() );
}
return i_Star;
}
void VStarCatalogue::printCatalogue( unsigned int i_nRows, double iMinBrightness, string iBand )
{
if( i_nRows == 0 || i_nRows >= fStars.size() )
{
i_nRows = fStars.size();
}
char hname[600];
for( unsigned int i = 0; i < i_nRows; i++ )
{
if( iBand == "V" && fStars[i]->fBrightness_V > iMinBrightness )
{
continue;
}
else if( iBand == "B" && fStars[i]->fBrightness_B > iMinBrightness )
{
continue;
}
cout << fStars[i]->fStarID << "\t_" << fStars[i]->fStarName;
cout << ", ra2000 = " << fStars[i]->fRA2000 << ", dec2000 = " << fStars[i]->fDec2000;
cout << ", l = " << fStars[i]->fRunGalLong1958 << ", b = " << fStars[i]->fRunGalLat1958 << "\t";
if( fStars[i]->fBrightness_V < 999. )
{
cout << "\t mag_V = " << fStars[i]->fBrightness_V;
}
if( fStars[i]->fBrightness_B < 999. )
{
cout << ", mag_B = " << fStars[i]->fBrightness_B;
}
cout << endl;
cout << "\tmajor (95\%) " << fStars[i]->fMajorDiameter;
if( fCatalogueVersion == 13 )
{
cout << ", minor (95\%) " << fStars[i]->fMinorDiameter;
cout << ", pos angle (95\%) " << fStars[i]->fPositionAngle << endl;
cout << "\tmajor (68\%) " << fStars[i]->fMajorDiameter_68;
cout << ", minor (68\%) " << fStars[i]->fMinorDiameter_68;
cout << ", pos angle (68\%) " << fStars[i]->fPositionAngle_68 << endl;
cout << "\tsignificance " << fStars[i]->fSignificance;
cout << ", index " << fStars[i]->fSpectralIndex;
cout << " +- " << fStars[i]->fSpectralIndexError;
}
cout << endl;
if( fStars[i]->fFluxEnergyMin.size() > 0 && fStars[i]->fFluxEnergyMin.size() == fStars[i]->fFluxEnergyMax.size()
&& fStars[i]->fFlux.size() == fStars[i]->fFluxEnergyMin.size() && fStars[i]->fFluxError.size() == fStars[i]->fFluxEnergyMin.size() )
{
for( unsigned int e = 0; e < fStars[i]->fFluxEnergyMin.size(); e++ )
{
cout << "\t";
sprintf( hname, "Flux (%.2f GeV - %.2f GeV): ", fStars[i]->fFluxEnergyMin[e], fStars[i]->fFluxEnergyMax[e] );
cout << hname;
sprintf( hname, "\t(%.4e +- %.4e) photons/cm2/s", fStars[i]->fFlux[e], fStars[i]->fFluxError[e] );
cout << hname;
cout << endl;
}
}
if( fStars[i]->fOtherNames.size() > 0 )
{
cout << "\tOther names: ";
for( unsigned int e = 0; e < fStars[i]->fOtherNames.size(); e++ )
{
cout << fStars[i]->fOtherNames[e] << ", ";
}
cout << endl;
}
if( fStars[i]->fType.size() > 2 )
{
cout << "\tType: " << fStars[i]->fType << endl;
}
if( fStars[i]->fAssociations.size() > 0 )
{
cout << "\tAssociations: ";
for( unsigned int e = 0; e < fStars[i]->fAssociations.size(); e++ )
{
cout << fStars[i]->fAssociations[e] << ", ";
}
cout << endl;
}
cout << "Quality flag: " << fStars[i]->fQualityFlag << endl;
}
}
void VStarCatalogue::printStarsInFOV()
{
printStarsInFOV( 999999. );
}
void VStarCatalogue::printStarsInFOV( double iMinBrightness, string iBand )
{
for( unsigned int i = 0; i < fStarsinFOV.size(); i++ )
{
if( iBand == "V" && fStarsinFOV[i]->fBrightness_V > iMinBrightness )
{
continue;
}
if( iBand == "B" && fStarsinFOV[i]->fBrightness_B > iMinBrightness )
{
continue;
}
cout << fStarsinFOV[i]->fStarID << "\t" << fStars[i]->fStarName;
cout << " RA2000: " << fStarsinFOV[i]->fRA2000 << " DEC2000: " << fStarsinFOV[i]->fDec2000 << "\t";
cout << fStarsinFOV[i]->fRACurrentEpoch << "\t" << fStarsinFOV[i]->fDecCurrentEpoch;
cout << " V: " << fStarsinFOV[i]->fBrightness_V;
cout << " B: " << fStarsinFOV[i]->fBrightness_B;
cout << " Diameter: " << fStarsinFOV[i]->fMajorDiameter << endl;
}
}
double VStarCatalogue::getStarMajorDiameter( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fMajorDiameter;
}
return 0.;
}
double VStarCatalogue::getStarBrightness( unsigned int iID, string iBand )
{
if( iID < fStars.size() && fStars[iID] )
{
if( iBand == "B" )
{
return fStars[iID]->fBrightness_B;
}
if( iBand == "V" )
{
return fStars[iID]->fBrightness_V;
}
}
return 0.;
}
double VStarCatalogue::getStarDecCurrentEpoch( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fDecCurrentEpoch;
}
return 0.;
}
double VStarCatalogue::getStarRACurrentEpoch( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fRACurrentEpoch;
}
return 0.;
}
string VStarCatalogue::getStarName( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fStarName;
}
string iN = "NONAME";
return iN;
}
unsigned int VStarCatalogue::getStarID( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fStarID;
}
return 0;
}
double VStarCatalogue::getStarDec2000( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fDec2000;
}
return 0.;
}
double VStarCatalogue::getStarRA2000( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fRA2000;
}
return 0.;
}
double VStarCatalogue::getStar_l( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fRunGalLong1958;
}
return 0.;
}
double VStarCatalogue::getStar_b( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fRunGalLat1958;
}
return 0.;
}
vector< double > VStarCatalogue::getStarFluxEnergyMin( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fFluxEnergyMin;
}
vector< double > a;
return a;
}
vector< double > VStarCatalogue::getStarFluxEnergyMax( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fFluxEnergyMax;
}
vector< double > a;
return a;
}
vector< double > VStarCatalogue::getStarFlux( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fFlux;
}
vector< double > a;
return a;
}
vector< double > VStarCatalogue::getStarFluxError( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fFluxError;
}
vector< double > a;
return a;
}
string VStarCatalogue::getStarType( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fType;
}
string a;
return a;
}
vector< string > VStarCatalogue::getStarOtherNames( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fOtherNames;
}
vector< string > a;
return a;
}
vector< string > VStarCatalogue::getStarAssociations( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fAssociations;
}
vector< string > a;
return a;
}
double VStarCatalogue::getStarSpectralIndex( unsigned int iID )
{
if( iID < fStars.size() && fStars[iID] )
{
return fStars[iID]->fSpectralIndex;
}
return 0.;
}
unsigned int VStarCatalogue::setFOV( string ra_hour, string dec, double FOV_x, double FOV_y, bool bJ2000 )
{
istringstream is_stream( ra_hour );
string temp2;
double d_tt = 0.;
is_stream >> temp2;
d_tt += atof( temp2.c_str() );
if( !(is_stream>>std::ws).eof() )
{
is_stream >> temp2;
d_tt += atof( temp2.c_str() ) / 60.;
}
if( !(is_stream>>std::ws).eof() )
{
is_stream >> temp2;
d_tt += atof( temp2.c_str() ) / 3600.;
}
double iSkyMapCentreRAJ2000 = d_tt / 24. * 360.;
istringstream is_dec( dec );
d_tt = 0.;
is_dec >> temp2;
d_tt += atof( temp2.c_str() );
if( !(is_dec>>std::ws).eof() )
{
is_dec >> temp2;
d_tt += atof( temp2.c_str() ) / 60.;
}
if( !(is_dec>>std::ws).eof() )
{
is_dec >> temp2;
d_tt += atof( temp2.c_str() ) / 3600.;
}
double iSkyMapCentreDecJ2000 = d_tt;
cout << "FOV Centre in deg: " << iSkyMapCentreRAJ2000 << "\t" << iSkyMapCentreDecJ2000 << endl;
return setFOV( iSkyMapCentreRAJ2000, iSkyMapCentreDecJ2000, FOV_x, FOV_y, bJ2000 );
}
/*!
loop over the current star catalogue and fill a list with stars in a box
centred around ra/dec with width iFOV_x/iFOV_y
all angles in [deg]
*/
unsigned int VStarCatalogue::setFOV( double ra, double dec, double iFOV_x, double iFOV_y, bool bJ2000, double iBrightness, string iBand )
{
double degrad = 180. / TMath::Pi();
fStarsinFOV.clear();
double iRA = 0.;
double iDec = 0.;
for( unsigned int i = 0; i < fStars.size(); i++ )
{
if( iBand == "B" && fStars[i]->fBrightness_B > iBrightness )
{
continue;
}
else if( iBand == "B" && fStars[i]->fBrightness_V > iBrightness )
{
continue;
}
if( bJ2000 )
{
iRA = fStars[i]->fRA2000;
iDec = fStars[i]->fDec2000;
}
else
{
iRA = fStars[i]->fRACurrentEpoch;
iDec = fStars[i]->fDecCurrentEpoch;
}
double x = 0.;
double y = 0.;
int ierr = 0;
VAstronometry::vlaDs2tp( iRA / degrad, iDec / degrad, ra / degrad, dec / degrad, &x, &y, &ierr );
x *= degrad;
y *= degrad;
if( ierr == 0 && fabs( y ) < iFOV_y )
{
if( fabs( x ) < iFOV_x )
{
fStarsinFOV.push_back( fStars[i] );
}
}
}
return fStarsinFOV.size();
}
void VStarCatalogue::purge()
{
fStars.clear();
fStars.swap( fStars );
}
bool VStarCatalogue::writeCatalogueToRootFile( string iRootFile )
{
TFile fOut( iRootFile.c_str(), "RECREATE" );
if( fOut.IsZombie() )
{
cout << "VStarCatalogue::writeCatalogueToRootFile error opening root file: " << fOut.GetName() << endl;
return false;
}
TTree* tCat = new TTree( "tCat", "star catalogue" );
unsigned int fStarID = 0;
Char_t fStarName[300];
double fDec2000 = 0.;
double fRA2000 = 0.;
double fRunGalLong1958 = 0.;
double fRunGalLat1958 = 0.;
double fBrightness_V = 0.;
double fBrightness_B = 0.;
double fMajorDiameter = 0.; // this is either the source diameter or the possitional error
double fMinorDiameter = 0.;
double fPositionAngle = 0.;
double fMajorDiameter_68 = 0.;
double fMinorDiameter_68 = 0.;
double fPositionAngle_68 = 0.;
double fSignificance = 0.;
double fSpectralIndex = 0.;
double fSpectralIndexError = 0.;
const unsigned int fMaxEnergyBins = 100; /// way too many
unsigned int fFluxEnergyBins = 0;
double fFluxEnergyMin[fMaxEnergyBins];
double fFluxEnergyMax[fMaxEnergyBins];
double fFlux[fMaxEnergyBins];
double fFluxError[fMaxEnergyBins];
double fCutOff_MeV = 0;
double fCutOffError_MeV = 0;
for( unsigned int i = 0; i < fMaxEnergyBins; i++ )
{
fFluxEnergyMin[i] = 0.;
fFluxEnergyMax[i] = 0.;
fFlux[i] = 0.;
fFluxError[i] = 0.;
}
unsigned int fVariability = 0;
Char_t fStarType[300];
int fQualityFlag = 0;
tCat->Branch( "StarID", &fStarID, "StarID/i" );
tCat->Branch( "StarName", &fStarName, "StarName/C" );
tCat->Branch( "Dec2000", &fDec2000, "Dec2000/D" );
tCat->Branch( "RA2000", &fRA2000, "RA2000/D" );
tCat->Branch( "GalLong1958", &fRunGalLong1958, "GalLong1958/D" );
tCat->Branch( "GalLat1958", &fRunGalLat1958, "GalLat1958/D" );
tCat->Branch( "Brightness_V", &fBrightness_V, "Brightness_V/D" );
tCat->Branch( "Brightness_B", &fBrightness_B, "Brightness_B/D" );
tCat->Branch( "MajorDiameter", &fMajorDiameter, "MajorDiameter/D" );
tCat->Branch( "MinorDiameter", &fMinorDiameter, "MinorDiameter/D" );
tCat->Branch( "PositionAngle", &fPositionAngle, "PositionAngle/D" );
tCat->Branch( "MajorDiameter_68", &fMajorDiameter_68, "MajorDiameter_68/D" );
tCat->Branch( "MinorDiameter_68", &fMinorDiameter_68, "MinorDiameter_68/D" );
tCat->Branch( "PositionAngle_68", &fPositionAngle_68, "PositionAngle_68/D" );
tCat->Branch( "Significance", &fSignificance, "Significance/D" );
tCat->Branch( "SpectralIndex", &fSpectralIndex, "SpectralIndex/D" );
tCat->Branch( "SpectralIndexError", &fSpectralIndexError, "SpectralIndexError/D" );
tCat->Branch( "NFluxEnergyBins", &fFluxEnergyBins, "NFluxEnergyBins/i" );
tCat->Branch( "FluxEnergyMin", fFluxEnergyMin, "FluxEnergyMin[NFluxEnergyBins]/D" );
tCat->Branch( "FluxEnergyMax", fFluxEnergyMax, "FluxEnergyMax[NFluxEnergyBins]/D" );
tCat->Branch( "Flux", fFlux, "Flux[NFluxEnergyBins]/D" );
tCat->Branch( "FluxError", fFluxError, "FluxError[NFluxEnergyBins]/D" );
tCat->Branch( "Variability", &fVariability, "Variability/i" );
tCat->Branch( "CutOff_MeV", &fCutOff_MeV, "CutOff_MeV/D" );
tCat->Branch( "CutOffError_MeV", &fCutOffError_MeV, "CutOffError_MeV/D" );
tCat->Branch( "Class", &fStarType, "Class/C" );
tCat->Branch( "QualityFlag", &fQualityFlag, "QualityFlag/I" );
// fill tree
for( unsigned int i = 0; i < fStars.size(); i++ )
{
fStarID = fStars[i]->fStarID;
sprintf( fStarName, "%s", fStars[i]->fStarName.c_str() );
fRA2000 = fStars[i]->fRA2000;
fDec2000 = fStars[i]->fDec2000;
fRunGalLong1958 = fStars[i]->fRunGalLong1958;
fRunGalLat1958 = fStars[i]->fRunGalLat1958;
fBrightness_V = fStars[i]->fBrightness_V;
fBrightness_B = fStars[i]->fBrightness_B;
fMajorDiameter = fStars[i]->fMajorDiameter;
fMinorDiameter = fStars[i]->fMinorDiameter;
fPositionAngle = fStars[i]->fPositionAngle;
fMajorDiameter_68 = fStars[i]->fMajorDiameter_68;
fMinorDiameter_68 = fStars[i]->fMinorDiameter_68;
fPositionAngle_68 = fStars[i]->fPositionAngle_68;
fSignificance = fStars[i]->fSignificance;
fSpectralIndex = fStars[i]->fSpectralIndex;
fSpectralIndexError = fStars[i]->fSpectralIndexError;
fQualityFlag = fStars[i]->fQualityFlag;
fVariability = fStars[i]->fVariability;
fCutOff_MeV = fStars[i]->fCutOff_MeV;
fCutOffError_MeV = fStars[i]->fCutOffError_MeV;
if( fStars[i]->fFluxEnergyMin.size() > 0 && fStars[i]->fFluxEnergyMin.size() == fStars[i]->fFluxEnergyMax.size() && fStars[i]->fFlux.size() == fStars[i]->fFluxEnergyMin.size() && fStars[i]->fFluxError.size() == fStars[i]->fFluxEnergyMin.size() )
{
fFluxEnergyBins = fStars[i]->fFluxEnergyMin.size();
for( unsigned int j = 0; j < fFluxEnergyBins; j++ )
{
fFluxEnergyMin[j] = fStars[i]->fFluxEnergyMin[j];
fFluxEnergyMax[j] = fStars[i]->fFluxEnergyMax[j];
fFlux[j] = fStars[i]->fFlux[j];
fFluxError[j] = fStars[i]->fFluxError[j];
}
}
sprintf( fStarType, "%s", fStars[i]->fType.c_str() );
tCat->Fill();
}
cout << "writing tree with " << tCat->GetEntries() << " entries to " << fOut.GetName() << endl;
tCat->Write();
fOut.Close();
return true;
}
VStar* VStarCatalogue::getStar( unsigned int ID )
{
if( ID < fStars.size() )
{
return fStars[ID];
}
return 0;
}
bool VStarCatalogue::checkTextBlocks( string iL, unsigned int iV )
{
unsigned int iTB = VUtilities::count_number_of_textblocks( iL );
// check for correct number of text blocks
// e.g. Hipparcos_MAG7_1997.dat
if( iV == 10 && iTB != 5 )
{
return false;
}
// e.g. BrightStarCatalogue.txt
else if( iV == 0 && iTB != 9 )
{
return false;
}
return true;
}
/*
set telescope pointing and calculate position of stars in FOV
*/
void VStarCatalogue::setTelescopePointing( unsigned int iTelID, double iDerotationAngle, double ra_deg, double dec_deg, double iCameraScale )
{
fTel_telescopeID = iTelID;
fTel_deRotationAngle_deg = iDerotationAngle;
fTel_ra = ra_deg;
fTel_dec = dec_deg;
fTel_camerascale = iCameraScale;
}
/*
get angular distance between a bright star in the FOV and a x,y position in the camera
*/
double VStarCatalogue::getDistanceToClosestStar( double x_cam_deg, double y_cam_deg )
{
double x_rot = 0.;
double y_rot = 0.;
double i_minDist = 1.e20;
// loop over all stars in the FOV
for( unsigned int i = 0; i < fStarsinFOV.size(); i++ )
{
double y = -1. * ( fStarsinFOV[i]->fDecCurrentEpoch - fTel_dec );
double x = 0.;
if( cos( fTel_dec * TMath::DegToRad() ) != 0. )
{
x = -1. * ( fStarsinFOV[i]->fRACurrentEpoch - fTel_ra ) * cos( fTel_dec * TMath::DegToRad() );
}
x_rot = x;
y_rot = y;
// derotation
VSkyCoordinatesUtilities::rotate( -1.*fTel_deRotationAngle_deg * TMath::DegToRad(), x_rot, y_rot );
x_rot *= -1. * fTel_camerascale;
y_rot *= fTel_camerascale;
double i_dist = sqrt( ( x_cam_deg - x_rot ) * ( x_cam_deg - x_rot ) + ( y_cam_deg - y_rot ) * ( y_cam_deg - y_rot ) );
if( i_dist < i_minDist )
{
i_minDist = i_dist;
}
}
return i_minDist;
}
| 32.846535 | 253 | 0.522155 | [
"object",
"vector"
] |
4a5dcd22820f789b1716a95e8e5cd489a4401bcb | 2,173 | cpp | C++ | runtime/src/blueoil_data_processor.cpp | tvlenin/blueoil | 810680df75e2640f67d515c377ba2b4531b9e584 | [
"Apache-2.0"
] | null | null | null | runtime/src/blueoil_data_processor.cpp | tvlenin/blueoil | 810680df75e2640f67d515c377ba2b4531b9e584 | [
"Apache-2.0"
] | null | null | null | runtime/src/blueoil_data_processor.cpp | tvlenin/blueoil | 810680df75e2640f67d515c377ba2b4531b9e584 | [
"Apache-2.0"
] | null | null | null | #include <dlfcn.h>
#include <string>
#include <vector>
#include <iostream>
#include <numeric>
#include <algorithm>
#include "blueoil.hpp"
#include "blueoil_image.hpp"
#include "blueoil_data_processor.hpp"
namespace blueoil {
namespace data_processor {
// TODO(wakisaka): imple resize.
Tensor Resize(const Tensor& image, const std::pair<int, int>& size) {
const int width = size.first;
const int height = size.second;
return blueoil::image::Resize(image, width, height,
blueoil::image::RESIZE_FILTER_NEAREST_NEIGHBOR);
}
Tensor DivideBy255(const Tensor& image) {
Tensor out(image);
auto div255 = [](float i) { return i/255; };
std::transform(image.begin(), image.end(), out.begin(), div255);
return out;
}
// TODO(wakisaka): impl
Tensor FormatYoloV2(const Tensor& input,
const std::vector<std::pair<float, float>>& anchors,
const int& boxes_per_cell,
const std::string& data_format,
const std::pair<int, int>& image_size,
const int& num_classes) {
Tensor t(input);
return t;
}
// TODO(wakisaka): optimize
Tensor FormatYoloV2(const Tensor& input, const FormatYoloV2Parameters& params) {
return FormatYoloV2(input,
params.anchors,
params.boxes_per_cell,
params.data_format,
params.image_size,
params.num_classes);
}
// TODO(wakisaka): impl
Tensor ExcludeLowScoreBox(const Tensor& input, const float& threshold) {
Tensor t(input);
return t;
}
// TODO(wakisaka): impl
Tensor NMS(const Tensor& input,
const std::vector<std::string>& classes,
const float& iou_threshold,
const int& max_output_size,
const bool& per_class) {
Tensor t(input);
return t;
}
// TODO(wakisaka): optimize
Tensor NMS(const Tensor& input, const NMSParameters& params){
return NMS(input,
params.classes,
params.iou_threshold,
params.max_output_size,
params.per_class);
};
} // namespace data_processor
} // namespace blueoil
| 27.1625 | 80 | 0.623102 | [
"vector",
"transform"
] |
4a712a91ee7442b90ce58dd9ca162c7cafba9136 | 671 | hpp | C++ | deprecated-material/include/aml/string.hpp | aandriko/libaml | 9db1a3ac13ef8160a33ed03e861be5d8cc8ea311 | [
"BSL-1.0"
] | null | null | null | deprecated-material/include/aml/string.hpp | aandriko/libaml | 9db1a3ac13ef8160a33ed03e861be5d8cc8ea311 | [
"BSL-1.0"
] | null | null | null | deprecated-material/include/aml/string.hpp | aandriko/libaml | 9db1a3ac13ef8160a33ed03e861be5d8cc8ea311 | [
"BSL-1.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2021 Andreas Milton Maniotis.
//
// Email: andreas.maniotis@gmail.com
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "./basic_types.hpp"
namespace aml
{
template<char... text>
using string = object<>::list<text...>;
template<typename Char=char, Char... txt> constexpr string<txt...> operator ""_() { return { }; }
}
| 29.173913 | 102 | 0.490313 | [
"object"
] |
4a76dd8508e69f2b0fade9cf1a08e8ab8bb782a2 | 1,927 | cpp | C++ | GameBackboneSln/GameBackbone/Source/Core/UniformAnimationSet.cpp | lavinrp/GameBackbone | 35593a6ae1a68ca5e987e098c0270a94b54eb2dd | [
"MIT"
] | 9 | 2017-04-16T20:15:48.000Z | 2019-10-19T18:49:03.000Z | GameBackboneSln/GameBackbone/Source/Core/UniformAnimationSet.cpp | lavinrp/GameBackbone | 35593a6ae1a68ca5e987e098c0270a94b54eb2dd | [
"MIT"
] | 226 | 2017-02-10T04:01:31.000Z | 2020-04-13T03:11:30.000Z | GameBackboneSln/GameBackbone/Source/Core/UniformAnimationSet.cpp | lavinrp/GameBackbone | 35593a6ae1a68ca5e987e098c0270a94b54eb2dd | [
"MIT"
] | 4 | 2017-04-09T14:56:52.000Z | 2020-04-18T17:32:46.000Z |
#include <GameBackbone/Core/AnimationSet.h>
#include <GameBackbone/Core/UniformAnimationSet.h>
#include <SFML/System/Vector2.hpp>
#include <exception>
#include <vector>
using namespace GB;
/// <summary>
/// Construct a new UniformAnimationSet object.
/// </summary>
/// <param name="frameSize"> The default frame size for an animation. </param>
UniformAnimationSet::UniformAnimationSet(sf::Vector2i frameSize) : defaultFrameSize(frameSize) {
}
/// <summary>
/// Construct a new UniformAnimationSet object.
/// The provided animations will all be added to the animation set.
/// </summary>
/// <param name="frameSize"> The default frame size for an animation. </param>
/// <param name="animations">
/// The animations to add. The UniformAnimation is a collection of sf::Vector2i pairs that act as (x, y) coordinates into the texture's frames.
/// </param>
UniformAnimationSet::UniformAnimationSet(sf::Vector2i frameSize, const std::vector<UniformAnimation>& animations)
: defaultFrameSize(frameSize) {
for (const UniformAnimation& animation : animations){
addAnimation(animation);
}
}
/// <summary>
/// Adds the UniformAnimation to the UniformAnimationSet.
/// The UniformAnimation is a collection of sf::Vector2i pairs that act as (x, y) coordinates into the texture's frames.
/// </summary>
/// <param name="animation"> The animation to add. </param>
void UniformAnimationSet::addAnimation(const UniformAnimation& animation){
Animation baseAnimation;
for (const sf::Vector2i& frameIndex : animation){
const sf::Vector2i animationPosition(frameIndex.x*defaultFrameSize.x, frameIndex.y*defaultFrameSize.y);
baseAnimation.emplace_back(sf::IntRect(animationPosition, defaultFrameSize));
}
addAnimation(std::move(baseAnimation));
}
/// <summary>
/// Returns the default size of UniformAnimation frames
/// </summary>
sf::Vector2i UniformAnimationSet::getDefaultFrameSize() const {
return defaultFrameSize;
} | 35.685185 | 143 | 0.757135 | [
"object",
"vector"
] |
4a76ddd6132e15715bd4e1484c87779a1d9d3ed4 | 2,694 | cpp | C++ | Codeforces/CF1394/D.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | Codeforces/CF1394/D.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | Codeforces/CF1394/D.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | /*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)2e13;
const int MOD=998244353;
int _abs(int x){return x<0 ? -x : x;}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=200005;
#define int long long
int n,a[N],b[N],dp[N][2],top=0;
vector<int> v[N];
struct node{
int a,b,val;
bool operator < (const node &rhs) const{
return val<rhs.val;
}
}t[N];
int calc(int cnt0,int cnt1,int flag,int x){
if(cnt0==cnt1) return cnt0+(x!=1);
if(!flag){
if(cnt0>cnt1) return cnt0;
else return cnt1+(x!=1);
}
else{
if(cnt1>cnt0) return cnt1;
else return cnt0+(x!=1);
}
}
void update(int x){
for(int i=1;i<=top;i++) t[i].val=t[i].b-t[i].a;
sort(t+1,t+top+1);
int ret=0,cnt0=top,cnt1=0;
for(int i=1;i<=top;i++) ret+=t[i].a;
checkmin(dp[x][0],ret+calc(cnt0,cnt1,0,x)*a[x]);
checkmin(dp[x][1],ret+calc(cnt0,cnt1,1,x)*a[x]);
for(int i=1;i<=top;i++){
cnt0--; cnt1++;
ret+=t[i].val;
checkmin(dp[x][0],ret+calc(cnt0,cnt1,0,x)*a[x]);
checkmin(dp[x][1],ret+calc(cnt0,cnt1,1,x)*a[x]);
}
}
void dfs(int u,int f){
for(auto &to : v[u]) if(to!=f) dfs(to,u);
top=0;
for(auto &to : v[u]) if(to!=f){
top++;
t[top].a=(b[to]>b[u] ? INF : dp[to][0]);
t[top].b=(b[to]<b[u] ? INF : dp[to][1]);
}
update(u);
}
signed main()
{
n=read();
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<=n;i++) b[i]=read();
for(int i=1;i<=n;i++){
for(int j=0;j<=2;j++) dp[i][j]=INF;
}
for(int i=1;i<n;i++){
int x=read(),y=read();
v[x].push_back(y); v[y].push_back(x);
}
dfs(1,-1);
int ans=min(dp[1][0],dp[1][1]);
cout<<ans<<endl;
return 0;
} | 27.212121 | 98 | 0.529696 | [
"vector"
] |
4a86472d23222d4a209e3b12baa435706ca55858 | 22,956 | hpp | C++ | alpaka/include/alpaka/core/Cuda.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 6 | 2021-02-01T09:01:39.000Z | 2021-11-14T17:09:03.000Z | alpaka/include/alpaka/core/Cuda.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 17 | 2020-11-09T14:13:50.000Z | 2021-11-03T11:54:54.000Z | alpaka/include/alpaka/core/Cuda.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | null | null | null | /* Copyright 2019 Axel Huebl, Benjamin Worpitz, Matthias Werner, René Widera
*
* This file is part of alpaka.
*
* 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/.
*/
#pragma once
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
# include <alpaka/core/BoostPredef.hpp>
# if !BOOST_LANG_CUDA
# error If ALPAKA_ACC_GPU_CUDA_ENABLED is set, the compiler has to support CUDA!
# endif
# include <alpaka/elem/Traits.hpp>
# include <alpaka/extent/Traits.hpp>
# include <alpaka/idx/Traits.hpp>
# include <alpaka/meta/Metafunctions.hpp>
# include <alpaka/offset/Traits.hpp>
# include <alpaka/vec/Vec.hpp>
// cuda_runtime_api.h: CUDA Runtime API C-style interface that does not require compiling with nvcc.
// cuda_runtime.h: CUDA Runtime API C++-style interface built on top of the C API.
// It wraps some of the C API routines, using overloading, references and default arguments.
// These wrappers can be used from C++ code and can be compiled with any C++ compiler.
// The C++ API also has some CUDA-specific wrappers that wrap C API routines that deal with symbols, textures, and
// device functions. These wrappers require the use of \p nvcc because they depend on code being generated by the
// compiler. For example, the execution configuration syntax to invoke kernels is only available in source code
// compiled with nvcc.
# include <cuda.h>
# include <cuda_runtime.h>
# include <cstddef>
# include <stdexcept>
# include <string>
# include <type_traits>
# include <utility>
# if(!defined(CUDART_VERSION) || (CUDART_VERSION < 9000))
# error "CUDA version 9.0 or greater required!"
# endif
# if(!defined(CUDA_VERSION) || (CUDA_VERSION < 9000))
# error "CUDA version 9.0 or greater required!"
# endif
# define ALPAKA_PP_CONCAT_DO(X, Y) X##Y
# define ALPAKA_PP_CONCAT(X, Y) ALPAKA_PP_CONCAT_DO(X, Y)
//! prefix a name with `cuda`
# define ALPAKA_API_PREFIX(name) ALPAKA_PP_CONCAT_DO(cuda, name)
namespace alpaka
{
namespace cuda
{
namespace detail
{
//-----------------------------------------------------------------------------
//! CUDA driver API error checking with log and exception, ignoring specific error values
ALPAKA_FN_HOST inline auto cudaDrvCheck(
CUresult const& error,
char const* desc,
char const* file,
int const& line) -> void
{
if(error == CUDA_SUCCESS)
return;
char const* cu_err_name = nullptr;
char const* cu_err_string = nullptr;
CUresult cu_result_name = cuGetErrorName(error, &cu_err_name);
CUresult cu_result_string = cuGetErrorString(error, &cu_err_string);
std::string sError
= std::string(file) + "(" + std::to_string(line) + ") " + std::string(desc) + " : '";
if(cu_result_name == CUDA_SUCCESS && cu_result_string == CUDA_SUCCESS)
{
sError += std::string(cu_err_name) + "': '" + std::string(cu_err_string) + "'!";
}
else
{
// cuGetError*() failed, so append corresponding error message
if(cu_result_name == CUDA_ERROR_INVALID_VALUE)
{
sError += " cuGetErrorName: 'Invalid Value'!";
}
if(cu_result_string == CUDA_ERROR_INVALID_VALUE)
{
sError += " cuGetErrorString: 'Invalid Value'!";
}
}
# if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
std::cerr << sError << std::endl;
# endif
ALPAKA_DEBUG_BREAK;
throw std::runtime_error(sError);
}
} // namespace detail
} // namespace cuda
} // namespace alpaka
//-----------------------------------------------------------------------------
//! CUDA driver error checking with log and exception.
# define ALPAKA_CUDA_DRV_CHECK(cmd) ::alpaka::cuda::detail::cudaDrvCheck(cmd, # cmd, __FILE__, __LINE__)
//-----------------------------------------------------------------------------
// CUDA vector_types.h trait specializations.
namespace alpaka
{
//-----------------------------------------------------------------------------
//! The CUDA specifics.
namespace cuda
{
namespace traits
{
//#############################################################################
//! The CUDA vectors 1D dimension get trait specialization.
template<typename T>
struct IsCudaBuiltInType
: std::integral_constant<
bool,
std::is_same<T, char1>::value || std::is_same<T, double1>::value
|| std::is_same<T, float1>::value || std::is_same<T, int1>::value
|| std::is_same<T, long1>::value || std::is_same<T, longlong1>::value
|| std::is_same<T, short1>::value || std::is_same<T, uchar1>::value
|| std::is_same<T, uint1>::value || std::is_same<T, ulong1>::value
|| std::is_same<T, ulonglong1>::value || std::is_same<T, ushort1>::value
|| std::is_same<T, char2>::value || std::is_same<T, double2>::value
|| std::is_same<T, float2>::value || std::is_same<T, int2>::value
|| std::is_same<T, long2>::value || std::is_same<T, longlong2>::value
|| std::is_same<T, short2>::value || std::is_same<T, uchar2>::value
|| std::is_same<T, uint2>::value || std::is_same<T, ulong2>::value
|| std::is_same<T, ulonglong2>::value || std::is_same<T, ushort2>::value
|| std::is_same<T, char3>::value || std::is_same<T, dim3>::value
|| std::is_same<T, double3>::value || std::is_same<T, float3>::value
|| std::is_same<T, int3>::value || std::is_same<T, long3>::value
|| std::is_same<T, longlong3>::value || std::is_same<T, short3>::value
|| std::is_same<T, uchar3>::value || std::is_same<T, uint3>::value
|| std::is_same<T, ulong3>::value || std::is_same<T, ulonglong3>::value
|| std::is_same<T, ushort3>::value || std::is_same<T, char4>::value
|| std::is_same<T, double4>::value || std::is_same<T, float4>::value
|| std::is_same<T, int4>::value || std::is_same<T, long4>::value
|| std::is_same<T, longlong4>::value || std::is_same<T, short4>::value
|| std::is_same<T, uchar4>::value || std::is_same<T, uint4>::value
|| std::is_same<T, ulong4>::value || std::is_same<T, ulonglong4>::value
|| std::is_same<T, ushort4>::value
// CUDA built-in variables have special types in clang native CUDA compilation
// defined in cuda_builtin_vars.h
# if BOOST_COMP_CLANG_CUDA
|| std::is_same<T, __cuda_builtin_threadIdx_t>::value
|| std::is_same<T, __cuda_builtin_blockIdx_t>::value
|| std::is_same<T, __cuda_builtin_blockDim_t>::value
|| std::is_same<T, __cuda_builtin_gridDim_t>::value
# endif
>
{
};
} // namespace traits
} // namespace cuda
namespace traits
{
//#############################################################################
//! The CUDA vectors 1D dimension get trait specialization.
template<typename T>
struct DimType<
T,
std::enable_if_t<
std::is_same<T, char1>::value || std::is_same<T, double1>::value || std::is_same<T, float1>::value
|| std::is_same<T, int1>::value || std::is_same<T, long1>::value || std::is_same<T, longlong1>::value
|| std::is_same<T, short1>::value || std::is_same<T, uchar1>::value || std::is_same<T, uint1>::value
|| std::is_same<T, ulong1>::value || std::is_same<T, ulonglong1>::value
|| std::is_same<T, ushort1>::value>>
{
using type = DimInt<1u>;
};
//#############################################################################
//! The CUDA vectors 2D dimension get trait specialization.
template<typename T>
struct DimType<
T,
std::enable_if_t<
std::is_same<T, char2>::value || std::is_same<T, double2>::value || std::is_same<T, float2>::value
|| std::is_same<T, int2>::value || std::is_same<T, long2>::value || std::is_same<T, longlong2>::value
|| std::is_same<T, short2>::value || std::is_same<T, uchar2>::value || std::is_same<T, uint2>::value
|| std::is_same<T, ulong2>::value || std::is_same<T, ulonglong2>::value
|| std::is_same<T, ushort2>::value>>
{
using type = DimInt<2u>;
};
//#############################################################################
//! The CUDA vectors 3D dimension get trait specialization.
template<typename T>
struct DimType<
T,
std::enable_if_t<
std::is_same<T, char3>::value || std::is_same<T, dim3>::value || std::is_same<T, double3>::value
|| std::is_same<T, float3>::value || std::is_same<T, int3>::value || std::is_same<T, long3>::value
|| std::is_same<T, longlong3>::value || std::is_same<T, short3>::value
|| std::is_same<T, uchar3>::value || std::is_same<T, uint3>::value || std::is_same<T, ulong3>::value
|| std::is_same<T, ulonglong3>::value || std::is_same<T, ushort3>::value
# if BOOST_COMP_CLANG_CUDA
|| std::is_same<T, __cuda_builtin_threadIdx_t>::value
|| std::is_same<T, __cuda_builtin_blockIdx_t>::value
|| std::is_same<T, __cuda_builtin_blockDim_t>::value
|| std::is_same<T, __cuda_builtin_gridDim_t>::value
# endif
>>
{
using type = DimInt<3u>;
};
//#############################################################################
//! The CUDA vectors 4D dimension get trait specialization.
template<typename T>
struct DimType<
T,
std::enable_if_t<
std::is_same<T, char4>::value || std::is_same<T, double4>::value || std::is_same<T, float4>::value
|| std::is_same<T, int4>::value || std::is_same<T, long4>::value || std::is_same<T, longlong4>::value
|| std::is_same<T, short4>::value || std::is_same<T, uchar4>::value || std::is_same<T, uint4>::value
|| std::is_same<T, ulong4>::value || std::is_same<T, ulonglong4>::value
|| std::is_same<T, ushort4>::value>>
{
using type = DimInt<4u>;
};
//#############################################################################
//! The CUDA vectors elem type trait specialization.
template<typename T>
struct ElemType<T, std::enable_if_t<cuda::traits::IsCudaBuiltInType<T>::value>>
{
using type = decltype(std::declval<T>().x);
};
} // namespace traits
namespace extent
{
namespace traits
{
//#############################################################################
//! The CUDA vectors extent get trait specialization.
template<typename TExtent>
struct GetExtent<
DimInt<Dim<TExtent>::value - 1u>,
TExtent,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 1)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getExtent(TExtent const& extent)
{
return extent.x;
}
};
//#############################################################################
//! The CUDA vectors extent get trait specialization.
template<typename TExtent>
struct GetExtent<
DimInt<Dim<TExtent>::value - 2u>,
TExtent,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 2)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getExtent(TExtent const& extent)
{
return extent.y;
}
};
//#############################################################################
//! The CUDA vectors extent get trait specialization.
template<typename TExtent>
struct GetExtent<
DimInt<Dim<TExtent>::value - 3u>,
TExtent,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 3)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getExtent(TExtent const& extent)
{
return extent.z;
}
};
//#############################################################################
//! The CUDA vectors extent get trait specialization.
template<typename TExtent>
struct GetExtent<
DimInt<Dim<TExtent>::value - 4u>,
TExtent,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 4)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getExtent(TExtent const& extent)
{
return extent.w;
}
};
//#############################################################################
//! The CUDA vectors extent set trait specialization.
template<typename TExtent, typename TExtentVal>
struct SetExtent<
DimInt<Dim<TExtent>::value - 1u>,
TExtent,
TExtentVal,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 1)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setExtent(TExtent const& extent, TExtentVal const& extentVal) -> void
{
extent.x = extentVal;
}
};
//#############################################################################
//! The CUDA vectors extent set trait specialization.
template<typename TExtent, typename TExtentVal>
struct SetExtent<
DimInt<Dim<TExtent>::value - 2u>,
TExtent,
TExtentVal,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 2)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setExtent(TExtent const& extent, TExtentVal const& extentVal) -> void
{
extent.y = extentVal;
}
};
//#############################################################################
//! The CUDA vectors extent set trait specialization.
template<typename TExtent, typename TExtentVal>
struct SetExtent<
DimInt<Dim<TExtent>::value - 3u>,
TExtent,
TExtentVal,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 3)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setExtent(TExtent const& extent, TExtentVal const& extentVal) -> void
{
extent.z = extentVal;
}
};
//#############################################################################
//! The CUDA vectors extent set trait specialization.
template<typename TExtent, typename TExtentVal>
struct SetExtent<
DimInt<Dim<TExtent>::value - 4u>,
TExtent,
TExtentVal,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TExtent>::value && (Dim<TExtent>::value >= 4)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setExtent(TExtent const& extent, TExtentVal const& extentVal) -> void
{
extent.w = extentVal;
}
};
} // namespace traits
} // namespace extent
namespace traits
{
//#############################################################################
//! The CUDA vectors offset get trait specialization.
template<typename TOffsets>
struct GetOffset<
DimInt<Dim<TOffsets>::value - 1u>,
TOffsets,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 1)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getOffset(TOffsets const& offsets)
{
return offsets.x;
}
};
//#############################################################################
//! The CUDA vectors offset get trait specialization.
template<typename TOffsets>
struct GetOffset<
DimInt<Dim<TOffsets>::value - 2u>,
TOffsets,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 2)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getOffset(TOffsets const& offsets)
{
return offsets.y;
}
};
//#############################################################################
//! The CUDA vectors offset get trait specialization.
template<typename TOffsets>
struct GetOffset<
DimInt<Dim<TOffsets>::value - 3u>,
TOffsets,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 3)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getOffset(TOffsets const& offsets)
{
return offsets.z;
}
};
//#############################################################################
//! The CUDA vectors offset get trait specialization.
template<typename TOffsets>
struct GetOffset<
DimInt<Dim<TOffsets>::value - 4u>,
TOffsets,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 4)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto getOffset(TOffsets const& offsets)
{
return offsets.w;
}
};
//#############################################################################
//! The CUDA vectors offset set trait specialization.
template<typename TOffsets, typename TOffset>
struct SetOffset<
DimInt<Dim<TOffsets>::value - 1u>,
TOffsets,
TOffset,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 1)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setOffset(TOffsets const& offsets, TOffset const& offset) -> void
{
offsets.x = offset;
}
};
//#############################################################################
//! The CUDA vectors offset set trait specialization.
template<typename TOffsets, typename TOffset>
struct SetOffset<
DimInt<Dim<TOffsets>::value - 2u>,
TOffsets,
TOffset,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 2)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setOffset(TOffsets const& offsets, TOffset const& offset) -> void
{
offsets.y = offset;
}
};
//#############################################################################
//! The CUDA vectors offset set trait specialization.
template<typename TOffsets, typename TOffset>
struct SetOffset<
DimInt<Dim<TOffsets>::value - 3u>,
TOffsets,
TOffset,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 3)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setOffset(TOffsets const& offsets, TOffset const& offset) -> void
{
offsets.z = offset;
}
};
//#############################################################################
//! The CUDA vectors offset set trait specialization.
template<typename TOffsets, typename TOffset>
struct SetOffset<
DimInt<Dim<TOffsets>::value - 4u>,
TOffsets,
TOffset,
std::enable_if_t<cuda::traits::IsCudaBuiltInType<TOffsets>::value && (Dim<TOffsets>::value >= 4)>>
{
ALPAKA_NO_HOST_ACC_WARNING
ALPAKA_FN_HOST_ACC static auto setOffset(TOffsets const& offsets, TOffset const& offset) -> void
{
offsets.w = offset;
}
};
//#############################################################################
//! The CUDA vectors idx type trait specialization.
template<typename TIdx>
struct IdxType<TIdx, std::enable_if_t<cuda::traits::IsCudaBuiltInType<TIdx>::value>>
{
using type = std::size_t;
};
} // namespace traits
} // namespace alpaka
# include <alpaka/core/UniformCudaHip.hpp>
#endif
| 46.563895 | 117 | 0.487933 | [
"3d"
] |
4a86b61e691ee93d5e3ba5b45fb91bc76dedd9a1 | 2,484 | cpp | C++ | src/Elba/Core/Components/MAT362/GammaController.cpp | nicholasammann/elba | 8d7a8ae7c8b55b87ee7dcd02aaea1b175e6dd8ce | [
"MIT"
] | 1 | 2018-10-01T19:34:57.000Z | 2018-10-01T19:34:57.000Z | src/Elba/Core/Components/MAT362/GammaController.cpp | nicholasammann/elba | 8d7a8ae7c8b55b87ee7dcd02aaea1b175e6dd8ce | [
"MIT"
] | 9 | 2018-09-09T16:07:22.000Z | 2018-11-06T20:34:30.000Z | src/Elba/Core/Components/MAT362/GammaController.cpp | nicholasammann/elba | 8d7a8ae7c8b55b87ee7dcd02aaea1b175e6dd8ce | [
"MIT"
] | null | null | null | #include "Elba/Core/Object.hpp"
#include "Elba/Core/Components/MAT362/GammaController.hpp"
#include "Elba/Core/CoreModule.hpp"
#include "Elba/Engine.hpp"
#include "Elba/Graphics/OpenGL/OpenGLMesh.hpp"
#include "Elba/Graphics/OpenGL/OpenGLSubmesh.hpp"
namespace Elba
{
GammaController::GammaController(Object* parent)
: Component(parent)
{
mModel = parent->GetComponent<Model>();
mGraphics = static_cast<OpenGLModule*>(GetParent()->GetCoreModule()->GetEngine()->GetGraphicsModule());
}
void GammaController::Initialize()
{
// set up Takagi Sugeno system for gamma control
// if average intensity is [0, 110], gamma should be high (g > 1). ---> if x is [0, 110] then g = 1.0f + log2(3.0f * 1 - x)
PiecewiseLinear piecewise;
piecewise.AddPoint(0.0f, 1.0f);
piecewise.AddPoint(55.0f, 1.0f);
piecewise.AddPoint(110.0f, 0.0f);
mFuzzySystem.AddRule(piecewise, [](float x) { return 1.0f + log2(3.0f * (1.0001f - x));});
// if average intensity is [90, 170], gamma should be one (g = 1). ---> if x is[90, 170] then g = 1
piecewise.ClearPoints();
piecewise.AddPoint(90.0f, 0.0f);
piecewise.AddPoint(130.0f, 1.0f);
piecewise.AddPoint(170.0f, 0.0f);
mFuzzySystem.AddRule(piecewise, [](float x) { return 1.0f; });
// if average intensity is [140, 255], gamma should be low (g < 1). ---> if x is[140, 255] then g = x + 0.01f
piecewise.ClearPoints();
piecewise.AddPoint(150.0f, 0.0f);
piecewise.AddPoint(200.0f, 1.0f);
piecewise.AddPoint(255.0f, 1.0f);
mFuzzySystem.AddRule(piecewise, [](float x) { return 1.00001f - (0.65f * x); });
}
void GammaController::Update(double dt)
{
OpenGLMesh* mesh = static_cast<OpenGLMesh*>(mModel->GetMesh());
auto& submeshes = mesh->GetSubmeshes();
OpenGLTexture* texture = submeshes.begin()->GetTexture(TextureType::Diffuse);
auto& image = texture->GetImage();
unsigned char average = CalculateAverageIntensity(image);
float gammaValue = mFuzzySystem.CalculateSystemOutput(static_cast<float>(average));
mGraphics->GetFramebuffer()->SetValueGamma(gammaValue);
}
unsigned char GammaController::CalculateAverageIntensity(std::vector<Pixel>& image)
{
unsigned int sum = 0.0f;
for (Pixel& pixel : image)
{
unsigned char intensity = static_cast<unsigned char>(0.3f * static_cast<float>(pixel.r) + 0.59f * static_cast<float>(pixel.g) + 0.11f * static_cast<float>(pixel.b));
sum += intensity;
}
return static_cast<unsigned char>(sum / image.size());
}
} // End of Elba namespace
| 34.985915 | 169 | 0.698873 | [
"mesh",
"object",
"vector",
"model"
] |
4a8c3b3c08e5cd6c8c2b206f21e0cd65428d3fd5 | 4,146 | cpp | C++ | src/copperfx/panels/NodeFlowViewPanel/NodeConnectionItem.cpp | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | 2 | 2019-06-25T23:36:55.000Z | 2022-03-07T04:15:50.000Z | src/copperfx/panels/NodeFlowViewPanel/NodeConnectionItem.cpp | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | null | null | null | src/copperfx/panels/NodeFlowViewPanel/NodeConnectionItem.cpp | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | 1 | 2019-08-22T08:23:37.000Z | 2019-08-22T08:23:37.000Z | #include <iostream>
#include <algorithm> // std::min
#include <QBrush>
#include <QPen>
#include <QGraphicsItem>
#include <QGraphicsScene>
#include "NodeConnectionItem.h"
#include "NodeSocketItem.h"
#include "NodeFlowScene.h"
namespace copper { namespace ui {
NodeConnectionItem::NodeConnectionItem(NodeFlowScene *scene): QGraphicsItem(nullptr) {
setAcceptHoverEvents(true);
setCacheMode(QGraphicsItem::DeviceCoordinateCache);
setZValue(2);
_scene = scene;
_scene->addItem(this);
_hovered = false;
_connected = false;
_socket_from = nullptr;
_socket_to = nullptr;
}
NodeConnectionItem::NodeConnectionItem(NodeFlowScene *scene, NodeSocketItem *socket_from, NodeSocketItem *socket_to): NodeConnectionItem(scene) {
setSocketFrom(socket_from);
setSocketTo(socket_to);
setFlag(QGraphicsItem::ItemIsSelectable, true);
setZValue(0);
}
NodeConnectionItem::~NodeConnectionItem() {
//if (_socket_from)
// _socket_from->connections().remove(_socket_from->connections().indexOf(this));
//if (_socket_to)
// _socket_to->connections().remove(_socket_to->connections().indexOf(this));
_scene->removeItem(this);
}
void NodeConnectionItem::setPosFrom(const QPointF &pos) {
if (_pos_from != pos) {
_pos_from = pos;
update();
}
}
void NodeConnectionItem::setPosTo(const QPointF &pos) {
if (_pos_to != pos) {
_pos_to = pos;
update();
}
}
void NodeConnectionItem::setSocketFrom(NodeSocketItem *socket_item) {
if(socket_item) {
_socket_from = socket_item;
_socket_from->connections().append(this);
if (_socket_to){
_connected = true;
setFlag(QGraphicsItem::ItemIsSelectable, true);
setZValue(0);
}
updatePosFromSockets();
}
}
void NodeConnectionItem::setSocketTo(NodeSocketItem *socket_item) {
if(socket_item) {
_socket_to = socket_item;
_socket_to->connections().append(this);
if (_socket_from){
_connected = true;
setFlag(QGraphicsItem::ItemIsSelectable, true);
setZValue(0);
}
updatePosFromSockets();
}
}
void NodeConnectionItem::updatePosFromSockets() {
if(_socket_from)_pos_from = _socket_from->scenePos();
if(_socket_to)_pos_to = _socket_to->scenePos();
update();
}
QRectF NodeConnectionItem::boundingRect() const {
return QRectF(
std::min(_pos_from.x(), _pos_to.x()) - 2.5,
std::min(_pos_from.y(), _pos_to.y()) - 2.5,
std::abs(_pos_from.x() - _pos_to.x()) + 5,
std::abs(_pos_from.y() - _pos_to.y()) + 5);
}
QPainterPath NodeConnectionItem::buildPath() const {
QPainterPath p;
p.moveTo(_pos_from);
qreal dx = _pos_to.x() - _pos_from.x();
qreal dy = _pos_to.y() - _pos_from.y();
QPointF ctr1(_pos_from.x() + dx * 0.25, _pos_from.y() + dy * 0.1);
QPointF ctr2(_pos_from.x() + dx * 0.75, _pos_from.y() + dy * 0.9);
p.cubicTo(ctr1, ctr2, _pos_to);
return p;
}
QPainterPath NodeConnectionItem::shape() const {
return buildPath();
}
void NodeConnectionItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(option);
Q_UNUSED(widget);
QPainterPath p = buildPath();
painter->setBrush(Qt::NoBrush);
painter->setPen(Qt::DashLine);
painter->setPen(QPen(Qt::black, 1.0));
if (_connected) {
// both sockets connected
painter->setPen(Qt::SolidLine);
if (isSelected()) {
painter->setPen(Qt::yellow);
} else {
if (_hovered) {
painter->setPen(QColor(255, 190, 64));
}
}
}
painter->drawPath(p);
if(!_connected) {
// this is a temporary connection, draw some pretty circles
painter->setBrush(Qt::SolidPattern);
painter->setPen(Qt::SolidLine);
painter->drawEllipse(QRectF(_pos_from.x()-2, _pos_from.y()-2, 4, 4));
painter->drawEllipse(QRectF(_pos_to.x()-2, _pos_to.y()-2, 4, 4));
}
}
NodeSocketItem* NodeConnectionItem::socketFrom() const {
return _socket_from;
}
NodeSocketItem* NodeConnectionItem::socketTo() const {
return _socket_to;
}
void NodeConnectionItem::hoverEnterEvent(QGraphicsSceneHoverEvent * event) {
_hovered = true;
QGraphicsItem::hoverEnterEvent(event);
}
void NodeConnectionItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * event) {
_hovered = false;
QGraphicsItem::hoverEnterEvent(event);
}
}}
| 22.906077 | 145 | 0.710806 | [
"shape"
] |
4a8fccde5e47a002f0b048fceb7ea6c066e3652a | 4,318 | cpp | C++ | java/cpp/com_automatak_dnp3_impl_CommandBuilderImpl.cpp | Kisensum/dnp3 | 0b525927562eb052e9406075811b283d80975bf8 | [
"Apache-2.0"
] | 1 | 2021-06-25T07:22:24.000Z | 2021-06-25T07:22:24.000Z | deps/dnp3/java/cpp/com_automatak_dnp3_impl_CommandBuilderImpl.cpp | danilob2/pyopendnp3_mac | c6b8297f6817555ebff28293bef82e9bffddc1fd | [
"Apache-2.0"
] | null | null | null | deps/dnp3/java/cpp/com_automatak_dnp3_impl_CommandBuilderImpl.cpp | danilob2/pyopendnp3_mac | c6b8297f6817555ebff28293bef82e9bffddc1fd | [
"Apache-2.0"
] | 1 | 2021-07-21T03:15:18.000Z | 2021-07-21T03:15:18.000Z | /*
* Copyright 2013-2016 Automatak, LLC
*
* Licensed to Automatak, LLC (www.automatak.com) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. Automatak, LLC
* licenses this file to you under the Apache License Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.html
*
* 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 "com_automatak_dnp3_impl_CommandBuilderImpl.h"
#include "opendnp3/master/CommandSet.h"
#include "jni/JCache.h"
#include "adapters/JNI.h"
using namespace opendnp3;
JNIEXPORT jlong JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_create_1native
(JNIEnv* env, jobject)
{
return (jlong) new CommandSet();
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_destroy_1native
(JNIEnv* env, jobject, jlong native)
{
delete (CommandSet*)native;
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_add_1crob_1native
(JNIEnv* env, jobject, jlong native, jobject jcommands)
{
const auto set = (CommandSet*) native;
std::vector<Indexed<ControlRelayOutputBlock>> commands;
auto process = [&](LocalRef<jobject> indexed)
{
const auto jindex = jni::JCache::IndexedValue.getindex(env, indexed);
const auto jcommand = jni::JCache::IndexedValue.getvalue(env, indexed);
auto& ref = jni::JCache::ControlRelayOutputBlock;
const auto code = jni::JCache::ControlCode.toType(env, ref.getfunction(env, jcommand));
const auto count = ref.getcount(env, jcommand);
const auto onTime = ref.getonTimeMs(env, jcommand);
const auto offTime = ref.getoffTimeMs(env, jcommand);
const auto status = jni::JCache::CommandStatus.toType(env, ref.getstatus(env, jcommand));
Indexed<ControlRelayOutputBlock> value(
ControlRelayOutputBlock(
static_cast<uint8_t>(code),
static_cast<uint8_t>(count),
static_cast<uint32_t>(onTime),
static_cast<uint32_t>(offTime),
CommandStatusFromType(static_cast<uint8_t>(status))
),
static_cast<uint16_t>(jindex)
);
commands.push_back(value);
};
JNI::Iterate(env, jcommands, process);
set->Add(commands);
}
template <class T, class Cache>
void process_analogs(JNIEnv* env, jlong native, jobject jcommands, Cache& cache)
{
const auto set = (CommandSet*)native;
std::vector<Indexed<T>> commands;
auto process = [&](jobject indexed)
{
const auto jindex = jni::JCache::IndexedValue.getindex(env, indexed);
const auto jcommand = jni::JCache::IndexedValue.getvalue(env, indexed);
const auto avalue = cache.getvalue(env, jcommand);
const auto status = jni::JCache::CommandStatus.toType(env, cache.getstatus(env, jcommand));
Indexed<T> value(
T(avalue, CommandStatusFromType(static_cast<uint8_t>(status))),
static_cast<uint16_t>(jindex)
);
commands.push_back(value);
};
JNI::Iterate(env, jcommands, process);
set->Add(commands);
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_add_1aoI16_1native
(JNIEnv* env, jobject, jlong native, jobject jcommands)
{
process_analogs<AnalogOutputInt16>(env, native, jcommands, jni::JCache::AnalogOutputInt16);
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_add_1aoI32_1native
(JNIEnv* env, jobject, jlong native, jobject jcommands)
{
process_analogs<AnalogOutputInt32>(env, native, jcommands, jni::JCache::AnalogOutputInt32);
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_add_1aoF32_1native
(JNIEnv* env, jobject, jlong native, jobject jcommands)
{
process_analogs<AnalogOutputFloat32>(env, native, jcommands, jni::JCache::AnalogOutputFloat32);
}
JNIEXPORT void JNICALL Java_com_automatak_dnp3_impl_CommandBuilderImpl_add_1aoD64_1native
(JNIEnv* env, jobject, jlong native, jobject jcommands)
{
process_analogs<AnalogOutputDouble64>(env, native, jcommands, jni::JCache::AnalogOutputDouble64);
}
| 34.269841 | 98 | 0.773043 | [
"vector"
] |
4a94cafde522deddf894b56a196fabb8fcf237c7 | 16,342 | hpp | C++ | tml/comm/comm_coll.hpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | tml/comm/comm_coll.hpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | tml/comm/comm_coll.hpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////
// //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing //
// http://earth.uq.edu.au/centre-geoscience-computing //
// //
// Primary Business: Brisbane, Queensland, Australia //
// Licensed under the Open Software License version 3.0 //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
/////////////////////////////////////////////////////////////
// --- collective communication primitives for TML_Comm ---
#include "tml/message/packed_multi_message.h"
/*!
broadcast single data to all other nodes
\param data the data to be broadcast
*/
template <typename T>
void TML_Comm::broadcast(T data)
{
MPI_Bcast(&data,1,GetType(data),rank(),m_comm);
}
/*!
broadcast an array of known size
\param data the array to be broadcast
\param ndata the size of the array (nr. of elements)
*/
template <typename T>
void TML_Comm::broadcast_array(T* data,int ndata)
{
MPI_Bcast(data,ndata,GetType(*data),rank(),m_comm);
}
/*!
broadcast the content of a STL container of simple types. Uses
2 MPI broadcasts for size and data.
\param data the data to be broadcast
*/
template <typename T>
void TML_Comm::broadcast_cont(const T& data)
{
int data_size=data.size();
// setup buffer
typename T::value_type *buffer=new typename T::value_type[data_size];
// put data into buffer
int count=0;
for(typename T::const_iterator iter=data.begin();
iter!=data.end();
iter++){
void* buf=reinterpret_cast<void*>(&(buffer[count])); // get memory adress for buffer element
new(buf)(typename T::value_type)(*iter); // initialize object at this adress
// the placement new stuff (see Stroustrup, p.255ff) is necessary
// because assignment buffer[count]=(*iter) doesn't work if the
// T::value_type contains constant member data. Initialization by
// calling the copy constructor directly doesn't work for builtin
// types
count++;
}
// broadcast size
broadcast(data_size);
// broadcast buffer
broadcast_array(buffer,data_size);
// clean up
delete [] buffer;
}
/*!
broadcast the content of a STL container of packable objects. Uses
2 MPI broadcasts for size and data.
\param data the data to be broadcast
*/
template <typename T>
void TML_Comm::broadcast_cont_packed(const T &data)
{
TML_Packed_Message* msg=new TML_Packed_Message(m_comm);
int nb_data=data.size();
msg->pack(nb_data); // pack number of items first
// pack data
for(typename T::const_iterator iter=data.begin();
iter!=data.end();
iter++){
msg->pack(*iter);
}
// broadcast size
broadcast(msg->size());
// broadcast data
broadcast_array(msg->buffer(),msg->size());
delete msg;
}
/*!
Receive broadcast of single data from a given node
\param data the data to be broadcast
\param root the node which sent the broadcast
*/
template <typename T>
void TML_Comm::recv_broadcast(T& data,int root)
{
MPI_Bcast(&data,1,GetType(data),root,m_comm);
}
/*!
Receive broadcast of an array of known size
\param data the array to be broadcast
\param ndata the size of the array (nr. of elements)
\param root the node which sent the broadcast
*/
template <typename T>
void TML_Comm::recv_broadcast_array(T* data,int ndata,int root)
{
MPI_Bcast(data,ndata,GetType(*data),root,m_comm);
}
/*!
Receive broadcast of the content of a STL container of simple types
from a given node. Uses 2 MPI broadcasts for size and data.
\param data the data to be broadcast
\param root the node which sent the broadcast
*/
template <typename T>
void TML_Comm::recv_broadcast_cont(T& data,int root)
{
int data_size;
//get size
recv_broadcast(data_size,root);
// setup recv buffer
typename T::value_type *buffer=new typename T::value_type[data_size];
//get data
recv_broadcast_array(buffer,data_size,root);
// insert into container
for(int i=0;i<data_size;i++){
data.insert(data.end(),buffer[i]);
}
//clean up
delete [] buffer;
}
/*!
Receive broadcast of the content of a STL container of packable objects
from a given node. Uses 2 MPI broadcasts for size and data.
\param data the data to be broadcast
\param root the node which sent the broadcast
*/
template <typename T>
void TML_Comm::recv_broadcast_cont_packed(T& data,int root)
{
int msg_size; // total size of the message
int nb_data; // number of data (i.e. the expected data.size())
//get size
recv_broadcast(msg_size,root);
//setup message
TML_Packed_Message* msg=new TML_Packed_Message(m_comm,msg_size);
//get data
recv_broadcast_array(msg->buffer(),msg_size,root);
// extract nuber of items
nb_data=msg->pop_int();
// unpack data
for(int i=0;i<nb_data;i++){
typename T::value_type tv;
msg->unpack(tv);
data.insert(data.end(),tv);
}
// clean up
delete msg;
}
/*!
scatter the content of a multimap. The key of the multimap is used to decide where to
send the data. Uses one MPI_Scatter (sizes) and one MPI_Scatterv (data) call.
\param data the multimap containing the data to be scattered
\todo checks, handling of out of range indices
*/
template <typename T>
void TML_Comm::scatter(const multimap<int,T> data)
{
// put data into buffer
int total_size=data.size();
T* buffer=new T[total_size];
int comm_size=size();
int *size_buffer=new int[comm_size];
int *offs_buffer=new int[comm_size];
int count=0;
int count_p=0;
for(int i=0;i<comm_size;i++){
typename multimap<int,T>::const_iterator begin=data.find(i);
typename multimap<int,T>::const_iterator end=data.upper_bound(i);
if(begin!=data.end()){
for(typename multimap<int,T>::const_iterator iter=begin;
iter!=end;
iter++){
buffer[count]=iter->second;
count++;
}
}
size_buffer[i]=count-count_p;
count_p=count;
}
// send size info
int dummy;
MPI_Scatter(size_buffer,1,MPI_INT,&dummy,1,MPI_INT,rank(),m_comm);
// construct offsets from sizes
offs_buffer[0]=0;
for(int i=1;i<comm_size;i++){
offs_buffer[i]=offs_buffer[i-1]+size_buffer[i-1];
}
// send data
T dummy2;
MPI_Scatterv(buffer,size_buffer,offs_buffer,GetType(*buffer),&dummy2,0,GetType(*buffer),rank(),m_comm);
// clean up
delete [] size_buffer;
delete [] offs_buffer;
delete [] buffer;
}
/*!
receive scattered data
\param data the received data
\param root the process which scattered the data
*/
template <typename T>
void TML_Comm::recv_scatter(T& data,int root)
{
// receive size
int size;
MPI_Scatter(NULL,0,MPI_INT,&size,1,MPI_INT,root,m_comm);
// allocate buffer buffer
typename T::value_type *buffer=new typename T::value_type[size];
// receive data
MPI_Scatterv(NULL,NULL,NULL,MPI_INT,buffer,size,GetType(*buffer),root,m_comm);
// put data in container
for(int i=0;i<size;i++){
data.insert(data.end(),buffer[i]);
}
// clean up
delete [] buffer;
}
/*!
Gather data from all other processes in the communicator into a multimap. The multimap-key
will be set according to the rank of the process where the data came from
\param data the multimap
*/
template <typename T>
void TML_Comm::gather(multimap<int,T>& data)
{
int dummy=0;
int comm_size=size();
int *size_buffer=new int[comm_size];
int *offs_buffer=new int[comm_size];
// receive sizes
MPI_Gather(&dummy,1,MPI_INT,size_buffer,1,MPI_INT,rank(),m_comm);
int totalsize=0;
for(int i=0;i<comm_size;i++){
totalsize+=size_buffer[i];
}
// setup receive buffer
T *buffer=new T[totalsize];
// construct offsets from sizes
offs_buffer[0]=0;
for(int i=1;i<comm_size;i++){
offs_buffer[i]=offs_buffer[i-1]+size_buffer[i-1];
}
// receive data
T dummy2;
MPI_Gatherv(&dummy2,0,GetType(dummy),buffer,size_buffer,offs_buffer,GetType(*buffer),rank(),m_comm);
// put data into multimap
for(int i=0;i<comm_size;i++){
for(int j=offs_buffer[i];j<offs_buffer[i]+size_buffer[i];j++){
data.insert(pair<int,T>(i,buffer[j]));
}
}
// clean up
delete [] size_buffer;
delete [] offs_buffer;
delete [] buffer;
}
/*!
Gather data from all other processes in the communicator into a multimap. The multimap-key
will be set according to the rank of the process where the data came from. Debug version
(output data)
\param data the multimap
*/
template <typename T>
void TML_Comm::gather_debug(multimap<int,T>& data)
{
int dummy=0;
int comm_size=size();
int *size_buffer=new int[comm_size];
int *offs_buffer=new int[comm_size];
// receive sizes
MPI_Gather(&dummy,1,MPI_INT,size_buffer,1,MPI_INT,rank(),m_comm);
int totalsize=0;
for(int i=0;i<comm_size;i++){
console.Debug() << "buffer size " << i << " - " << size_buffer[i] << "\n";
totalsize+=size_buffer[i];
}
// setup receive buffer
T *buffer=new T[totalsize];
// construct offsets from sizes
offs_buffer[0]=0;
for(int i=1;i<comm_size;i++){
offs_buffer[i]=offs_buffer[i-1]+size_buffer[i-1];
}
// receive data
T dummy2;
MPI_Gatherv(&dummy2,0,GetType(dummy),buffer,size_buffer,offs_buffer,GetType(*buffer),rank(),m_comm);
// put data into multimap
for(int i=0;i<comm_size;i++){
for(int j=offs_buffer[i];j<offs_buffer[i]+size_buffer[i];j++){
data.insert(pair<int,T>(i,buffer[j]));
}
}
// clean up
delete [] size_buffer;
delete [] offs_buffer;
delete [] buffer;
}
/*!
Send data to be gathered by a root process.
\param data the data (a container)
\param root the root process
*/
template <typename T>
void TML_Comm::send_gather(T& data,int root)
{
// send size
int size=data.size();
MPI_Gather(&size,1,MPI_INT,NULL,0,MPI_INT,root,m_comm);
// setup send buffer
typename T::value_type *buffer=new typename T::value_type[size];
// put data into send buffer
int count=0;
for(typename T::const_iterator iter=data.begin();
iter!=data.end();
iter++){
buffer[count]=*iter;
count++;
}
// send data
MPI_Gatherv(buffer,size,GetType(*buffer),NULL,NULL,NULL,MPI_INT,root,m_comm);
// clean up
delete [] buffer;
}
/*!
Send data to be gathered by a root process. Debug version.
\param data the data (a container)
\param root the root process
*/
template <typename T>
void TML_Comm::send_gather_debug(T& data,int root)
{
// send size
int size=data.size();
console.Debug() << "send size :" << size << "\n";
MPI_Gather(&size,1,MPI_INT,NULL,0,MPI_INT,root,m_comm);
// setup send buffer
typename T::value_type *buffer=new typename T::value_type[size];
// put data into send buffer
int count=0;
for(typename T::const_iterator iter=data.begin();
iter!=data.end();
iter++){
buffer[count]=*iter;
count++;
}
console.Debug() << "send count :" << count << "\n";
// send data
MPI_Gatherv(buffer,size,GetType(*buffer),NULL,NULL,NULL,MPI_INT,root,m_comm);
// clean up
delete [] buffer;
}
/*!
Scatter the content of a multimap of packable objects. The key of the multimap is used to decide where to
send the data. Uses one MPI_Scatter (sizes) and one MPI_Scatterv (data) call.
\param data the multimap containing the data to be scattered
\todo checks, handling of out of range indices
*/
template <typename T>
void TML_Comm::scatter_packed(const multimap<int,T> data)
{
int comm_size=size();
// construct new packed multimessage
TML_PackedMultiMessage *msg=new TML_PackedMultiMessage(m_comm);
// pack data
for(int i=1;i<comm_size;i++){
typename multimap<int,T>::const_iterator begin=data.find(i);
typename multimap<int,T>::const_iterator end=data.upper_bound(i);
(*msg)[i].pack(int(data.count(i)));
if(begin!=data.end()){
for(typename multimap<int,T>::const_iterator iter=begin;
iter!=end;
iter++){
(*msg)[i].pack(iter->second);
}
}
}
// send size
int dummy;
MPI_Scatter(msg->sizes(),1,MPI_INT,&dummy,1,MPI_INT,rank(),m_comm);
// send data
T dummy2;
MPI_Datatype data_type=GetType(*(msg->buffer()));
MPI_Scatterv(msg->buffer(),msg->sizes(),msg->offsets(),data_type,
&dummy2,0,data_type,rank(),m_comm);
// clean up
delete msg;
}
/*!
receive scattered packed data
\param data the received data
\param root the process which scattered the data
*/
template <typename T>
void TML_Comm::recv_scatter_packed(T& data,int root)
{
// receive size
int msg_size;
MPI_Scatter(NULL,0,MPI_INT,&msg_size,1,MPI_INT,root,m_comm);
// construct packed message of sufficient size
TML_Packed_Message* msg=new TML_Packed_Message(m_comm,msg_size);
// recceive data
MPI_Datatype data_type=GetType(*(msg->buffer()));
MPI_Scatterv(NULL,NULL,NULL,MPI_INT,msg->buffer(),msg_size,data_type,root,m_comm);
// extract number of items
msg->begin_unpack();
int nitems=msg->pop_int();
// unpack data
typename T::value_type item;
for(int i=0;i<nitems;i++){
msg->unpack(item);
data.insert(data.end(),item);
}
// clean up
delete msg;
}
template <typename T>
void TML_Comm::gather_packed(multimap<int,T> &data)
{
console.Debug() << "TML_Comm::gather_packed: enter\n";
int dummy=0;
int comm_size=size();
int *size_buffer=new int[comm_size];
int *offs_buffer=new int[comm_size];
// receive sizes
console.Debug()
<< "TML_Comm::gather_packed: gathering sizes\n";
MPI_Gather(&dummy,1,MPI_INT,size_buffer,1,MPI_INT,rank(),m_comm);
int totalsize=0;
for(int i=0;i<comm_size;i++){
//console.Debug()
// << "TML_Comm::gather_packed:"
// << " size from rank " << i << " = " << size_buffer[i] << "\n";
totalsize+=size_buffer[i];
}
console.Debug()
<< "TML_Comm::gather_packed: total msg size = " << totalsize << "\n";
// setup receive buffer
//setup message
TML_Packed_Message* msg=new TML_Packed_Message(m_comm,totalsize);
// construct offsets from sizes
offs_buffer[0]=0;
for(int i=1;i<comm_size;i++){
offs_buffer[i]=offs_buffer[i-1]+size_buffer[i-1];
}
// receive data
T dummy2;
console.Debug()
<< "TML_Comm::gather_packed: gathering data\n";
MPI_Gatherv(
&dummy2,0, GetType(dummy), msg->buffer(), size_buffer, offs_buffer,
GetType(*(msg->buffer())),rank(),m_comm
);
// put data into multimap
console.Debug()
<< "TML_Comm::gather_packed: unpacking into multi-map\n";
for(int i=0;i<comm_size;i++){
if (size_buffer[i] > 0)
{
const int numElems = msg->pop_int();
for(int j=0; j < numElems; j++){
//console.Debug()
// << "TML_Comm::gather_packed:"
// << " unpacking object (" << i << "," << j << ")\n";
T t;
msg->unpack(t);
data.insert(pair<int,T>(i, t));
}
}
}
console.Debug() << "TML_Comm::gather_packed: done unpacking into multi-map\n";
// clean up
delete [] size_buffer;
delete [] offs_buffer;
delete msg;
console.Debug() << "TML_Comm::gather_packed: exit\n";
}
template <typename T>
void TML_Comm::send_gather_packed(const T &data, int root)
{
console.Debug() << "TML_Comm::send_gather_packed: enter\n";
// setup send buffer
TML_Packed_Message* msg =
new TML_Packed_Message(
m_comm,
std::max(static_cast<size_t>(64), data.size()*sizeof(typename T::value_type))
);
// put data into send buffer
const int numElems = data.size();
msg->pack(numElems);
for(typename T::const_iterator iter=data.begin();
iter!=data.end();
iter++){
msg->pack(*iter);
}
// send size
int size = msg->size();
console.Debug() << "TML_Comm::send_gather_packed: sending data size...\n";
MPI_Gather(&size,1,MPI_INT,NULL,0,MPI_INT,root,m_comm);
// send data
console.Debug() << "TML_Comm::send_gather_packed: sending data...\n";
MPI_Gatherv(
msg->buffer(), msg->size(),
GetType(*(msg->buffer())),
NULL, NULL, NULL, MPI_INT, root, m_comm
);
// clean up
delete msg;
console.Debug() << "TML_Comm::send_gather_packed: exit\n";
}
template <typename T>
T TML_Comm::sum_all(const T& data)
{
T res;
MPI_Datatype data_type=GetType(data);
MPI_Allreduce((void*)(&data),(void*)(&res),1,data_type,MPI_SUM,m_comm);
return res;
}
| 27.792517 | 107 | 0.662771 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.