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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f836f69ff7160bb3952b68ff60a659804964a376 | 2,978 | cxx | C++ | vital/types/object_track_set.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | 1 | 2020-10-14T18:22:42.000Z | 2020-10-14T18:22:42.000Z | vital/types/object_track_set.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | null | null | null | vital/types/object_track_set.cxx | neal-siekierski/kwiver | 1c97ad72c8b6237cb4b9618665d042be16825005 | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +29
* Copyright 2013-2017, 2019 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* \brief Implementation of \link kwiver::vital::track_set track_set \endlink
* member functions
*/
#include "object_track_set.h"
#include <limits>
namespace kwiver {
namespace vital {
typedef std::unique_ptr< track_set_implementation > tsi_uptr;
/// Default Constructor
object_track_set
::object_track_set()
: track_set( tsi_uptr( new simple_track_set_implementation ) )
{
}
/// Constructor specifying the implementation
object_track_set
::object_track_set( std::unique_ptr<track_set_implementation> impl )
: track_set( std::move( impl ) )
{
}
/// Constructor from a vector of tracks
object_track_set
::object_track_set( std::vector< track_sptr > const& tracks )
: track_set( tsi_uptr( new simple_track_set_implementation( tracks ) ) )
{
}
/// Clone the track state (polymorphic copy constructor)
track_state_sptr
object_track_state::clone ( clone_type ct ) const
{
if ( ct == clone_type::DEEP )
{
auto new_detection =
( this->detection_ ? this->detection_->clone() : nullptr );
auto copy = std::make_shared< object_track_state >(
this->frame(), this->time(), std::move( new_detection ) );
copy->set_image_point( this->image_point_ );
copy->set_track_point( this->track_point_ );
return std::move( copy );
}
else
{
return std::make_shared< object_track_state >( *this );
}
}
} } // end namespace vital
| 31.020833 | 81 | 0.733714 | [
"vector"
] |
f8395e97846e46c88984c384bfad2d2d9a0e3d30 | 231 | cpp | C++ | bindings/python/file.cpp | jbx81-1337/binlex | ea8bedd0283a57ac55d1d8844c83f7a5d20a6c9c | [
"Unlicense"
] | null | null | null | bindings/python/file.cpp | jbx81-1337/binlex | ea8bedd0283a57ac55d1d8844c83f7a5d20a6c9c | [
"Unlicense"
] | null | null | null | bindings/python/file.cpp | jbx81-1337/binlex | ea8bedd0283a57ac55d1d8844c83f7a5d20a6c9c | [
"Unlicense"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "file.h"
#include <vector>
namespace py = pybind11;
void init_file(py::module &handle){
py::class_<binlex::File>(handle, "File", "Binlex File (Base) Module");
}
| 21 | 72 | 0.701299 | [
"vector"
] |
f83c7c1987a55675a3d16445a86a9ef93250dc1f | 7,978 | hpp | C++ | bsengine/src/bstorm/obj_shot.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | bsengine/src/bstorm/obj_shot.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | bsengine/src/bstorm/obj_shot.hpp | At-sushi/bstorm | 156036afd698d98f0ed67f0efa6bc416115806f7 | [
"MIT"
] | null | null | null | #pragma once
#include <bstorm/point2D.hpp>
#include <bstorm/vertex.hpp>
#include <bstorm/obj_render.hpp>
#include <bstorm/obj_move.hpp>
#include <bstorm/obj_col.hpp>
#include <list>
#include <deque>
namespace bstorm
{
class ShotData;
class ShotIntersection;
class ShotCounter;
class ObjShot : public ObjRender, public ObjMove, public ObjCol, public std::enable_shared_from_this<ObjShot>
{
public:
ObjShot(bool isPlayerShot, const std::shared_ptr<CollisionDetector>& colDetector, const std::shared_ptr<Package>& package);
~ObjShot();
void Update() override;
void OnDead() noexcept override;
void Render(const std::shared_ptr<Renderer>& renderer) override;
bool IsRegistered() const;
void Regist();
bool IsPlayerShot() const;
// intersection
void AddIntersectionCircleA1(float r);
void AddIntersectionCircleA2(float x, float y, float r);
void AddIntersectionLine(float x1, float y1, float x2, float y2, float width);
void AddTempIntersectionCircleA1(float r);
void AddTempIntersectionCircleA2(float x, float y, float r);
void AddTempIntersectionLine(float x1, float y1, float x2, float y2, float width);
bool IsIntersectionEnabled() const;
void SetIntersectionEnable(bool enable);
bool IsTempIntersectionMode() const;
// shot data
const NullableSharedPtr<ShotData>& GetShotData() const;
virtual void SetShotData(const std::shared_ptr<ShotData>& shotData);
int GetAnimationFrameCount() const;
int GetAnimationIndex() const;
double GetDamage() const;
void SetDamage(double damage);
int GetPenetration() const;
void SetPenetration(int penetration);
int GetDelay() const;
void SetDelay(int delay);
bool IsDelay() const;
int GetSourceBlendType() const;
void SetSourceBlendType(int blendType);
float GetAngularVelocity() const;
void SetAngularVelocity(float angularVelocity);
bool IsSpellResistEnabled() const;
void SetSpellResistEnable(bool enable);
bool IsSpellFactorEnabled() const;
void SetSpellFactor(bool enable);
bool IsEraseShotEnabled() const;
void SetEraseShotEnable(bool enable);
bool IsItemChangeEnabled() const;
void SetItemChangeEnable(bool enable);
bool IsAutoDeleteEnabled() const;
void SetAutoDeleteEnable(bool enable);
// delete
void ToItem();
void EraseWithSpell();
void DeleteImmediate();
void FadeDelete();
float GetFadeScale() const;
bool IsFadeDeleteStarted() const;
bool IsFrameDeleteStarted() const;
int GetDeleteFrameTimer() const;
int GetFadeDeleteFrameTimer() const;
void SetDeleteFrame(int frame);
// graze
virtual void Graze();
virtual bool IsGrazeEnabled() const;
// spawn
class AddedShot
{
public:
AddedShot(int objId, int frame);
AddedShot(int objId, int frame, float dist, float angle);
enum class Type
{
A1,
A2
};
const Type type;
const int objId;
int frame;
const float dist;
const float angle;
};
void AddShotA1(int shotObjId, int frame);
void AddShotA2(int shotObjId, int frame, float dist, float angle);
int GetFrameCountForAddShot() const;
const std::list<AddedShot>& GetAddedShot() const;
virtual void GenerateBonusItem();
protected:
void OnTrans(float dx, float dy) override;
void RenderIntersection(const std::shared_ptr<Renderer>& renderer);
void CheckAutoDelete(float x, float y);
void UpdateAnimationPosition();
void TickDelayTimer();
void TickDeleteFrameTimer();
void TickAddedShotFrameCount();
void TickFadeDeleteTimer();
NullableSharedPtr<ShotData> shotData_;
bool isGrazeInvalid_;
bool isTempIntersectionMode_;
private:
void AddIntersection(const std::shared_ptr<ShotIntersection>& isect);
void AddTempIntersection(const std::shared_ptr<ShotIntersection>& isect);
const bool isPlayerShot_;
bool isRegistered_;
bool isFrameDeleteStarted_;
bool isFadeDeleteStarted_;
bool spellResistEnable_;
bool eraseShotEnable_;
bool spellFactorEnable_;
bool itemChangeEnable_;
bool intersectionEnable_;
bool autoDeleteEnable_;
float angularVelocity_;
double damage_;
int sourceBlendType_;
int penetration_;
int fadeDeleteTimer_;
int delayTimer_;
int deleteFrameTimer_;
int fadeDeleteFrame_;
int animationFrameCnt_;
int animationIdx_;
std::list<AddedShot> addedShots_;
int addedShotFrameCnt_;
};
class ObjLaser : public ObjShot
{
public:
ObjLaser(bool isPlayerShot, const std::shared_ptr<CollisionDetector>& colDetector, const std::shared_ptr<Package>& package);
void SetShotData(const std::shared_ptr<ShotData>& shotData) override;
void Graze() override;
bool IsGrazeEnabled() const override;
float GetLength() const;
void SetLength(float len); // 上限の長さを設定
float GetRenderWidth() const;
virtual void SetRenderWidth(float width);
float GetIntersectionWidth() const;
void SetIntersectionWidth(float width);
float GetGrazeInvalidFrame() const;
void SetGrazeInvalidFrame(int frame);
float GetGrazeInvalidTimer() const;
float GetItemDistance() const;
void SetItemDistance(float distance);
protected:
void OnTrans(float dx, float dy) override {}
void TickGrazeInvalidTimer();
private:
float length_;
float renderWidth_;
float intersectionWidth_;
bool hasIntersectionWidth_;
int grazeInvalidFrame_;
int grazeInvalidTimer_;
float itemDistance_;
};
class ObjLooseLaser : public ObjLaser
{
public:
ObjLooseLaser(bool isPlayerShot, const std::shared_ptr<CollisionDetector>& colDetector, const std::shared_ptr<Package>& package);
void Update() override;
void Render(const std::shared_ptr<Renderer>& renderer) override;
void GenerateBonusItem() override;
float GetInvalidLengthHead() const;
float GetInvalidLengthTail() const;
bool IsDefaultInvalidLengthEnabled() const;
void SetDefaultInvalidLengthEnable(bool enable);
void SetInvalidLength(float head, float tail);
virtual Point2D GetHead() const;
virtual Point2D GetTail() const;
virtual float GetRenderLength() const;
protected:
void UpdateIntersection();
void RenderLaser(float width, float length, float angle, const std::shared_ptr<Renderer>& renderer);
private:
void Extend();
bool defaultInvalidLengthEnable_;
float invalidLengthHead_;
float invalidLengthTail_;
float renderLength_; // レーザーの描画時の長さ, 不変条件 : 常に正
};
class ObjStLaser : public ObjLooseLaser
{
public:
ObjStLaser(bool isPlayerShot, const std::shared_ptr<CollisionDetector>& colDetector, const std::shared_ptr<Package>& package);
void Update() override;
void Render(const std::shared_ptr<Renderer>& renderer) override;
Point2D GetTail() const override;
float GetLaserAngle() const;
void SetLaserAngle(float angle);
bool HasSource() const;
void SetSource(bool hasSource);
float GetRenderLength() const override;
private:
float laserAngle_;
bool laserSourceEnable_;
float laserWidthScale_;
};
class ObjCrLaser : public ObjLaser
{
public:
ObjCrLaser(bool isPlayerShot, const std::shared_ptr<CollisionDetector>& colDetector, const std::shared_ptr<Package>& package);
void Update() override;
void Render(const std::shared_ptr<Renderer>& renderer) override;
void GenerateBonusItem() override;
void SetRenderWidth(float width) override;
float GetTipDecrement() const;
void SetTipDecrement(float dec);
int GetLaserNodeCount() const;
protected:
void FixVertexDistance_(float width);
void Extend(float x, float y);
std::vector<Vertex> trail_;
float totalLaserLength_;
std::deque<float> laserNodeLengthList_;
int tailPos_;
bool hasHead_;
const size_t shrinkThresholdOffset_;
float headX_;
float headY_;
float tipDecrement_;
};
} | 32.430894 | 133 | 0.725244 | [
"render",
"vector"
] |
f843abfb1fbf31a9a282e94a1e173396094e4813 | 711 | cc | C++ | src/leetcode/linklist_test.cc | zhaozigu/algs-multi-langs | 65ef5fc6df6236064a5c81e5bb7e99c4bae044a7 | [
"CNRI-Python"
] | null | null | null | src/leetcode/linklist_test.cc | zhaozigu/algs-multi-langs | 65ef5fc6df6236064a5c81e5bb7e99c4bae044a7 | [
"CNRI-Python"
] | null | null | null | src/leetcode/linklist_test.cc | zhaozigu/algs-multi-langs | 65ef5fc6df6236064a5c81e5bb7e99c4bae044a7 | [
"CNRI-Python"
] | null | null | null | #include "gtest/gtest.h"
#include <vector>
using namespace ::testing;
using namespace std;
#include "linklist.hpp"
TEST(treenode, BuildLinkedListByOneElement)
{
ListNode root(1);
vector<int> ins = {2};
vector<int> out = {1, 2};
ASSERT_EQ(out, LinkToArray(PushBackList(&root, ins)));
DestroyLinkList(&root);
}
TEST(treenode, BuildLinkedListByMultiElements)
{
ListNode root(1);
vector<int> ins = {2, 3, 4, 5};
vector<int> out = {1, 2, 3, 4, 5};
ASSERT_EQ(out, LinkToArray(PushBackList(&root, ins)));
DestroyLinkList(&root);
}
TEST(treenode, BuildLinkedListByDefaultConstructFunction)
{
ListNode root;
ASSERT_EQ(0, root.val);
ASSERT_EQ(nullptr, root.next);
DestroyLinkList(&root);
} | 22.21875 | 57 | 0.704641 | [
"vector"
] |
f8535063ede6b7be7aa06bd7177dbc58dd6d3287 | 7,060 | cpp | C++ | src/Index/src/DocumentFrequencyTable.cpp | jasonfeihe/BitFunnel | 859f3038e1978d066426ebaef17354c8ec408402 | [
"MIT"
] | 364 | 2016-08-08T21:45:24.000Z | 2022-03-27T13:46:51.000Z | src/Index/src/DocumentFrequencyTable.cpp | jasonfeihe/BitFunnel | 859f3038e1978d066426ebaef17354c8ec408402 | [
"MIT"
] | 321 | 2016-08-08T22:00:28.000Z | 2020-11-30T23:03:16.000Z | src/Index/src/DocumentFrequencyTable.cpp | jasonfeihe/BitFunnel | 859f3038e1978d066426ebaef17354c8ec408402 | [
"MIT"
] | 44 | 2016-08-14T16:20:29.000Z | 2021-10-03T07:46:26.000Z | // The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <algorithm> // std::sort()
#include <istream>
#include "BitFunnel/Exceptions.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/ITermToText.h"
#include "CsvTsv/Csv.h"
#include "DocumentFrequencyTable.h"
#include "TermToText.h"
namespace BitFunnel
{
//*************************************************************************
//
// Factory methods
//
//*************************************************************************
std::unique_ptr<IDocumentFrequencyTable>
Factories::CreateDocumentFrequencyTable(std::istream& input)
{
return
std::unique_ptr<IDocumentFrequencyTable>(
new DocumentFrequencyTable(input));
}
//*************************************************************************
//
// DocumentFrequencyTable
//
//*************************************************************************
DocumentFrequencyTable::DocumentFrequencyTable()
{
}
DocumentFrequencyTable::DocumentFrequencyTable(std::istream& input)
{
//
// Read sorted entries from stream.
//
CsvTsv::CsvTableParser parser(input);
CsvTsv::TableReader reader(parser);
CsvTsv::InputColumn<Term::Hash> hash(
"hash",
"Term's raw hash.");
hash.SetHexMode(true);
// NOTE: Cannot use OutputColumn<Term::GramSize> because OutputColumn
// does not implement a specialization for char.
CsvTsv::InputColumn<unsigned> gramSize(
"gramSize",
"Term's gram size.");
// NOTE: Cannot use OutputColumn<Term::StreamId> because OutputColumn
// does not implement a specialization for char.
CsvTsv::InputColumn<unsigned> streamId(
"streamId",
"Term's stream id.");
CsvTsv::InputColumn<double> frequency(
"frequency",
"Term's frequency.");
CsvTsv::InputColumn<std::string> text(
"text",
"Term's text.");
reader.DefineColumn(hash);
reader.DefineColumn(gramSize);
reader.DefineColumn(streamId);
reader.DefineColumn(frequency);
reader.DefineColumn(text);
reader.ReadPrologue();
while (!reader.AtEOF())
{
reader.ReadDataRow();
Term term(hash,
static_cast<Term::StreamId>(streamId),
static_cast<Term::GramSize>(gramSize));
if (m_entries.size() > 0 && m_entries.back().GetFrequency() < frequency)
{
RecoverableError
error("DocumentFrequencyTable: expect non-increasing frequencies.");
throw error;
}
m_entries.push_back(Entry(term, frequency));
}
// TODO: Seems like this would read past EOF.
reader.ReadEpilogue();
}
void DocumentFrequencyTable::Write(std::ostream & output,
ITermToText const * termToText)
{
//
// Sort entries by descending frequency.
//
struct
{
bool operator() (Entry a, Entry b)
{
// Sorts by decreasing frequency.
return a.GetFrequency() > b.GetFrequency();
}
} compare;
// Sort document frequency records by decreasing frequency.
std::sort(m_entries.begin(), m_entries.end(), compare);
//
// Write sorted entries to stream.
//
CsvTsv::CsvTableFormatter formatter(output);
CsvTsv::TableWriter writer(formatter);
CsvTsv::OutputColumn<Term::Hash> hash(
"hash",
"Term's raw hash.");
hash.SetHexMode(true);
// NOTE: Cannot use OutputColumn<Term::GramSize> because OutputColumn
// does not implement a specialization for char.
CsvTsv::OutputColumn<unsigned> gramSize(
"gramSize",
"Term's gram size.");
// NOTE: Cannot use OutputColumn<Term::StreamId> because OutputColumn
// does not implement a specialization for char.
CsvTsv::OutputColumn<unsigned> streamId(
"streamId",
"Term's stream id.");
CsvTsv::OutputColumn<double> frequency(
"frequency",
"Term's frequency.");
CsvTsv::OutputColumn<std::string> text(
"text",
"Term's text.");
writer.DefineColumn(hash);
writer.DefineColumn(gramSize);
writer.DefineColumn(streamId);
writer.DefineColumn(frequency);
writer.DefineColumn(text);
writer.WritePrologue();
for (auto & entry : m_entries)
{
Term const & term = entry.GetTerm();
hash = term.GetRawHash();
gramSize = term.GetGramSize();
streamId = term.GetStream();
frequency = entry.GetFrequency();
if (termToText != nullptr)
{
text = termToText->Lookup(term.GetRawHash());
}
else
{
text = std::string("");
}
writer.WriteDataRow();
}
writer.WriteEpilogue();
}
void DocumentFrequencyTable::AddEntry(Entry const & entry)
{
m_entries.push_back(entry);
}
DocumentFrequencyTable::Entry const & DocumentFrequencyTable::operator[](size_t index) const
{
return m_entries[index];
}
std::vector<DocumentFrequencyTable::Entry>::const_iterator DocumentFrequencyTable::begin() const
{
return m_entries.begin();
}
std::vector<DocumentFrequencyTable::Entry>::const_iterator DocumentFrequencyTable::end() const
{
return m_entries.end();
}
size_t DocumentFrequencyTable::size() const
{
return m_entries.size();
}
}
| 29.663866 | 100 | 0.572663 | [
"vector"
] |
f85fb36405a7cefe6498f306959ec397284cbc5e | 4,908 | hpp | C++ | data/train/cpp/e7fa6d74cb11d364357a907ed9fae4a04265e0f9tool_locator.hpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/cpp/e7fa6d74cb11d364357a907ed9fae4a04265e0f9tool_locator.hpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/cpp/e7fa6d74cb11d364357a907ed9fae4a04265e0f9tool_locator.hpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | /******************************************************************************
BigWorld Technology
Copyright BigWorld Pty, Ltd.
All Rights Reserved. Commercial in confidence.
WARNING: This computer program is protected by copyright law and international
treaties. Unauthorized use, reproduction or distribution of this program, or
any portion of this program, may result in the imposition of civil and
criminal penalties as provided by law.
******************************************************************************/
#ifndef TOOL_LOCATOR_HPP
#define TOOL_LOCATOR_HPP
#include "cstdmf/named_object.hpp"
#include "math/matrix.hpp"
/**
* This class keeps the factory methods for all types of Tool Locators
* It is right after #include named_object.hpp because borland
* dislikes it after some other include files.
*/
class ToolLocator;
typedef NamedObject<ToolLocator * (*)()> LocatorFactory;
#include "cstdmf/smartpointer.hpp"
#include "pyscript/pyobject_plus.hpp"
#include "pyscript/script.hpp"
#include "math/planeeq.hpp"
class Tool;
#define LOCATOR_FACTORY_DECLARE( CONSTRUCT ) \
static LocatorFactory s_factory; \
virtual LocatorFactory & factory() { return s_factory; } \
static ToolLocator * s_create() { return new CONSTRUCT; } \
#define LOCATOR_FACTORY( CLASS ) \
LocatorFactory CLASS::s_factory( #CLASS, CLASS::s_create ); \
/**
* The ToolLocator class positions a tool in the world.
*/
class ToolLocator : public PyObjectPlus
{
Py_Header( ToolLocator, PyObjectPlus )
public:
ToolLocator( PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool ) = 0;
virtual bool positionValid() const { return true; }
const Matrix& transform() const { return transform_; }
void transform( const Matrix& m ) { transform_ = m; }
virtual Vector3 direction() const { return Vector3( 0.f, 1.f, 0.f ); };
protected:
Matrix transform_;
};
typedef SmartPointer<ToolLocator> ToolLocatorPtr;
PY_SCRIPT_CONVERTERS_DECLARE( ToolLocator )
/**
* This class implements a tool locator that sits at the origin.
*/
class OriginLocator : public ToolLocator
{
Py_Header( OriginLocator, ToolLocator )
public:
OriginLocator( PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
PY_FACTORY_DECLARE()
private:
LOCATOR_FACTORY_DECLARE( OriginLocator() )
};
/**
* This class implements a tool locator that sits on a plane.
*/
class PlaneToolLocator : public ToolLocator
{
Py_Header( PlaneToolLocator, ToolLocator )
public:
PlaneToolLocator( PlaneEq * pPlane = NULL, PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
PY_FACTORY_DECLARE()
private:
PlaneEq planeEq_;
LOCATOR_FACTORY_DECLARE( PlaneToolLocator() )
};
/**
* This class implements a tool locator that sits on the most orthogonal
* plane of the 3 major axes to the camera.
*/
class TriPlaneToolLocator : public ToolLocator
{
Py_Header( TriPlaneToolLocator, ToolLocator )
public:
TriPlaneToolLocator( const Vector3& pos = s_lastPos, PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
PY_FACTORY_DECLARE()
private:
PlaneEq planeEq_[3];
Vector3 fulcrum_;
static Vector3 s_lastPos;
};
/**
* This class implements a tool locator that sits on the most orthogonal
* plane to the camera, and takes a position for the planes' fulcra.
*/
class AdaptivePlaneToolLocator : public ToolLocator
{
Py_Header( AdaptivePlaneToolLocator, ToolLocator )
public:
AdaptivePlaneToolLocator( const Vector3& pos, PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
PY_FACTORY_DECLARE()
private:
Vector3 fulcrum_;
};
/**
* This class implements a tool locator that sits on a line.
*/
class LineToolLocator : public ToolLocator
{
Py_Header( LineToolLocator, ToolLocator )
public:
LineToolLocator( const Vector3& origin = Vector3( 0, 0, 0), const Vector3& direction = Vector3( 0, 0, 1), PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
virtual Vector3 direction() const { return direction_; }
PY_FACTORY_DECLARE()
private:
Vector3 origin_;
Vector3 direction_;
LOCATOR_FACTORY_DECLARE( LineToolLocator() )
};
class ChunkToolLocator : public ToolLocator
{
Py_Header( ChunkToolLocator, ToolLocator )
public:
ChunkToolLocator( PyTypePlus * pType = &s_type_ );
};
/**
* This class implements a tool locator that finds the chunk a tool is in.
*/
class PlaneChunkLocator : public ChunkToolLocator
{
Py_Header( PlaneChunkLocator, ChunkToolLocator )
public:
PlaneChunkLocator( PyTypePlus * pType = &s_type_ );
virtual void calculatePosition( const Vector3& worldRay, Tool& tool );
PY_FACTORY_DECLARE()
private:
LOCATOR_FACTORY_DECLARE( PlaneChunkLocator() )
};
#endif | 28.206897 | 139 | 0.729829 | [
"transform"
] |
f861dd2889ad04b5babfb65ac885640d5fc11fec | 15,290 | cpp | C++ | src/gl/gltex.cpp | eckserah/nifskope_updated | f037410e824263b8351b8b85da91e33cfc7a4b19 | [
"RSA-MD"
] | 4 | 2022-02-06T03:21:00.000Z | 2022-02-09T17:39:09.000Z | src/gl/gltex.cpp | eckserah/nifskope_updated | f037410e824263b8351b8b85da91e33cfc7a4b19 | [
"RSA-MD"
] | null | null | null | src/gl/gltex.cpp | eckserah/nifskope_updated | f037410e824263b8351b8b85da91e33cfc7a4b19 | [
"RSA-MD"
] | 2 | 2022-02-09T17:39:11.000Z | 2022-03-31T03:55:53.000Z | /***** BEGIN LICENSE BLOCK *****
BSD License
Copyright (c) 2005-2015, NIF File Format Library and Tools
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. The name of the NIF File Format Library and Tools project may not be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
***** END LICENCE BLOCK *****/
#include "gltex.h"
#include "message.h"
#include "gl/glscene.h"
#include "gl/gltexloaders.h"
#include "model/nifmodel.h"
#include <fsengine/fsengine.h>
#include "gamemanager.h"
#include <QDebug>
#include <QDir>
#include <QFileSystemWatcher>
#include <QListView>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QSettings>
#include <algorithm>
//! @file gltex.cpp TexCache management
#ifdef WIN32
PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = nullptr;
PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = nullptr;
#endif
//! Number of texture units
GLint num_texture_units = 0;
//! Maximum anisotropy
float max_anisotropy = 1.0f;
void set_max_anisotropy()
{
static QSettings settings;
max_anisotropy = std::min( std::pow( settings.value( "Settings/Render/General/Anisotropic Filtering", 4.0 ).toFloat(), 2.0f ),
max_anisotropy );
}
float get_max_anisotropy()
{
return max_anisotropy;
}
void initializeTextureUnits( const QOpenGLContext * context )
{
if ( context->hasExtension( "GL_ARB_multitexture" ) ) {
glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &num_texture_units );
if ( num_texture_units < 1 )
num_texture_units = 1;
//qDebug() << "texture units" << num_texture_units;
} else {
qCWarning( nsGl ) << QObject::tr( "Multitexturing not supported." );
num_texture_units = 1;
}
if ( context->hasExtension( "GL_EXT_texture_filter_anisotropic" ) ) {
glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
set_max_anisotropy();
//qDebug() << "maximum anisotropy" << max_anisotropy;
}
#ifdef WIN32
if ( !glActiveTextureARB )
glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)context->getProcAddress( "glActiveTextureARB" );
if ( !glClientActiveTextureARB )
glClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)context->getProcAddress( "glClientActiveTextureARB" );
#endif
initializeTextureLoaders( context );
}
bool activateTextureUnit( int stage )
{
if ( num_texture_units <= 1 )
return ( stage == 0 );
if ( stage < num_texture_units ) {
glActiveTextureARB( GL_TEXTURE0 + stage );
glClientActiveTextureARB( GL_TEXTURE0 + stage );
return true;
}
return false;
}
void resetTextureUnits( int numTex )
{
if ( num_texture_units <= 1 ) {
glDisable( GL_TEXTURE_2D );
return;
}
for ( int x = numTex - 1; x >= 0; x-- ) {
glActiveTextureARB( GL_TEXTURE0 + x );
glDisable( GL_TEXTURE_2D );
glMatrixMode( GL_TEXTURE );
glLoadIdentity();
glMatrixMode( GL_MODELVIEW );
glClientActiveTextureARB( GL_TEXTURE0 + x );
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
}
}
/*
* TexCache
*/
TexCache::TexCache( QObject * parent ) : QObject( parent )
{
watcher = new QFileSystemWatcher( this );
connect( watcher, &QFileSystemWatcher::fileChanged, this, &TexCache::fileChanged );
}
TexCache::~TexCache()
{
//flush();
}
QString TexCache::find( const QString & file, const QString & nifdir, Game::GameMode game )
{
return find( file, nifdir, *(new QByteArray()), game );
}
QString TexCache::find( const QString & file, const QString & nifdir, QByteArray & data, Game::GameMode game )
{
if ( file.isEmpty() )
return QString();
if ( QFile( file ).exists() )
return file;
QSettings settings;
QString filename = QDir::toNativeSeparators( file );
QStringList extensions;
extensions << ".dds";
bool replaceExt = false;
bool textureAlternatives = settings.value( "Settings/Resources/Alternate Extensions", false ).toBool();
if ( textureAlternatives ) {
extensions << ".tga" << ".png" << ".bmp" << ".nif" << ".texcache";
for ( const QString ext : QStringList{ extensions } )
{
if ( filename.endsWith( ext, Qt::CaseInsensitive ) ) {
extensions.removeAll( ext );
extensions.prepend( ext );
filename = filename.left( filename.length() - ext.length() );
replaceExt = true;
break;
}
}
}
// attempt to find the texture in one of the folders
QDir dir;
for ( const QString& ext : extensions ) {
if ( replaceExt ) {
filename += ext;
}
auto appdir = QDir::currentPath();
// First search NIF root
dir.setPath( nifdir );
if ( dir.exists( filename ) ) {
return dir.filePath( filename );
}
// Next search NifSkope dir
dir.setPath( appdir );
if ( dir.exists( filename ) ) {
return dir.filePath( filename );
}
for ( QString folder : Game::GameManager::folders(game) ) {
// TODO: Always search nifdir without requiring a relative entry
// in folders? Not too intuitive to require ".\" in your texture folder list
// even if it is added by default.
if ( folder.startsWith( "./" ) || folder.startsWith( ".\\" ) ) {
folder = nifdir + "/" + folder;
}
dir.setPath( folder );
if ( dir.exists( filename ) ) {
filename = dir.filePath( filename );
filename = QDir::toNativeSeparators( filename );
return filename;
}
}
// Search through archives last, and load any requested textures into memory.
for ( FSArchiveFile * archive : Game::GameManager::opened_archives(game) ) {
if ( archive ) {
filename = QDir::fromNativeSeparators( filename.toLower() );
if ( archive->hasFile( filename ) ) {
QByteArray outData;
archive->fileContents( filename, outData );
if ( !outData.isEmpty() ) {
data = outData;
filename = QDir::toNativeSeparators( filename );
return filename;
}
}
}
}
// For Skyrim and FO4 which occasionally leave the textures off
if ( !filename.startsWith( "textures", Qt::CaseInsensitive ) ) {
QRegularExpression re( "textures[\\\\/]", QRegularExpression::CaseInsensitiveOption );
int texIdx = filename.indexOf( re );
if ( texIdx > 0 ) {
filename.remove( 0, texIdx );
} else {
while ( filename.startsWith( "/" ) || filename.startsWith( "\\" ) )
filename.remove( 0, 1 );
if ( !filename.startsWith( "textures", Qt::CaseInsensitive ) && !filename.startsWith( "shaders", Qt::CaseInsensitive ) )
filename.prepend( "textures\\" );
}
return find( filename, nifdir, data, game );
}
if ( !replaceExt )
break;
// Remove file extension
filename = filename.left( filename.length() - ext.length() );
}
bool searchFallback = settings.value("Settings/Resources/Other Games Fallback", true).toBool();
if ( searchFallback && game != Game::OTHER )
return find(file, nifdir, data, Game::OTHER);
// Fix separators
filename = QDir::toNativeSeparators( filename );
if ( replaceExt )
return filename + extensions.value( 0 ); // Restore original file extension
return filename;
}
/*!
* Note: all original morrowind nifs use name.ext only for addressing the
* textures, but most mods use something like textures/[subdir/]name.ext.
* This is due to a feature in Morrowind resource manager: it loads name.ext,
* textures/name.ext and textures/subdir/name.ext but NOT subdir/name.ext.
*/
QString TexCache::stripPath( const QString & filepath, const QString & nifFolder )
{
QString file = filepath;
file = file.replace( "/", "\\" ).toLower();
QDir basePath;
QSettings settings;
// TODO: New asset manager support
QStringList folders = settings.value( "Settings/Resources/Folders", QStringList() ).toStringList();
for ( QString base : folders ) {
if ( base.startsWith( "./" ) || base.startsWith( ".\\" ) ) {
base = nifFolder + "/" + base;
}
basePath.setPath( base );
base = basePath.absolutePath();
base = base.replace( "/", "\\" ).toLower();
/*
* note that basePath.relativeFilePath( file ) here is *not*
* what we want - see the above doc comments for this function
*/
if ( file.startsWith( base ) ) {
file.remove( 0, base.length() );
break;
}
}
if ( file.startsWith( "/" ) || file.startsWith( "\\" ) )
file.remove( 0, 1 );
return file;
}
bool TexCache::canLoad( const QString & filePath )
{
return texCanLoad( filePath );
}
bool TexCache::isSupported( const QString & filePath )
{
return texIsSupported( filePath );
}
void TexCache::fileChanged( const QString & filepath )
{
QMutableHashIterator<QString, Tex *> it( textures );
while ( it.hasNext() ) {
it.next();
Tex * tx = it.value();
if ( tx && tx->filepath == filepath ) {
// Remove from watcher now to prevent multiple signals
watcher->removePath( tx->filepath );
if ( QFile::exists( tx->filepath ) ) {
tx->reload = true;
emit sigRefresh();
} else {
it.remove();
if ( tx->id )
glDeleteTextures( 1, &tx->id );
delete tx;
}
}
}
}
int TexCache::bind( const QString & fname, Game::GameMode game )
{
Tex * tx = textures.value( fname );
if ( !tx ) {
tx = new Tex;
tx->filename = fname;
tx->id = 0;
tx->data = QByteArray();
tx->mipmaps = 0;
tx->reload = false;
textures.insert( tx->filename, tx );
if ( !isSupported( fname ) )
tx->id = 0xFFFFFFFF;
}
if ( tx->id == 0xFFFFFFFF )
return 0;
QByteArray outData;
if ( tx->filepath.isEmpty() || tx->reload )
tx->filepath = find( tx->filename, nifFolder, outData, game );
if ( !outData.isEmpty() || tx->reload ) {
tx->data = outData;
}
if ( !tx->id || tx->reload ) {
if ( QFile::exists( tx->filepath ) && QFileInfo( tx->filepath ).isWritable()
&& ( !watcher->files().contains( tx->filepath ) ) )
watcher->addPath( tx->filepath );
tx->load();
} else {
if ( !tx->target )
tx->target = GL_TEXTURE_2D;
glBindTexture( tx->target, tx->id );
}
return tx->mipmaps;
}
int TexCache::bind( const QModelIndex & iSource, Game::GameMode game )
{
const NifModel * nif = qobject_cast<const NifModel *>( iSource.model() );
if ( nif && iSource.isValid() ) {
if ( nif->get<quint8>( iSource, "Use External" ) == 0 ) {
QModelIndex iData = nif->getBlock( nif->getLink( iSource, "Pixel Data" ) );
if ( iData.isValid() ) {
Tex * tx = embedTextures.value( iData );
if ( !tx ) {
tx = new Tex();
tx->id = 0;
tx->reload = false;
try
{
glGenTextures( 1, &tx->id );
glBindTexture( GL_TEXTURE_2D, tx->id );
embedTextures.insert( iData, tx );
texLoad( iData, tx->format, tx->target, tx->width, tx->height, tx->mipmaps, tx->id );
}
catch ( QString & e ) {
tx->status = e;
}
} else {
glBindTexture( GL_TEXTURE_2D, tx->id );
}
return tx->mipmaps;
}
} else if ( !nif->get<QString>( iSource, "File Name" ).isEmpty() ) {
return bind( nif->get<QString>( iSource, "File Name" ), game );
}
}
return 0;
}
void TexCache::flush()
{
for ( Tex * tx : textures ) {
if ( tx->id )
glDeleteTextures( 1, &tx->id );
}
qDeleteAll( textures );
textures.clear();
for ( Tex * tx : embedTextures ) {
if ( tx->id )
glDeleteTextures( 1, &tx->id );
}
qDeleteAll( embedTextures );
embedTextures.clear();
if ( !watcher->files().empty() ) {
watcher->removePaths( watcher->files() );
}
}
void TexCache::setNifFolder( const QString & folder )
{
nifFolder = folder;
flush();
emit sigRefresh();
}
QString TexCache::info( const QModelIndex & iSource )
{
QString temp;
const NifModel * nif = qobject_cast<const NifModel *>( iSource.model() );
if ( nif && iSource.isValid() ) {
if ( nif->get<quint8>( iSource, "Use External" ) == 0 ) {
QModelIndex iData = nif->getBlock( nif->getLink( iSource, "Pixel Data" ) );
if ( iData.isValid() ) {
Tex * tx = embedTextures.value( iData );
temp = QString( "Embedded texture: %1\nWidth: %2\nHeight: %3\nMipmaps: %4" )
.arg( tx->format )
.arg( tx->width )
.arg( tx->height )
.arg( tx->mipmaps );
} else {
temp = QString( "Embedded texture invalid" );
}
} else {
QString filename = nif->get<QString>( iSource, "File Name" );
Tex * tx = textures.value( filename );
temp = QString( "External texture file: %1\nTexture path: %2\nFormat: %3\nWidth: %4\nHeight: %5\nMipmaps: %6" )
.arg( tx->filename )
.arg( tx->filepath )
.arg( tx->format )
.arg( tx->width )
.arg( tx->height )
.arg( tx->mipmaps );
}
}
return temp;
}
bool TexCache::exportFile( const QModelIndex & iSource, QString & filepath )
{
Tex * tx = embedTextures.value( iSource );
if ( !tx ) {
tx = new Tex();
tx->id = 0;
}
return tx->saveAsFile( iSource, filepath );
}
bool TexCache::importFile( NifModel * nif, const QModelIndex & iSource, QModelIndex & iData )
{
//const NifModel * nif = qobject_cast<const NifModel *>( iSource.model() );
if ( nif && iSource.isValid() ) {
if ( nif->get<quint8>( iSource, "Use External" ) == 1 ) {
QString filename = nif->get<QString>( iSource, "File Name" );
//qDebug() << "TexCache::importFile: Texture has filename (from NIF) " << filename;
Tex * tx = textures.value( filename );
return tx->savePixelData( nif, iSource, iData );
}
}
return false;
}
/*
* TexCache::Tex
*/
void TexCache::Tex::load()
{
if ( !id )
glGenTextures( 1, &id );
width = height = mipmaps = 0;
reload = false;
status = QString();
if ( target )
glBindTexture( target, id );
try
{
texLoad( filepath, format, target, width, height, mipmaps, data, id );
}
catch ( QString & e )
{
status = e;
}
}
bool TexCache::Tex::saveAsFile( const QModelIndex & index, QString & savepath )
{
texLoad( index, format, target, width, height, mipmaps, id );
if ( savepath.toLower().endsWith( ".tga" ) ) {
return texSaveTGA( index, savepath, width, height );
}
return texSaveDDS( index, savepath, width, height, mipmaps );
}
bool TexCache::Tex::savePixelData( NifModel * nif, const QModelIndex & iSource, QModelIndex & iData )
{
Q_UNUSED( iSource );
// gltexloaders function goes here
//qDebug() << "TexCache::Tex:savePixelData: Packing" << iSource << "from file" << filepath << "to" << iData;
return texSaveNIF( nif, filepath, iData );
}
| 26.136752 | 127 | 0.659778 | [
"render",
"model"
] |
f86374a46e5011b635a5b9af1527f4488065b9f9 | 3,599 | cpp | C++ | dev/opengl_tests/qt/build-qt_opengl_widget-Desktop_Qt_5_9_0_MSVC2013_64bit-Debug/debug/moc_glmainwindow.cpp | gilson27/amaryllis | 58e7afa31d2637038fc846b3456ad6a557be84d0 | [
"MIT"
] | null | null | null | dev/opengl_tests/qt/build-qt_opengl_widget-Desktop_Qt_5_9_0_MSVC2013_64bit-Debug/debug/moc_glmainwindow.cpp | gilson27/amaryllis | 58e7afa31d2637038fc846b3456ad6a557be84d0 | [
"MIT"
] | null | null | null | dev/opengl_tests/qt/build-qt_opengl_widget-Desktop_Qt_5_9_0_MSVC2013_64bit-Debug/debug/moc_glmainwindow.cpp | gilson27/amaryllis | 58e7afa31d2637038fc846b3456ad6a557be84d0 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'glmainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../qt_opengl_widget/glmainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'glmainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_GLMainWindow_t {
QByteArrayData data[3];
char stringdata0[38];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_GLMainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_GLMainWindow_t qt_meta_stringdata_GLMainWindow = {
{
QT_MOC_LITERAL(0, 0, 12), // "GLMainWindow"
QT_MOC_LITERAL(1, 13, 23), // "on_openGLWidget_resized"
QT_MOC_LITERAL(2, 37, 0) // ""
},
"GLMainWindow\0on_openGLWidget_resized\0"
""
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_GLMainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void GLMainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
GLMainWindow *_t = static_cast<GLMainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_openGLWidget_resized(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject GLMainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_GLMainWindow.data,
qt_meta_data_GLMainWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *GLMainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *GLMainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_GLMainWindow.stringdata0))
return static_cast<void*>(const_cast< GLMainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int GLMainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 31.025862 | 97 | 0.612114 | [
"object"
] |
d379afdcfca9faeaec90718f3ca72746a720378e | 9,332 | hpp | C++ | include/System/Net/FtpDataStream.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Net/FtpDataStream.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Net/FtpDataStream.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.IO.Stream
#include "System/IO/Stream.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: FtpWebRequest
class FtpWebRequest;
}
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: SeekOrigin
struct SeekOrigin;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
// Type namespace: System.Net
namespace System::Net {
// Size: 0x40
#pragma pack(push, 1)
// Autogenerated type: System.Net.FtpDataStream
class FtpDataStream : public System::IO::Stream {
public:
// Nested type: System::Net::FtpDataStream::WriteDelegate
class WriteDelegate;
// Nested type: System::Net::FtpDataStream::ReadDelegate
class ReadDelegate;
// private System.Net.FtpWebRequest request
// Size: 0x8
// Offset: 0x28
System::Net::FtpWebRequest* request;
// Field size check
static_assert(sizeof(System::Net::FtpWebRequest*) == 0x8);
// private System.IO.Stream networkStream
// Size: 0x8
// Offset: 0x30
System::IO::Stream* networkStream;
// Field size check
static_assert(sizeof(System::IO::Stream*) == 0x8);
// private System.Boolean disposed
// Size: 0x1
// Offset: 0x38
bool disposed;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean isRead
// Size: 0x1
// Offset: 0x39
bool isRead;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: isRead and: totalRead
char __padding3[0x2] = {};
// private System.Int32 totalRead
// Size: 0x4
// Offset: 0x3C
int totalRead;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: FtpDataStream
FtpDataStream(System::Net::FtpWebRequest* request_ = {}, System::IO::Stream* networkStream_ = {}, bool disposed_ = {}, bool isRead_ = {}, int totalRead_ = {}) noexcept : request{request_}, networkStream{networkStream_}, disposed{disposed_}, isRead{isRead_}, totalRead{totalRead_} {}
// System.Void .ctor(System.Net.FtpWebRequest request, System.IO.Stream stream, System.Boolean isRead)
// Offset: 0x16A6FC8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FtpDataStream* New_ctor(System::Net::FtpWebRequest* request, System::IO::Stream* stream, bool isRead) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Net::FtpDataStream::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FtpDataStream*, creationType>(request, stream, isRead)));
}
// private System.Int32 ReadInternal(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
// Offset: 0x16A72B4
int ReadInternal(::Array<uint8_t>* buffer, int offset, int size);
// private System.Void WriteInternal(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
// Offset: 0x16A7B98
void WriteInternal(::Array<uint8_t>* buffer, int offset, int size);
// private System.Void System.IDisposable.Dispose()
// Offset: 0x16A8298
void System_IDisposable_Dispose();
// private System.Void CheckDisposed()
// Offset: 0x16A76FC
void CheckDisposed();
// public override System.Boolean get_CanRead()
// Offset: 0x16A709C
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanRead()
bool get_CanRead();
// public override System.Boolean get_CanWrite()
// Offset: 0x16A70A4
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanWrite()
bool get_CanWrite();
// public override System.Boolean get_CanSeek()
// Offset: 0x16A70B4
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanSeek()
bool get_CanSeek();
// public override System.Int64 get_Length()
// Offset: 0x16A70BC
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::get_Length()
int64_t get_Length();
// public override System.Int64 get_Position()
// Offset: 0x16A711C
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::get_Position()
int64_t get_Position();
// public override System.Void set_Position(System.Int64 value)
// Offset: 0x16A717C
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::set_Position(System.Int64 value)
void set_Position(int64_t value);
// public override System.Void Close()
// Offset: 0x16A71DC
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Close()
void Close();
// public override System.Void Flush()
// Offset: 0x16A71F0
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Flush()
void Flush();
// public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
// Offset: 0x16A71F4
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::Seek(System.Int64 offset, System.IO.SeekOrigin origin)
int64_t Seek(int64_t offset, System::IO::SeekOrigin origin);
// public override System.Void SetLength(System.Int64 value)
// Offset: 0x16A7254
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::SetLength(System.Int64 value)
void SetLength(int64_t value);
// public override System.IAsyncResult BeginRead(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.AsyncCallback cb, System.Object state)
// Offset: 0x16A7578
// Implemented from: System.IO.Stream
// Base method: System.IAsyncResult Stream::BeginRead(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.AsyncCallback cb, System.Object state)
System::IAsyncResult* BeginRead(::Array<uint8_t>* buffer, int offset, int size, System::AsyncCallback* cb, ::Il2CppObject* state);
// public override System.Int32 EndRead(System.IAsyncResult asyncResult)
// Offset: 0x16A786C
// Implemented from: System.IO.Stream
// Base method: System.Int32 Stream::EndRead(System.IAsyncResult asyncResult)
int EndRead(System::IAsyncResult* asyncResult);
// public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
// Offset: 0x16A79B4
// Implemented from: System.IO.Stream
// Base method: System.Int32 Stream::Read(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
int Read(::Array<uint8_t>* buffer, int offset, int size);
// public override System.IAsyncResult BeginWrite(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.AsyncCallback cb, System.Object state)
// Offset: 0x16A7CC8
// Implemented from: System.IO.Stream
// Base method: System.IAsyncResult Stream::BeginWrite(System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.AsyncCallback cb, System.Object state)
System::IAsyncResult* BeginWrite(::Array<uint8_t>* buffer, int offset, int size, System::AsyncCallback* cb, ::Il2CppObject* state);
// public override System.Void EndWrite(System.IAsyncResult asyncResult)
// Offset: 0x16A7F10
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::EndWrite(System.IAsyncResult asyncResult)
void EndWrite(System::IAsyncResult* asyncResult);
// public override System.Void Write(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
// Offset: 0x16A803C
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Write(System.Byte[] buffer, System.Int32 offset, System.Int32 size)
void Write(::Array<uint8_t>* buffer, int offset, int size);
// protected override System.Void Finalize()
// Offset: 0x16A8220
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
// protected override System.Void Dispose(System.Boolean disposing)
// Offset: 0x16A8318
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Dispose(System.Boolean disposing)
void Dispose(bool disposing);
}; // System.Net.FtpDataStream
#pragma pack(pop)
static check_size<sizeof(FtpDataStream), 60 + sizeof(int)> __System_Net_FtpDataStreamSizeCheck;
static_assert(sizeof(FtpDataStream) == 0x40);
}
DEFINE_IL2CPP_ARG_TYPE(System::Net::FtpDataStream*, "System.Net", "FtpDataStream");
| 48.352332 | 287 | 0.694921 | [
"object"
] |
d384958d4f6eed7e217f42b0210ba9156959de39 | 6,215 | cpp | C++ | Source/Game/CharacterHandler.cpp | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | 8 | 2020-02-06T13:14:13.000Z | 2020-11-03T06:26:04.000Z | Source/Game/CharacterHandler.cpp | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | null | null | null | Source/Game/CharacterHandler.cpp | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | 6 | 2019-06-19T00:24:16.000Z | 2020-12-08T05:03:59.000Z | #include "PrecompiledHeader.h"
#include "CharacterHandler.h"
CharacterHandler::CharacterHandler( Context* context ) :
HandlerImpl( context ),
characterNodeID_( -1 ),
character_( nullptr ),
isWalking_( false ),
animationToSet_( 0, false ),
selectedNode_( nullptr ),
hoveredNode_( nullptr ),
mapIDToLoad_( MapID::Undefined )
{
SubscribeToEvent( E_UPDATE, URHO3D_HANDLER( CharacterHandler, HandleUpdate ) );
SubscribeToEvent( E_POSTUPDATE, URHO3D_HANDLER( CharacterHandler, HandlePostUpdate ) );
SubscribeToEvent( E_MOUSEBUTTONDOWN, URHO3D_HANDLER( CharacterHandler, HandleMouseDown ) );
SubscribeToEvent( E_NETWORKUPDATESENT, URHO3D_HANDLER( CharacterHandler, HandleNetworkUpdateSent ) );
}
CharacterHandler::~CharacterHandler()
{
if( character_ )
{
character_->Remove();
character_ = nullptr;
}
}
bool CharacterHandler::HandleWorldData( Connection* connection, MemoryBuffer& message ) //@MSGID_WorldData
{
//Set Character Node ID
characterNodeID_ = message.ReadInt();
mapIDToLoad_ = (MapID)message.ReadInt();
//Change to World Screen
SCREENMANAGER->ChangeScreen(ScreenType::World);
return true;
}
void CharacterHandler::LoadCharacter()
{
auto characterNode = character_->GetNode();
if( characterNode )
{
//Load Animation Set
character_->animationMgr_->Load( "Definitions/Animations/fighter.json" );
//Set Camera Position
CAMERAMANAGER->SetCameraType( CameraType::Follow, characterNode );
}
}
void CharacterHandler::UnLoad()
{
characterNodeID_ = -1;
character_ = nullptr;
selectedNode_ = nullptr;
hoveredNode_ = nullptr;
mapIDToLoad_ = MapID::Undefined;
CAMERAMANAGER->SetCameraType( CameraType::Undefined, nullptr );
}
void CharacterHandler::ChangeAnimation( const Core::AnimationType& animationType, bool exclusive )
{
if( character_ )
{
auto animationData = character_->animationMgr_->GetAnimationData( animationType );
if( animationData )
ChangeAnimation( animationData->id, exclusive );
}
}
void CharacterHandler::HandleUpdate( StringHash eventType, VariantMap& eventData )
{
using namespace CharacterData;
if( SCREEN_TYPE == ScreenType::World && character_ && CONNECTIONG )
{
auto characterNode = character_->GetNode();
if( characterNode )
{
//Set Connection Controls
Controls controls;
controls.yaw_ = CAMERAMANAGER->GetCameraYaw() + CAMERAMANAGER->GetMouseYaw();
controls.extraData_[P_ANIMATIONID] = -1;
controls.extraData_[P_MAPID] = (MAP_ID)MAPMANAGER->GetCurrentMapID();
if( !USERINTERFACE->GetFocusElement() )
controls.Set( CHARACTERCONTROL_Forward, INPUT->GetMouseButtonDown( MOUSEB_LEFT ) || isWalking_ );
else
isWalking_ = false;
if( INPUT->GetMouseButtonDown( MOUSEB_RIGHT ) )
{
ChangeAnimation( Core::AnimationType::Attack );
}
//Have animation to set?
if( animationToSet_.first_ != 0 )
{
controls.extraData_[P_ANIMATIONID] = animationToSet_.first_;
controls.extraData_[P_ANIMATIONEXCLUSIVE] = animationToSet_.second_;
}
CONNECTIONG->SetPosition( characterNode->GetPosition() );
CONNECTIONG->SetRotation( characterNode->GetRotation() );
CONNECTIONG->SetControls( controls );
}
}
}
void CharacterHandler::HandlePostUpdate( StringHash eventType, VariantMap& eventData )
{
if( SCREEN_TYPE == ScreenType::World )
{
//Look for Character Component
if( character_ == nullptr )
{
if( ACTIVESCREEN == nullptr )
return;
auto characterNode = ACTIVESCREEN->GetScene()->GetNode( characterNodeID_ );
//Character Node Found!
if( characterNode )
{
characterNode->RemoveComponent<RigidBody>();
characterNode->RemoveComponent<CollisionShape>();
character_ = characterNode->GetComponent<Core::Character>( true );
character_->CreatePhysicsComponent( 0.56f, 1.51f );
character_->connection_ = CONNECTIONG;
character_->animationMgr_ = characterNode->GetComponent<Core::AnimationEntity>( true );
//Intercept Network Position
characterNode->SetInterceptNetworkUpdate( "Network Position", true );
characterNode->SetInterceptNetworkUpdate( "Network Rotation", true );
//Disabled: characterNode->GetComponent<AnimationController>( true )->SetInterceptNetworkUpdate( "Network Animations", true );
//Load Map
MAPMANAGER->Load( mapIDToLoad_ );
//Load Character
LoadCharacter();
}
}
//Find Hovered Node
hoveredNode_ = CAMERAMANAGER->GetNodeRaycast();
}
}
void CharacterHandler::HandleMouseDown( StringHash eventType, VariantMap& eventData )
{
//Character isn't created yet
if( character_ == nullptr )
return;
//Get Dynamic Navigation Mesh Pointer
auto navigationMesh = character_->GetNode()->GetScene()->GetComponent<NavigationMesh>( true );
//Has Dynamic Navigation Mesh?
if( navigationMesh )
{
selectedNode_ = CAMERAMANAGER->GetNodeRaycast();
//Self selecting? Ignore it!
if( selectedNode_ == (character_ ? character_->GetNode() : nullptr) )
selectedNode_ = nullptr;
//Found Selected Node?
if( selectedNode_ )
character_->SetTargetPosition( selectedNode_->GetWorldPosition() );
else
character_->ResetTargetPosition();
}
if( eventData[MouseButtonDown::P_BUTTON].GetInt() == MOUSEB_LEFT && eventData[MouseButtonDown::P_CLICKS].GetInt() == 2 )
isWalking_ = true;
else
isWalking_ = false;
}
void CharacterHandler::HandleNetworkUpdateSent( StringHash eventType, VariantMap & eventData )
{
animationToSet_.first_ = 0;
}
| 32.202073 | 142 | 0.641512 | [
"mesh"
] |
d384a4cb66a4c34538378398bab7057a484ee580 | 932 | cpp | C++ | GameEngine/CoreEngine/CoreEngine/src/ObjectTemplate.meta.cpp | mettaursp/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | 1 | 2021-01-17T13:05:20.000Z | 2021-01-17T13:05:20.000Z | GameEngine/CoreEngine/CoreEngine/src/ObjectTemplate.meta.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | GameEngine/CoreEngine/CoreEngine/src/ObjectTemplate.meta.cpp | suddenly-games/SuddenlyGames | e2ff1c2771d4ca54824650e4f1a33a527536ca61 | [
"Apache-2.0"
] | null | null | null | #include "ObjectTemplate.h"
// use these as shortcuts to open the other templates with reflection examples
// #include "TypeTemplate.meta.cpp"
// #include "InheritedTemplate.meta.cpp"
namespace ExampleNamespace
{
using Engine::Object;
Reflect_Inherited(ObjectTemplate, Object,
Document_Class(
"-------------------------------------------------------------------------------"
"This is a template for future game object types. It is also an example of a "
"good practice for documenting items. I like to use this 80 character bar of "
"hyphens as a reference point for how long to make a single line and use c "
"style literal string concatenation to split apart lines. Please do this if "
"the documentation goes over 100 or so characters to keep things nice and "
"tidy."
);
// To see an example of how to configure reflection data check "TypeTemplate.meta.cpp and InheritedTemplate.meta.cpp"
);
}
| 37.28 | 119 | 0.68133 | [
"object"
] |
d3851a546bcc098eba86535e6510a02c2210734a | 640 | cpp | C++ | src/algorithms/implementation/divisible_sum_pairs/divisible_sum_pairs.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/implementation/divisible_sum_pairs/divisible_sum_pairs.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/implementation/divisible_sum_pairs/divisible_sum_pairs.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | #include "divisible_sum_pairs.h"
#include <iostream>
#include <string>
#include <vector>
using namespace hackerrank::bmgandre::algorithms::implementation;
/// Practice>Algorithms>Implementation>Divisible Sum Pairs
///
/// https://www.hackerrank.com/challenges/divisible-sum-pairs
void divisible_sum_pairs::solve()
{
auto n = 0, k = 0;
std::cin >> n >> k;
std::vector<int> a(n);
for (auto i = 0; i < n; i++)
{
std::cin >> a[i];
}
auto valid_pairs = 0;
for (auto i = 0; i < n; i++) {
for (auto j = i + 1; j < n; j++) {
if ((a[i] + a[j]) % k == 0) {
valid_pairs++;
}
}
}
std::cout << valid_pairs << std::endl;
}
| 19.393939 | 65 | 0.6 | [
"vector"
] |
d3853962c40c254431d453ff1432963c8e2a31de | 1,611 | cpp | C++ | cpp/ast/LILValueList.cpp | veosotano/lil | 27ef338e7e21403acf2b0202f7db8ef662425d44 | [
"MIT"
] | 6 | 2021-01-02T16:36:28.000Z | 2022-01-23T21:50:29.000Z | cpp/ast/LILValueList.cpp | veosotano/lil | 27ef338e7e21403acf2b0202f7db8ef662425d44 | [
"MIT"
] | null | null | null | cpp/ast/LILValueList.cpp | veosotano/lil | 27ef338e7e21403acf2b0202f7db8ef662425d44 | [
"MIT"
] | null | null | null | /********************************************************************
*
* LIL Is a Language
*
* AUTHORS: Miro Keller
*
* COPYRIGHT: ©2020-today: All Rights Reserved
*
* LICENSE: see LICENSE file
*
* This file holds multiple values separated by commas
*
********************************************************************/
#include "LILValueList.h"
#include "LILVarNode.h"
using namespace LIL;
LILValueList::LILValueList()
: LILTypedNode(NodeTypeValueList)
{
}
LILValueList::LILValueList(const LILValueList &other)
: LILTypedNode(other)
{
}
std::shared_ptr<LILValueList> LILValueList::clone() const
{
return std::static_pointer_cast<LILValueList> (this->cloneImpl());
}
std::shared_ptr<LILClonable> LILValueList::cloneImpl() const
{
std::shared_ptr<LILValueList> clone(new LILValueList(*this));
for (auto node : this->getChildNodes()) {
clone->addValue(node->clone());
}
//clone LILTypedNode
if (this->_type) {
clone->setType(this->_type->clone());
}
return clone;
}
LILValueList::~LILValueList()
{
}
void LILValueList::receiveNodeData(const LIL::LILString &data)
{
}
void LILValueList::addValue(std::shared_ptr<LILNode> arg)
{
this->addNode(arg);
}
void LILValueList::setValues(std::vector<std::shared_ptr<LILNode>> vals)
{
this->clearChildNodes();
for (auto val : vals) {
this->addValue(val);
}
}
void LILValueList::clearValues()
{
this->clearChildNodes();
}
std::vector<std::shared_ptr<LILNode>> LILValueList::getValues() const
{
return this->getChildNodes();
}
| 19.646341 | 72 | 0.61018 | [
"vector"
] |
d388e04ad6036281d63ec8731a5c494f1b9f60e2 | 301 | cpp | C++ | Codeforces/Div2/theaterSquare.cpp | SanchitTaliyan/Codes | 7b714f9981c50dfdc6c5045446f95a0f4a3aeb22 | [
"MIT"
] | 1 | 2020-11-05T03:32:27.000Z | 2020-11-05T03:32:27.000Z | Codeforces/Div2/theaterSquare.cpp | SanchitTaliyan/Codes | 7b714f9981c50dfdc6c5045446f95a0f4a3aeb22 | [
"MIT"
] | null | null | null | Codeforces/Div2/theaterSquare.cpp | SanchitTaliyan/Codes | 7b714f9981c50dfdc6c5045446f95a0f4a3aeb22 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main() {
int n, m, a;
cin >> n >> m >> a;
//cout << ceil(n/a) << "\n";
//cout <<ceil(m/a)<< "\n";
unsigned long long ans = ceil((double)m/a) * ceil((double)n/a);
cout << ans;
return 0;
} | 15.05 | 67 | 0.51495 | [
"vector"
] |
d38f7dfc84666276091fd4eef7e8d2bbfe2e2f47 | 1,736 | cpp | C++ | 21.merge_two_sorted_lists.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 5 | 2019-09-12T05:23:44.000Z | 2021-11-15T11:19:39.000Z | 21.merge_two_sorted_lists.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 18 | 2019-09-23T13:11:06.000Z | 2019-11-09T11:20:17.000Z | 21.merge_two_sorted_lists.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | null | null | null | /*
* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
*
* Example:
*
* Input: 1->2->4, 1->3->4
* Output: 1->1->2->3->4->4
*/
#include "include/header/list.hpp"
#include <vector>
using namespace std;
class Solution
{
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
ListNode *cur = nullptr, *head = nullptr;
while (l1 || l2)
{
ListNode *select;
if (l1 && l2)
{
if (l1->val <= l2->val)
{
select = l1;
l1 = l1->next;
}
else
{
select = l2;
l2 = l2->next;
}
}
else
{
if (!l1 && l2)
{
select = l2;
l2 = l2->next;
}
else
{
select = l1;
l1 = l1->next;
}
}
if (!head)
{
head = select;
}
if (!cur)
{
cur = select;
}
else
{
cur->next = select;
cur = select;
}
}
return head;
}
};
int main()
{
Solution s;
vector<int> a1 = {1, 2, 4};
vector<int> a2 = {1, 3, 4};
auto l1 = ListNode::deserialize(a1);
auto l2 = ListNode::deserialize(a2);
assert(ListNode::serialize(s.mergeTwoLists(l1, l2)) == vector<int>({1, 1, 2, 3, 4, 4}));
return 0;
} | 20.666667 | 144 | 0.367512 | [
"vector"
] |
d396c028a307b9234a2d841ce6c713bb8b5d5210 | 5,582 | cpp | C++ | libnorth/src/Targets/IR/Utils.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Targets/IR/Utils.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Targets/IR/Utils.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | //===--- IR/Utils.cpp - Transformation AST to LLVM IR -----------*- C++ -*-===//
//
// The North Compiler Infrastructure
//
// This file is distributed under the MIT License.
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Targets/IRBuilder.h"
#include "Type/Type.h"
#include <llvm/Support/raw_ostream.h>
namespace north::targets {
using namespace llvm;
type::Type *IRBuilder::getTypeFromIdent(ast::Node *Ident) {
if (auto Literal = dyn_cast<ast::LiteralExpr>(Ident)) {
if (auto Type = Module->getTypeOrNull(Literal->getTokenInfo().toString()))
return Type;
auto Pos = Literal->getTokenInfo().Pos;
auto Range = llvm::SMRange(
llvm::SMLoc::getFromPointer(Pos.Offset),
llvm::SMLoc::getFromPointer(Pos.Offset + Pos.Length));
Module->getSourceManager().PrintMessage(Range.Start, llvm::SourceMgr::DiagKind::DK_Error,
"unknown symbol `" + Literal->getTokenInfo().toString() + "`", Range);
}
llvm_unreachable("getTypeFromIdent() argument must be a literal");
return nullptr;
}
Value *IRBuilder::cmpWithTrue(llvm::Value *Val) {
return Builder.CreateICmpEQ(Val, ConstantInt::get(Val->getType(), 1, false));
}
Value *IRBuilder::getStructField(ast::Node *Expr, Value *IR,
ast::QualifiedIdentifierExpr &Ident) {
if (auto InitExpr = dyn_cast<ast::StructInitExpr>(Expr)) {
auto IRVal = IR;
auto getFieldNumber = [&](StringRef FieldName) -> Constant * {
auto Struct = InitExpr->getType();
uint64_t I = 0;
for (auto F : Struct->getFieldList()) {
if (F->getIdentifier() == FieldName) {
InitExpr = static_cast<ast::StructInitExpr *>(InitExpr->getValue(I));
return ConstantInt::get(IntegerType::getInt32Ty(Context), I);
}
++I;
}
auto Pos = Struct->getPosition();
auto Range = llvm::SMRange(
llvm::SMLoc::getFromPointer(Pos.Offset),
llvm::SMLoc::getFromPointer(Pos.Offset + Pos.Length));
Module->getSourceManager().PrintMessage(Range.Start, llvm::SourceMgr::DiagKind::DK_Error,
"structure " + Struct->getIdentifier() + "doesn't has field `" + FieldName + "`", Range);
return nullptr;
};
std::vector<Value *> Indicies{
ConstantInt::get(IntegerType::getInt32Ty(Context), 0)};
for (auto Part = 1; Part <= Ident.getSize() - 1; ++Part)
Indicies.push_back(getFieldNumber(Ident.getPart(Part)));
auto GEP = Builder.CreateInBoundsGEP(IRVal, Indicies);
return GetVal ? Builder.CreateLoad(GEP) : GEP;
}
if (auto InitExpr = dyn_cast<ast::CallExpr>(Expr)) {
auto IRVal = IR;
auto Identifier = InitExpr->getIR()->getType()->getStructName();
auto getFieldNumber = [&](StringRef FieldName) -> Constant * {
auto TypeDecl = Module->getType(Identifier)->getDecl();
auto Struct =
cast<ast::StructDecl>(cast<ast::TypeDef>(TypeDecl)->getTypeDecl());
uint64_t I = 0;
for (auto F : Struct->getFieldList()) {
if (F->getIdentifier() == FieldName) {
Identifier = Struct->getField(I)->getType()->getIdentifier();
return ConstantInt::get(IntegerType::getInt32Ty(Context), I);
}
++I;
}
auto Pos = Struct->getPosition();
auto Range = llvm::SMRange(
llvm::SMLoc::getFromPointer(Pos.Offset),
llvm::SMLoc::getFromPointer(Pos.Offset + Pos.Length));
Module->getSourceManager().PrintMessage(Range.Start, llvm::SourceMgr::DiagKind::DK_Error,
"structure " + Struct->getIdentifier() + "doesn't has field `" + FieldName + "`", Range);
return nullptr;
};
std::vector<Value *> Indicies{
ConstantInt::get(IntegerType::getInt32Ty(Context), 0)};
for (auto Part = 1; Part <= Ident.getSize() - 1; ++Part)
Indicies.push_back(getFieldNumber(Ident.getPart(Part)));
auto GEP = Builder.CreateInBoundsGEP(IRVal, Indicies);
return GetVal ? Builder.CreateLoad(GEP) : GEP;
}
if (ast::VarDecl *Var = dyn_cast<ast::VarDecl>(Expr)) {
auto IRVal = IR;
auto Identifier = Var->getType();
auto getFieldNumber = [&](StringRef FieldName) -> Constant * {
auto TypeDecl = Module->getType(Identifier->getIdentifier())->getDecl();
auto Struct =
cast<ast::StructDecl>(cast<ast::TypeDef>(TypeDecl)->getTypeDecl());
uint64_t I = 0;
for (auto F : Struct->getFieldList()) {
if (F->getIdentifier() == FieldName) {
Identifier = Struct->getField(I)->getType();
return ConstantInt::get(IntegerType::getInt32Ty(Context), I);
}
++I;
}
auto Pos = Struct->getPosition();
auto Range = llvm::SMRange(
llvm::SMLoc::getFromPointer(Pos.Offset),
llvm::SMLoc::getFromPointer(Pos.Offset + Pos.Length));
Module->getSourceManager().PrintMessage(Range.Start, llvm::SourceMgr::DiagKind::DK_Error,
"structure " + Struct->getIdentifier() + "doesn't has field `" + FieldName + "`", Range);
return nullptr;
};
std::vector<Value *> Indicies{
ConstantInt::get(IntegerType::getInt32Ty(Context), 0)};
for (auto Part = 1; Part <= Ident.getSize() - 1; ++Part)
Indicies.push_back(getFieldNumber(Ident.getPart(Part)));
auto GEP = Builder.CreateInBoundsGEP(IRVal, Indicies);
return GetVal ? Builder.CreateLoad(GEP) : GEP;
}
llvm_unreachable("struct w/o initializer");
}
} // namespace north::targets
| 34.8875 | 99 | 0.614475 | [
"vector"
] |
d398407d620c8bcc13e2420e8f64ad1eeeb7a9d2 | 1,235 | cpp | C++ | URI Online Judge/1152 - Estradas Escuras/1152 - Estradas Escuras.cpp | MarcoRhayden/Uri-Online-Judge | 92bed9fd0e5455686d54500f8e36588d6518f1b3 | [
"MIT"
] | 1 | 2019-03-29T11:52:44.000Z | 2019-03-29T11:52:44.000Z | URI Online Judge/1152 - Estradas Escuras/1152 - Estradas Escuras.cpp | MarcoRhayden/Uri-Online-Judge | 92bed9fd0e5455686d54500f8e36588d6518f1b3 | [
"MIT"
] | null | null | null | URI Online Judge/1152 - Estradas Escuras/1152 - Estradas Escuras.cpp | MarcoRhayden/Uri-Online-Judge | 92bed9fd0e5455686d54500f8e36588d6518f1b3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<int> subset;
struct Graph {
int x, y, z;
};
bool compare(Graph A, Graph B) {
return (A.z < B.z);
}
void make(int vertexes) {
for (int x = 0; x < vertexes; x++)
subset[x] = x;
}
int find(int v) {
return ((subset[v] == v) ? v : subset[v] = find(subset[v]));
}
void unionSet(int p, int q) {
subset[find(p)] = find(q);
}
bool isSameSet(int i, int j) {
return find(i) == find(j);
}
int main(int argc, char *argv[]) {
int m, n, minimum;
vector<Graph> edges;
while (cin >> m && cin >> n) {
if (m == 0 && n == 0)
break;
minimum = 0;
edges.resize(n);
subset.resize(n);
for (int i = 0; i < n; i++) {
cin >> edges[i].x;
cin >> edges[i].y;
cin >> edges[i].z;
}
sort(edges.begin(), edges.end(), compare);
make(m);
for (int nx = 0; nx < n; nx++) {
if (!isSameSet(edges[nx].x, edges[nx].y))
unionSet(edges[nx].x, edges[nx].y);
else
minimum += edges[nx].z;
}
subset.clear();
edges.clear();
cout << minimum << endl;
}
return(0);
}
| 20.932203 | 64 | 0.460729 | [
"vector"
] |
d398f32398c1b23327750778bc8e0cab500c0d59 | 836 | cpp | C++ | TerzaLezione/product-of-array.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | TerzaLezione/product-of-array.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | TerzaLezione/product-of-array.cpp | NeverMendel/Competitive-Programming-Risorse | e75c28394a38ecc6c28b3ec4b9311fdf6b6ea8ed | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
/*
Given an integer array nums, return an array answer such that answer[i] is
equal to the product of all the elements of nums except nums[i].
You don't have to worry about integer overflow.
You cannot use the division operation.
Example
Input: [1,2,3,4]
Output: [24,12,8,6]
*/
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res(nums.size(), 0);
int prod = 1;
for(int i = 0; i < nums.size(); i++){
res[i] = prod;
prod *= nums[i];
}
prod = 1;
for(int i = nums.size() - 1; i >= 0; i--){
res[i] *= prod;
prod *= nums[i];
}
return res;
}
int main(){
vector<int> v = {1,2,3,4};
vector<int> res = productExceptSelf(v);
for(const int& el : res){
cout << el << ' ';
}
cout << '\n';
// [24,12,8,6]
} | 20.390244 | 77 | 0.584928 | [
"vector"
] |
d39969a4486b1103f483c158d57514636bfae549 | 2,643 | cpp | C++ | src/Algorithms/AuxFunctions.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null | src/Algorithms/AuxFunctions.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null | src/Algorithms/AuxFunctions.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null |
#include "AuxFunctions.h"
namespace Aux
{
/*
* Count equivalence classes in the maximal equivalence fragment of a give relation.
* @param n Number of elements of a set
* @param st Set of states
* @return Number of classes
*/
int countEqClasses(int n, set<int>& st, set<pair<int, int>>& rel)
{
vector<int> cl(n);
set<pair<int, int>> relprime;
for(unsigned i = 0; i < cl.size(); i++)
{
cl[i] = i;
}
for(auto& t : rel)
{
if(st.find(t.first) != st.end() && st.find(t.second) != st.end())
relprime.insert(t);
}
for(const auto& t : relprime)
{
if(relprime.find({t.second, t.first}) != relprime.end())
{
int fnd = cl[t.second];
int rpl = cl[t.first];
for(unsigned i = 0; i < cl.size(); i++)
{
if(cl[i] == fnd)
cl[i] = rpl;
}
}
}
set<int> ret;
for(auto s : st)
{
ret.insert(cl[s]);
}
return ret.size();
}
/*
* Get all subsets of a given vector
* @param set Set represented as a vector
* @return All subsets
*/
vector< vector<int> > getAllSubsets(vector<int> set)
{
vector< vector<int> > subset;
vector<int> empty;
subset.push_back( empty );
for (unsigned i = 0; i < set.size(); i++)
{
vector< vector<int> > subsetTemp = subset;
for (unsigned j = 0; j < subsetTemp.size(); j++)
subsetTemp[j].push_back( set[i] );
for (unsigned j = 0; j < subsetTemp.size(); j++)
subset.push_back( subsetTemp[j] );
}
return subset;
}
/*
* Get all subsets of a given vector (of maximum size max)
* @param set Set represented as a vector
* @return All subsets
*/
vector< vector<int> > getAllSubsets(vector<int> set, unsigned max)
{
vector< vector<int> > subset;
vector<int> empty;
subset.push_back( empty );
for (unsigned i = 0; i < set.size(); i++)
{
vector< vector<int> > subsetTemp = subset;
for (unsigned j = 0; j < subsetTemp.size(); j++)
{
subsetTemp[j].push_back( set[i] );
}
for (unsigned j = 0; j < subsetTemp.size(); j++)
{
if(subsetTemp[j].size() <= max)
subset.push_back( subsetTemp[j] );
}
}
return subset;
}
/*
* Convert to string the contents of a given vector
* @param st Vector to be converted to string
* @return String representation
*/
string printVector(vector<int> st)
{
string ret;
for (auto s : st)
ret += std::to_string(s) + " ";
if(ret.back() == ' ')
ret.pop_back();
return "{" + ret + "}";
}
std::string printIntSet(std::set<int> st)
{
std::string ret;
for (auto s : st)
ret += std::to_string(s) + " ";
if(ret.back() == ' ')
ret.pop_back();
return "{" + ret + "}";
}
}
| 20.488372 | 84 | 0.575861 | [
"vector"
] |
d39ecaaa96bfa9f2c263effeaaa169aa13f8a95f | 4,857 | cpp | C++ | mmap.cpp | devcybiko/mmap | 98f9c53a424fff70940cd57de275d249e8128716 | [
"MIT"
] | null | null | null | mmap.cpp | devcybiko/mmap | 98f9c53a424fff70940cd57de275d249e8128716 | [
"MIT"
] | null | null | null | mmap.cpp | devcybiko/mmap | 98f9c53a424fff70940cd57de275d249e8128716 | [
"MIT"
] | null | null | null | #include <node.h>
#include <node_buffer.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
struct hint_wrap {
size_t length;
};
static void Map_finalise(char *data, void*hint_void)
{
struct hint_wrap *h = (struct hint_wrap *)hint_void;
if(h->length > 0) {
munmap(data, h->length);
}
delete h;
}
void Node_Sync(const v8::FunctionCallbackInfo<v8::Value>& args)
{
auto *isolate = args.GetIsolate();
auto buffer = args.This()->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
char *data = node::Buffer::Data(static_cast<v8::Local<v8::Object>>(buffer));
size_t length = node::Buffer::Length(buffer);
// First optional argument: offset
if (args.Length() > 0) {
const size_t offset = args[0]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
if(length <= offset) return;
data += offset;
length -= offset;
}
// Second optional argument: length
if (args.Length() > 1) {
const size_t range = args[1]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
if(range < length) length = range;
}
// Third optional argument: flags
int flags;
if (args.Length() > 2) {
flags = args[2]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
} else {
flags = MS_SYNC;
}
args.GetReturnValue().Set((0 == msync(data, length, flags)) ? v8::True(isolate) : v8::False(isolate));
}
void Node_Unmap(const v8::FunctionCallbackInfo<v8::Value>& args)
{
auto *isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
auto buffer = args.This()->ToObject(context).ToLocalChecked();
char *data = node::Buffer::Data(buffer);
auto keyString = v8::String::NewFromUtf8(isolate,"mmap_dptr").ToLocalChecked();
auto key = v8::Private::New(isolate, keyString);
struct hint_wrap *d = (struct hint_wrap *)v8::External::Cast(*buffer->GetPrivate(context, key).ToLocalChecked())->Value();
bool ok = true;
if(d->length > 0 && -1 == munmap(data, d->length)) {
ok = false;
} else {
d->length = 0;
(void)buffer->CreateDataProperty(isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, "length").ToLocalChecked(),
v8::Number::New(isolate, 0));
}
args.GetReturnValue().Set(ok? v8::True(isolate): v8::False(isolate));
}
void Node_Map(const v8::FunctionCallbackInfo<v8::Value>& args)
{
auto *isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
if (args.Length() <= 3)
{
isolate->ThrowException(
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, "mmap() takes 4 arguments: size, protection, flags, fd and offset.").ToLocalChecked()));
return;
}
const size_t length = args[0]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
const int protection = args[1]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
const int flags = args[2]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
const int fd = args[3]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
const off_t offset = args[4]->ToInteger(isolate->GetCurrentContext()).ToLocalChecked()->Value();
char* data = (char *) mmap(0, length, protection, flags, fd, offset);
if(data == MAP_FAILED)
{
isolate->ThrowException(node::ErrnoException(isolate, errno, "mmap", ""));
return;
}
struct hint_wrap *d = new hint_wrap;
d->length = length;
auto buffer = node::Buffer::New(isolate, data, length, Map_finalise, (void*)d).ToLocalChecked();
auto buffer_object = buffer->ToObject(context).ToLocalChecked();
auto UNMAP = v8::String::NewFromUtf8(isolate, "unmap").ToLocalChecked();
auto SYNC = v8::String::NewFromUtf8(isolate, "sync").ToLocalChecked();
auto MMAP_DPTR = v8::Private::New(isolate, v8::String::NewFromUtf8(isolate, "mmap_dptr").ToLocalChecked());
auto UnmapFN = v8::FunctionTemplate::New(isolate, Node_Unmap)->GetFunction(context).ToLocalChecked();
auto SyncFN = v8::FunctionTemplate::New(isolate, Node_Sync)->GetFunction(context).ToLocalChecked();
auto MMAP_DPTR_COPY = v8::External::New(isolate, (void*)d);
buffer_object->Set(context, UNMAP, UnmapFN);
buffer_object->Set(context, SYNC, SyncFN);
buffer_object->SetPrivate(context,MMAP_DPTR, MMAP_DPTR_COPY);
args.GetReturnValue().Set(buffer);
}
static void RegisterModule(v8::Local<v8::Object> exports)
{
const int PAGESIZE = sysconf(_SC_PAGESIZE);
NODE_SET_METHOD(exports, "map", Node_Map);
NODE_DEFINE_CONSTANT(exports, PROT_READ);
NODE_DEFINE_CONSTANT(exports, PROT_WRITE);
NODE_DEFINE_CONSTANT(exports, PROT_EXEC);
NODE_DEFINE_CONSTANT(exports, PROT_NONE);
NODE_DEFINE_CONSTANT(exports, MAP_SHARED);
NODE_DEFINE_CONSTANT(exports, MAP_PRIVATE);
NODE_DEFINE_CONSTANT(exports, PAGESIZE);
NODE_DEFINE_CONSTANT(exports, MS_ASYNC);
NODE_DEFINE_CONSTANT(exports, MS_SYNC);
NODE_DEFINE_CONSTANT(exports, MS_INVALIDATE);
}
NODE_MODULE(mmap, RegisterModule);
| 33.267123 | 125 | 0.715874 | [
"object"
] |
d3b5ec35561d18fd2914c7e2c154671d17c7c5ed | 4,039 | cpp | C++ | Shooter/GameState/StateOverworld.cpp | mschrandt/Personal-Projects | 7d4200176a7ebbff3233a86c870da910217c3a4e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | Shooter/GameState/StateOverworld.cpp | mschrandt/Personal-Projects | 7d4200176a7ebbff3233a86c870da910217c3a4e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | Shooter/GameState/StateOverworld.cpp | mschrandt/Personal-Projects | 7d4200176a7ebbff3233a86c870da910217c3a4e | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "StateOverworld.h"
#include "StateMachine.h"
StateOverworld::StateOverworld(StateMachine* p) : parent(p), map("resources/testMap.txt") , view(sf::FloatRect(0, 0, (float)VISIBLE_W, (float)VISIBLE_H))//view(0, 0, SCREEN_W, SCREEN_H)
{
initKeyboard();
}
void StateOverworld::handleEvents(sf::Event& ev)
{
if(ev.type == sf::Event::KeyPressed)
{
switch(ev.key.code)
{
case sf::Keyboard::Up:
player.jump();
//player.y_vel -= PLAYER_VEL;
break;
case sf::Keyboard::Down:
//player.y_vel += PLAYER_VEL;
break;
case sf::Keyboard::Right:
player.x_vel += PLAYER_VEL;
break;
case sf::Keyboard::Left:
player.x_vel -= PLAYER_VEL;
break;
case sf::Keyboard::Z:
bullets.push_back(player.shoot());
break;
case sf::Keyboard::X:
player.changeBullets();
break;
}
}
else if(ev.type == sf::Event::KeyReleased)
{
switch(ev.key.code)
{
case sf::Keyboard::Up:
if(player.y_vel < 0)
player.y_vel /= 3;
//player.y_vel += PLAYER_VEL;
break;
case sf::Keyboard::Down:
//player.y_vel -= PLAYER_VEL;
break;
case sf::Keyboard::Right:
player.x_vel -= PLAYER_VEL;
break;
case sf::Keyboard::Left:
player.x_vel += PLAYER_VEL;
break;
}
}
}
//call this when switching states
void StateOverworld::initKeyboard()
{
//if(game.keymap.isPressed(KEY_UP))
// player.y_vel -= PLAYER_VEL;
//if(game.keymap.isPressed(KEY_DOWN))
// player.y_vel += PLAYER_VEL;
if(game.keymap.isPressed(KEY_RIGHT))
player.x_vel += PLAYER_VEL;
if(game.keymap.isPressed(KEY_LEFT))
player.x_vel -= PLAYER_VEL;
}
void StateOverworld::correctView()
{
sf::Vector2f newCenter = player.center();
if(newCenter.x < VISIBLE_W / 2.0)
newCenter.x = (int) VISIBLE_W / 2;
else if(newCenter.x > map.getWidth() * TILE_W - VISIBLE_W / 2)
newCenter.x = (int) (map.getWidth() * TILE_W - VISIBLE_W / 2);
if(newCenter.y < VISIBLE_H / 2)
newCenter.y = (int) VISIBLE_H / 2;
else if (newCenter.y > map.getHeight()*TILE_W - VISIBLE_H / 2)
newCenter.y = (int) (map.getHeight() * TILE_W - VISIBLE_H / 2);
view.setCenter(newCenter);
/*
if(view.Left < 0)
{
view.Left = 0;
view.Right = SCREEN_W;
}
else if(view.Right > map.getWidth() * 32)
{
view.Right = map.getWidth() * 32;
view.Left = view.Right - SCREEN_W;
}
if(view.Top < 0)
{
view.Top = 0;
view.Bottom = SCREEN_H;
}
else if(view.Bottom > map.getHeight() * 32)
{
view.Bottom = map.getHeight() * 32;
view.Top = view.Bottom - SCREEN_H;
}
*/
}
void StateOverworld::updateBullets()
{
//update bullets
vector<int> bulletsToRemove;
vector<Missile*>::iterator begin;
int index = 0;
for(begin = bullets.begin(); begin < bullets.end(); begin++ )
{
(*begin)->update();
if((*begin)->hit(map))
bulletsToRemove.push_back(index);
else
index++;
}
//remove bullets that have collided with the map
while(bulletsToRemove.size() > 0)
{
delete *(bullets.begin() + *bulletsToRemove.begin());
bullets.erase(bullets.begin() + *bulletsToRemove.begin());
bulletsToRemove.erase(bulletsToRemove.begin());
}
}
void StateOverworld::logic()
{
player.update(this);
//DEBUG
//player.move(player.x_vel * game.time.asSeconds(), player.y_vel* game.time.asSeconds());
correctView();
updateBullets();
map.update();
}
void StateOverworld::drawBullets()
{
vector<Missile*>::iterator begin;
for(begin = bullets.begin(); begin < bullets.end(); begin++)
//(*begin)->draw(view);
(*begin)->draw();
}
void StateOverworld::draw()
{
view.setViewport(sf::FloatRect(0, 0, (float)VISIBLE_W/SCREEN_W, (float)VISIBLE_H/SCREEN_H));
game.window.setView(view);
map.draw();
drawBullets();
//player.draw(view);
player.draw();
game.window.setView(game.window.getDefaultView());
drawHud();
}
void StateOverworld::drawHud()
{
int BULLET_HUD_Y = 445;
int BULLET_HUD_X = 10;
game.bulletSelect.setPosition(BULLET_HUD_X + ((int)player.getBulletType())*(25-1), BULLET_HUD_Y);
game.bulletHud.setPosition(BULLET_HUD_X, BULLET_HUD_Y);
game.window.draw(game.bulletHud);
game.window.draw(game.bulletSelect);
} | 22.691011 | 185 | 0.670463 | [
"vector"
] |
d3d018c12cca477165043b7d062d9aedc683619e | 7,890 | cpp | C++ | cpp/geometric_quantities.cpp | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | cpp/geometric_quantities.cpp | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | cpp/geometric_quantities.cpp | jorgensd/asimov-contact | 08704ade6343c346bc54dfd38186983cc7ab4485 | [
"MIT"
] | null | null | null | // Copyright (C) 2021-2022 Sarah Roggendorf and Jørgen S. Dokken
//
// This file is part of DOLFINx_CONTACT
//
// SPDX-License-Identifier: MIT
#include "geometric_quantities.h"
#include <xtensor/xbuilder.hpp>
#include <xtensor/xtensor.hpp>
using namespace dolfinx_contact;
void dolfinx_contact::pull_back_nonaffine(
xt::xtensor<double, 2>& X, xt::xtensor<double, 2>& J,
xt::xtensor<double, 2>& K, xt::xtensor<double, 4>& basis,
const std::array<double, 3>& x, const dolfinx::fem::CoordinateElement& cmap,
const xt::xtensor<double, 2>& cell_geometry, double tol, int max_it)
{
assert((std::size_t)cmap.dim() == cell_geometry.shape(0));
assert(X.shape(0) == 1);
assert(X.shape(1) == J.shape(1));
// Temporary data structures for Newton iteration
const std::size_t tdim = J.shape(1);
xt::xtensor<double, 2> dphi({tdim, (std::size_t)cmap.dim()});
xt::xtensor<double, 2> Xk = xt::zeros<double>({(std::size_t)1, tdim});
std::array<double, 3> xk;
std::array<double, 3> dX = {0, 0, 0};
int k;
for (k = 0; k < max_it; ++k)
{
// Tabulate coordinate basis at Xk
cmap.tabulate(1, Xk, basis);
// x = cell_geometry * phi
auto phi = xt::view(basis, 0, 0, xt::all(), 0);
std::fill(xk.begin(), xk.end(), 0.0);
for (std::size_t i = 0; i < cell_geometry.shape(1); ++i)
for (std::size_t j = 0; j < cell_geometry.shape(0); ++j)
xk[i] += cell_geometry(j, i) * phi[j];
// Compute Jacobian, its inverse and determinant
std::fill(J.begin(), J.end(), 0.0);
dphi = xt::view(basis, xt::range(1, tdim + 1), 0, xt::all(), 0);
dolfinx::fem::CoordinateElement::compute_jacobian(dphi, cell_geometry, J);
dolfinx::fem::CoordinateElement::compute_jacobian_inverse(J, K);
// Compute dXk = K (x-xk)
std::fill(dX.begin(), dX.end(), 0.0);
for (std::size_t i = 0; i < K.shape(0); ++i)
for (std::size_t j = 0; j < K.shape(1); ++j)
dX[i] += K(i, j) * (x[j] - xk[j]);
// Compute Xk += dX
std::transform(dX.cbegin(), std::next(dX.cbegin(), tdim), Xk.cbegin(),
Xk.begin(), [](double a, double b) { return a + b; });
// Compute dot(dX, dX)
auto dX_squared = std::transform_reduce(dX.cbegin(), dX.cend(), 0.0,
std::plus<double>(),
[](const auto v) { return v * v; });
if (std::sqrt(dX_squared) < tol)
break;
}
std::copy(Xk.cbegin(), std::next(Xk.cbegin(), tdim), X.begin());
if (k == max_it)
{
throw std::runtime_error(
"Newton method failed to converge for non-affine geometry");
}
}
std::array<double, 3> dolfinx_contact::push_forward_facet_normal(
xt::xtensor<double, 2>& J, xt::xtensor<double, 2>& K,
const std::array<double, 3>& x,
const xt::xtensor<double, 2>& coordinate_dofs,
const std::size_t facet_index, const dolfinx::fem::CoordinateElement& cmap,
const xt::xtensor<double, 2>& reference_normals)
{
assert(J.shape(0) == K.shape(1));
assert(K.shape(0) == J.shape(1));
// Shapes needed for computing the Jacobian inverse
const size_t tdim = K.shape(0);
const size_t gdim = K.shape(1);
// Data structures for computing J inverse
std::array<std::size_t, 4> shape = cmap.tabulate_shape(1, 1);
xt::xtensor<double, 4> phi(shape);
xt::xtensor<double, 2> dphi({tdim, shape[2]});
xt::xtensor<double, 2> X({1, tdim});
// Compute Jacobian inverse
std::fill(J.begin(), J.end(), 0);
std::fill(K.begin(), K.end(), 0);
if (cmap.is_affine())
{
// Affine Jacobian can be computed at any point in the cell (0,0,0) in
// the reference cell
std::fill(X.begin(), X.end(), 0);
cmap.tabulate(1, X, phi);
dphi = xt::view(phi, xt::range(1, tdim + 1), 0, xt::all(), 0);
dolfinx::fem::CoordinateElement::compute_jacobian(dphi, coordinate_dofs, J);
std::fill(K.begin(), K.end(), 0);
dolfinx::fem::CoordinateElement::compute_jacobian_inverse(J, K);
}
else
{
// For non-affine geometries we have to compute the point in the reference
// cell, which is a nonlinear operation.
dolfinx_contact::pull_back_nonaffine(X, J, K, phi, x, cmap,
coordinate_dofs);
cmap.tabulate(1, X, phi);
dphi = xt::view(phi, xt::range(1, tdim + 1), 0, xt::all(), 0);
std::fill(J.begin(), J.end(), 0);
dolfinx::fem::CoordinateElement::compute_jacobian(dphi, coordinate_dofs, J);
std::fill(K.begin(), K.end(), 0);
dolfinx::fem::CoordinateElement::compute_jacobian_inverse(J, K);
}
// Push forward reference facet normal
std::array<double, 3> normal = {0, 0, 0};
physical_facet_normal(xtl::span(normal.data(), gdim), K,
xt::row(reference_normals, facet_index));
return normal;
}
//-----------------------------------------------------------------------------
double dolfinx_contact::compute_circumradius(
const dolfinx::mesh::Mesh& mesh, double detJ,
const xt::xtensor<double, 2>& coordinate_dofs)
{
const dolfinx::mesh::CellType cell_type = mesh.topology().cell_type();
const int gdim = mesh.geometry().dim();
switch (cell_type)
{
case dolfinx::mesh::CellType::triangle:
{
// Formula for circumradius of a triangle with sides with length a, b, c
// is R = a b c / (4 A) where A is the area of the triangle
const double ref_area = basix::cell::volume(basix::cell::type::triangle);
double area = ref_area * std::abs(detJ);
// Compute the lenghts of each side of the cell
std::array<double, 3> sides
= {0, 0, 0}; // Array to hold lenghts of sides of triangle
for (int i = 0; i < gdim; i++)
{
sides[0] += std::pow(coordinate_dofs(0, i) - coordinate_dofs(1, i), 2);
sides[1] += std::pow(coordinate_dofs(1, i) - coordinate_dofs(2, i), 2);
sides[2] += std::pow(coordinate_dofs(2, i) - coordinate_dofs(0, i), 2);
}
std::for_each(sides.begin(), sides.end(),
[](double& side) { side = std::sqrt(side); });
return sides[0] * sides[1] * sides[2] / (4 * area);
}
case dolfinx::mesh::CellType::tetrahedron:
{
// Formula for circunradius of a tetrahedron with volume V.
// Given three edges meeting at a vertex with length a, b, c,
// and opposite edges with corresponding length A, B, C we have that the
// circumradius
// R = sqrt((aA + bB + cC)(aA+bB-cC)(aA-bB+cC)(-aA +bB+cC))/24V
const double ref_volume
= basix::cell::volume(basix::cell::type::tetrahedron);
double cellvolume = std::abs(detJ) * ref_volume;
// Edges ordered as a, b, c, A, B, C
std::array<double, 6> edges = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < gdim; i++)
{
// Accummulate a^2, b^2, c^2
edges[0] += std::pow(coordinate_dofs(0, i) - coordinate_dofs(1, i), 2);
edges[1] += std::pow(coordinate_dofs(0, i) - coordinate_dofs(2, i), 2);
edges[2] += std::pow(coordinate_dofs(0, i) - coordinate_dofs(3, i), 2);
// Accumulate A^2, B^2, C^2
edges[3] += std::pow(coordinate_dofs(2, i) - coordinate_dofs(3, i), 2);
edges[4] += std::pow(coordinate_dofs(1, i) - coordinate_dofs(3, i), 2);
edges[5] += std::pow(coordinate_dofs(1, i) - coordinate_dofs(2, i), 2);
}
// Compute length of each edge
std::for_each(edges.begin(), edges.end(),
[](double& edge) { edge = std::sqrt(edge); });
// Compute temporary variables
const double aA = edges[0] * edges[3];
const double bB = edges[1] * edges[4];
const double cC = edges[2] * edges[5];
// Compute circumradius
double h = std::sqrt((aA + bB + cC) * (aA + bB - cC) * (aA - bB + cC)
* (-aA + bB + cC))
/ (24 * cellvolume);
return h;
}
default:
throw std::invalid_argument("Unsupported cell_type "
+ dolfinx::mesh::to_string(cell_type));
}
} | 39.253731 | 80 | 0.592269 | [
"mesh",
"geometry",
"shape",
"transform"
] |
d3d0520a669599b6bee3dd12adb79d557043049a | 6,200 | cpp | C++ | inference_cls.cpp | jackx2006/DFQ | 6f15805cfdbf2769275defd54728df0a5d30dbc6 | [
"MIT"
] | 196 | 2019-11-10T10:54:52.000Z | 2022-03-23T10:30:38.000Z | inference_cls.cpp | jackx2006/DFQ | 6f15805cfdbf2769275defd54728df0a5d30dbc6 | [
"MIT"
] | 41 | 2019-11-11T16:20:57.000Z | 2022-01-13T01:50:44.000Z | inference_cls.cpp | jackx2006/DFQ | 6f15805cfdbf2769275defd54728df0a5d30dbc6 | [
"MIT"
] | 33 | 2019-12-18T07:44:52.000Z | 2021-10-16T02:24:15.000Z | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "platform.h"
#include "net.h"
#if NCNN_VULKAN
#include "gpu.h"
#endif // NCNN_VULKAN
int parse_images_dir(const std::string& base_path, std::vector<std::string>& file_path)
{
file_path.clear();
const cv::String base_path_str(base_path);
std::vector<cv::String> image_list;
cv::glob(base_path_str, image_list, true);
for (size_t i = 0; i < image_list.size(); i++)
{
const cv::String& image_path = image_list[i];
file_path.push_back(image_path);
}
return 0;
}
static int print_topk(const std::vector<float>& cls_scores, int topk)
{
// partial sort topk with index
int size = cls_scores.size();
std::vector< std::pair<float, int> > vec;
vec.resize(size);
for (int i=0; i<size; i++)
{
vec[i] = std::make_pair(cls_scores[i], i);
}
std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
std::greater< std::pair<float, int> >());
int pred_idx;
// print topk and score
for (int i=0; i<topk; i++)
{
float score = vec[i].first;
int index = vec[i].second;
if(0==i)
{
pred_idx = index;
}
// fprintf(stderr, "%d = %f\n", index, score);
}
return pred_idx;
}
static int detect_net(const std::vector<std::string>& image_list, std::vector<float>& cls_scores,
const std::string ncnn_param_file_path, const std::string ncnn_bin_file_path, const std::string out_layer)
{
ncnn::Net net;
size_t size = image_list.size();
printf("Number of images: %lu\n", size);
#if NCNN_VULKAN
net.opt.use_vulkan_compute = true;
#endif // NCNN_VULKAN
net.load_param(&ncnn_param_file_path[0]);
net.load_model(&ncnn_bin_file_path[0]);
const float mean_vals[3] = {0.485f*255.f, 0.456f*255.f, 0.406f*255.f};
const float std_vals[3] = {1/0.229f/255.f, 1/0.224f/255.f, 1/0.225f/255.f};
int correct_count = 0;
int label = -1;
std::string folder_name = "dummy";
for (size_t i = 0; i < image_list.size(); i++)
{
std::string img_name = image_list[i];
std::istringstream f(img_name);
std::string s;
while(std::getline(f, s, '/'))
{
if((s.substr(0, 2) == "n0" || s.substr(0, 2) == "n1") && s.size() == 9 && folder_name != s)
{
label++;
folder_name = s;
}
}
if ((i + 1) % 1000 == 0)
{
fprintf(stderr, " %d/%d, acc:%f\n", static_cast<int>(i + 1), static_cast<int>(size), static_cast<float>(correct_count)/static_cast<float>(i));
}
#if OpenCV_VERSION_MAJOR > 2
cv::Mat bgr = cv::imread(img_name, cv::IMREAD_COLOR);
#else
cv::Mat bgr = cv::imread(img_name, CV_LOAD_IMAGE_COLOR);
#endif
if (bgr.empty())
{
fprintf(stderr, "cv::imread %s failed\n", img_name.c_str());
return -1;
}
ncnn::Mat resized = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, bgr.cols, bgr.rows, 256, 256);
ncnn::Mat in;
ncnn::copy_cut_border(resized, in, 16, 16, 16, 16);
in.substract_mean_normalize(mean_vals, std_vals);
ncnn::Extractor ex = net.create_extractor();
ex.set_num_threads(2);
ex.input("0", in);
ncnn::Mat out;
ex.extract(&out_layer[0], out);
cls_scores.resize(out.w);
for (int j=0; j<out.w; j++)
{
cls_scores[j] = out[j];
}
int pred_idx = print_topk(cls_scores, 3);
// printf("label: %d, pred: %d\n", label, pred_idx);
// printf("=======================================\n");
if(pred_idx == label)
{
correct_count++;
}
}
printf("Acc: %f\n", static_cast<float>(correct_count)/static_cast<float>(size));
return 0;
}
int main(int argc, char** argv)
{
const char* key_map =
"{help h usage ? | | print this message }"
"{param p | | path to ncnn.param file }"
"{bin b | | path to ncnn.bin file }"
"{images i | | path to calibration images folder }"
"{out_layer o | | name of the final layer (innerproduct or softmax) }"
;
cv::CommandLineParser parser(argc, argv, key_map);
const std::string image_folder_path = parser.get<cv::String>("images");
const std::string ncnn_param_file_path = parser.get<cv::String>("param");
const std::string ncnn_bin_file_path = parser.get<cv::String>("bin");
const std::string out_layer = parser.get<cv::String>("out_layer");
// check the input param
if (image_folder_path.empty() || ncnn_param_file_path.empty() || ncnn_bin_file_path.empty())
{
fprintf(stderr, "One or more path may be empty, please check and try again.\n");
return 0;
}
// parse the image file.
std::vector<std::string> image_file_path_list;
parse_images_dir(image_folder_path, image_file_path_list);
#if NCNN_VULKAN
ncnn::create_gpu_instance();
#endif // NCNN_VULKAN
std::vector<float> cls_scores;
detect_net(image_file_path_list, cls_scores, ncnn_param_file_path, ncnn_bin_file_path, out_layer);
#if NCNN_VULKAN
ncnn::destroy_gpu_instance();
#endif // NCNN_VULKAN
return 0;
}
| 31.313131 | 163 | 0.606613 | [
"vector"
] |
d3d72a4d422a8bdde6d0c41ab1a000d68ad390c0 | 11,400 | hpp | C++ | src/editor/renderers/line_renderer.hpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 36 | 2021-05-03T10:47:49.000Z | 2022-03-19T12:54:03.000Z | src/editor/renderers/line_renderer.hpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 29 | 2020-05-17T08:26:31.000Z | 2022-03-27T08:52:47.000Z | src/editor/renderers/line_renderer.hpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 2 | 2022-01-24T09:24:37.000Z | 2022-01-31T20:45:36.000Z | #pragma once
#include "erhe/components/component.hpp"
#include "erhe/graphics/buffer.hpp"
#include "erhe/graphics/configuration.hpp"
#include "erhe/graphics/fragment_outputs.hpp"
#include "erhe/graphics/pipeline.hpp"
#include "erhe/graphics/pipeline.hpp"
#include "erhe/graphics/shader_resource.hpp"
#include "erhe/graphics/state/color_blend_state.hpp"
#include "erhe/graphics/state/depth_stencil_state.hpp"
#include "erhe/graphics/state/input_assembly_state.hpp"
#include "erhe/graphics/state/rasterization_state.hpp"
#include "erhe/graphics/state/vertex_input_state.hpp"
#include "erhe/graphics/vertex_attribute_mappings.hpp"
#include "erhe/graphics/vertex_format.hpp"
#include <imgui.h>
#include <glm/glm.hpp>
#include <cstdint>
#include <deque>
#include <list>
#include <memory>
#include <vector>
namespace erhe::graphics
{
class Buffer;
class OpenGL_state_tracker;
class Sampler;
class Shader_stages;
}
namespace erhe::scene
{
class ICamera;
class Viewport;
}
namespace erhe::ui
{
class Font;
}
namespace editor
{
class Configuration;
class Shader_monitor;
class Line
{
public:
glm::vec3 p0;
glm::vec3 p1;
};
//class Color_line
//{
//public:
// glm::vec4 color0;
// glm::vec3 p0;
// glm::vec4 color1;
// glm::vec3 p1;
//};
class Line_renderer
: public erhe::components::Component
{
public:
static constexpr std::string_view c_name{"Line_renderer"};
static constexpr uint32_t hash = compiletime_xxhash::xxh32(c_name.data(), c_name.size(), {});
Line_renderer ();
~Line_renderer() override;
// Implements Component
auto get_type_hash () const -> uint32_t override { return hash; }
void connect () override;
void initialize_component() override;
// Public API
void next_frame();
void render(
const erhe::scene::Viewport camera_viewport,
const erhe::scene::ICamera& camera
);
private:
static constexpr size_t s_frame_resources_count = 4;
class Pipeline
{
public:
void initialize(Shader_monitor* shader_monitor);
bool reverse_depth{false};
erhe::graphics::Fragment_outputs fragment_outputs;
erhe::graphics::Vertex_attribute_mappings attribute_mappings;
erhe::graphics::Vertex_format vertex_format;
std::unique_ptr<erhe::graphics::Shader_resource> view_block;
std::unique_ptr<erhe::graphics::Shader_stages> shader_stages;
erhe::graphics::Shader_resource default_uniform_block; // containing sampler uniforms
size_t clip_from_world_offset {0};
size_t view_position_in_world_offset{0};
size_t viewport_offset {0};
size_t fov_offset {0};
};
Pipeline m_pipeline;
class Frame_resources
{
public:
static inline const erhe::graphics::Color_blend_state color_blend_visible_lines{
true, // enabled
{ // rgb
gl::Blend_equation_mode::func_add,
gl::Blending_factor::src_alpha,
gl::Blending_factor::one_minus_src_alpha
},
{ // alpha
gl::Blend_equation_mode::func_add,
gl::Blending_factor::src_alpha,
gl::Blending_factor::one_minus_src_alpha
},
glm::vec4{0.0f, 0.0f, 0.0f, 1.0f}, // constant
true,
true,
true,
true
};
static inline const erhe::graphics::Color_blend_state color_blend_hidden_lines{
true, // enabled
{ // rgb
gl::Blend_equation_mode::func_add,
gl::Blending_factor::constant_alpha,
gl::Blending_factor::one_minus_constant_alpha
},
{ // alpha
gl::Blend_equation_mode::func_add,
gl::Blending_factor::constant_alpha,
gl::Blending_factor::one_minus_constant_alpha
},
glm::vec4{0.0f, 0.0f, 0.0f, 0.1f}, // constant
true,
true,
true,
true
};
static constexpr gl::Buffer_storage_mask storage_mask{
gl::Buffer_storage_mask::map_coherent_bit |
gl::Buffer_storage_mask::map_persistent_bit |
gl::Buffer_storage_mask::map_write_bit
};
static constexpr gl::Map_buffer_access_mask access_mask{
gl::Map_buffer_access_mask::map_coherent_bit |
gl::Map_buffer_access_mask::map_persistent_bit |
gl::Map_buffer_access_mask::map_write_bit
};
Frame_resources(
const bool reverse_depth,
const size_t view_stride,
const size_t view_count,
const size_t vertex_count,
erhe::graphics::Shader_stages* shader_stages,
erhe::graphics::Vertex_attribute_mappings attribute_mappings,
erhe::graphics::Vertex_format& vertex_format
)
: vertex_buffer{
gl::Buffer_target::array_buffer,
vertex_format.stride() * vertex_count,
storage_mask,
access_mask
}
, view_buffer{
gl::Buffer_target::uniform_buffer,
view_stride * view_count,
storage_mask,
access_mask
}
, vertex_input_state{
attribute_mappings,
vertex_format,
&vertex_buffer,
nullptr
}
, pipeline_depth_pass{
shader_stages,
&vertex_input_state,
&erhe::graphics::Input_assembly_state::lines,
&erhe::graphics::Rasterization_state::cull_mode_none,
erhe::graphics::Depth_stencil_state::depth_test_enabled_stencil_test_disabled(reverse_depth),
&erhe::graphics::Color_blend_state::color_blend_premultiplied,
nullptr
}
, pipeline_depth_fail{
shader_stages,
&vertex_input_state,
&erhe::graphics::Input_assembly_state::lines,
&erhe::graphics::Rasterization_state::cull_mode_none,
&erhe::graphics::Depth_stencil_state::depth_test_disabled_stencil_test_disabled,
&color_blend_hidden_lines,
nullptr
}
{
vertex_buffer.set_debug_label("Line Renderer Vertex");
view_buffer.set_debug_label("Line Renderer View");
}
Frame_resources(const Frame_resources&) = delete;
void operator= (const Frame_resources&) = delete;
Frame_resources(Frame_resources&&) = delete;
void operator= (Frame_resources&&) = delete;
erhe::graphics::Buffer vertex_buffer;
erhe::graphics::Buffer view_buffer;
erhe::graphics::Vertex_input_state vertex_input_state;
erhe::graphics::Pipeline pipeline_depth_pass;
erhe::graphics::Pipeline pipeline_depth_fail;
};
erhe::graphics::OpenGL_state_tracker* m_pipeline_state_tracker{nullptr};
class Buffer_range
{
public:
size_t first_byte_offset{0};
size_t byte_count {0};
};
class Buffer_writer
{
public:
Buffer_range range;
size_t write_offset{0};
void begin()
{
range.first_byte_offset = write_offset;
}
void end()
{
range.byte_count = write_offset - range.first_byte_offset;
}
void reset()
{
range.first_byte_offset = 0;
range.byte_count = 0;
write_offset = 0;
}
};
public:
class Style
{
public:
Style();
Style (const Style&) = delete; // Due to std::deque<Frame_resources> m_frame_resources
void operator=(const Style&) = delete; // Style must be non-copyable and non-movable.
Style (Style&&) = delete;
void operator=(Style&&) = delete;
// Public API
[[nodiscard]] auto current_frame_resources() -> Frame_resources&;
void create_frame_resources(Pipeline* pipeline, const Configuration* const configuration);
void next_frame ();
void render(
erhe::graphics::OpenGL_state_tracker* pipeline_state_tracker,
const erhe::scene::Viewport camera_viewport,
const erhe::scene::ICamera& camera,
const bool show_visible_lines,
const bool show_hidden_lines
);
void set_line_color(const uint32_t color)
{
m_line_color = color;
}
void set_line_color(const float r, const float g, const float b, const float a)
{
m_line_color = ImGui::ColorConvertFloat4ToU32(ImVec4{r, g, b, a});
}
void set_line_color(const glm::vec3 color)
{
m_line_color = ImGui::ColorConvertFloat4ToU32(ImVec4{color.r, color.g, color.b, 1.0f});
}
void add_lines(
const std::initializer_list<Line> lines,
const float thickness
);
void add_lines(
const glm::mat4 transform,
const std::initializer_list<Line> lines,
const float thickness
);
void add_lines(
const glm::mat4 transform,
const uint32_t color,
const std::initializer_list<Line> lines,
const float thickness
)
{
set_line_color(color);
add_lines(transform, lines, thickness);
}
//void add_lines(
// const glm::mat4 transform,
// const std::initializer_list<Color_line> color_lines,
// const float thickness = 2.0f
//);
private:
void put(
const glm::vec3 point,
const float thickness,
const uint32_t color,
const gsl::span<float>& gpu_float_data,
const gsl::span<uint32_t>& gpu_uint_data,
size_t& word_offset
);
std::deque<Frame_resources> m_frame_resources;
Pipeline* m_pipeline{nullptr};
size_t m_line_count{0};
Buffer_writer m_view_writer;
Buffer_writer m_vertex_writer;
size_t m_current_frame_resource_slot{0};
uint32_t m_line_color {0xffffffffu};
};
Style visible;
Style hidden;
};
}
| 32.758621 | 110 | 0.550702 | [
"render",
"vector",
"transform"
] |
d3da6cc7ddfcaff8a4e4327132ffd82e1aa9ab0a | 1,827 | cpp | C++ | gurobi912/linux64/examples/c++/params_c++.cpp | UtileFuzzball/test_eran | 34d5f49dd4cac2a95cb915499a57a8a11829b93e | [
"Apache-2.0"
] | null | null | null | gurobi912/linux64/examples/c++/params_c++.cpp | UtileFuzzball/test_eran | 34d5f49dd4cac2a95cb915499a57a8a11829b93e | [
"Apache-2.0"
] | null | null | null | gurobi912/linux64/examples/c++/params_c++.cpp | UtileFuzzball/test_eran | 34d5f49dd4cac2a95cb915499a57a8a11829b93e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021, Gurobi Optimization, LLC */
/* Use parameters that are associated with a model.
A MIP is solved for a few seconds with different sets of parameters.
The one with the smallest MIP gap is selected, and the optimization
is resumed until the optimal solution is found.
*/
#include "gurobi_c++.h"
using namespace std;
int
main(int argc,
char *argv[])
{
if (argc < 2)
{
cout << "Usage: params_c++ filename" << endl;
return 1;
}
GRBEnv* env = 0;
GRBModel *bestModel = 0, *m = 0;
try
{
// Read model and verify that it is a MIP
env = new GRBEnv();
m = new GRBModel(*env, argv[1]);
if (m->get(GRB_IntAttr_IsMIP) == 0)
{
cout << "The model is not an integer program" << endl;
return 1;
}
// Set a 2 second time limit
m->set(GRB_DoubleParam_TimeLimit, 2);
// Now solve the model with different values of MIPFocus
bestModel = new GRBModel(*m);
bestModel->optimize();
for (int i = 1; i <= 3; ++i)
{
m->reset();
m->set(GRB_IntParam_MIPFocus, i);
m->optimize();
if (bestModel->get(GRB_DoubleAttr_MIPGap) >
m->get(GRB_DoubleAttr_MIPGap))
{
swap(bestModel, m);
}
}
// Finally, delete the extra model, reset the time limit and
// continue to solve the best model to optimality
delete m;
m = 0;
bestModel->set(GRB_DoubleParam_TimeLimit, GRB_INFINITY);
bestModel->optimize();
cout << "Solved with MIPFocus: " <<
bestModel->get(GRB_IntParam_MIPFocus) << endl;
}
catch (GRBException e)
{
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
}
catch (...)
{
cout << "Error during optimization" << endl;
}
delete bestModel;
delete m;
delete env;
return 0;
}
| 23.126582 | 71 | 0.603722 | [
"model"
] |
d3e0c0a5be9946eb4cdb0fd163feb5fa3a2cc5b3 | 31,143 | cc | C++ | src/engines/knapp-mic/knapp-mic.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 61 | 2015-03-25T04:49:09.000Z | 2020-11-24T08:36:19.000Z | src/engines/knapp-mic/knapp-mic.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 32 | 2015-04-29T08:20:39.000Z | 2017-02-09T22:49:37.000Z | src/engines/knapp-mic/knapp-mic.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 11 | 2015-07-24T22:48:05.000Z | 2020-09-10T11:48:47.000Z | #include <nba/engines/knapp/defs.hh>
#include <nba/engines/knapp/mictypes.hh>
#include <nba/engines/knapp/sharedtypes.hh>
#include <nba/engines/knapp/sharedutils.hh>
#include <nba/engines/knapp/micintrinsic.hh>
#include <nba/engines/knapp/micbarrier.hh>
#include <nba/engines/knapp/micutils.hh>
#include <nba/engines/knapp/ctrl.pb.h>
#include <nba/engines/knapp/pollring.hh>
#include <nba/engines/knapp/rma.hh>
#include <nba/engines/knapp/kernels.hh>
#include "apps/ipv4route.hh"
#include <nba/core/enumerate.hh>
#include <nba/framework/datablock_shared.hh>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <tuple>
#include <vector>
#include <unordered_set>
#include <map>
#include <algorithm>
#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <locale.h>
namespace nba { namespace knapp {
worker_func_t worker_funcs[KNAPP_MAX_KERNEL_TYPES];
/* MIC daemon consists of 3 types of threads:
* (1) control_thread_loop: global state mgmt (e.g., "cudaMalloc", "cudaMmecpy")
* (2) master_thread_loop: vDevice controller
* (3) worker_thread_loop: vDevice worker
*
* Each vDevice has at least one master and zero or more workers.
*/
static uint32_t mic_num_pcores = 0;
static uint32_t mic_num_lcores = 0;
static uint64_t global_vdevice_counter = 0;
static bool pcore_used[KNAPP_NUM_CORES];
static pthread_t control_thread;
static std::unordered_set<struct nba::knapp::vdevice *> vdevs;
static volatile bool exit_flag = false;
static RMABuffer *global_rma_buffers[KNAPP_GLOBAL_MAX_RMABUFFERS];
void *control_thread_loop(void *arg);
void *master_thread_loop(void *arg);
void *worker_thread_loop(void *arg);
void stop_all();
void handle_signal(int signal);
struct vdevice *create_vdev(
uint32_t num_pcores,
uint32_t num_lcores_per_pcore,
uint32_t pipeline_depth,
pthread_barrier_t *ready_barrier);
void destroy_vdev(struct vdevice *vdev);
bool create_pollring(
struct vdevice *vdev, uint32_t ring_id,
size_t len, off_t peer_ra);
bool destroy_pollring(
struct vdevice *vdev, uint32_t ring_id);
bool create_rma(
struct vdevice *vdev, uint32_t buffer_id,
size_t size, off_t peer_ra);
bool create_rma(
scif_epd_t ctrl_epd, uint32_t buffer_id,
size_t size, off_t peer_ra);
bool destroy_rma(
struct vdevice *vdev, uint32_t buffer_id);
}} // endns(nba::knapp)
using namespace nba::knapp;
static struct vdevice *nba::knapp::create_vdev(
uint32_t num_pcores,
uint32_t num_lcores_per_pcore,
uint32_t pipeline_depth,
pthread_barrier_t *ready_barrier)
{
int rc;
bool avail = true;
uint32_t pcore_begin = 0;
struct vdevice *vdev = nullptr;
/* Find available slots and allocate among MIC cores. */
for (uint32_t i = 0; i < mic_num_pcores - num_pcores; i++) {
avail = true;
for (uint32_t j = 0; j < num_pcores; j++) {
if (pcore_used[i + j]) {
avail = false;
break;
}
}
if (avail) {
pcore_begin = i;
break;
}
}
if (avail) {
vdev = new struct vdevice();
vdev->pcores.clear();
vdev->lcores.clear();
for (uint32_t i = 0; i < num_pcores; i++) {
pcore_used[pcore_begin + i] = true;
vdev->pcores.push_back(pcore_begin + i);
for (uint32_t j = 0; j < num_lcores_per_pcore; j++) {
vdev->lcores.push_back(mic_pcore_to_lcore(pcore_begin + i, j));
}
}
} else {
return nullptr;
}
vdev->device_id = (++global_vdevice_counter);
vdev->pipeline_depth = pipeline_depth;
vdev->ht_per_core = num_lcores_per_pcore;
vdev->num_worker_threads = vdev->pcores.size() * num_lcores_per_pcore;
vdev->master_core = pcore_begin;
vdev->threads_alive = false;
log_device(vdev->device_id, "Created. (pcore_begin=%d, pcores=%u, num_workers=%u)\n",
pcore_begin, vdev->pcores.size(), vdev->num_worker_threads);
/* Initialize barriers. */
vdev->data_ready_barriers = (Barrier **) _mm_malloc(sizeof(Barrier *) * vdev->pipeline_depth, CACHE_LINE_SIZE);
vdev->task_done_barriers = (Barrier **) _mm_malloc(sizeof(Barrier *) * vdev->pipeline_depth, CACHE_LINE_SIZE);
for (uint32_t i = 0; i < vdev->pipeline_depth; i++) {
vdev->data_ready_barriers[i] = new Barrier(vdev->num_worker_threads, vdev->device_id, KNAPP_BARRIER_PROFILE_INTERVAL);
vdev->task_done_barriers[i] = new Barrier(vdev->num_worker_threads, vdev->device_id, KNAPP_BARRIER_PROFILE_INTERVAL);
}
memzero(vdev->poll_rings, KNAPP_VDEV_MAX_POLLRINGS);
memzero(vdev->rma_buffers, KNAPP_VDEV_MAX_RMABUFFERS);
vdev->task_params = nullptr;
vdev->d2h_params = nullptr;
/* Spawn the master thread. */
vdev->threads_alive = true;
vdev->master_ready_barrier = ready_barrier;
vdev->term_barrier = new pthread_barrier_t;
pthread_barrier_init(vdev->term_barrier, nullptr, vdev->num_worker_threads + 2);
pthread_attr_t attr;
pthread_attr_init(&attr);
int master_lcore = mic_pcore_to_lcore(pcore_begin, KNAPP_MAX_THREADS_PER_CORE - 1);
set_cpu_mask(&attr, master_lcore, mic_num_lcores);
rc = pthread_create(&vdev->master_thread, &attr, master_thread_loop, (void *) vdev);
assert(0 == rc);
log_device(vdev->device_id, "Spawned the master thread at lcore %d.\n", master_lcore);
pthread_attr_destroy(&attr);
return vdev;
}
static void nba::knapp::destroy_vdev(struct vdevice *vdev)
{
/* Destroy master and worker threads. */
log_device(vdev->device_id, "Deleting vDevice...\n");
vdev->exit = true;
log_device(vdev->device_id, "killing all workers...\n");
pthread_barrier_wait(vdev->term_barrier);
pthread_barrier_destroy(vdev->term_barrier);
delete vdev->term_barrier;
vdev->threads_alive = false;
for (int c : vdev->pcores)
pcore_used[c] = false;
for (uint32_t i = 0; i < vdev->pipeline_depth; i++) {
delete vdev->data_ready_barriers[i];
delete vdev->task_done_barriers[i];
}
_mm_free(vdev->data_ready_barriers);
_mm_free(vdev->task_done_barriers);
for (int i = 0; i < KNAPP_VDEV_MAX_POLLRINGS; i++) {
if (vdev->poll_rings[i] != nullptr)
delete vdev->poll_rings[i];
}
for (int i = 0; i < KNAPP_VDEV_MAX_RMABUFFERS; i++) {
if (vdev->rma_buffers[i] != nullptr)
delete vdev->rma_buffers[i];
}
if (vdev->task_params != nullptr)
delete vdev->task_params;
if (vdev->d2h_params != nullptr)
delete vdev->d2h_params;
_mm_free(vdev->thread_info_array);
for (unsigned pd = 0; pd < vdev->pipeline_depth; pd++) {
_mm_free(vdev->per_thread_work_info[pd]);
}
_mm_free(vdev->per_thread_work_info);
log_device(vdev->device_id, "Deleted vDevice.\n");
scif_close(vdev->data_epd);
scif_close(vdev->data_listen_epd);
delete vdev;
}
static bool nba::knapp::create_pollring(
struct vdevice *vdev, uint32_t ring_id,
size_t len, off_t peer_ra)
{
PollRing *r = new PollRing(vdev->data_epd, len);
log_device(vdev->device_id, "Creating PollRing[%u] "
"(length %u, ra %p, peer_ra %p).\n",
ring_id, len, r->ra(), peer_ra);
r->set_peer_ra(peer_ra);
vdev->poll_rings[ring_id] = r;
return true;
}
static bool nba::knapp::destroy_pollring(
struct vdevice *vdev, uint32_t ring_id)
{
delete vdev->poll_rings[ring_id];
vdev->poll_rings[ring_id] = nullptr;
log_device(vdev->device_id, "Deleted PollRing[%u].\n", ring_id);
return true;
}
static bool nba::knapp::create_rma(
struct vdevice *vdev, uint32_t buffer_id,
size_t size, off_t peer_ra)
{
RMABuffer *b = new RMABuffer(vdev->data_epd, size);
b->set_peer_ra(peer_ra);
log_device(vdev->device_id, "Creating RMABuffer[%u] "
"(size %'u bytes, ra %p, peer_ra %p).\n",
buffer_id, size, b->ra(), peer_ra);
switch (buffer_id) {
case BUFFER_TASK_PARAMS:
assert(nullptr == vdev->task_params);
vdev->task_params = b;
break;
case BUFFER_D2H_PARAMS:
assert(nullptr == vdev->d2h_params);
vdev->d2h_params = b;
break;
default:
assert(nullptr == vdev->rma_buffers[buffer_id]);
vdev->rma_buffers[buffer_id] = b;
}
return true;
}
static bool nba::knapp::create_rma(
scif_epd_t ctrl_epd, uint32_t global_idx,
size_t size, off_t peer_ra)
{
RMABuffer *b = new RMABuffer(ctrl_epd, size);
log_info("Creating global RMABuffer[%d] "
"(size %'u bytes, ra %p, peer_ra %p).\n",
global_idx, size, b->ra(), peer_ra);
assert(nullptr == global_rma_buffers[global_idx]);
global_rma_buffers[global_idx] = b;
b->set_peer_ra(peer_ra);
return true;
}
static bool nba::knapp::destroy_rma(
struct vdevice *vdev, uint32_t buffer_id)
{
if (vdev == nullptr) {
uint32_t global_idx;
tie(std::ignore, global_idx, std::ignore) = decompose_buffer_id(buffer_id);
delete global_rma_buffers[global_idx];
global_rma_buffers[global_idx] = nullptr;
log_info("Deleted global RMABuffer[%u].\n", global_idx);
} else {
delete vdev->rma_buffers[buffer_id];
vdev->rma_buffers[buffer_id] = nullptr;
log_device(vdev->device_id, "Deleted RMABuffer[%u].\n", buffer_id);
}
return true;
}
static void *nba::knapp::worker_thread_loop(void *arg)
{
struct worker_thread_info *info = (struct worker_thread_info *) arg;
const int tid = info->thread_id;
struct vdevice *vdev = info->vdev;
log_device(vdev->device_id, "Starting worker[%d]\n", tid);
pthread_barrier_wait(info->worker_ready_barrier);
info->worker_ready_barrier = nullptr;
while (!vdev->exit) {
if (unlikely(vdev->poll_rings[0] == nullptr)) {
/* The host has not initialized yet! */
insert_pause();
continue;
}
bool timeout = false;
/* former worker_preproc() */
{
struct work &w =
vdev->per_thread_work_info[vdev->next_task_id][tid];
if (tid != 0) {
w.data_ready_barrier->here(tid);
}
if (tid == 0) {
uint32_t task_id = vdev->next_task_id;
vdev->cur_task_id = task_id;
vdev->poll_rings[0]->wait(task_id, KNAPP_TASK_READY);
/* init latency/stat measurement */
//vdev->poll_rings[0]->notify(task_id, KNAPP_COPY_PENDING);
w.data_ready_barrier->here(0);
vdev->next_task_id = (task_id + 1) % vdev->poll_rings[0]->len();
}
}
{
uint32_t task_id = vdev->cur_task_id;
struct work &w = vdev->per_thread_work_info[task_id][tid];
auto &pktproc_func = worker_funcs[w.kernel_id];
struct datablock_kernel_arg **datablocks
= static_cast<struct datablock_kernel_arg **>(w.args[0]);
// count (w.args[1]) is not used.
uint32_t *item_counts = static_cast<uint32_t *>(w.args[2]);
uint32_t num_batches;
memcpy(&num_batches, &w.args[3], sizeof(uint32_t));
size_t num_remaining_args = w.num_args - 4;
pktproc_func(w.begin_idx, w.begin_idx + w.num_items,
datablocks, item_counts, num_batches,
num_remaining_args, &w.args[4]);
w.task_done_barrier->here(tid);
/* former worker_postproc() */
if (tid == 0) {
/* finalize latency/stat measurement */
struct d2hcopy &c = reinterpret_cast<struct d2hcopy *>(vdev->d2h_params->va())[task_id];
for (unsigned j = 0; j < c.num_copies; j++) {
RMABuffer *b = vdev->rma_buffers[c.buffer_id[j]];
assert(nullptr != b);
if (c.size[j] > 0) {
b->write(c.offset[j], c.size[j], false);
}
}
vdev->poll_rings[0]->remote_notify(task_id, KNAPP_D2H_COMPLETE);
}
}
insert_pause();
}
log_device(vdev->device_id, "Terminating worker[%d]\n", tid);
pthread_barrier_wait(vdev->term_barrier);
return nullptr;
}
static void *nba::knapp::master_thread_loop(void *arg)
{
struct vdevice *vdev = (struct vdevice *) arg;
int backlog = 1;
int rc = 0;
uint16_t data_port = get_mic_data_port(vdev->device_id);
log_device(vdev->device_id, "Opening data channel (port %u)\n", data_port);
vdev->data_listen_epd = scif_open();
assert(SCIF_OPEN_FAILED != vdev->data_listen_epd);
rc = scif_bind(vdev->data_listen_epd, data_port);
assert(data_port == (uint16_t) rc);
rc = scif_listen(vdev->data_listen_epd, backlog);
assert(0 == rc);
/* Initialize worker thread info. */
pthread_barrier_t worker_ready_barrier;
pthread_barrier_init(&worker_ready_barrier, nullptr, vdev->num_worker_threads + 1);
vdev->thread_info_array = (struct worker_thread_info *) _mm_malloc(
sizeof(struct worker_thread_info) * vdev->num_worker_threads,
CACHE_LINE_SIZE);
assert(nullptr != vdev->thread_info_array);
for (unsigned i = 0; i < vdev->num_worker_threads; i++) {
struct worker_thread_info *info = &vdev->thread_info_array[i];
info->thread_id = i;
info->vdev = vdev;
info->worker_ready_barrier = &worker_ready_barrier;
}
/* Initialize pipelined worker info. */
vdev->per_thread_work_info = (struct work **) _mm_malloc(
sizeof(struct work *) * vdev->pipeline_depth,
CACHE_LINE_SIZE);
assert(nullptr != vdev->per_thread_work_info);
for (unsigned pd = 0; pd < vdev->pipeline_depth; pd++) {
vdev->per_thread_work_info[pd] = (struct work *) _mm_malloc(
sizeof(struct work) * vdev->num_worker_threads,
CACHE_LINE_SIZE);
assert(nullptr != vdev->per_thread_work_info[pd]);
}
log_device(vdev->device_id, "Allocated %d per-worker-thread work info.\n", vdev->num_worker_threads);
for (unsigned pd = 0; pd < vdev->pipeline_depth; pd++) {
for (unsigned i = 0; i < vdev->num_worker_threads; i++) {
struct work &w = vdev->per_thread_work_info[pd][i];
w.data_ready_barrier = vdev->data_ready_barriers[pd];
w.task_done_barrier = vdev->task_done_barriers[pd];
}
}
/* Spawn worker threads for this vDevice. */
vdev->worker_threads = (pthread_t *) _mm_malloc(
sizeof(pthread_t) * vdev->num_worker_threads,
CACHE_LINE_SIZE);
assert(nullptr != vdev->worker_threads);
assert(vdev->num_worker_threads == vdev->lcores.size());
for (auto&& pair : enumerate(vdev->lcores)) {
int i, lcore;
std::tie(i, lcore) = pair;
log_device(vdev->device_id, "Creating worker[%d] at lcore %d...\n", i, lcore);
pthread_attr_t attr;
pthread_attr_init(&attr);
set_cpu_mask(&attr, lcore, mic_num_lcores);
rc = pthread_create(&vdev->worker_threads[i], &attr,
worker_thread_loop,
(void *) &vdev->thread_info_array[i]);
assert(0 == rc);
pthread_attr_destroy(&attr);
}
/* Wait until all workers starts. */
pthread_barrier_wait(&worker_ready_barrier);
pthread_barrier_destroy(&worker_ready_barrier);
/* Now we are ready to respond the API client. */
pthread_barrier_wait(vdev->master_ready_barrier);
vdev->master_ready_barrier = nullptr;
struct scif_portID temp;
rc = scif_accept(vdev->data_listen_epd, &temp,
&vdev->data_epd, SCIF_ACCEPT_SYNC);
assert(0 == rc);
log_device(vdev->device_id, "Data channel established between "
"local port %d and peer(%d) port %d.\n",
data_port, temp.node, temp.port);
log_device(vdev->device_id, "Running processing daemon...\n");
uint32_t cur_task_id = 0;
while (!vdev->exit) {
bool timeout = false;
/* The host has not initialized yet! */
if (unlikely(vdev->poll_rings[0] == nullptr)) {
insert_pause();
continue;
}
vdev->poll_rings[0]->wait(cur_task_id, KNAPP_H2D_COMPLETE);
struct taskitem &ti = reinterpret_cast<struct taskitem *>(vdev->task_params->va())[cur_task_id];
if (ti.task_id != cur_task_id) {
log_device(vdev->device_id, "offloaded task id (%d) doesn't match pending id (%d)\n", ti.task_id, cur_task_id);
exit(1);
}
/* Split the input items for each worker thread. */
uint32_t remaining = ti.num_items;
uint32_t max_num_items = (ti.num_items + vdev->num_worker_threads)
/ vdev->num_worker_threads;
for (int i = 0; i < vdev->num_worker_threads; i++) {
struct work &w = vdev->per_thread_work_info[cur_task_id][i];
w.num_items = std::min(remaining, max_num_items);
w.begin_idx = remaining - w.num_items;
w.num_args = ti.num_args;
w.kernel_id = ti.kernel_id;
memcpy(w.args, ti.args, sizeof(void*) * ti.num_args);
remaining -= w.num_items;
}
/* Now we are ready to run the processing function.
* Notify worker threads. */
vdev->poll_rings[0]->notify(cur_task_id, KNAPP_TASK_READY);
cur_task_id = (cur_task_id + 1) % (vdev->poll_rings[0]->len());
}
log_device(vdev->device_id, "Terminating master thread.\n");
pthread_barrier_wait(vdev->term_barrier);
return nullptr;
}
static void *nba::knapp::control_thread_loop(void *arg)
{
scif_epd_t ctrl_listen_epd, ctrl_epd;
struct scif_portID accepted_ctrl_port;
int backlog = 1;
int rc = 0;
sigset_t intr_mask, orig_mask;
sigemptyset(&intr_mask);
sigaddset(&intr_mask, SIGINT);
sigaddset(&intr_mask, SIGTERM);
pthread_sigmask(SIG_BLOCK, &intr_mask, &orig_mask);
uint16_t scif_nodes[32];
uint16_t local_node;
size_t num_nodes;
num_nodes = scif_get_nodeIDs(scif_nodes, 32, &local_node);
ctrl_listen_epd = scif_open();
rc = scif_bind(ctrl_listen_epd, KNAPP_CTRL_PORT);
assert(KNAPP_CTRL_PORT == rc);
rc = scif_listen(ctrl_listen_epd, backlog);
assert(0 == rc);
log_info("Starting the control channel...\n");
/* For simplicty, we allow only a single concurrent connection. */
while (!exit_flag) {
struct pollfd p = {ctrl_listen_epd, POLLIN, 0};
rc = ppoll(&p, 1, nullptr, &orig_mask);
if (rc == -1 && errno == EINTR && exit_flag)
break;
rc = scif_accept(ctrl_listen_epd, &accepted_ctrl_port,
&ctrl_epd, SCIF_ACCEPT_SYNC);
assert(0 == rc);
log_info("A control session started.\n");
CtrlRequest request;
CtrlResponse resp;
while (!exit_flag) {
resp.Clear();
if (!recv_ctrlmsg(ctrl_epd, request, &orig_mask))
// usually, EINTR or ECONNRESET.
break;
switch (request.type()) {
case CtrlRequest::PING:
if (request.has_text()) {
const std::string &msg = request.text().msg();
log_info("CONTROL: PING with \"%s\"\n", msg.c_str());
resp.set_reply(CtrlResponse::SUCCESS);
resp.mutable_text()->set_msg(msg);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::MALLOC:
if (request.has_malloc()) {
void *ptr = _mm_malloc(request.malloc().size(), request.malloc().align());
if (ptr == nullptr) {
resp.set_reply(CtrlResponse::FAILURE);
resp.mutable_text()->set_msg("_mm_malloc failed.");
} else {
resp.set_reply(CtrlResponse::SUCCESS);
resp.mutable_resource()->set_handle((uintptr_t) ptr);
}
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::FREE:
if (request.has_resource()) {
void *ptr = (void *) request.resource().handle();
_mm_free(ptr);
resp.set_reply(CtrlResponse::SUCCESS);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::CREATE_VDEV:
if (request.has_vdevinfo()) {
pthread_barrier_t ready_barrier;
pthread_barrier_init(&ready_barrier, nullptr, 2);
struct vdevice *vdev = create_vdev(request.vdevinfo().num_pcores(),
request.vdevinfo().num_lcores_per_pcore(),
request.vdevinfo().pipeline_depth(),
&ready_barrier);
if (vdev == nullptr) {
pthread_barrier_destroy(&ready_barrier);
resp.set_reply(CtrlResponse::FAILURE);
resp.mutable_text()->set_msg("vDevice creation failed.");
} else {
pthread_barrier_wait(&ready_barrier);
pthread_barrier_destroy(&ready_barrier);
vdevs.insert(vdev);
resp.set_reply(CtrlResponse::SUCCESS);
resp.mutable_resource()->set_handle((uintptr_t) vdev);
resp.mutable_resource()->set_id(vdev->device_id);
}
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::DESTROY_VDEV:
if (request.has_resource()) {
struct vdevice *vdev = (struct vdevice *) request.resource().handle();
destroy_vdev(vdev);
vdevs.erase(vdev);
resp.set_reply(CtrlResponse::SUCCESS);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::CREATE_POLLRING:
if (request.has_pollring()) {
struct vdevice *vdev = (struct vdevice *) request.pollring().vdev_handle();
uint32_t id = request.pollring().ring_id();
if (create_pollring(vdev, id, request.pollring().len(),
request.pollring().local_ra())) {
resp.set_reply(CtrlResponse::SUCCESS);
resp.mutable_resource()->set_peer_ra((uint64_t) vdev->poll_rings[id]->ra());
} else
resp.set_reply(CtrlResponse::FAILURE);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::DESTROY_POLLRING:
if (request.has_pollring_ref()) {
struct vdevice *vdev = (struct vdevice *) request.pollring_ref().vdev_handle();
if (destroy_pollring(vdev, request.pollring_ref().ring_id())) {
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::CREATE_RMABUFFER:
if (request.has_rma()) {
struct vdevice *vdev = (struct vdevice *) request.rma().vdev_handle();
uint32_t buffer_id = request.rma().buffer_id();
uint32_t global_idx;
bool is_global;
rma_direction dir;
std::tie(is_global, global_idx, dir) = decompose_buffer_id(buffer_id);
if (vdev == nullptr) {
assert(is_global);
assert(dir == INPUT);
if (create_rma(ctrl_epd, global_idx, request.rma().size(),
request.rma().local_ra())) {
resp.mutable_resource()->set_peer_ra(static_cast<uint64_t>(global_rma_buffers[global_idx]->ra()));
resp.mutable_resource()->set_peer_va(static_cast<uint64_t>(global_rma_buffers[global_idx]->va()));
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
} else {
switch (buffer_id) {
case BUFFER_TASK_PARAMS:
if (create_rma(vdev, buffer_id, request.rma().size(),
request.rma().local_ra())) {
resp.mutable_resource()->set_peer_ra(static_cast<uint64_t>(vdev->task_params->ra()));
resp.mutable_resource()->set_peer_va(static_cast<uint64_t>(vdev->task_params->va()));
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
break;
case BUFFER_D2H_PARAMS:
if (create_rma(vdev, buffer_id, request.rma().size(),
request.rma().local_ra())) {
resp.mutable_resource()->set_peer_ra(static_cast<uint64_t>(vdev->d2h_params->ra()));
resp.mutable_resource()->set_peer_va(static_cast<uint64_t>(vdev->d2h_params->va()));
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
break;
default:
assert(!is_global);
if (create_rma(vdev, buffer_id, request.rma().size(),
request.rma().local_ra())) {
resp.mutable_resource()->set_peer_ra(static_cast<uint64_t>(vdev->rma_buffers[buffer_id]->ra()));
resp.mutable_resource()->set_peer_va(static_cast<uint64_t>(vdev->rma_buffers[buffer_id]->va()));
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
}
}
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
case CtrlRequest::DESTROY_RMABUFFER:
if (request.has_rma_ref()) {
struct vdevice *vdev = (struct vdevice *) request.rma_ref().vdev_handle();
if (destroy_rma(vdev, request.rma_ref().buffer_id())) {
resp.set_reply(CtrlResponse::SUCCESS);
} else
resp.set_reply(CtrlResponse::FAILURE);
} else {
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid parameter.");
}
break;
default:
log_error("CONTROL: Not implemented request type: %d\n", request.type());
resp.set_reply(CtrlResponse::INVALID);
resp.mutable_text()->set_msg("Invalid request type.");
break;
}
if (!send_ctrlresp(ctrl_epd, resp))
break;
} // endwhile
scif_close(ctrl_epd);
log_info("The control session terminated.\n");
} // endwhile
log_info("Terminating the control channel...\n");
scif_close(ctrl_listen_epd);
return nullptr;
}
static void nba::knapp::stop_all() {
exit_flag = true;
for (auto vdev : vdevs)
vdev->exit = true;
log_info("Stopping...\n");
for (auto vdev : vdevs) {
destroy_vdev(vdev);
}
vdevs.clear();
/* Ensure propagation of signals. */
pthread_kill(control_thread, SIGINT);
pthread_join(control_thread, nullptr);
}
static void nba::knapp::handle_signal(int signal) {
/* Ensure that this is the main thread. */
if (pthread_self() != control_thread)
stop_all();
}
#ifdef EMPTY_CYCLES
int num_bubble_cycles = 100;
#endif
int main (int argc, char *argv[])
{
int rc;
mic_num_lcores = sysconf(_SC_NPROCESSORS_ONLN);
mic_num_pcores = sysconf(_SC_NPROCESSORS_ONLN) / KNAPP_MAX_THREADS_PER_CORE;
memzero(pcore_used, KNAPP_NUM_CORES);
memzero(global_rma_buffers, KNAPP_GLOBAL_MAX_RMABUFFERS);
log_info("%ld lcores (%ld pcores) detected.\n", mic_num_lcores, mic_num_pcores);
setlocale(LC_NUMERIC, "");
#ifdef EMPTY_CYCLES
if (argc > 1) {
num_bubble_cycles = atoi(argv[1]);
assert(num_bubble_cycles > 0);
fprintf(stderr, "# of bubbles in kernel set to %d\n", num_bubble_cycles);
} else {
fprintf(stderr, "Need extra parameter for # of empty cycles\n");
exit(EXIT_FAILURE);
}
#endif
exit_flag = false;
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
set_cpu_mask(&attr, 0, mic_num_lcores);
pcore_used[0] = true;
rc = pthread_create(&control_thread, &attr, control_thread_loop, nullptr);
assert(0 == rc);
pthread_attr_destroy(&attr);
}
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
pthread_join(control_thread, nullptr);
return 0;
}
// vim: ts=8 sts=4 sw=4 et
| 38.977472 | 128 | 0.577176 | [
"vector"
] |
d3ec1fb06d496a5c677f728c3a8e63b151e35e47 | 12,185 | cc | C++ | server-src/internal-api.cc | Lalaland/DataChannelServer | 349caa6070795345b61689b6db088b302110c3b6 | [
"MIT"
] | 25 | 2016-07-22T12:08:37.000Z | 2021-03-13T00:47:14.000Z | server-src/internal-api.cc | Lalaland/DataChannelServer | 349caa6070795345b61689b6db088b302110c3b6 | [
"MIT"
] | null | null | null | server-src/internal-api.cc | Lalaland/DataChannelServer | 349caa6070795345b61689b6db088b302110c3b6 | [
"MIT"
] | 11 | 2016-12-27T05:54:11.000Z | 2020-05-29T08:31:33.000Z | #include "DataChannelServer/server-src/internal-api.h"
#include "webrtc/api/peerconnectioninterface.h"
#include "webrtc/api/test/fakeconstraints.h"
#include "webrtc/base/json.h"
#include <cstdio>
struct ProcessingThread {
std::unique_ptr<rtc::Thread> thread;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory;
};
ProcessingThread* CreateProcessingThread() {
ProcessingThread* result = new ProcessingThread();
result->thread = rtc::Thread::Create();
result->thread->Start();
result->thread->Invoke<bool>(RTC_FROM_HERE, [result]() {
result->factory = webrtc::CreatePeerConnectionFactory();
return true;
});
return result;
}
class PeerConnectionObserverWrapper {
public:
PeerConnectionObserverWrapper(PeerConnectionObserver observer) : observer_(observer) {}
~PeerConnectionObserverWrapper() {
observer_.Deleter(observer_.data);
}
void OnOpen() {
observer_.OnOpen(observer_.data);
}
void OnClose() {
observer_.OnClose(observer_.data);
}
void ProcessWebsocketMessage(const char* message, int message_length) {
observer_.ProcessWebsocketMessage(observer_.data, message, message_length);
}
void ProcessDataChannelMessage(const char* message, int message_length) {
observer_.ProcessDataChannelMessage(observer_.data, message, message_length);
}
private:
PeerConnectionObserver observer_;
};
class Foo;
class ChannelThingy;
struct PeerConnection {
public:
PeerConnection(PeerConnectionObserver observer) : observer_(observer) {}
PeerConnectionObserverWrapper observer_;
std::unique_ptr<Foo> f;
std::unique_ptr<ChannelThingy> channel;
rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> offer_obs;
rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> set_local_obs;
rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> set_remote_obs;
rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel;
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection;
};
class ChannelThingy : public webrtc::DataChannelObserver {
public:
ChannelThingy(PeerConnection* a_peer) : peer(a_peer) {}
private:
// The data channel state have changed.
void OnStateChange() override {
printf("STATE CHANGE FOR CHANNEL %d\n", peer->data_channel->state());
if (peer->data_channel->state() == webrtc::DataChannelInterface::kOpen) {
peer->observer_.OnOpen();
} else if (peer->data_channel->state() == webrtc::DataChannelInterface::kClosed) {
peer->observer_.OnClose();
}
}
// A data buffer was successfully received.
void OnMessage(const webrtc::DataBuffer& buffer) override {
printf("GOT MESSAGE %s\n", std::string((char*)buffer.data.data(), buffer.data.size()).c_str());
peer->observer_.ProcessDataChannelMessage((char*)buffer.data.data(), buffer.data.size());
}
// The data channel's buffered_amount has changed.
void OnBufferedAmountChange(uint64_t previous_amount) override {
printf("BUFFER AMOUNT CHANGE? WTF? %lu\n", previous_amount);
}
PeerConnection* peer;
};
class Foo : public webrtc::PeerConnectionObserver {
public:
Foo(PeerConnection* a_peer) : peer(a_peer) {}
private:
virtual void OnSignalingChange(
webrtc::PeerConnectionInterface::SignalingState new_state) {
printf("Signal\n");
}
// Triggered when media is received on a new stream from remote peer.
virtual void OnAddStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
printf("Add stream\n");
}
// Triggered when a remote peer close a stream.
virtual void OnRemoveStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
printf("Remove stream\n");
}
// Triggered when a remote peer opens a data channel.
virtual void OnDataChannel(
rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
printf("Data channel\n");
}
// Triggered when renegotiation is needed. For example, an ICE restart
// has begun.
virtual void OnRenegotiationNeeded() { printf("On renegotiion\n"); }
// Called any time the IceConnectionState changes.
virtual void OnIceConnectionChange(
webrtc::PeerConnectionInterface::IceConnectionState new_state) {
printf("ICE\n");
}
// Called any time the IceGatheringState changes.
virtual void OnIceGatheringChange(
webrtc::PeerConnectionInterface::IceGatheringState new_state) {
printf("ICE Gathering\n");
}
// A new ICE candidate has been gathered.
virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
printf("ICE Candidate\n");
std::string candidate_str;
;
if (!candidate->ToString(&candidate_str)) {
printf("FAILED TO STRING ICE\n");
}
Json::Value root;
root["type"] = "icecandidate";
Json::Value ice;
ice["candidate"] = candidate_str;
ice["sdpMid"] = candidate->sdp_mid();
ice["sdpMLineIndex"] = candidate->sdp_mline_index();
root["ice"] = ice;
std::string message = rtc::JsonValueToString(root);
peer->observer_.ProcessWebsocketMessage(message.data(), message.size());
}
// Ice candidates have been removed.
virtual void OnIceCandidatesRemoved(
const std::vector<cricket::Candidate>& candidates) {
printf("ICE remove\n");
}
// Called when the ICE connection receiving status changes.
virtual void OnIceConnectionReceivingChange(bool receiving) {
printf("Ice connection change\n");
}
private:
PeerConnection* peer;
};
class SetLocalOfferObserver : public webrtc::SetSessionDescriptionObserver {
public:
SetLocalOfferObserver(PeerConnection* a_peer, Json::Value a_sdi)
: peer(a_peer), sdi(std::move(a_sdi)) {}
void OnSuccess() override {
Json::Value root;
root["type"] = "offer";
root["sdi"] = sdi;
std::string message = rtc::JsonValueToString(root);
peer->observer_.ProcessWebsocketMessage(message.data(), message.size());
}
void OnFailure(const std::string& error) {
printf("FAILFAILFAILFAIL SET LOCAL OFFER %s\n", error.c_str());
}
private:
PeerConnection* peer;
Json::Value sdi;
};
class SetRemoteOfferObserver : public webrtc::SetSessionDescriptionObserver {
public:
SetRemoteOfferObserver(PeerConnection* a_peer) : peer(a_peer) {}
void OnSuccess() override {
printf("I AM GOOD TO GO!!!!\n");
(void)peer;
}
void OnFailure(const std::string& error) {
printf("FAILFAILFAILFAIL SET REMOTE OFFER %s\n", error.c_str());
}
private:
PeerConnection* peer;
};
class CreateOfferObserver : public webrtc::CreateSessionDescriptionObserver {
public:
CreateOfferObserver(PeerConnection* a_peer) : peer(a_peer) {}
void OnSuccess(webrtc::SessionDescriptionInterface* sdi) override {
std::string sdp;
if (!sdi->ToString(&sdp)) {
printf("FAIL SERIALIZE THINGY \n");
}
Json::Value sdi_obj;
sdi_obj["type"] = sdi->type();
sdi_obj["sdp"] = sdp;
peer->set_local_obs =
new rtc::RefCountedObject<SetLocalOfferObserver>(peer, sdi_obj);
peer->peer_connection->SetLocalDescription(peer->set_local_obs, sdi);
}
void OnFailure(const std::string& error) override {
printf("FAILFAILFAILFAIL CREATE OFFER %s\n", error.c_str());
}
private:
PeerConnection* peer;
};
EXPORT PeerConnection* CreatePeerConnection(
ProcessingThread* thread,
PeerConnectionObserver observer,
DataChannelOptions options) {
return thread->thread->Invoke<PeerConnection*>(
RTC_FROM_HERE,
[thread, observer, options]() {
PeerConnection* peer = new PeerConnection(observer);
peer->channel = std::unique_ptr<ChannelThingy>(new ChannelThingy(peer));
webrtc::PeerConnectionInterface::RTCConfiguration config;
webrtc::PeerConnectionInterface::IceServer ice_server;
ice_server.uri = "stun:stun.l.google.com:19302";
config.servers.push_back(ice_server);
webrtc::FakeConstraints constraints;
constraints.AddOptional(
webrtc::MediaConstraintsInterface::kEnableDtlsSrtp, "true");
peer->f = std::unique_ptr<Foo>(new Foo(peer));
peer->peer_connection = thread->factory->CreatePeerConnection(
config, &constraints, nullptr, nullptr, peer->f.get());
webrtc::DataChannelInit data_channel_config;
data_channel_config.ordered = options.ordered;
data_channel_config.maxRetransmitTime = options.maxRetransmitTime;
data_channel_config.maxRetransmits = options.maxRetransmits;
peer->data_channel =
peer->peer_connection->CreateDataChannel("lolchannel", &data_channel_config);
peer->data_channel->RegisterObserver(peer->channel.get());
peer->offer_obs = new rtc::RefCountedObject<CreateOfferObserver>(peer);
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
peer->peer_connection->CreateOffer(peer->offer_obs, options);
return peer;
});
}
void DeletePeerConnection(ProcessingThread* thread, PeerConnection* peer) {
thread->thread->Invoke<bool>(RTC_FROM_HERE, [peer]() {
delete peer;
return true;
});
}
void DeleteProcessingThread(ProcessingThread* thread) {
thread->thread->Stop();
delete thread;
}
template <typename F>
struct OnceFunctorHelper : rtc::MessageHandler {
OnceFunctorHelper(F functor) : functor_(functor) {}
void OnMessage(rtc::Message* /*msg*/) override {
functor_();
delete this;
}
F functor_;
};
template <typename F>
rtc::MessageHandler* OnceFunctor(F functor) {
return new OnceFunctorHelper<F>(functor);
}
void ProcessAnswer(PeerConnection* peer, const Json::Value& sdi_obj) {
std::string sdp_str = sdi_obj["sdp"].asString();
std::string type_str = sdi_obj["type"].asString();
webrtc::SessionDescriptionInterface* sdi =
webrtc::CreateSessionDescription(type_str, sdp_str, nullptr);
if (sdi == nullptr) {
printf("THE SDI IS NULL???? WHYWHYWHYW %s\n",
rtc::JsonValueToString(sdi_obj).c_str());
}
peer->set_remote_obs =
new rtc::RefCountedObject<SetRemoteOfferObserver>(peer);
peer->peer_connection->SetRemoteDescription(peer->set_remote_obs, sdi);
}
void ProcessIce(PeerConnection* peer, const Json::Value& ice_obj) {
std::string candidate_str = ice_obj["candidate"].asString();
std::string sdp_mid_str = ice_obj["sdpMid"].asString();
int sdp_mline_index = ice_obj["sdpMLineIndex"].asInt();
webrtc::IceCandidateInterface* ice = webrtc::CreateIceCandidate(
sdp_mid_str, sdp_mline_index, candidate_str, nullptr);
if (ice == nullptr) {
printf("THE ICE IS NULL???? WHYWHYWHYW %s\n",
rtc::JsonValueToString(ice_obj).c_str());
}
peer->peer_connection->AddIceCandidate(ice);
delete ice;
}
void ProcessWebsocketMessage(PeerConnection* peer, const std::string& message) {
Json::Value root;
Json::Reader reader;
if (!reader.parse(message, root)) {
printf("FAILED TO PARSE%s \n", message.c_str());
}
std::string type = root["type"].asString();
if (type == "answer") {
ProcessAnswer(peer, root["sdi"]);
} else if (type == "icecandidate") {
ProcessIce(peer, root["ice"]);
} else {
printf("INVALID TYPE %s \n", message.c_str());
}
}
void SendWebsocketMessage(ProcessingThread* thread,
PeerConnection* peer,
const char* message,
int message_length) {
std::string data(message, message_length);
auto handle =
OnceFunctor([peer, data]() { ProcessWebsocketMessage(peer, data); });
thread->thread->Post(RTC_FROM_HERE, handle);
}
void ProcessDataChannelMessage(PeerConnection* peer,
const std::string& message) {
if (!peer->data_channel->Send(webrtc::DataBuffer(message))) {
printf("THE SEND FOR DATA CHANNEL DIDN'T WORK PROPERLY!\n");
}
}
void SendDataChannelMessage(ProcessingThread* thread,
PeerConnection* peer,
const char* message,
int message_length) {
std::string data(message, message_length);
auto handle =
OnceFunctor([peer, data]() { ProcessDataChannelMessage(peer, data); });
thread->thread->Post(RTC_FROM_HERE, handle);
}
| 30.235732 | 99 | 0.701847 | [
"vector"
] |
d3f268e3820180474d1dea5d9a8db57dc69213b2 | 9,773 | cpp | C++ | ElE/ElE.cpp | Paruck/ElE | ce352f8e6ad71f22dd6ce2558045a7fed1583194 | [
"MIT"
] | 1 | 2017-08-29T04:32:16.000Z | 2017-08-29T04:32:16.000Z | ElE/ElE.cpp | Paruck/ElE | ce352f8e6ad71f22dd6ce2558045a7fed1583194 | [
"MIT"
] | null | null | null | ElE/ElE.cpp | Paruck/ElE | ce352f8e6ad71f22dd6ce2558045a7fed1583194 | [
"MIT"
] | null | null | null | #include "ElE.h"
#include "ElEMainScene.h"
ElEGraphicsComponents ElE::graphicsComp;
ElEAudioComponents ElE::audioComp;
ElEPhysicsComponents ElE::physicsComp;
ElEint ElE::setFlags;
ElEuint ElE::screenWidth,
ElE::screenHeight;
MotorFlags ElE::motorFlags;
ElEWindow* ElE::window;
ElERender* ElE::render;
ElESurface* ElE::surface;
ElETexture* ElE::texture;
std::vector<void(*)()> ElE::initFunctions;
ElEchar* ElE::windowTitle;
ElEGLContext* ElE::context;
#ifndef RASPBERRY_COMPILE
SDL_Event ElE::event;
#else
EGLStuff ElE::stuff;
GLMeshIDManager ElE::mngr;
#endif
void ElE::App(
const _IN_ ElEGraphicsComponents & graph,
const _IN_ ElEAudioComponents & audio,
const _IN_ ElEPhysicsComponents & phys,
const _IN_ ElEint & flags,
const _IN_ MotorFlags & mFlags,
const _IN_ ElEuint & width,
const _IN_ ElEuint & height,
_IN_ ElEchar* title)
{
graphicsComp = graph;
audioComp = audio;
physicsComp = phys;
setFlags = flags;
screenWidth = width;
screenHeight = height;
motorFlags = mFlags;
windowTitle = title;
PrepareJumpTables();
Init();
ElEThreadPool::getInstance(threadAmmount);
ElESceneManager::getInstance()->ChangeScene(new ElEMainScene());
while (1)
{
#ifndef RASPBERRY_COMPILE
PollEvents();
if (event.type == SDL_QUIT) exit(0);
SDL_RenderClear(render->render.sdlRender);
SDL_RenderPresent(render->render.sdlRender);
#endif
ElESceneManager::getInstance()->SceneMainLoop();
}
}
void ElE::PrepareJumpTables()
{
initFunctions.push_back(ElE::InitSFML);
initFunctions.push_back(ElE::InitSDL);
initFunctions.push_back(ElE::InitVulkan);
initFunctions.push_back(ElE::InitOpenGLes20Rasp);
initFunctions.push_back(ElE::InitCDM);
}
void ElE::InitSFML()
{
#ifndef RASPBERRY_COMPILE
window = new ElEWindow(graphicsComp);
ElEint f = 0;
if (setFlags & none)
f |= sf::Style::None;
if (setFlags & titleBar)
f |= sf::Style::Titlebar;
if (setFlags & resizable)
f |= sf::Style::Resize;
if (setFlags & closeButton)
f |= sf::Style::Close;
if (setFlags & fullScreen)
f |= sf::Style::Fullscreen;
if (setFlags & autoFlagsW)
f |= sf::Style::Default;
if (setFlags & openGL)
{
sf::ContextSettings set;
set.depthBits = 24;
set.stencilBits = 8;
set.sRgbCapable = true;
set.antialiasingLevel = 4;
set.minorVersion = 3;
set.majorVersion = 4;
window->window.sfmlWindow = new sf::Window(sf::VideoMode(screenWidth, screenHeight), windowTitle, f, set);
}
else
window->window.sfmlWindow = new sf::Window(sf::VideoMode(screenWidth, screenHeight), windowTitle, f);
#endif
}
void ElE::InitSDL()
{
#ifndef RASPBERRY_COMPILE
//Inicializaciones, SDL se encarga de detectar la plataforma
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
//Manejo de errores criticos, cierra la aplicacion al encontrar un error
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
exit(-1);
}
//Se encarga de comprobar si al inicializar la escenas hay un error
if (SDL_CreateWindowAndRenderer(screenWidth, screenHeight, motorFlags.sdl, &window->window.sdlWindow, &render->render.sdlRender) == -1)
{
SDL_Log("Failed to initialize Window: %s", SDL_GetError());
exit(-2);
}
SDL_SetWindowTitle(window->window.sdlWindow, windowTitle);
surface->surface.sdlSurface = SDL_GetWindowSurface(window->window.sdlWindow);
texture->texture.sdlTexture = SDL_CreateTextureFromSurface(render->render.sdlRender, surface->surface.sdlSurface);
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
printf("Mix_OpenAudio: %s\n", Mix_GetError());
exit(-5);
}
const ElEint flags = MIX_INIT_FLAC |
MIX_INIT_MP3 |
MIX_INIT_OGG;
if ((Mix_Init(flags) & flags) != flags)
{
SDL_Log("Failed to initialize audio library.");
exit(-6);
}
if (TTF_Init() == -1)
{
SDL_Log("TTF failed to initialize.");
exit(-7);
}
const ElEint flagsI = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF;
if ((IMG_Init(flagsI) & flagsI) != flagsI)
{
SDL_Log("Failed to initialize Image Library: %s", IMG_GetError());
exit(-8);
}
Mix_VolumeMusic(100);
SDL_SetRenderDrawColor(render->render.sdlRender, 0, 0, 0, 255);
#endif
}
void ElE::InitVulkan()
{
printf("oiie papu, vulkan inicio\n");
}
void ElE::InitCDM()
{
}
#define RASPBERRY_COMPILE
void ElE::InitOpenGLes20Rasp()
{
#ifdef RASPBERRY_COMPILE
bcm_host_init();
EGLBoolean result;
static const EGLint attribute_list[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 16,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
static const EGLint context_attributes[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
context = new ElEGLContext(graphicsComp);
EGLConfig config;
render->render.eglRender = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(render->render.eglRender != EGL_NO_DISPLAY);
result = eglInitialize(render->render.eglRender, NULL, NULL);
assert(result != EGL_FALSE);
result = eglChooseConfig(render->render.eglRender, attribute_list, &config, 1, &stuff.num_config);
assert(result != EGL_FALSE);
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(result != EGL_FALSE);
context->context.EGLcontext = eglCreateContext(render->render.eglRender, config,
EGL_NO_CONTEXT, context_attributes);
assert(context != EGL_NO_CONTEXT);
stuff.success = graphics_get_display_size(0, &screenWidth, &screenHeight);
assert(stuff.success >= 0);
stuff.dst_rect.x = 0;
stuff.dst_rect.y = 0;
stuff.dst_rect.width = screenWidth;
stuff.dst_rect.height = screenHeight;
stuff.src_rect.x = 0;
stuff.src_rect.y = 0;
stuff.src_rect.width = screenWidth << 16;
stuff.src_rect.height = screenHeight << 16;
stuff.dispman_display = vc_dispmanx_display_open(0);
stuff.dispman_update = vc_dispmanx_update_start(0);
stuff.dispman_element = vc_dispmanx_element_add(
stuff.dispman_update, stuff.dispman_display, 0,
&stuff.dst_rect, 0, &stuff.src_rect,
DISPMANX_PROTECTION_NONE, 0, 0,
(DISPMANX_TRANSFORM_T)0);
stuff.nativeWindow.element = stuff.dispman_element;
stuff.nativeWindow.width = screenWidth;
stuff.nativeWindow.height = screenHeight;
vc_dispmanx_update_submit_sync(stuff.dispman_update);
window->window.eglWindow = &stuff.nativeWindow;
surface->surface.eglSurface = eglCreateWindowSurface(render->render.eglRender, config,
window->window.eglWindow, NULL);
assert(surface->surface.eglSurface != EGL_NO_SURFACE);
result = eglMakeCurrent(render->render.eglRender, surface->surface.eglSurface,
surface->surface.eglSurface, context->context.EGLcontext);
assert(result != EGL_FALSE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, screenWidth, screenHeight);
eglSwapBuffers(render->render.eglRender, surface->surface.eglSurface);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
glEnable(GL_BLEND);
glEnable(GL_SCISSOR_TEST);
std::cout << "OpenGLes initialized" << std::endl;
#endif
}
void ElE::Init()
{
render = new ElERender(graphicsComp);
surface = new ElESurface(graphicsComp);
window = new ElEWindow(graphicsComp);
texture = new ElETexture(graphicsComp);
(initFunctions.at(graphicsComp))();
}
void ElE::PollEvents()
{
//cambiar por tabla de salto
switch (graphicsComp)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
SDL_PollEvent(&event);
break;
#else
case OpenGLes20Rasp:
break;
#endif
}
}
#ifdef RASPBERRY_COMPILE
void ElE::InitGLesPlane()
{
}
#endif
ElE::ElE()
{
}
ElE::~ElE()
{
}
ElEWindow::ElEWindow(const ElEGraphicsComponents & renderT)
{
type = renderT;
switch (renderT)
{
#ifndef RASPBERRY_COMPILE
case OpenGL:
window.sfmlWindow = nullptr;
break;
case SDLGraphics:
window.sdlWindow = nullptr;
break;
#endif
case OpenGLes20Rasp:
window.eglWindow = nullptr;
break;
}
}
ElEWindow::~ElEWindow()
{
switch (type)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
SDL_DestroyWindow(window.sdlWindow);
break;
#endif
}
}
ElESurface::ElESurface(const ElEGraphicsComponents & renderT)
{
type = renderT;
switch (renderT)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
surface.sdlSurface = nullptr;
break;
#endif
}
}
ElESurface::~ElESurface()
{
switch (type)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
SDL_FreeSurface(surface.sdlSurface);
break;
#endif
}
}
ElETexture::ElETexture(const ElEGraphicsComponents & renderT)
{
type = renderT;
switch (renderT)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
texture.sdlTexture = nullptr;
break;
#endif
}
}
ElETexture::~ElETexture()
{
switch (type)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
SDL_DestroyTexture(texture.sdlTexture);
break;
#endif
}
}
ElERender::ElERender(const ElEGraphicsComponents & renderT)
{
type = renderT;
switch (renderT)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
render.sdlRender = nullptr;
break;
#endif
}
}
ElERender::~ElERender()
{
switch (type)
{
#ifndef RASPBERRY_COMPILE
case SDLGraphics:
SDL_DestroyRenderer(render.sdlRender);
break;
#endif
}
}
ElEGLContext::ElEGLContext(const ElEGraphicsComponents & renderT)
{
type = renderT;
}
ElEGLContext::~ElEGLContext()
{
switch (type)
{
}
}
GLMeshIDManager::GLMeshIDManager()
{
data = new struct Sdata[GL_MAX_VERTEX_ATTRIBS-1];
for(ElEuint i = GL_MAX_VERTEX_ATTRIBS; i--;)
data[i].id = i;
}
ElEuint GLMeshIDManager::getUnusedID()
{
for(ElEuint i = GL_MAX_VERTEX_ATTRIBS; i--;)
{
if(!data[i].inUse)
{
data[i].inUse = ElEtrue;
return data[i].id;
}
}
return -1;
}
ElEvoid GLMeshIDManager::cleanUsedID(ElEuint idTag)
{
data[idTag].inUse = ElEfalse;
}
| 22.675174 | 136 | 0.712268 | [
"render",
"vector"
] |
d3f488ab1c12392cf5ad4c3970fe4a6fe586fadb | 1,320 | cpp | C++ | Data Structure I/88.cpp | felixny/LeetCode | 9f76dad8063187e10d848228ea5b1a8a875d1894 | [
"MIT"
] | null | null | null | Data Structure I/88.cpp | felixny/LeetCode | 9f76dad8063187e10d848228ea5b1a8a875d1894 | [
"MIT"
] | null | null | null | Data Structure I/88.cpp | felixny/LeetCode | 9f76dad8063187e10d848228ea5b1a8a875d1894 | [
"MIT"
] | null | null | null | // 88. Merge Sorted Array
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
/* map<int, bool> map;
for (int i = 0; i < m; i++) {
map[nums1[i]] = true;
}
for (int i = 0; i < n; i++) {
map[nums2[i]] = true;
}
*/
vector<int> merged(m + n);
int i = 0, j = 0, k = 0;
while (i < m && j < n) {
if (nums1[i] < nums2[j]) {
merged[k++] = nums1[i++];
} else {
merged[k++] = nums2[j++];
}
}
while (i < m) {
merged[k++] = nums1[i++];
}
while (j < n) {
merged[k++] = nums2[j++];
}
nums1 = merged;
}
void merge1(vector<int>& nums1, int m, vector<int>& nums2, int n) {
map<int, bool> map;
for (int i = 0; i < m; i++) {
map[nums1[i]] = true;
}
for (int i = 0; i < n; i++) {
map[nums2[i]] = true;
}
vector<int> key(m+n);
vector<bool> value;
for (std::map<int, bool>::iterator it = map.begin(); it != map.end(); it++) {
key.push_back(it->first);
value.push_back(it->second);
cout << "Key: " << it->first << endl;
cout << "Value: " << it->second << endl;
}
nums1 = key;
}
int main() {
vector<int> nums1 = {1, 2, 3, 0, 0, 0};
vector<int> nums2 = {2, 5, 6};
merge1(nums1,3,nums2,3);
return 0;
} | 18.591549 | 79 | 0.501515 | [
"vector"
] |
108b602844c02f7e7db71029f6e5d4db8aa18f42 | 1,302 | hpp | C++ | src/geometry/geometry.hpp | bwiberg/position-based-dynamics | cde7665df830f2e4625aad8ec1e76247c7ae5623 | [
"WTFPL"
] | 33 | 2016-11-18T02:37:31.000Z | 2021-11-13T10:00:35.000Z | src/geometry/geometry.hpp | bwiberg/position-based-dynamics | cde7665df830f2e4625aad8ec1e76247c7ae5623 | [
"WTFPL"
] | null | null | null | src/geometry/geometry.hpp | bwiberg/position-based-dynamics | cde7665df830f2e4625aad8ec1e76247c7ae5623 | [
"WTFPL"
] | 3 | 2017-10-24T17:36:12.000Z | 2019-03-21T07:21:32.000Z | #pragma once
#include <vector>
#include <CL/cl.hpp>
#include <glm/glm.hpp>
#define ATTR_PACKED __attribute__ ((__packed__))
namespace pbd {
enum VertexAttributes {
POSITION = 0,
NORMAL = 1,
TEX_COORD = 2,
COLOR = 3,
VELOCITY = 4,
MASS = 5
};
/**
* Host (CPU) representation of a vertex.
* Matches the memory layout of the Vertex struct
* in kernels/common/Mesh.cl
*/
struct ATTR_PACKED Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoord;
glm::vec4 color;
};
/**
* Host (CPU) representation of an edge.
* Matches the memory layout of the Edge struct
* in kernels/common/Mesh.cl
*/
struct ATTR_PACKED Edge {
// [0] is always valid
// [1] can be -1, which means that this edge belongs to a single triangle
int triangles[2];
// [0, 1] are the vertices that make up the edge
// [2, 3] are the remaining vertices of the connecting triangles
int vertices[4];
};
/**
* Host (CPU) representation of a triangle.
* Matches the memory layout of the Triangle struct
* in kernels/common/Mesh.cl
*/
struct ATTR_PACKED Triangle {
glm::uvec3 vertices;
};
}
| 23.672727 | 81 | 0.580645 | [
"mesh",
"vector"
] |
1096cf4d4596c07b9e1463311163f7afd13ae2fd | 3,990 | cpp | C++ | LightOJ/LightOJ - 1150/Time Limit Exceeded.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | LightOJ/LightOJ - 1150/Time Limit Exceeded.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | LightOJ/LightOJ - 1150/Time Limit Exceeded.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2018-05-16 19:55:31
* solution_verdict: Time Limit Exceeded language: C++
* run_time (ms): memory_used (MB):
* problem: https://vjudge.net/problem/LightOJ-1150
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int inf=1e9;
const int N=50;
int t,tc,n,ind[26][26],_dis[26][26],man,gst,lft[N+2],rgt[N+2],dis[N+2];
char s[26],mat[26][26];
int dr[]={0,0,1,-1};
int dc[]={1,-1,0,0};
vector<pair<int,int> >hum;
vector<int>adj[N+2];
int _bfs(int r,int c,int tr,int tc)
{
queue<pair<int,int> >q;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
_dis[i][j]=inf;
_dis[r][c]=0;
q.push({r,c});
while(q.size())
{
pair<int,int>p=q.front();
//cout<<p.first<<" "<<p.second<<endl;
q.pop();
for(int i=0;i<4;i++)
{
int uu=p.first+dr[i];
int vv=p.second+dc[i];
if(uu==tr&&vv==tc)return _dis[p.first][p.second]+1;
if(uu>n||uu<1||vv>n||vv<1||mat[uu][vv]=='#'||mat[uu][vv]=='H'||_dis[uu][vv]!=inf)
continue;
_dis[uu][vv]=_dis[p.first][p.second]+1;
q.push({uu,vv});
}
}
return _dis[tr][tc];
}
void make_graph(int xx)
{
for(int i=1;i<=N;i++)adj[i].clear();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(mat[i][j]!='G')continue;
for(int k=0;k<hum.size();k++)
{
int tmp=_bfs(i,j,hum[k].first,hum[k].second);
// cout<<i<<" "<<j<<" "<<hum[k].first<<" "<<hum[k].second<<" "<<tmp<<endl;
// getchar();
if(tmp*2+2<=xx)
{
adj[ind[i][j]].push_back(ind[hum[k].first][hum[k].second]);
//cout<<i<<" "<<j<<" "<<hum[k].first<<" "<<hum[k].second<<endl;
}
}
}
}
// for(int i=1;i<=6;i++)
// {
// for(auto x:adj[i])
// {
// cout<<x<<" ";
// }
// cout<<endl;
// }
}
bool bfs(void)
{
queue<int>q;
for(int i=1;i<=n;i++)
{
if(lft[i]==0)
{
dis[i]=0;
q.push(i);
}
else dis[i]=inf;
}
dis[0]=inf;
while(q.size())
{
int u=q.front();
q.pop();
for(int i=0;i<adj[u].size();i++)
{
int v=adj[u][i];
if(dis[rgt[v]]<=dis[u]+1)continue;
dis[rgt[v]]=dis[u]+1;
q.push(rgt[v]);
}
}
return dis[0]!=inf;
}
bool dfs(int u)
{
if(!u)return true;
for(int i=0;i<adj[u].size();i++)
{
int v=adj[u][i];
if(dis[rgt[v]]!=dis[u]+1)continue;
if(dfs(rgt[v]))
{
lft[u]=v;
rgt[v]=u;
return true;
}
}
return false;
}
int Hopcroft(void)
{
memset(lft,0,sizeof(lft));
memset(rgt,0,sizeof(rgt));
int matching=0;
while(bfs())
{
for(int i=1;i<=n;i++)
{
if(dis[i])continue;
if(dfs(i))matching++;
}
}
return matching;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
man=0,gst=0;
hum.clear();
for(int i=1;i<=n;i++)
{
scanf("%s",s);
for(int j=1;j<=n;j++)
{
mat[i][j]=s[j-1];
if(mat[i][j]=='G')ind[i][j]=++gst;
if(mat[i][j]=='H')
{
ind[i][j]=++man;
hum.push_back({i,j});
}
}
}
//getchar();
// for(auto x:hum)
// {
// cout<<x.first<<" "<<x.second<<endl;
// }
int lo=0,hi=100,md;
while(hi-lo>2)
{
md=(lo+hi)/2;
make_graph(md);
int tmp=Hopcroft();
if(tmp>=man)hi=md;
else lo=md;
}
int pr=-1;
for(int i=lo;i<=hi;i++)
{
make_graph(i);
int tmp=Hopcroft();
if(tmp==man)
{
pr=i;
break;
}
}
if(pr==-1)printf("Case %d: Vuter Dol Kupokat\n",++tc);
else printf("Case %d: %d\n",++tc,pr);
}
return 0;
} | 21.803279 | 111 | 0.422306 | [
"vector"
] |
109c8919f050a1ce2716ad5db578b45265ac8ed6 | 1,146 | cpp | C++ | CppSTL/Chapter1/vectors/transform_une.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | CppSTL/Chapter1/vectors/transform_une.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | CppSTL/Chapter1/vectors/transform_une.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | #include <iostream>
#include <vector>
#include <algorithm> // trasnform function
using namespace std;
template<class T>
T SQRT(T num) {
return (num<=0) ? 0 : num*num;
}
template<class T>
T CUBE(T num) {
return (num<=0) ? 0 : num*num*num;
}
template<class T>
void PRINT(const vector<T> &vec) {
for(const auto & v : vec)
cout << v << " ";
cout << endl;
}
template<class type>
void Transform(vector<type> &vec, size_t operation = 0) {
switch(operation)
{
case 0:
transform(vec.begin(), vec.end(), vec.begin(), SQRT<type>);
PRINT<type>(vec);
break;
case 1:
transform(vec.begin(), vec.end(), vec.begin(), CUBE<type>);
PRINT<type>(vec);
break;
default:
cout << "Choose square root OR cube operations only...\n";
break;
}
}
int main()
{
vector<int> nums{1,2,3,4,5,6,7,8,9,10};
cout << "Nums vector:\n";
PRINT<int>(nums);
cout << "Nums vector squared:\n";
Transform<int>(nums);
cout << "Nums vector squared-squared:\n";
Transform<int>(nums, 1);
return 0;
} | 20.836364 | 71 | 0.546248 | [
"vector",
"transform"
] |
109ccf888d0577cb2b105aabb34e0da4f7efd77c | 3,780 | cpp | C++ | src/tools/HonViewer/FilesView.cpp | wangyanxing/Demi3D | 73e684168bd39b894f448779d41fab600ba9b150 | [
"MIT"
] | 10 | 2015-03-04T04:27:15.000Z | 2020-06-04T14:06:47.000Z | src/tools/HonViewer/FilesView.cpp | wangyanxing/Demi3D | 73e684168bd39b894f448779d41fab600ba9b150 | [
"MIT"
] | null | null | null | src/tools/HonViewer/FilesView.cpp | wangyanxing/Demi3D | 73e684168bd39b894f448779d41fab600ba9b150 | [
"MIT"
] | 5 | 2015-10-17T19:09:58.000Z | 2021-11-15T23:42:18.000Z | /**********************************************************************
This source file is a part of Demi3D
__ ___ __ __ __
| \|_ |\/|| _)| \
|__/|__| || __)|__/
Copyright (c) 2013-2014 Demi team
https://github.com/wangyanxing/Demi3D
Released under the MIT License
https://github.com/wangyanxing/Demi3D/blob/master/License.txt
***********************************************************************/
#include "ViewerPch.h"
#include "FilesView.h"
#include "ZipArchive.h"
#include "K2ModelView.h"
#include "HonViewerApp.h"
#include "MyGUI_TreeControlItem.h"
namespace tools
{
FilesView::FilesView(MyGUI::Widget* _parent) :
wraps::BaseLayout("FilesView.layout", _parent)
, mResourcesTree(nullptr)
, mResources(nullptr)
{
assignWidget(mResourcesTree, "ResourcesTree");
mResourcesTree->eventTreeNodePrepare += newDelegate(this, &FilesView::notifyTreeNodePrepare);
mResourcesTree->eventTreeNodeSelected += newDelegate(this, &FilesView::notifyTreeNodeSelected);
}
FilesView::~FilesView()
{
if (mResources)
{
DI_DELETE mResources;
mResources = nullptr;
}
mResourcesTree->eventTreeNodePrepare -= newDelegate(this, &FilesView::notifyTreeNodePrepare);
mResourcesTree->eventTreeNodeSelected -= newDelegate(this, &FilesView::notifyTreeNodeSelected);
}
void FilesView::notifyTreeNodePrepare(MyGUI::TreeControl* pTreeControl, MyGUI::TreeControl::Node* pNode)
{
if (pNode == pTreeControl->getRoot())
return;
pNode->removeAll();
DiFileTree* filetree = *(pNode->getData<DiFileTree*>());
for (auto i = filetree->children.begin(); i != filetree->children.end(); ++i)
{
DiFileTree* cur = i->second;
MyGUI::TreeControl::Node* nd = new MyGUI::TreeControl::Node(cur->fileName.c_str(), cur->folder ? "Folder" : "File");
nd->setData(cur);
if (!cur->folder)
nd->setPrepared(true);
pNode->add(nd);
}
}
void FilesView::scanFiles()
{
DiZipArchive* zip = DiK2Configs::RESOURCE_PACK;
if (!zip)
return;
DiTimer timer;
mResources = nullptr;
zip->GenerateFileTree(mResources, "*.mdf");
MyGUI::TreeControl::Node* root = mResourcesTree->getRoot();
root->removeAll();
DiFileTree* nullfile = nullptr;
root->setData(nullfile);
for (auto i = mResources->children.begin(); i != mResources->children.end(); ++i)
{
DiFileTree* cur = i->second;
MyGUI::TreeControl::Node* pNode = new MyGUI::TreeControl::Node(cur->fileName.c_str(), cur->folder ? "Folder" : "File");
pNode->setData(cur);
if (!cur->folder)
pNode->setPrepared(true);
root->add(pNode);
}
double loadingTime = timer.GetElapse();
DI_LOG("Zip files scanning time: %f", loadingTime);
}
void FilesView::notifyTreeNodeSelected(MyGUI::TreeControl* pTreeControl, MyGUI::TreeControl::Node* pNode)
{
if (!pNode || pNode->emptyData())
return;
DiFileTree* filetree = *(pNode->getData<DiFileTree*>(false));
if (!filetree || filetree->folder)
return;
DiString fullpath = pNode->getText().asUTF8().c_str();
MyGUI::TreeControl::Node* cur = pNode->getParent();
while (cur->getParent())
{
fullpath = cur->getText().asUTF8().c_str() + DiString("/") + fullpath;
cur = cur->getParent();
}
DI_DEBUG("Model %s selected", fullpath.c_str());
HonViewerApp::GetViewerApp()->GetModelViewer()->LoadModel(fullpath);
}
} // namespace tools
| 32.869565 | 131 | 0.580159 | [
"model"
] |
10b2f2a734909b18cce3c57cf612fc20544ae017 | 14,677 | cpp | C++ | src/llvm/carat/src/Allocation.cpp | chend666/CS446-allocator | 22394cff3bf525e700654efa17581552fcf21871 | [
"MIT"
] | null | null | null | src/llvm/carat/src/Allocation.cpp | chend666/CS446-allocator | 22394cff3bf525e700654efa17581552fcf21871 | [
"MIT"
] | null | null | null | src/llvm/carat/src/Allocation.cpp | chend666/CS446-allocator | 22394cff3bf525e700654efa17581552fcf21871 | [
"MIT"
] | null | null | null | /*
* This file is part of the Nautilus AeroKernel developed
* by the Hobbes and V3VEE Projects with funding from the
* United States National Science Foundation and the Department of Energy.
*
* The V3VEE Project is a joint project between Northwestern University
* and the University of New Mexico. The Hobbes Project is a collaboration
* led by Sandia National Laboratories that includes several national
* laboratories and universities. You can find out more at:
* http://www.v3vee.org and
* http://xstack.sandia.gov/hobbes
*
* Copyright (c) 2020, Drew Kersnar <drewkersnar2021@u.northwestern.edu>
* Copyright (c) 2020, Gaurav Chaudhary <gauravchaudhary2021@u.northwestern.edu>
* Copyright (c) 2020, Souradip Ghosh <sgh@u.northwestern.edu>
* Copyright (c) 2020, Brian Suchy <briansuchy2022@u.northwestern.edu>
* Copyright (c) 2020, Peter Dinda <pdinda@northwestern.edu>
* Copyright (c) 2020, The V3VEE Project <http://www.v3vee.org>
* The Hobbes Project <http://xstack.sandia.gov/hobbes>
* All rights reserved.
*
* Authors: Drew Kersnar, Gaurav Chaudhary, Souradip Ghosh,
* Brian Suchy, Peter Dinda
*
* This is free software. You are permitted to use,
* redistribute, and modify it as specified in the file "LICENSE.txt".
*/
#include "../include/Allocation.hpp"
/*
* ---------- Constructors ----------
*/
AllocationHandler::AllocationHandler(Module *M)
{
DEBUG_ERRS << "--- Allocation Constructor ---\n";
/*
* Set state
*/
this->M = M;
this->Target = M->getFunction(CARAT_GLOBALS_TARGET);
assert(!!(this->Target)
&& "AllocationHandler::AllocationHandler: Couldn't find nk_carat_init!");
/*
* Perform initial processing
*/
this->_getAllNecessaryInstructions();
this->_getAllGlobals();
}
/*
* ---------- Drivers ----------
*/
void AllocationHandler::Inject()
{
/*
* TOP --- Instrument all globals, memory allocations
* (malloc) and memory deallocations (frees)
*/
/*
* Instrument globals
*/
if (!NoGlobals) InstrumentGlobals();
/*
* Instrument allocations
*/
if (!NoMallocs)
{
/*
* Instrument system mallocs
*/
InstrumentMallocs(
AllocID::SysMalloc,
0 /* Size operand no */
);
/*
* Instrument aspace/allocator mallocs
*/
InstrumentMallocs(
AllocID::ASpaceMalloc,
1 /* Size operand no */
);
}
if (!NoFrees)
{
/*
* Instrument system frees
*/
InstrumentFrees(
AllocID::SysFree,
0 /* Pointer operand no */
);
/*
* Instrument aspace/allocator frees
*/
InstrumentFrees(
AllocID::ASpaceFree,
1 /* Pointer operand no */
);
}
/*
* Verify transformations
*/
Utils::Verify(*M);
return;
}
/*
* ---------- Private methods ----------
*/
void AllocationHandler::_getAllNecessaryInstructions()
{
/*
* Instrument "malloc"s and "free"s per function
*/
for (auto &F : *M)
{
/*
* Skip if non-instrumentable
*/
if (!(Utils::IsInstrumentable(F))) { continue; }
/*
* Debugging
*/
DEBUG_ERRS << "Entering function " << F.getName() << "\n";
/*
* Iterate
*/
for (auto &B : F)
{
for (auto &I : B)
{
/*
* Analyze all call instructions --- if a call is
* found to have a "malloc" or "free" callee, mark
* the instruction for instrumentation
*/
/*
* Ignore all other instructions
*/
if (!isa<CallInst>(&I)) { continue; }
/*
* Fetch the call instruction
*/
CallInst *NextCall = cast<CallInst>(&I);
/*
* Fetch the callee
*/
Function *Callee = NextCall->getCalledFunction();
/*
* If the callee isn't a "malloc" or "free",
* ignore the call instruction
*
* NOTE --- THIS IGNORES INDIRECT CALLS --- FIX
*/
if (KernelAllocMethodsToIDs.find(Callee) == KernelAllocMethodsToIDs.end()) { continue; }
/*
* Fetch the AllocID, mark each call for instrumentation
*/
InstructionsToInstrument[KernelAllocMethodsToIDs[Callee]].insert(NextCall);
}
}
}
return;
}
bool AllocationHandler::_isGlobalInstrumentable(GlobalValue &Global)
{
/*
* TOP --- a decision-tree-esque way of determining
* if a global value should be instrumentable or not
*
* TRUE=Instrumentable
* FALSE=NotInstrumentable
*/
/*
* Check the following:
* 1)
* Check linkage type --- if there is a private linkage,
* we cannot instrument (common in Nautilus)
*
* Private objects are necessarily not lowered to the
* symbol table at the end of compilation
*
* 2)
* If @Global does not have an exact definition (i.e. a variable
* was declared as an 'extern' but its value was never resolved),
* then we cannot instrument it because the symbol table will mark
* the symbol with size 0 and no classification (not O, F, etc.)
*
* 3)
* We cannot instrument the global carat context itself
*
* 4)
* We cannot instrument the global pointer (that points to
* a non-canonical address) used for protections checks
*/
if (false
|| Global.hasPrivateLinkage()
|| !(Global.hasExactDefinition())
|| (Global.getName() == "global_carat_context")
|| (Global.getName() == "non_canonical")) return false;
/*
* Check the section that @Global will be assigned to. If
* there is no discernable section at compile-time, we need
* to continue analyzing. However, if there IS an assigned
* section --- we can always instrument @Global as long as
* the section isn't the middle-end metadata ("llvm.metadata")
*/
if (Global.hasSection()) return (Global.getSection() != "llvm.metadata");
/*
* NOTE --- Many globals have internal linkage --- which can
* allow the compiler to resolve @Global and other globals
* with the same value (i.e. unnamed_addr values) as one
* single global in the symbol table. Whether or not a global
* will be resolved in this way is impossible to know in the
* middle-end. The runtime needs to handle these globals differently
*/
return true;
}
void AllocationHandler::_getAllGlobals()
{
/*
* TOP --- Iterate through all global variables, calculate
* size, mark for instrumentation if possible
*/
/*
* Build llvm::DataLayout object to determine info useful
* to calculate struct sizes, pointer widths, etc.
*/
DataLayout TheLayout = DataLayout(M);
/*
* Iterate through globals list
*/
for (auto &Global : M->getGlobalList())
{
/*
* Ignore globals that can't be instrumented
*/
if (!_isGlobalInstrumentable(Global)) continue;
/*
* Sanity check each global --- must be of a
* pointer type (invariant)
*/
assert(Global.getType()->isPointerTy() &&
"_getAllGlobals: Found a non-pointer typed global!");
/*
* Fetch type of global variable
*/
Type *GlobalTy = Global.getValueType();
/*
* Calculate the size of the global variable
*/
uint64_t GlobalSize = Utils::CalculateObjectSize(GlobalTy, &TheLayout);
/*
* Store the [global : {size, ID}] mapping,
* increment the next global variable ID
*/
Globals[&Global] = { GlobalSize, NextGlobalID };
NextGlobalID++;
/*
* Debugging
*/
DEBUG_ERRS << "Global: " << Global << "\n"
<< "Type: " << *GlobalTy << "\n"
<< "TypeID: " << GlobalTy->getTypeID() << "\n"
<< "GlobalID: " << NextGlobalID - 1 << "\n"
<< "Linkage: " << Global.getLinkage() << "\n"
<< "Visibility: " << Global.getVisibility() << "\n"
<< "hasExactDefinition()" << Global.hasExactDefinition() << "\n"
<< "Section: " << Global.getSection() << "\n"
<< "Size: " << GlobalSize << "\n\n";
/*
* Output a warning if the global is thread local
* --- in the future, we want to track these variables
* in a special way
*/
if (Global.isThreadLocal())
{
errs() << "WARNING (ThreadLocal): "
<< Global << "\n";
}
}
return;
}
void AllocationHandler::InstrumentGlobals()
{
/*
* TOP --- Instrument each global variable --- inject
* instrumentation into "nk_carat_init"
*/
/*
* Fetch insertion point as the terminator of "nk_carat_init"
*/
Instruction *InsertionPoint = Target->back().getTerminator();
assert(isa<ReturnInst>(InsertionPoint)
&& "InstrumentGlobals: Back block terminator of 'nk_carat_init' is not return!");
/*
* Set up IRBuilder
*/
IRBuilder<> TargetBuilder =
Utils::GetBuilder(
Target,
InsertionPoint
);
/*
* Set up for injections
*/
Type *VoidPointerType = TargetBuilder.getInt8PtrTy();
Function *CARATGlobalMalloc = CARATNamesToMethods[CARAT_GLOBAL_MALLOC];
/*
* Iterate through all globals to be intrumented
*/
for (auto const &[GV, Info] : Globals)
{
/*
* Deconstruct the "Info" pair
*/
uint64_t Length = Info.first,
ID = Info.second;
/*
* If there is a global with length=0, skip --- FIX
*/
if (Length == 0)
{
errs() << "Skipping global: "
<< *GV << "\n";
continue;
}
/*
* Build void pointer cast for current global --- necessary
* to process in the CARAT kernel runtime
*/
Value *PointerCast =
TargetBuilder.CreatePointerCast(
GV, VoidPointerType
);
/*
* Set up call parameters
*/
ArrayRef<Value *> CallArgs = {
PointerCast,
TargetBuilder.getInt64(Length),
TargetBuilder.getInt64(ID)
};
/*
* Inject
*/
CallInst *Instrumentation =
TargetBuilder.CreateCall(
CARATGlobalMalloc,
CallArgs
);
}
return;
}
void AllocationHandler::InstrumentMallocs(
AllocID MallocTypeID,
unsigned SizeOperandNo
)
{
/*
* Set up for injection
*/
Function *CARATMalloc = CARATNamesToMethods[CARAT_MALLOC];
IRBuilder<> TypeBuilder{M->getContext()};
Type *VoidPointerType = TypeBuilder.getInt8PtrTy(),
*Int64Type = TypeBuilder.getInt64Ty();
/*
* Instrument all collected "malloc"ss
*/
for (auto NextMalloc : InstructionsToInstrument[MallocTypeID])
{
/*
* Debugging
*/
errs() << "NextMalloc: " << *NextMalloc << "\n";
/*
* Set up insertion point
*/
Instruction *InsertionPoint = NextMalloc->getNextNode();
assert(!!InsertionPoint
&& "InstrumentMallocs: Can't find an insertion point!");
/*
* Set up IRBuilder
*/
IRBuilder<> Builder =
Utils::GetBuilder(
NextMalloc->getFunction(),
InsertionPoint
);
/*
* Cast return value from "malloc" to void pointer
*/
Value *MallocReturnCast =
Builder.CreatePointerCast(
NextMalloc,
VoidPointerType
);
/*
* Cast size parameter to "malloc" into i64
*/
Value *MallocSizeArgCast =
Builder.CreateZExtOrBitCast(
NextMalloc->getOperand(SizeOperandNo),
Int64Type
);
/*
* Set up call parameters
*/
ArrayRef<Value *> CallArgs = {
MallocReturnCast,
MallocSizeArgCast
};
/*
* Inject
*/
CallInst *InstrumentMalloc =
Builder.CreateCall(
CARATMalloc,
CallArgs
);
}
return;
}
void AllocationHandler::InstrumentFrees(
AllocID FreeTypeID,
unsigned PointerOperandNo
)
{
/*
* Set up for injection
*/
Function *CARATFree = CARATNamesToMethods[CARAT_REMOVE_ALLOC];
IRBuilder<> TypeBuilder{M->getContext()};
Type *VoidPointerType = TypeBuilder.getInt8PtrTy();
/*
* Iterate
*/
for (auto NextFree : InstructionsToInstrument[FreeTypeID])
{
/*
* Debugging
*/
errs() << "NextFree: " << *NextFree << "\n";
/*
* Set up insertion point
*/
Instruction *InsertionPoint = NextFree->getNextNode();
assert(!!InsertionPoint
&& "InstrumentFrees: Can't find an insertion point!");
/*
* Set up IRBuilder
*/
IRBuilder<> Builder =
Utils::GetBuilder(
NextFree->getFunction(),
InsertionPoint
);
/*
* Cast inst as value passed to free
*/
Value *ParameterToFree =
Builder.CreatePointerCast(
NextFree->getOperand(PointerOperandNo),
VoidPointerType
);
/*
* Set up call parameters
*/
ArrayRef<Value *> CallArgs = {
ParameterToFree
};
/*
* Inject
*/
CallInst *InstrumentFree =
Builder.CreateCall(
CARATFree,
CallArgs
);
}
return;
}
| 24.380399 | 104 | 0.525789 | [
"object"
] |
10b60f4a400704a2cfa996c1d9a70da76bfb76d0 | 32,568 | cpp | C++ | generated/niswitch/niswitch_client.cpp | tdunkle/grpc-device | 2c784476327595fdeae06d6a3fc7aaf6daac597e | [
"MIT"
] | 24 | 2021-03-25T18:37:59.000Z | 2022-03-03T16:33:56.000Z | generated/niswitch/niswitch_client.cpp | tdunkle/grpc-device | 2c784476327595fdeae06d6a3fc7aaf6daac597e | [
"MIT"
] | 129 | 2021-04-03T15:16:04.000Z | 2022-03-25T21:48:18.000Z | generated/niswitch/niswitch_client.cpp | tdunkle/grpc-device | 2c784476327595fdeae06d6a3fc7aaf6daac597e | [
"MIT"
] | 24 | 2021-03-31T12:36:14.000Z | 2022-02-25T03:01:25.000Z |
//---------------------------------------------------------------------
// This file is automatically generated. All manual edits will be lost.
//---------------------------------------------------------------------
// EXPERIMENTAL Client convenience wrapper for NI-SWITCH.
//---------------------------------------------------------------------
#include "niswitch_client.h"
#include <grpcpp/grpcpp.h>
#include <niswitch.grpc.pb.h>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <vector>
namespace niswitch_grpc::experimental::client {
AbortScanResponse
abort_scan(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = AbortScanRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = AbortScanResponse{};
raise_if_error(
stub->AbortScan(&context, request, &response));
return response;
}
CanConnectResponse
can_connect(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel1, const pb::string& channel2)
{
::grpc::ClientContext context;
auto request = CanConnectRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel1(channel1);
request.set_channel2(channel2);
auto response = CanConnectResponse{};
raise_if_error(
stub->CanConnect(&context, request, &response));
return response;
}
CheckAttributeViBooleanResponse
check_attribute_vi_boolean(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const bool& attribute_value)
{
::grpc::ClientContext context;
auto request = CheckAttributeViBooleanRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value(attribute_value);
auto response = CheckAttributeViBooleanResponse{};
raise_if_error(
stub->CheckAttributeViBoolean(&context, request, &response));
return response;
}
CheckAttributeViInt32Response
check_attribute_vi_int32(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const simple_variant<NiSwitchInt32AttributeValues, pb::int32>& attribute_value)
{
::grpc::ClientContext context;
auto request = CheckAttributeViInt32Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
const auto attribute_value_ptr = attribute_value.get_if<NiSwitchInt32AttributeValues>();
const auto attribute_value_raw_ptr = attribute_value.get_if<pb::int32>();
if (attribute_value_ptr) {
request.set_attribute_value(*attribute_value_ptr);
}
else if (attribute_value_raw_ptr) {
request.set_attribute_value_raw(*attribute_value_raw_ptr);
}
auto response = CheckAttributeViInt32Response{};
raise_if_error(
stub->CheckAttributeViInt32(&context, request, &response));
return response;
}
CheckAttributeViReal64Response
check_attribute_vi_real64(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const double& attribute_value_raw)
{
::grpc::ClientContext context;
auto request = CheckAttributeViReal64Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value_raw(attribute_value_raw);
auto response = CheckAttributeViReal64Response{};
raise_if_error(
stub->CheckAttributeViReal64(&context, request, &response));
return response;
}
CheckAttributeViStringResponse
check_attribute_vi_string(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const pb::string& attribute_value_raw)
{
::grpc::ClientContext context;
auto request = CheckAttributeViStringRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value_raw(attribute_value_raw);
auto response = CheckAttributeViStringResponse{};
raise_if_error(
stub->CheckAttributeViString(&context, request, &response));
return response;
}
CheckAttributeViSessionResponse
check_attribute_vi_session(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const nidevice_grpc::Session& attribute_value)
{
::grpc::ClientContext context;
auto request = CheckAttributeViSessionRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.mutable_attribute_value()->CopyFrom(attribute_value);
auto response = CheckAttributeViSessionResponse{};
raise_if_error(
stub->CheckAttributeViSession(&context, request, &response));
return response;
}
ClearErrorResponse
clear_error(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ClearErrorRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ClearErrorResponse{};
raise_if_error(
stub->ClearError(&context, request, &response));
return response;
}
ClearInterchangeWarningsResponse
clear_interchange_warnings(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ClearInterchangeWarningsRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ClearInterchangeWarningsResponse{};
raise_if_error(
stub->ClearInterchangeWarnings(&context, request, &response));
return response;
}
CloseResponse
close(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = CloseRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = CloseResponse{};
raise_if_error(
stub->Close(&context, request, &response));
return response;
}
CommitResponse
commit(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = CommitRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = CommitResponse{};
raise_if_error(
stub->Commit(&context, request, &response));
return response;
}
ConfigureScanListResponse
configure_scan_list(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& scanlist, const simple_variant<ScanMode, pb::int32>& scan_mode)
{
::grpc::ClientContext context;
auto request = ConfigureScanListRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_scanlist(scanlist);
const auto scan_mode_ptr = scan_mode.get_if<ScanMode>();
const auto scan_mode_raw_ptr = scan_mode.get_if<pb::int32>();
if (scan_mode_ptr) {
request.set_scan_mode(*scan_mode_ptr);
}
else if (scan_mode_raw_ptr) {
request.set_scan_mode_raw(*scan_mode_raw_ptr);
}
auto response = ConfigureScanListResponse{};
raise_if_error(
stub->ConfigureScanList(&context, request, &response));
return response;
}
ConfigureScanTriggerResponse
configure_scan_trigger(const StubPtr& stub, const nidevice_grpc::Session& vi, const double& scan_delay, const simple_variant<TriggerInput, pb::int32>& trigger_input, const simple_variant<ScanAdvancedOutput, pb::int32>& scan_advanced_output)
{
::grpc::ClientContext context;
auto request = ConfigureScanTriggerRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_scan_delay(scan_delay);
const auto trigger_input_ptr = trigger_input.get_if<TriggerInput>();
const auto trigger_input_raw_ptr = trigger_input.get_if<pb::int32>();
if (trigger_input_ptr) {
request.set_trigger_input(*trigger_input_ptr);
}
else if (trigger_input_raw_ptr) {
request.set_trigger_input_raw(*trigger_input_raw_ptr);
}
const auto scan_advanced_output_ptr = scan_advanced_output.get_if<ScanAdvancedOutput>();
const auto scan_advanced_output_raw_ptr = scan_advanced_output.get_if<pb::int32>();
if (scan_advanced_output_ptr) {
request.set_scan_advanced_output(*scan_advanced_output_ptr);
}
else if (scan_advanced_output_raw_ptr) {
request.set_scan_advanced_output_raw(*scan_advanced_output_raw_ptr);
}
auto response = ConfigureScanTriggerResponse{};
raise_if_error(
stub->ConfigureScanTrigger(&context, request, &response));
return response;
}
ConnectResponse
connect(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel1, const pb::string& channel2)
{
::grpc::ClientContext context;
auto request = ConnectRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel1(channel1);
request.set_channel2(channel2);
auto response = ConnectResponse{};
raise_if_error(
stub->Connect(&context, request, &response));
return response;
}
ConnectMultipleResponse
connect_multiple(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& connection_list)
{
::grpc::ClientContext context;
auto request = ConnectMultipleRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_connection_list(connection_list);
auto response = ConnectMultipleResponse{};
raise_if_error(
stub->ConnectMultiple(&context, request, &response));
return response;
}
DisableResponse
disable(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = DisableRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = DisableResponse{};
raise_if_error(
stub->Disable(&context, request, &response));
return response;
}
DisconnectResponse
disconnect(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel1, const pb::string& channel2)
{
::grpc::ClientContext context;
auto request = DisconnectRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel1(channel1);
request.set_channel2(channel2);
auto response = DisconnectResponse{};
raise_if_error(
stub->Disconnect(&context, request, &response));
return response;
}
DisconnectAllResponse
disconnect_all(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = DisconnectAllRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = DisconnectAllResponse{};
raise_if_error(
stub->DisconnectAll(&context, request, &response));
return response;
}
DisconnectMultipleResponse
disconnect_multiple(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& disconnection_list)
{
::grpc::ClientContext context;
auto request = DisconnectMultipleRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_disconnection_list(disconnection_list);
auto response = DisconnectMultipleResponse{};
raise_if_error(
stub->DisconnectMultiple(&context, request, &response));
return response;
}
ErrorMessageResponse
error_message(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::int32& error_code)
{
::grpc::ClientContext context;
auto request = ErrorMessageRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_error_code(error_code);
auto response = ErrorMessageResponse{};
raise_if_error(
stub->ErrorMessage(&context, request, &response));
return response;
}
ErrorQueryResponse
error_query(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ErrorQueryRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ErrorQueryResponse{};
raise_if_error(
stub->ErrorQuery(&context, request, &response));
return response;
}
GetAttributeViBooleanResponse
get_attribute_vi_boolean(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id)
{
::grpc::ClientContext context;
auto request = GetAttributeViBooleanRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
auto response = GetAttributeViBooleanResponse{};
raise_if_error(
stub->GetAttributeViBoolean(&context, request, &response));
return response;
}
GetAttributeViInt32Response
get_attribute_vi_int32(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id)
{
::grpc::ClientContext context;
auto request = GetAttributeViInt32Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
auto response = GetAttributeViInt32Response{};
raise_if_error(
stub->GetAttributeViInt32(&context, request, &response));
return response;
}
GetAttributeViReal64Response
get_attribute_vi_real64(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id)
{
::grpc::ClientContext context;
auto request = GetAttributeViReal64Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
auto response = GetAttributeViReal64Response{};
raise_if_error(
stub->GetAttributeViReal64(&context, request, &response));
return response;
}
GetAttributeViStringResponse
get_attribute_vi_string(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id)
{
::grpc::ClientContext context;
auto request = GetAttributeViStringRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
auto response = GetAttributeViStringResponse{};
raise_if_error(
stub->GetAttributeViString(&context, request, &response));
return response;
}
GetAttributeViSessionResponse
get_attribute_vi_session(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id)
{
::grpc::ClientContext context;
auto request = GetAttributeViSessionRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
auto response = GetAttributeViSessionResponse{};
raise_if_error(
stub->GetAttributeViSession(&context, request, &response));
return response;
}
GetChannelNameResponse
get_channel_name(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::int32& index)
{
::grpc::ClientContext context;
auto request = GetChannelNameRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_index(index);
auto response = GetChannelNameResponse{};
raise_if_error(
stub->GetChannelName(&context, request, &response));
return response;
}
GetErrorResponse
get_error(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = GetErrorRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = GetErrorResponse{};
raise_if_error(
stub->GetError(&context, request, &response));
return response;
}
GetNextCoercionRecordResponse
get_next_coercion_record(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = GetNextCoercionRecordRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = GetNextCoercionRecordResponse{};
raise_if_error(
stub->GetNextCoercionRecord(&context, request, &response));
return response;
}
GetNextInterchangeWarningResponse
get_next_interchange_warning(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = GetNextInterchangeWarningRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = GetNextInterchangeWarningResponse{};
raise_if_error(
stub->GetNextInterchangeWarning(&context, request, &response));
return response;
}
GetPathResponse
get_path(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel1, const pb::string& channel2)
{
::grpc::ClientContext context;
auto request = GetPathRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel1(channel1);
request.set_channel2(channel2);
auto response = GetPathResponse{};
raise_if_error(
stub->GetPath(&context, request, &response));
return response;
}
GetRelayCountResponse
get_relay_count(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& relay_name)
{
::grpc::ClientContext context;
auto request = GetRelayCountRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_relay_name(relay_name);
auto response = GetRelayCountResponse{};
raise_if_error(
stub->GetRelayCount(&context, request, &response));
return response;
}
GetRelayNameResponse
get_relay_name(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::int32& index)
{
::grpc::ClientContext context;
auto request = GetRelayNameRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_index(index);
auto response = GetRelayNameResponse{};
raise_if_error(
stub->GetRelayName(&context, request, &response));
return response;
}
GetRelayPositionResponse
get_relay_position(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& relay_name)
{
::grpc::ClientContext context;
auto request = GetRelayPositionRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_relay_name(relay_name);
auto response = GetRelayPositionResponse{};
raise_if_error(
stub->GetRelayPosition(&context, request, &response));
return response;
}
InitResponse
init(const StubPtr& stub, const pb::string& resource_name, const bool& id_query, const bool& reset_device)
{
::grpc::ClientContext context;
auto request = InitRequest{};
request.set_resource_name(resource_name);
request.set_id_query(id_query);
request.set_reset_device(reset_device);
auto response = InitResponse{};
raise_if_error(
stub->Init(&context, request, &response));
return response;
}
InitWithOptionsResponse
init_with_options(const StubPtr& stub, const pb::string& resource_name, const bool& id_query, const bool& reset_device, const pb::string& option_string)
{
::grpc::ClientContext context;
auto request = InitWithOptionsRequest{};
request.set_resource_name(resource_name);
request.set_id_query(id_query);
request.set_reset_device(reset_device);
request.set_option_string(option_string);
auto response = InitWithOptionsResponse{};
raise_if_error(
stub->InitWithOptions(&context, request, &response));
return response;
}
InitWithTopologyResponse
init_with_topology(const StubPtr& stub, const pb::string& resource_name, const pb::string& topology, const bool& simulate, const bool& reset_device)
{
::grpc::ClientContext context;
auto request = InitWithTopologyRequest{};
request.set_resource_name(resource_name);
request.set_topology(topology);
request.set_simulate(simulate);
request.set_reset_device(reset_device);
auto response = InitWithTopologyResponse{};
raise_if_error(
stub->InitWithTopology(&context, request, &response));
return response;
}
InitiateScanResponse
initiate_scan(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = InitiateScanRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = InitiateScanResponse{};
raise_if_error(
stub->InitiateScan(&context, request, &response));
return response;
}
InvalidateAllAttributesResponse
invalidate_all_attributes(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = InvalidateAllAttributesRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = InvalidateAllAttributesResponse{};
raise_if_error(
stub->InvalidateAllAttributes(&context, request, &response));
return response;
}
IsDebouncedResponse
is_debounced(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = IsDebouncedRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = IsDebouncedResponse{};
raise_if_error(
stub->IsDebounced(&context, request, &response));
return response;
}
IsScanningResponse
is_scanning(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = IsScanningRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = IsScanningResponse{};
raise_if_error(
stub->IsScanning(&context, request, &response));
return response;
}
RelayControlResponse
relay_control(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& relay_name, const simple_variant<RelayAction, pb::int32>& relay_action)
{
::grpc::ClientContext context;
auto request = RelayControlRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_relay_name(relay_name);
const auto relay_action_ptr = relay_action.get_if<RelayAction>();
const auto relay_action_raw_ptr = relay_action.get_if<pb::int32>();
if (relay_action_ptr) {
request.set_relay_action(*relay_action_ptr);
}
else if (relay_action_raw_ptr) {
request.set_relay_action_raw(*relay_action_raw_ptr);
}
auto response = RelayControlResponse{};
raise_if_error(
stub->RelayControl(&context, request, &response));
return response;
}
ResetResponse
reset(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ResetRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ResetResponse{};
raise_if_error(
stub->Reset(&context, request, &response));
return response;
}
ResetInterchangeCheckResponse
reset_interchange_check(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ResetInterchangeCheckRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ResetInterchangeCheckResponse{};
raise_if_error(
stub->ResetInterchangeCheck(&context, request, &response));
return response;
}
ResetWithDefaultsResponse
reset_with_defaults(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = ResetWithDefaultsRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = ResetWithDefaultsResponse{};
raise_if_error(
stub->ResetWithDefaults(&context, request, &response));
return response;
}
RevisionQueryResponse
revision_query(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = RevisionQueryRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = RevisionQueryResponse{};
raise_if_error(
stub->RevisionQuery(&context, request, &response));
return response;
}
RouteScanAdvancedOutputResponse
route_scan_advanced_output(const StubPtr& stub, const nidevice_grpc::Session& vi, const simple_variant<ScanAdvancedOutput, pb::int32>& scan_advanced_output_connector, const simple_variant<ScanAdvancedOutput, pb::int32>& scan_advanced_output_bus_line, const bool& invert)
{
::grpc::ClientContext context;
auto request = RouteScanAdvancedOutputRequest{};
request.mutable_vi()->CopyFrom(vi);
const auto scan_advanced_output_connector_ptr = scan_advanced_output_connector.get_if<ScanAdvancedOutput>();
const auto scan_advanced_output_connector_raw_ptr = scan_advanced_output_connector.get_if<pb::int32>();
if (scan_advanced_output_connector_ptr) {
request.set_scan_advanced_output_connector(*scan_advanced_output_connector_ptr);
}
else if (scan_advanced_output_connector_raw_ptr) {
request.set_scan_advanced_output_connector_raw(*scan_advanced_output_connector_raw_ptr);
}
const auto scan_advanced_output_bus_line_ptr = scan_advanced_output_bus_line.get_if<ScanAdvancedOutput>();
const auto scan_advanced_output_bus_line_raw_ptr = scan_advanced_output_bus_line.get_if<pb::int32>();
if (scan_advanced_output_bus_line_ptr) {
request.set_scan_advanced_output_bus_line(*scan_advanced_output_bus_line_ptr);
}
else if (scan_advanced_output_bus_line_raw_ptr) {
request.set_scan_advanced_output_bus_line_raw(*scan_advanced_output_bus_line_raw_ptr);
}
request.set_invert(invert);
auto response = RouteScanAdvancedOutputResponse{};
raise_if_error(
stub->RouteScanAdvancedOutput(&context, request, &response));
return response;
}
RouteTriggerInputResponse
route_trigger_input(const StubPtr& stub, const nidevice_grpc::Session& vi, const simple_variant<TriggerInput, pb::int32>& trigger_input_connector, const simple_variant<TriggerInput, pb::int32>& trigger_input_bus_line, const bool& invert)
{
::grpc::ClientContext context;
auto request = RouteTriggerInputRequest{};
request.mutable_vi()->CopyFrom(vi);
const auto trigger_input_connector_ptr = trigger_input_connector.get_if<TriggerInput>();
const auto trigger_input_connector_raw_ptr = trigger_input_connector.get_if<pb::int32>();
if (trigger_input_connector_ptr) {
request.set_trigger_input_connector(*trigger_input_connector_ptr);
}
else if (trigger_input_connector_raw_ptr) {
request.set_trigger_input_connector_raw(*trigger_input_connector_raw_ptr);
}
const auto trigger_input_bus_line_ptr = trigger_input_bus_line.get_if<TriggerInput>();
const auto trigger_input_bus_line_raw_ptr = trigger_input_bus_line.get_if<pb::int32>();
if (trigger_input_bus_line_ptr) {
request.set_trigger_input_bus_line(*trigger_input_bus_line_ptr);
}
else if (trigger_input_bus_line_raw_ptr) {
request.set_trigger_input_bus_line_raw(*trigger_input_bus_line_raw_ptr);
}
request.set_invert(invert);
auto response = RouteTriggerInputResponse{};
raise_if_error(
stub->RouteTriggerInput(&context, request, &response));
return response;
}
ScanResponse
scan(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& scanlist, const simple_variant<HandshakingInitiation, pb::int32>& initiation)
{
::grpc::ClientContext context;
auto request = ScanRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_scanlist(scanlist);
const auto initiation_ptr = initiation.get_if<HandshakingInitiation>();
const auto initiation_raw_ptr = initiation.get_if<pb::int32>();
if (initiation_ptr) {
request.set_initiation(*initiation_ptr);
}
else if (initiation_raw_ptr) {
request.set_initiation_raw(*initiation_raw_ptr);
}
auto response = ScanResponse{};
raise_if_error(
stub->Scan(&context, request, &response));
return response;
}
SelfTestResponse
self_test(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = SelfTestRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = SelfTestResponse{};
raise_if_error(
stub->SelfTest(&context, request, &response));
return response;
}
SendSoftwareTriggerResponse
send_software_trigger(const StubPtr& stub, const nidevice_grpc::Session& vi)
{
::grpc::ClientContext context;
auto request = SendSoftwareTriggerRequest{};
request.mutable_vi()->CopyFrom(vi);
auto response = SendSoftwareTriggerResponse{};
raise_if_error(
stub->SendSoftwareTrigger(&context, request, &response));
return response;
}
SetAttributeViBooleanResponse
set_attribute_vi_boolean(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const bool& attribute_value)
{
::grpc::ClientContext context;
auto request = SetAttributeViBooleanRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value(attribute_value);
auto response = SetAttributeViBooleanResponse{};
raise_if_error(
stub->SetAttributeViBoolean(&context, request, &response));
return response;
}
SetAttributeViInt32Response
set_attribute_vi_int32(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const simple_variant<NiSwitchInt32AttributeValues, pb::int32>& attribute_value)
{
::grpc::ClientContext context;
auto request = SetAttributeViInt32Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
const auto attribute_value_ptr = attribute_value.get_if<NiSwitchInt32AttributeValues>();
const auto attribute_value_raw_ptr = attribute_value.get_if<pb::int32>();
if (attribute_value_ptr) {
request.set_attribute_value(*attribute_value_ptr);
}
else if (attribute_value_raw_ptr) {
request.set_attribute_value_raw(*attribute_value_raw_ptr);
}
auto response = SetAttributeViInt32Response{};
raise_if_error(
stub->SetAttributeViInt32(&context, request, &response));
return response;
}
SetAttributeViReal64Response
set_attribute_vi_real64(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const double& attribute_value_raw)
{
::grpc::ClientContext context;
auto request = SetAttributeViReal64Request{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value_raw(attribute_value_raw);
auto response = SetAttributeViReal64Response{};
raise_if_error(
stub->SetAttributeViReal64(&context, request, &response));
return response;
}
SetAttributeViStringResponse
set_attribute_vi_string(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const pb::string& attribute_value_raw)
{
::grpc::ClientContext context;
auto request = SetAttributeViStringRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.set_attribute_value_raw(attribute_value_raw);
auto response = SetAttributeViStringResponse{};
raise_if_error(
stub->SetAttributeViString(&context, request, &response));
return response;
}
SetAttributeViSessionResponse
set_attribute_vi_session(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& channel_name, const NiSwitchAttribute& attribute_id, const nidevice_grpc::Session& attribute_value)
{
::grpc::ClientContext context;
auto request = SetAttributeViSessionRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_channel_name(channel_name);
request.set_attribute_id(attribute_id);
request.mutable_attribute_value()->CopyFrom(attribute_value);
auto response = SetAttributeViSessionResponse{};
raise_if_error(
stub->SetAttributeViSession(&context, request, &response));
return response;
}
SetContinuousScanResponse
set_continuous_scan(const StubPtr& stub, const nidevice_grpc::Session& vi, const bool& continuous_scan)
{
::grpc::ClientContext context;
auto request = SetContinuousScanRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_continuous_scan(continuous_scan);
auto response = SetContinuousScanResponse{};
raise_if_error(
stub->SetContinuousScan(&context, request, &response));
return response;
}
SetPathResponse
set_path(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::string& path_list)
{
::grpc::ClientContext context;
auto request = SetPathRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_path_list(path_list);
auto response = SetPathResponse{};
raise_if_error(
stub->SetPath(&context, request, &response));
return response;
}
WaitForDebounceResponse
wait_for_debounce(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::int32& maximum_time_ms)
{
::grpc::ClientContext context;
auto request = WaitForDebounceRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_maximum_time_ms(maximum_time_ms);
auto response = WaitForDebounceResponse{};
raise_if_error(
stub->WaitForDebounce(&context, request, &response));
return response;
}
WaitForScanCompleteResponse
wait_for_scan_complete(const StubPtr& stub, const nidevice_grpc::Session& vi, const pb::int32& maximum_time_ms)
{
::grpc::ClientContext context;
auto request = WaitForScanCompleteRequest{};
request.mutable_vi()->CopyFrom(vi);
request.set_maximum_time_ms(maximum_time_ms);
auto response = WaitForScanCompleteResponse{};
raise_if_error(
stub->WaitForScanComplete(&context, request, &response));
return response;
}
} // namespace niswitch_grpc::experimental::client
| 28.543383 | 270 | 0.765168 | [
"vector"
] |
10c20957d29c39188ab4177995ab898ca3d412a8 | 3,371 | hpp | C++ | include/poplibs_support/popopsPerformanceEstimation.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | 1 | 2021-02-23T05:58:24.000Z | 2021-02-23T05:58:24.000Z | include/poplibs_support/popopsPerformanceEstimation.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | include/poplibs_support/popopsPerformanceEstimation.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#ifndef _popops_performance_estimation_h_
#define _popops_performance_estimation_h_
#include "popops/Expr.hpp"
#include <poplar/Target.hpp>
namespace popops {
/** Supervisor context cycle estimate for BinaryOp and UnaryOp supervisor
* codelets.
*
* \param isScaledPtr64Type Is true if vector vertex field is ScaledPtr64
* and false otherwise.
*
* \returns Estimated number of cycles.
*/
std::uint64_t basicOpSupervisorOverhead(const bool isScaledPtr64Type = false);
/** Cycle cost for processing an arbitrary number of elements given the cycle
* cost for processing a vector of elements simultaneously.
*
* \param numElems Number of elements in the operand.
* \param vectorSize Size of vector of elements that can be processed
* simultaneously.
* \param cyclesPerVector Cycle cost per vector of elements.
*
* \returns Estimated number of cycles.
*/
std::uint64_t basicOpLoopCycles(const unsigned numElems,
const unsigned vectorSize,
const unsigned cyclesPerVector);
/** Cycle cost for processing an arbitrary number of elements given the cycle
* cost for processing a vector of elements simultaneously.
*
* \param target The target on which the operation should be estimated
* \param type Data type of elements.
* \param cyclesPerVector Cycle cost per vector of elements.
* \param vectorSize Size of vector of elements that be processed
* simultaneously.
* \param numElems Number of elements in the operand.
* \param overheadPerLoop Cycles overhead per loop.
*
* \returns Estimated number of cycles.
*/
std::uint64_t binaryOpInnerLoopCycles(const poplar::Target &target,
const poplar::Type &type,
const unsigned cyclesPerVector,
const bool vectorize,
const unsigned numElems,
const std::uint64_t overheadPerLoop);
/** Cycle estimate for Dynamic Slice 1D vertex.
*
* \param target The target on which the operation should be estimated.
* \param type Data type of elements.
* \param regionSize Number of elements in tensor to be sliced.
* \param numSubElements Number of elements per slice.
*
* \returns Estimated number of cycles.
*/
std::uint64_t getDynamicSlice1dEstimate(const poplar::Target &target,
const poplar::Type &type,
const unsigned regionSize,
const unsigned numSubElements);
/** Cycle estimate for Binary-1D In-Place Supervisor vertex.
*
* \param target The target on which the operation should be estimated.
* \param type Data type of elements.
* \param op Binary operator type.
* \param numElems Total number of output elements.
*
* \returns Estimated number of cycles.
*/
std::uint64_t getBinaryOp1DInPlaceSupervisorEstimate(
const poplar::Target &target, const poplar::Type &type,
const popops::expr::BinaryOpType op, const unsigned numElems);
} // namespace popops
#endif // _popops_performance_estimation_h_
| 40.130952 | 79 | 0.652625 | [
"vector"
] |
10c3c836e13b947091d9a907a603e68981f5321b | 12,196 | hpp | C++ | sql_cpp/include/sql_cpp/detail/nonlogicaloperators.hpp | sWombacher/Utility | bb38fb090fd11fd36c07a318e7c6a301e0e21322 | [
"WTFPL",
"Unlicense"
] | 1 | 2015-02-25T21:56:12.000Z | 2015-02-25T21:56:12.000Z | sql_cpp/include/sql_cpp/detail/nonlogicaloperators.hpp | sWombacher/Utility | bb38fb090fd11fd36c07a318e7c6a301e0e21322 | [
"WTFPL",
"Unlicense"
] | null | null | null | sql_cpp/include/sql_cpp/detail/nonlogicaloperators.hpp | sWombacher/Utility | bb38fb090fd11fd36c07a318e7c6a301e0e21322 | [
"WTFPL",
"Unlicense"
] | null | null | null | #pragma once
#include "sql_cpp/detail/operatorbase.hpp"
#include "sql_cpp/detail/table.hpp"
namespace sql_cpp::detail {
static constexpr inline auto NonLogicalOperator_Offset = 16;
enum class NonLogicalOperatorType : uint8_t {
// arithmetic types
ADD = NonLogicalOperator_Offset * uint8_t(OperatorType::arithmetic),
SUBTRACT,
MULTIPLY,
DIVIDE,
MODULO,
// bitwise types
BITWISE_AND = NonLogicalOperator_Offset * uint8_t(OperatorType::bitwise),
BITWISE_OR,
BITWISE_XOR,
// comparison types
EQUAL_TO = NonLogicalOperator_Offset * uint8_t(OperatorType::comparison),
GREATER_THAN,
LESS_THAN,
GREATER_EQUAL,
LESS_EQUAL,
NOT_EQUAL,
// compound types
ADD_EQUAL = NonLogicalOperator_Offset * uint8_t(OperatorType::compound),
SUBTRACT_EQUAL,
MULTIPLY_EQUAL,
DIVIDE_EQUAL,
MODULO_EQUAL,
BITWISE_AND_EQUAL,
BITWISE_OR_EQUAL,
BITWISE_XOR_EQUAL,
};
static constexpr OperatorType
NonLogicalOperator_to_Operator(NonLogicalOperatorType tpot) {
return OperatorType(uint8_t(tpot) / NonLogicalOperator_Offset);
}
static constexpr std::string_view
NonLogicalOperatorType_to_SqlString(NonLogicalOperatorType tpot) {
// clang-format off
switch (tpot) {
// arithmetic types
case NonLogicalOperatorType::ADD: return " + ";
case NonLogicalOperatorType::SUBTRACT: return " - ";
case NonLogicalOperatorType::MULTIPLY: return " * ";
case NonLogicalOperatorType::DIVIDE: return " / ";
case NonLogicalOperatorType::MODULO: return " % ";
// bitwise types
case NonLogicalOperatorType::BITWISE_AND: return " & ";
case NonLogicalOperatorType::BITWISE_OR: return " | ";
case NonLogicalOperatorType::BITWISE_XOR: return " ^ ";
// comparison types
case NonLogicalOperatorType::EQUAL_TO: return " = ";
case NonLogicalOperatorType::GREATER_EQUAL: return " >= ";
case NonLogicalOperatorType::GREATER_THAN: return " > ";
case NonLogicalOperatorType::LESS_EQUAL: return " <= ";
case NonLogicalOperatorType::LESS_THAN: return " < ";
case NonLogicalOperatorType::NOT_EQUAL: return " <> ";
// compound types
case NonLogicalOperatorType::ADD_EQUAL: return " &= ";
case NonLogicalOperatorType::SUBTRACT_EQUAL: return " -= ";
case NonLogicalOperatorType::MULTIPLY_EQUAL: return " *= ";
case NonLogicalOperatorType::DIVIDE_EQUAL: return " /= ";
case NonLogicalOperatorType::MODULO_EQUAL: return " %= ";
case NonLogicalOperatorType::BITWISE_AND_EQUAL: return " &= ";
case NonLogicalOperatorType::BITWISE_OR_EQUAL: return " |*= ";
case NonLogicalOperatorType::BITWISE_XOR_EQUAL: return " ^-= ";
}
// clang-format on
throw std::runtime_error("Invalid Comparison String");
}
template <detail::NonLogicalOperatorType Type>
class NonLogicalOperator
: public detail::SqlOperatorBase<detail::NonLogicalOperator_to_Operator(
Type)> {
using super =
detail::SqlOperatorBase<detail::NonLogicalOperator_to_Operator(Type)>;
public:
template <typename Parameter0, typename Parameter1>
NonLogicalOperator(Parameter0&& lhs, Parameter1&& rhs)
: m_Comparison(InitOperatorString(std::forward<Parameter0>(lhs),
std::forward<Parameter1>(rhs))),
m_RequiredClassTypes(
detail::MultipleTypesToRequiredClassType<Parameter0,
Parameter1>()) {}
std::string&& to_string() && noexcept override {
return std::move(m_Comparison);
}
const std::vector<detail::RequiredClassType>&
requiredClassTypes() const noexcept override {
return m_RequiredClassTypes;
}
private:
template <typename P0, typename P1>
static auto InitOperatorString(P0&& p0, P1&& p1) {
/// TODO: check type checking, compairing string with ints is bad
return super::TypeToString(std::forward<P0>(p0)) +
std::string(detail::NonLogicalOperatorType_to_SqlString(Type)) +
super::TypeToString(std::forward<P1>(p1));
}
private:
std::string m_Comparison;
const std::vector<detail::RequiredClassType> m_RequiredClassTypes;
};
} // namespace sql_cpp::detail
namespace sql_cpp {
#define HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(name, type) \
template <typename Parameter0, typename Parameter1> \
auto name(Parameter0&& p0, Parameter1&& p1) { \
return detail::NonLogicalOperator<type>(std::forward<Parameter0>(p0), \
std::forward<Parameter1>(p1)); \
}
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(plus,
detail::NonLogicalOperatorType::ADD);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
plus_equal, detail::NonLogicalOperatorType::ADD_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
minus, detail::NonLogicalOperatorType::SUBTRACT);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
minus_equal, detail::NonLogicalOperatorType::SUBTRACT_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
multiplies, detail::NonLogicalOperatorType::MULTIPLY);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
multiplies_equal, detail::NonLogicalOperatorType::MULTIPLY_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
divides, detail::NonLogicalOperatorType::DIVIDE);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
divides_equal, detail::NonLogicalOperatorType::DIVIDE_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
modulus, detail::NonLogicalOperatorType::MODULO);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
modulus_equal, detail::NonLogicalOperatorType::MODULO_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_and, detail::NonLogicalOperatorType::BITWISE_AND);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_and_equal, detail::NonLogicalOperatorType::BITWISE_AND_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_or, detail::NonLogicalOperatorType::BITWISE_OR);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_or_equal, detail::NonLogicalOperatorType::BITWISE_OR_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_xor, detail::NonLogicalOperatorType::BITWISE_XOR);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
bit_xor_equal, detail::NonLogicalOperatorType::BITWISE_XOR_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
equal_to, detail::NonLogicalOperatorType::EQUAL_TO);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
greater, detail::NonLogicalOperatorType::GREATER_THAN);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
greater_equal, detail::NonLogicalOperatorType::GREATER_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
less, detail::NonLogicalOperatorType::LESS_THAN);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
less_equal, detail::NonLogicalOperatorType::LESS_EQUAL);
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(
not_equal_to, detail::NonLogicalOperatorType::NOT_EQUAL);
#undef HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION
namespace detail {
template <typename ValueType, typename TableStruct> class OperatorOverloadBase {
public:
constexpr OperatorOverloadBase(ValueType TableStruct::*ptr) : m_Ptr(ptr) {}
protected:
const ValueType TableStruct::*m_Ptr;
};
#define HELPER_MACRO_CREATE_OPERATOR_MEMBER(Operator, funcName) \
auto operator Operator(ValueType&& rhs) const { \
return funcName(this->m_Ptr, std::move(rhs)); \
} \
auto operator Operator(const ValueType& rhs) const { \
return funcName(this->m_Ptr, rhs); \
} \
friend auto operator Operator(ValueType&& lhs, const self_type& self) { \
return funcName(std::move(lhs), self.m_Ptr); \
} \
friend auto operator Operator(const ValueType& lhs, \
const self_type& self) { \
return funcName(lhs, self.m_Ptr); \
}
template <typename ValueType, typename TableStruct>
class Comparison : public OperatorOverloadBase<ValueType, TableStruct> {
public:
using self_type = Comparison;
constexpr Comparison(ValueType TableStruct::*ptr)
: OperatorOverloadBase<ValueType, TableStruct>(ptr) {}
HELPER_MACRO_CREATE_OPERATOR_MEMBER(==, equal_to)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(!=, not_equal_to)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(<, less)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(<=, less_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(>, greater)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(>=, greater_equal)
};
template <typename ValueType, typename TableStruct>
class Arithmetic : public OperatorOverloadBase<ValueType, TableStruct> {
public:
using self_type = Arithmetic;
constexpr Arithmetic(ValueType TableStruct::*ptr)
: OperatorOverloadBase<ValueType, TableStruct>(ptr) {}
HELPER_MACRO_CREATE_OPERATOR_MEMBER(+, plus)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(-, minus)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(*, multiplies)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(/, divides)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(%, modulus)
};
template <typename ValueType, typename TableStruct>
class Bitwise : public OperatorOverloadBase<ValueType, TableStruct> {
public:
using self_type = Bitwise;
constexpr Bitwise(ValueType TableStruct::*ptr)
: OperatorOverloadBase<ValueType, TableStruct>(ptr) {}
HELPER_MACRO_CREATE_OPERATOR_MEMBER(&, bit_and)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(|, bit_or)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(^, bit_xor)
};
template <typename ValueType, typename TableStruct>
class Compound : public OperatorOverloadBase<ValueType, TableStruct> {
public:
using self_type = Compound;
constexpr Compound(ValueType TableStruct::*ptr)
: OperatorOverloadBase<ValueType, TableStruct>(ptr) {}
HELPER_MACRO_CREATE_OPERATOR_MEMBER(+=, plus_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(-=, minus_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(*=, multiplies_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(/=, divides_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(%=, modulus_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(&=, bit_and_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(|=, bit_or_equal)
HELPER_MACRO_CREATE_OPERATOR_MEMBER(^=, bit_xor_equal)
};
#undef HELPER_MACRO_CREATE_OPERATOR_MEMBER
/**
* 'public virtual' seem to have bigger size than just raw inheritance
*/
template <typename ValueType, typename TableStruct>
class AllOperators : public Comparison<ValueType, TableStruct>,
public Arithmetic<ValueType, TableStruct>,
public Bitwise<ValueType, TableStruct>,
public Compound<ValueType, TableStruct> {
public:
constexpr AllOperators(ValueType TableStruct::*ptr)
: Comparison<ValueType, TableStruct>(ptr),
Arithmetic<ValueType, TableStruct>(ptr),
Bitwise<ValueType, TableStruct>(ptr),
Compound<ValueType, TableStruct>(ptr) {}
};
} // namespace detail
#define HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(funcName, ClassName) \
template <typename ValueType, typename TableStruct> \
constexpr auto funcName(ValueType TableStruct::*ptr) { \
return detail::ClassName<ValueType, TableStruct>(ptr); \
}
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(arithmetic, Arithmetic)
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(bitwise, Bitwise)
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(comparison, Comparison)
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(compound, Compound)
HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION(operators, AllOperators)
#undef HELPER_MACRO_CREATE_SQL_OPERATOR_FUNCTION
} // namespace sql_cpp
| 40.518272 | 80 | 0.707117 | [
"vector"
] |
10c98849ff23a5dc89bee91d6460cb85fe2ed43d | 1,402 | hpp | C++ | include/display3r/Solid.hpp | tomtix/display3r | 00c5d7be1b2bea685c7df053f0333bb6828d48f8 | [
"MIT"
] | null | null | null | include/display3r/Solid.hpp | tomtix/display3r | 00c5d7be1b2bea685c7df053f0333bb6828d48f8 | [
"MIT"
] | null | null | null | include/display3r/Solid.hpp | tomtix/display3r | 00c5d7be1b2bea685c7df053f0333bb6828d48f8 | [
"MIT"
] | null | null | null | #ifndef DISPLAY3R_SOLID_H
#define DISPLAY3R_SOLID_H
#include <SDL.h>
#include <string>
#include <vector>
#include <fstream>
namespace display3r { class Solid; }
#include "display3r/Object3D.hpp"
#include "display3r/Color.hpp"
#include "display3r/Drawable.hpp"
#include "display3r/Texture.hpp"
#include "display3r/Equation.hpp"
//#include "equation.hpp"
namespace display3r {
class Renderer;
using std::string;
using std::ifstream;
using std::vector;
class Solid : public Drawable {
public:
Solid(string filepath, Texture*);
Solid(Equation const&, Texture*);
private:
void DrawHandler(Renderer &renderer) override;
private:
void LoadOBJ(ifstream &file);
void ParseVertex(vector<string> const &s, vector<vec3> &vertex);
void ParseNormal(vector<string> const &s, vector<vec3> &normal);
void ParseTexCoord(vector<string> const &s, vector<vec2> &texcoord);
Vertex ParseVertexIndex(string rep,
vector<vec3>const &vertex,
vector<vec3>const &normal,
vector<vec2>const &texcoord);
void ParseFace(vector<string> const &s,
vector<vec3>const &v/*ertex*/,
vector<vec3>const &n/*ormal*/,
vector<vec2>const &t/*excoord*/);
vector<Face> m_faces;
Texture *m_texture;
string m_name;
};
};
#endif //DISPLAY3R_SOLID_H
| 24.172414 | 72 | 0.653352 | [
"vector",
"solid"
] |
10d0824d0821ca6ad8f0a02daff9bfd16ff5df7b | 883 | cpp | C++ | Section 1.3/Mixing Milk/milk.cpp | memset0x3f/usaco | 9b3029e33afa441b823ac2c75eabb0ccdae70b0d | [
"MIT"
] | 14 | 2016-05-12T12:19:33.000Z | 2021-12-12T02:39:54.000Z | Section 1.3/Mixing Milk/milk.cpp | akommula/usaco | 9b3029e33afa441b823ac2c75eabb0ccdae70b0d | [
"MIT"
] | null | null | null | Section 1.3/Mixing Milk/milk.cpp | akommula/usaco | 9b3029e33afa441b823ac2c75eabb0ccdae70b0d | [
"MIT"
] | 18 | 2017-04-23T01:29:44.000Z | 2022-03-20T03:45:53.000Z | /*
ID: cloudzf2
PROG: milk
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <unordered_map>
#include <cstring>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool cmp(pair<int, int> a, pair<int, int> b) {
return a.first < b.first;
}
int main(int argc, const char * argv[]) {
ifstream fin ("milk.in");
ofstream fout ("milk.out");
int N, M;
int P, A;
vector<pair<int, int> > milk;
fin >> N >> M;
for (int i = 0; i < M; i++) {
fin >> P >> A;
milk.push_back(make_pair(P, A));
}
sort(milk.begin(), milk.end(), cmp);
int cost = 0;
for (int i = 0; i < M; i++) {
cost += milk[i].first * min(N, milk[i].second);
N -= min(N, milk[i].second);
if (N == 0) break;
}
fout << cost << endl;
return 0;
}
| 20.068182 | 55 | 0.544734 | [
"vector"
] |
10d0945542a1cb6f4961de96edbbcba9dd63911e | 1,674 | hpp | C++ | module/server_daemon/include/EXAMPLE_Simon.hpp | selfeki/social-gaming-platform | 8d59512620470c57fa760998f3bcf1e4469130ef | [
"MIT"
] | null | null | null | module/server_daemon/include/EXAMPLE_Simon.hpp | selfeki/social-gaming-platform | 8d59512620470c57fa760998f3bcf1e4469130ef | [
"MIT"
] | null | null | null | module/server_daemon/include/EXAMPLE_Simon.hpp | selfeki/social-gaming-platform | 8d59512620470c57fa760998f3bcf1e4469130ef | [
"MIT"
] | null | null | null | #pragma once
#include <arepa/game/DefaultController.hpp>
#include <set>
/**
* An example Simon-says game.
*
* This differs from normal simon says in that you simply have to perfectly re-type what Simon says.
* The difficulty comes from when you make typos ;)
*/
class EXAMPLE_Simon : public arepa::game::DefaultController {
#pragma mark - Fields -
protected:
arepa::chat::Player::Id _simon;
std::string _simon_message;
std::set<arepa::chat::Player::Id> _incomplete;
#pragma mark - Constructors -
public:
virtual ~EXAMPLE_Simon() = default;
#pragma mark - Methods (Protected) -
protected:
/**
* Ends the current round.
* This will disqualify all the players who didn't finish.
*/
void end_round();
/**
* Prepares the next round.
* @param message The message.
*/
void next_round(std::string message);
/**
* Check if a player wins.
*/
void check_win();
/**
* Gets the current Simon's name.
* @return The Simon's name.
*/
std::string simon_name();
#pragma mark - Methods (Controller) -
public:
void initialize(arepa::game::Environment& environment) override;
Intercept intercept_player_message(Player& player, const std::string& message) override;
Intercept intercept_player_command(Player& player, const Command& command) override;
void on_player_quit(Player& player) override;
arepa::Result<void, std::string> on_option_change(const OptionKey& option, const OptionValue& value) override;
std::vector<std::pair<OptionKey, std::string>> list_option_descriptions() override;
void update() override;
void start() override;
};
| 25.753846 | 114 | 0.682198 | [
"vector"
] |
10d67a3aa63bd4a2f9a88812b692702acd70b0f7 | 43,251 | cc | C++ | src/atlas/mesh/actions/BuildParallelFields.cc | ecmwf/atlas | d589893bf6aa28c6df649a46d642fab006b00a8d | [
"Apache-2.0"
] | 67 | 2018-03-01T06:56:49.000Z | 2022-03-08T18:44:47.000Z | src/atlas/mesh/actions/BuildParallelFields.cc | ecmwf/atlas | d589893bf6aa28c6df649a46d642fab006b00a8d | [
"Apache-2.0"
] | 93 | 2018-12-07T17:38:04.000Z | 2022-03-31T10:04:51.000Z | src/atlas/mesh/actions/BuildParallelFields.cc | ecmwf/atlas | d589893bf6aa28c6df649a46d642fab006b00a8d | [
"Apache-2.0"
] | 33 | 2018-02-28T17:06:19.000Z | 2022-01-20T12:12:27.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <cmath>
#include <iostream>
#include <stdexcept>
#include "atlas/array.h"
#include "atlas/array/ArrayView.h"
#include "atlas/array/IndexView.h"
#include "atlas/field/Field.h"
#include "atlas/mesh/HybridElements.h"
#include "atlas/mesh/Mesh.h"
#include "atlas/mesh/Nodes.h"
#include "atlas/mesh/actions/BuildParallelFields.h"
#include "atlas/parallel/GatherScatter.h"
#include "atlas/parallel/mpi/Buffer.h"
#include "atlas/parallel/mpi/mpi.h"
#include "atlas/runtime/Exception.h"
#include "atlas/runtime/Log.h"
#include "atlas/runtime/Trace.h"
#include "atlas/util/CoordinateEnums.h"
#include "atlas/util/PeriodicTransform.h"
#include "atlas/util/Unique.h"
#define EDGE(jedge) \
"Edge(" << node_gidx(edge_nodes(jedge, 0)) << "[p" << node_part(edge_nodes(jedge, 0)) << "] " \
<< node_gidx(edge_nodes(jedge, 1)) << "[p" << node_part(edge_nodes(jedge, 1)) << "])"
//#define DEBUGGING_PARFIELDS
#ifdef DEBUGGING_PARFIELDS
#define own1 2419089
#define own2 2423185
#define OWNED_EDGE(jedge) \
((node_gidx(edge_nodes(jedge, 0)) == own1 && node_gidx(edge_nodes(jedge, 1)) == own2) || \
(node_gidx(edge_nodes(jedge, 0)) == own2 && node_gidx(edge_nodes(jedge, 1)) == own1))
#define per1 -1
#define per2 -1
#define PERIODIC_EDGE(jedge) \
((node_gidx(edge_nodes(jedge, 0)) == per1 && node_gidx(edge_nodes(jedge, 1)) == per2) || \
(node_gidx(edge_nodes(jedge, 0)) == per2 && node_gidx(edge_nodes(jedge, 1)) == per1))
#define find1 39 // 1697
#define find2 41 // 1698
#define FIND_EDGE(jedge) \
((node_gidx(edge_nodes(jedge, 0)) == find1 && node_gidx(edge_nodes(jedge, 1)) == find2) || \
(node_gidx(edge_nodes(jedge, 0)) == find2 && node_gidx(edge_nodes(jedge, 1)) == find1))
#define find_gidx 689849552510167040
#define FIND_GIDX(UID) ((UID) == find_gidx)
#endif
using Topology = atlas::mesh::Nodes::Topology;
using atlas::util::PeriodicTransform;
using atlas::util::UniqueLonLat;
namespace atlas {
namespace mesh {
namespace actions {
Field& build_nodes_partition(mesh::Nodes& nodes);
Field& build_nodes_remote_idx(mesh::Nodes& nodes);
Field& build_nodes_global_idx(mesh::Nodes& nodes);
Field& build_edges_partition(Mesh& mesh);
Field& build_edges_remote_idx(Mesh& mesh);
Field& build_edges_global_idx(Mesh& mesh);
//----------------------------------------------------------------------------------------------------------------------
using uid_t = gidx_t;
namespace {
struct Node {
Node(gidx_t gid, idx_t idx) {
g = gid;
i = idx;
}
gidx_t g;
idx_t i;
bool operator<(const Node& other) const { return (g < other.g); }
};
} // namespace
//----------------------------------------------------------------------------------------------------------------------
void build_parallel_fields(Mesh& mesh) {
ATLAS_TRACE();
build_nodes_parallel_fields(mesh.nodes());
}
//----------------------------------------------------------------------------------------------------------------------
void build_nodes_parallel_fields(mesh::Nodes& nodes) {
ATLAS_TRACE();
bool parallel = false;
nodes.metadata().get("parallel", parallel);
if (!parallel) {
build_nodes_partition(nodes);
build_nodes_remote_idx(nodes);
build_nodes_global_idx(nodes);
}
nodes.metadata().set("parallel", true);
}
//----------------------------------------------------------------------------------------------------------------------
void build_edges_parallel_fields(Mesh& mesh) {
ATLAS_TRACE();
build_edges_partition(mesh);
build_edges_remote_idx(mesh);
/*
* We turn following off. It is expensive and we don't really care about a nice
* contiguous
* ordering.
*/
// build_edges_global_idx( mesh );
}
//----------------------------------------------------------------------------------------------------------------------
Field& build_nodes_global_idx(mesh::Nodes& nodes) {
ATLAS_TRACE();
array::ArrayView<gidx_t, 1> glb_idx = array::make_view<gidx_t, 1>(nodes.global_index());
UniqueLonLat compute_uid(nodes);
for (idx_t jnode = 0; jnode < glb_idx.shape(0); ++jnode) {
if (glb_idx(jnode) <= 0) {
glb_idx(jnode) = compute_uid(jnode);
}
}
return nodes.global_index();
}
void renumber_nodes_glb_idx(mesh::Nodes& nodes) {
bool human_readable(false);
nodes.global_index().metadata().get("human_readable", human_readable);
if (human_readable) {
/* nothing to be done */
return;
}
ATLAS_TRACE();
// TODO: ATLAS-14: fix renumbering of EAST periodic boundary points
// --> Those specific periodic points at the EAST boundary are not checked for
// uid,
// and could receive different gidx for different tasks
UniqueLonLat compute_uid(nodes);
// unused // int mypart = mpi::rank();
int nparts = mpi::size();
idx_t root = 0;
array::ArrayView<gidx_t, 1> glb_idx = array::make_view<gidx_t, 1>(nodes.global_index());
/*
* Sorting following gidx will define global order of
* gathered fields. Special care needs to be taken for
* pole edges, as their centroid might coincide with
* other edges
*/
int nb_nodes = glb_idx.shape(0);
for (int jnode = 0; jnode < nb_nodes; ++jnode) {
if (glb_idx(jnode) <= 0) {
glb_idx(jnode) = compute_uid(jnode);
}
}
// 1) Gather all global indices, together with location
array::ArrayT<uid_t> loc_id_arr(nb_nodes);
array::ArrayView<uid_t, 1> loc_id = array::make_view<uid_t, 1>(loc_id_arr);
for (int jnode = 0; jnode < nb_nodes; ++jnode) {
loc_id(jnode) = glb_idx(jnode);
}
std::vector<int> recvcounts(mpi::size());
std::vector<int> recvdispls(mpi::size());
ATLAS_TRACE_MPI(GATHER) { mpi::comm().gather(nb_nodes, recvcounts, root); }
recvdispls[0] = 0;
for (int jpart = 1; jpart < nparts; ++jpart) { // start at 1
recvdispls[jpart] = recvcounts[jpart - 1] + recvdispls[jpart - 1];
}
int glb_nb_nodes = std::accumulate(recvcounts.begin(), recvcounts.end(), 0);
array::ArrayT<uid_t> glb_id_arr(glb_nb_nodes);
array::ArrayView<uid_t, 1> glb_id = array::make_view<uid_t, 1>(glb_id_arr);
ATLAS_TRACE_MPI(GATHER) {
mpi::comm().gatherv(loc_id.data(), loc_id.size(), glb_id.data(), recvcounts.data(), recvdispls.data(), root);
}
// 2) Sort all global indices, and renumber from 1 to glb_nb_edges
std::vector<Node> node_sort;
node_sort.reserve(glb_nb_nodes);
ATLAS_TRACE_SCOPE("sort global indices") {
for (idx_t jnode = 0; jnode < glb_id.shape(0); ++jnode) {
node_sort.emplace_back(glb_id(jnode), jnode);
}
std::sort(node_sort.begin(), node_sort.end());
}
// Assume edge gid start
uid_t gid = 0;
const idx_t nb_sorted_nodes = static_cast<idx_t>(node_sort.size());
for (idx_t jnode = 0; jnode < nb_sorted_nodes; ++jnode) {
if (jnode == 0) {
++gid;
}
else if (node_sort[jnode].g != node_sort[jnode - 1].g) {
++gid;
}
idx_t inode = node_sort[jnode].i;
glb_id(inode) = gid;
}
// 3) Scatter renumbered back
ATLAS_TRACE_MPI(SCATTER) {
mpi::comm().scatterv(glb_id.data(), recvcounts.data(), recvdispls.data(), loc_id.data(), loc_id.size(), root);
}
for (int jnode = 0; jnode < nb_nodes; ++jnode) {
glb_idx(jnode) = loc_id(jnode);
}
nodes.global_index().metadata().set("human_readable", true);
}
//----------------------------------------------------------------------------------------------------------------------
Field& build_nodes_remote_idx(mesh::Nodes& nodes) {
ATLAS_TRACE();
idx_t mypart = static_cast<idx_t>(mpi::rank());
idx_t nparts = static_cast<idx_t>(mpi::size());
UniqueLonLat compute_uid(nodes);
std::vector<idx_t> proc(nparts);
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
proc[jpart] = jpart;
}
auto ridx = array::make_indexview<idx_t, 1>(nodes.remote_index());
auto part = array::make_view<int, 1>(nodes.partition());
idx_t nb_nodes = nodes.size();
idx_t varsize = 2;
std::vector<std::vector<uid_t>> send_needed(mpi::size());
std::vector<std::vector<uid_t>> recv_needed(mpi::size());
int sendcnt = 0;
std::map<uid_t, int> lookup;
for (idx_t jnode = 0; jnode < nb_nodes; ++jnode) {
uid_t uid = compute_uid(jnode);
if (idx_t(part(jnode)) == mypart) {
lookup[uid] = jnode;
ridx(jnode) = jnode;
}
else {
ATLAS_ASSERT(jnode < part.shape(0));
if (part(jnode) >= static_cast<int>(proc.size())) {
std::stringstream msg;
msg << "Assertion [part(" << jnode << ") < proc.size()] failed\n"
<< "part(" << jnode << ") = " << part(jnode) << "\n"
<< "proc.size() = " << proc.size();
throw_AssertionFailed(msg.str(), Here());
}
ATLAS_ASSERT(part(jnode) < (idx_t)proc.size());
ATLAS_ASSERT((size_t)proc[part(jnode)] < send_needed.size());
send_needed[proc[part(jnode)]].push_back(uid);
send_needed[proc[part(jnode)]].push_back(jnode);
sendcnt++;
}
}
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_needed, recv_needed); }
std::vector<std::vector<int>> send_found(mpi::size());
std::vector<std::vector<int>> recv_found(mpi::size());
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<uid_t>& recv_node = recv_needed[proc[jpart]];
const idx_t nb_recv_nodes = idx_t(recv_node.size()) / varsize;
for (idx_t jnode = 0; jnode < nb_recv_nodes; ++jnode) {
uid_t uid = recv_node[jnode * varsize + 0];
int inode = recv_node[jnode * varsize + 1];
if (lookup.count(uid)) {
send_found[proc[jpart]].push_back(inode);
send_found[proc[jpart]].push_back(lookup[uid]);
}
else {
std::stringstream msg;
msg << "[" << mpi::rank() << "] "
<< "Node requested by rank [" << jpart << "] with uid [" << uid
<< "] that should be owned is not found";
throw_Exception(msg.str(), Here());
}
}
}
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_found, recv_found); }
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<int>& recv_node = recv_found[proc[jpart]];
const idx_t nb_recv_nodes = recv_node.size() / 2;
// array::ArrayView<int,2> recv_node( recv_found[ proc[jpart] ].data(),
// array::make_shape(recv_found[ proc[jpart] ].size()/2,2) );
for (idx_t jnode = 0; jnode < nb_recv_nodes; ++jnode) {
ridx(recv_node[jnode * 2 + 0]) = recv_node[jnode * 2 + 1];
}
}
return nodes.remote_index();
}
//----------------------------------------------------------------------------------------------------------------------
Field& build_nodes_partition(mesh::Nodes& nodes) {
ATLAS_TRACE();
return nodes.partition();
}
//----------------------------------------------------------------------------------------------------------------------
Field& build_edges_partition(Mesh& mesh) {
ATLAS_TRACE();
const mesh::Nodes& nodes = mesh.nodes();
idx_t mypart = mpi::rank();
mesh::HybridElements& edges = mesh.edges();
auto edge_part = array::make_view<int, 1>(edges.partition());
//const auto edge_glb_idx = array::make_view<gidx_t, 1>( edges.global_index() );
const auto& edge_nodes = edges.node_connectivity();
const auto& edge_to_elem = edges.cell_connectivity();
const auto node_part = array::make_view<int, 1>(nodes.partition());
const auto xy = array::make_view<double, 2>(nodes.xy());
const auto flags = array::make_view<int, 1>(nodes.flags());
const auto node_gidx = array::make_view<gidx_t, 1>(nodes.global_index());
const auto elem_gidx = array::make_view<gidx_t, 1>(mesh.cells().global_index());
const auto elem_part = array::make_view<int, 1>(mesh.cells().partition());
//const auto elem_halo = array::make_view<int, 1>( mesh.cells().halo() );
auto check_flags = [&](idx_t jedge, int flag) {
idx_t ip1 = edge_nodes(jedge, 0);
idx_t ip2 = edge_nodes(jedge, 1);
return Topology::check(flags(ip1), flag) && Topology::check(flags(ip2), flag);
};
auto domain_bdry = [&](idx_t jedge) {
if (check_flags(jedge, Topology::BC | Topology::NORTH)) {
return true;
}
if (check_flags(jedge, Topology::BC | Topology::SOUTH)) {
return true;
}
if (check_flags(jedge, Topology::BC | Topology::WEST)) {
return true;
}
if (check_flags(jedge, Topology::BC | Topology::EAST)) {
return true;
}
return false;
};
auto periodic_east = [&](idx_t jedge) {
if (check_flags(jedge, Topology::PERIODIC | Topology::EAST)) {
return true;
}
return false;
};
auto periodic_west = [&](idx_t jedge) {
if (check_flags(jedge, Topology::PERIODIC | Topology::WEST)) {
return true;
}
return false;
};
auto periodic_west_bdry = [&](idx_t jedge) {
if (check_flags(jedge, Topology::PERIODIC | Topology::WEST | Topology::BC)) {
return true;
}
return false;
};
idx_t nb_edges = edges.size();
std::vector<gidx_t> bdry_edges;
bdry_edges.reserve(nb_edges);
std::map<gidx_t, idx_t> global_to_local;
PeriodicTransform transform_periodic_east(-360.);
PeriodicTransform transform_periodic_west(+360.);
UniqueLonLat _compute_uid(mesh);
auto compute_uid = [&](idx_t jedge) -> gidx_t {
if (periodic_east(jedge)) {
return -_compute_uid(edge_nodes.row(jedge), transform_periodic_east);
}
else if (periodic_west_bdry(jedge)) {
return _compute_uid(edge_nodes.row(jedge));
}
else if (periodic_west(jedge)) {
return -_compute_uid(edge_nodes.row(jedge), transform_periodic_west);
}
else {
return _compute_uid(edge_nodes.row(jedge));
}
};
// should be unit-test
{
ATLAS_ASSERT(util::unique_lonlat(360., 0., transform_periodic_east) == util::unique_lonlat(0., 0.));
ATLAS_ASSERT(util::unique_lonlat(0., 0., transform_periodic_west) == util::unique_lonlat(360., 0.));
}
for (idx_t jedge = 0; jedge < nb_edges; ++jedge) {
gidx_t edge_gidx = compute_uid(jedge);
global_to_local[edge_gidx] = jedge;
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge)) {
std::cout << "[" << mypart << "] " << EDGE(jedge) << " has gidx " << edge_gidx << std::endl;
if (periodic_east(jedge)) {
std::cout << "[" << mypart << "] " << EDGE(jedge) << " is periodic_east " << std::endl;
}
else if (periodic_west(jedge)) {
std::cout << "[" << mypart << "] " << EDGE(jedge) << " is periodic_west " << std::endl;
}
else {
std::cout << "[" << mypart << "] " << EDGE(jedge) << " is not periodic" << std::endl;
}
}
if (FIND_GIDX(edge_gidx))
std::cout << "[" << mypart << "] "
<< "has " << EDGE(jedge) << " with gidx " << edge_gidx << std::endl;
#endif
idx_t ip1 = edge_nodes(jedge, 0);
idx_t ip2 = edge_nodes(jedge, 1);
int pn1 = node_part(ip1);
int pn2 = node_part(ip2);
int y1 = util::microdeg(xy(ip1, YY));
int y2 = util::microdeg(xy(ip2, YY));
int p;
if (y1 == y2) {
int x1 = util::microdeg(xy(ip1, XX));
int x2 = util::microdeg(xy(ip2, XX));
p = (x1 < x2) ? pn1 : pn2;
}
else {
p = (y1 > y2) ? pn1 : pn2;
}
idx_t elem1 = edge_to_elem(jedge, 0);
idx_t elem2 = edge_to_elem(jedge, 1);
idx_t missing = edge_to_elem.missing_value();
if (elem1 == missing && elem2 == missing) {
// Don't attempt to change p
}
else if (elem1 == missing) {
ATLAS_NOTIMPLEMENTED;
}
else if (elem2 == missing) {
if (pn1 == pn2) {
p = pn1;
}
else if (periodic_east(jedge)) {
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge))
std::cout << "[" << mypart << "] "
<< "periodic_east" << std::endl;
#endif
bdry_edges.push_back(edge_gidx);
p = -1;
}
else if (periodic_west_bdry(jedge)) {
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge))
std::cout << "[" << mypart << "] "
<< "periodic_west_bdry" << std::endl;
#endif
p = elem_part(elem1);
}
else if (periodic_west(jedge)) {
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge))
std::cout << "[" << mypart << "] "
<< "periodic_west" << std::endl;
#endif
bdry_edges.push_back(edge_gidx);
p = -1;
}
else if (domain_bdry(jedge)) {
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge))
std::cout << "[" << mypart << "] "
<< "domain_bdry" << std::endl;
#endif
p = elem_part(elem1);
}
else {
bdry_edges.push_back(edge_gidx);
p = -1;
}
}
else if (p != elem_part(elem1) && p != elem_part(elem2)) {
p = (p == pn1) ? pn2 : pn1;
if (p != elem_part(elem1) and p != elem_part(elem2)) {
std::stringstream msg;
msg << "[" << mpi::rank() << "] " << EDGE(jedge) << " has nodes and elements of different rank: elem1[p"
<< elem_part(elem1) << "] elem2[p" << elem_part(elem2) << "]";
throw_Exception(msg.str(), Here());
}
}
edge_part(jedge) = p;
}
std::sort(bdry_edges.begin(), bdry_edges.end());
auto is_bdry_edge = [&bdry_edges](gidx_t gid) {
std::vector<uid_t>::iterator it = std::lower_bound(bdry_edges.begin(), bdry_edges.end(), gid);
bool found = !(it == bdry_edges.end() || gid < *it);
return found;
};
int mpi_size = mpi::size();
mpi::Buffer<gidx_t, 1> recv_bdry_edges_from_parts(mpi_size);
std::vector<std::vector<gidx_t>> send_gidx(mpi_size);
std::vector<std::vector<int>> send_part(mpi_size);
std::vector<std::vector<gidx_t>> send_bdry_gidx(mpi_size);
std::vector<std::vector<int>> send_bdry_elem_part(mpi_size);
std::vector<std::vector<gidx_t>> send_bdry_elem_gidx(mpi_size);
mpi::comm().allGatherv(bdry_edges.begin(), bdry_edges.end(), recv_bdry_edges_from_parts);
for (int p = 0; p < mpi_size; ++p) {
auto view = recv_bdry_edges_from_parts[p];
for (size_t j = 0; j < view.size(); ++j) {
gidx_t gidx = view[j];
gidx_t master_gidx = std::abs(gidx);
if (global_to_local.count(master_gidx)) {
idx_t iedge = global_to_local[master_gidx];
#ifdef DEBUGGING_PARFIELDS
if (FIND_GIDX(master_gidx))
std::cout << "[" << mypart << "] found " << EDGE(iedge) << std::endl;
#endif
if (not is_bdry_edge(master_gidx)) {
send_gidx[p].push_back(gidx);
send_part[p].push_back(edge_part(iedge));
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(iedge)) {
std::cout << "[" << mypart << "] found " << EDGE(iedge) " for part " << p << std::endl;
}
#endif
}
else { // boundary edge with nodes of different rank
idx_t ielem = (edge_to_elem(iedge, 0) != edge_to_elem.missing_value() ? edge_to_elem(iedge, 0)
: edge_to_elem(iedge, 1));
send_bdry_gidx[p].push_back(gidx);
send_bdry_elem_part[p].push_back(elem_part(ielem));
send_bdry_elem_gidx[p].push_back(elem_gidx(ielem));
}
}
}
}
std::vector<std::vector<gidx_t>> recv_gidx(mpi_size);
std::vector<std::vector<int>> recv_part(mpi_size);
mpi::comm().allToAll(send_gidx, recv_gidx);
mpi::comm().allToAll(send_part, recv_part);
for (int p = 0; p < mpi_size; ++p) {
const auto& recv_gidx_p = recv_gidx[p];
const auto& recv_part_p = recv_part[p];
for (size_t j = 0; j < recv_gidx_p.size(); ++j) {
idx_t iedge = global_to_local[recv_gidx_p[j]];
// int prev = edge_part( iedge );
edge_part(iedge) = recv_part_p[j];
// if( edge_part(iedge) != prev )
// Log::error() << EDGE(iedge) << " part " << prev << " --> " <<
// edge_part(iedge) << std::endl;
}
}
std::vector<std::vector<gidx_t>> recv_bdry_gidx(mpi_size);
std::vector<std::vector<int>> recv_bdry_elem_part(mpi_size);
std::vector<std::vector<gidx_t>> recv_bdry_elem_gidx(mpi_size);
mpi::comm().allToAll(send_bdry_gidx, recv_bdry_gidx);
mpi::comm().allToAll(send_bdry_elem_part, recv_bdry_elem_part);
mpi::comm().allToAll(send_bdry_elem_gidx, recv_bdry_elem_gidx);
for (int p = 0; p < mpi_size; ++p) {
const auto& recv_bdry_gidx_p = recv_bdry_gidx[p];
const auto& recv_bdry_elem_part_p = recv_bdry_elem_part[p];
const auto& recv_bdry_elem_gidx_p = recv_bdry_elem_gidx[p];
for (size_t j = 0; j < recv_bdry_gidx_p.size(); ++j) {
idx_t iedge = global_to_local[recv_bdry_gidx_p[j]];
idx_t e1 = (edge_to_elem(iedge, 0) != edge_to_elem.missing_value() ? edge_to_elem(iedge, 0)
: edge_to_elem(iedge, 1));
if (elem_gidx(e1) != recv_bdry_elem_gidx_p[j]) {
idx_t ip1 = edge_nodes(iedge, 0);
idx_t ip2 = edge_nodes(iedge, 1);
int pn1 = node_part(ip1);
int pn2 = node_part(ip2);
int y1 = util::microdeg(xy(ip1, YY));
int y2 = util::microdeg(xy(ip2, YY));
int ped;
if (y1 == y2) {
int x1 = util::microdeg(xy(ip1, XX));
int x2 = util::microdeg(xy(ip2, XX));
ped = (x1 < x2) ? pn1 : pn2;
}
else {
ped = (y1 > y2) ? pn1 : pn2;
}
int pe1 = elem_part(e1);
int pe2 = recv_bdry_elem_part_p[j];
if (ped != pe1 && ped != pe2) {
ped = (ped == pn1) ? pn2 : pn1;
if (ped != pe1 && p != pe2) {
std::stringstream msg;
msg << "[" << mpi::rank() << "] " << EDGE(iedge)
<< " has nodes and elements of different rank: elem1[p" << pe1 << "] elem2[p" << pe2 << "]";
throw_Exception(msg.str(), Here());
}
}
edge_part(iedge) = ped;
}
}
}
// Sanity check
auto edge_flags = array::make_view<int, 1>(edges.flags());
auto is_pole_edge = [&](idx_t e) { return Topology::check(edge_flags(e), Topology::POLE); };
bool has_pole_edges = false;
mesh.edges().metadata().get("pole_edges", has_pole_edges);
int insane = 0;
for (idx_t jedge = 0; jedge < nb_edges; ++jedge) {
idx_t ip1 = edge_nodes(jedge, 0);
idx_t ip2 = edge_nodes(jedge, 1);
idx_t elem1 = edge_to_elem(jedge, 0);
idx_t elem2 = edge_to_elem(jedge, 1);
int p = edge_part(jedge);
int pn1 = node_part(ip1);
int pn2 = node_part(ip2);
if (has_pole_edges && is_pole_edge(jedge)) {
if (p != pn1 || p != pn2) {
Log::error() << "pole edge " << EDGE(jedge) << " [p" << p << "] is not correct" << std::endl;
insane = 1;
}
}
else {
if (elem1 == edge_to_elem.missing_value() && elem2 == edge_to_elem.missing_value()) {
Log::error() << EDGE(jedge) << " has no neighbouring elements" << std::endl;
insane = 1;
}
}
bool edge_is_partition_boundary =
(elem1 == edge_to_elem.missing_value() || elem2 == edge_to_elem.missing_value());
bool edge_partition_is_same_as_one_of_nodes = (p == pn1 || p == pn2);
if (edge_is_partition_boundary) {
if (not edge_partition_is_same_as_one_of_nodes) {
gidx_t edge_gidx = compute_uid(jedge);
if (elem1 != edge_to_elem.missing_value()) {
Log::error() << "[" << mypart << "] " << EDGE(jedge) << " " << edge_gidx << " [p" << p
<< "] at partition_boundary is not correct. elem1[p" << elem_part(elem1) << "]"
<< std::endl;
}
else {
Log::error() << "[" << mypart << "] " << EDGE(jedge) << " " << edge_gidx << " [p" << p
<< "] at partition_boundary is not correct elem2[p" << elem_part(elem2) << "]"
<< std::endl;
}
insane = 1;
}
}
else {
int pe1 = elem_part(elem1);
int pe2 = elem_part(elem2);
bool edge_partition_is_same_as_one_of_elems = (p == pe1 || p == pe2);
if (not edge_partition_is_same_as_one_of_elems and not edge_partition_is_same_as_one_of_nodes) {
Log::error() << EDGE(jedge) << " is not correct elem1[p" << pe1 << "] elem2[p" << pe2 << "]"
<< std::endl;
insane = 1;
}
}
}
mpi::comm().allReduceInPlace(insane, eckit::mpi::max());
if (insane && mpi::rank() == 0) {
throw_Exception("Sanity check failed", Here());
}
//#ifdef DEBUGGING_PARFIELDS
// if( OWNED_EDGE(jedge) )
// DEBUG( EDGE(jedge) << " --> part " << edge_part(jedge));
//#endif
//#ifdef DEBUGGING_PARFIELDS_disable
// if( PERIODIC_EDGE(jedge) )
// DEBUG_VAR( " the part is " << edge_part(jedge) );
//#endif
// }
return edges.partition();
}
Field& build_edges_remote_idx(Mesh& mesh) {
ATLAS_TRACE();
const mesh::Nodes& nodes = mesh.nodes();
UniqueLonLat compute_uid(mesh);
idx_t mypart = mpi::rank();
idx_t nparts = mpi::size();
mesh::HybridElements& edges = mesh.edges();
auto edge_ridx = array::make_indexview<idx_t, 1>(edges.remote_index());
const array::ArrayView<int, 1> edge_part = array::make_view<int, 1>(edges.partition());
const mesh::HybridElements::Connectivity& edge_nodes = edges.node_connectivity();
array::ArrayView<const double, 2> xy = array::make_view<double, 2>(nodes.xy());
array::ArrayView<const int, 1> flags = array::make_view<int, 1>(nodes.flags());
#ifdef DEBUGGING_PARFIELDS
array::ArrayView<gidx_t, 1> node_gidx = array::make_view<gidx_t, 1>(nodes.global_index());
array::ArrayView<int, 1> node_part = array::make_view<int, 1>(nodes.partition());
#endif
auto edge_flags = array::make_view<int, 1>(edges.flags());
auto is_pole_edge = [&](idx_t e) { return Topology::check(edge_flags(e), Topology::POLE); };
bool has_pole_edges = false;
mesh.edges().metadata().get("pole_edges", has_pole_edges);
const int nb_edges = edges.size();
double centroid[2];
std::vector<std::vector<uid_t>> send_needed(mpi::size());
std::vector<std::vector<uid_t>> recv_needed(mpi::size());
int sendcnt = 0;
std::map<uid_t, int> lookup;
PeriodicTransform transform;
for (int jedge = 0; jedge < nb_edges; ++jedge) {
int ip1 = edge_nodes(jedge, 0);
int ip2 = edge_nodes(jedge, 1);
centroid[XX] = 0.5 * (xy(ip1, XX) + xy(ip2, XX));
centroid[YY] = 0.5 * (xy(ip1, YY) + xy(ip2, YY));
if (has_pole_edges && is_pole_edge(jedge)) {
centroid[YY] = centroid[YY] > 0 ? 90. : -90.;
}
bool needed(false);
if ((Topology::check(flags(ip1), Topology::PERIODIC) &&
!Topology::check(flags(ip1), Topology::BC | Topology::WEST) &&
Topology::check(flags(ip2), Topology::PERIODIC) &&
!Topology::check(flags(ip2), Topology::BC | Topology::WEST)) ||
(Topology::check(flags(ip1), Topology::PERIODIC) &&
!Topology::check(flags(ip1), Topology::BC | Topology::WEST) &&
Topology::check(flags(ip2), Topology::BC | Topology::WEST)) ||
(Topology::check(flags(ip1), Topology::BC | Topology::WEST) &&
Topology::check(flags(ip2), Topology::PERIODIC) &&
!Topology::check(flags(ip2), Topology::BC | Topology::WEST))) {
needed = true;
if (Topology::check(flags(ip1), Topology::EAST)) {
transform(centroid, -1);
}
else {
transform(centroid, +1);
}
}
uid_t uid = util::unique_lonlat(centroid);
if (idx_t(edge_part(jedge)) == mypart && !needed) // All interior edges fall here
{
lookup[uid] = jedge;
edge_ridx(jedge) = jedge;
#ifdef DEBUGGING_PARFIELDS
if (FIND_EDGE(jedge)) {
ATLAS_DEBUG("Found " << EDGE(jedge));
}
#endif
}
else // All ghost edges PLUS the periodic edges identified edges above
// fall here
{
send_needed[edge_part(jedge)].push_back(uid);
send_needed[edge_part(jedge)].push_back(jedge);
#ifdef DEBUGGING_PARFIELDS
send_needed[edge_part(jedge)].push_back(node_gidx(ip1));
send_needed[edge_part(jedge)].push_back(node_gidx(ip2));
send_needed[edge_part(jedge)].push_back(node_part(ip1));
send_needed[edge_part(jedge)].push_back(node_part(ip2));
#endif
sendcnt++;
}
}
idx_t varsize = 2;
#ifdef DEBUGGING_PARFIELDS
varsize = 6;
#endif
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_needed, recv_needed); }
std::vector<std::vector<int>> send_found(mpi::size());
std::vector<std::vector<int>> recv_found(mpi::size());
std::map<uid_t, int>::iterator found;
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<uid_t>& recv_edge = recv_needed[jpart];
const idx_t nb_recv_edges = idx_t(recv_edge.size()) / varsize;
// array::ArrayView<uid_t,2> recv_edge( recv_needed[ jpart ].data(),
// array::make_shape(recv_needed[ jpart ].size()/varsize,varsize) );
for (idx_t jedge = 0; jedge < nb_recv_edges; ++jedge) {
uid_t recv_uid = recv_edge[jedge * varsize + 0];
int recv_idx = recv_edge[jedge * varsize + 1];
found = lookup.find(recv_uid);
if (found != lookup.end()) {
send_found[jpart].push_back(recv_idx);
send_found[jpart].push_back(found->second);
}
else {
std::stringstream msg;
#ifdef DEBUGGING_PARFIELDS
msg << "Edge(" << recv_edge[jedge * varsize + 2] << "[p" << recv_edge[jedge * varsize + 4] << "] "
<< recv_edge[jedge * varsize + 3] << "[p" << recv_edge[jedge * varsize + 5] << "])";
#else
msg << "Edge with uid " << recv_uid;
#endif
msg << " requested by rank [" << jpart << "]";
msg << " that should be owned by " << mpi::rank()
<< " is not found. This could be because no "
"halo was built.";
// throw_Exception(msg.str(),Here());
Log::warning() << msg.str() << " @ " << Here() << std::endl;
}
}
}
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_found, recv_found); }
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<int>& recv_edge = recv_found[jpart];
const idx_t nb_recv_edges = recv_edge.size() / 2;
// array::ArrayView<int,2> recv_edge( recv_found[ jpart ].data(),
// array::make_shape(recv_found[ jpart ].size()/2,2) );
for (idx_t jedge = 0; jedge < nb_recv_edges; ++jedge) {
edge_ridx(recv_edge[jedge * 2 + 0]) = recv_edge[jedge * 2 + 1];
}
}
return edges.remote_index();
}
Field& build_edges_global_idx(Mesh& mesh) {
ATLAS_TRACE();
UniqueLonLat compute_uid(mesh);
int nparts = mpi::size();
idx_t root = 0;
mesh::HybridElements& edges = mesh.edges();
array::make_view<gidx_t, 1>(edges.global_index()).assign(-1);
array::ArrayView<gidx_t, 1> edge_gidx = array::make_view<gidx_t, 1>(edges.global_index());
const mesh::HybridElements::Connectivity& edge_nodes = edges.node_connectivity();
array::ArrayView<double, 2> xy = array::make_view<double, 2>(mesh.nodes().xy());
auto edge_flags = array::make_view<int, 1>(edges.flags());
auto is_pole_edge = [&](idx_t e) { return Topology::check(edge_flags(e), Topology::POLE); };
bool has_pole_edges = false;
mesh.edges().metadata().get("pole_edges", has_pole_edges);
/*
* Sorting following edge_gidx will define global order of
* gathered fields. Special care needs to be taken for
* pole edges, as their centroid might coincide with
* other edges
*/
double centroid[2];
int nb_edges = edges.size();
for (int jedge = 0; jedge < nb_edges; ++jedge) {
if (edge_gidx(jedge) <= 0) {
centroid[XX] = 0.5 * (xy(edge_nodes(jedge, 0), XX) + xy(edge_nodes(jedge, 1), XX));
centroid[YY] = 0.5 * (xy(edge_nodes(jedge, 0), YY) + xy(edge_nodes(jedge, 1), YY));
if (has_pole_edges && is_pole_edge(jedge)) {
centroid[YY] = centroid[YY] > 0 ? 90. : -90.;
}
edge_gidx(jedge) = util::unique_lonlat(centroid);
}
}
/*
* REMOTE INDEX BASE = 1
*/
// 1) Gather all global indices, together with location
array::ArrayT<uid_t> loc_edge_id_arr(nb_edges);
array::ArrayView<uid_t, 1> loc_edge_id = array::make_view<uid_t, 1>(loc_edge_id_arr);
for (int jedge = 0; jedge < nb_edges; ++jedge) {
loc_edge_id(jedge) = edge_gidx(jedge);
}
std::vector<int> recvcounts(mpi::size());
std::vector<int> recvdispls(mpi::size());
ATLAS_TRACE_MPI(GATHER) { mpi::comm().gather(nb_edges, recvcounts, root); }
recvdispls[0] = 0;
for (int jpart = 1; jpart < nparts; ++jpart) // start at 1
{
recvdispls[jpart] = recvcounts[jpart - 1] + recvdispls[jpart - 1];
}
int glb_nb_edges = std::accumulate(recvcounts.begin(), recvcounts.end(), 0);
array::ArrayT<uid_t> glb_edge_id_arr(glb_nb_edges);
array::ArrayView<uid_t, 1> glb_edge_id = array::make_view<uid_t, 1>(glb_edge_id_arr);
ATLAS_TRACE_MPI(GATHER) {
mpi::comm().gatherv(loc_edge_id.data(), loc_edge_id.size(), glb_edge_id.data(), recvcounts.data(),
recvdispls.data(), root);
}
// 2) Sort all global indices, and renumber from 1 to glb_nb_edges
std::vector<Node> edge_sort;
edge_sort.reserve(glb_nb_edges);
for (idx_t jedge = 0; jedge < glb_edge_id.shape(0); ++jedge) {
edge_sort.emplace_back(Node(glb_edge_id(jedge), jedge));
}
std::sort(edge_sort.begin(), edge_sort.end());
// Assume edge gid start
uid_t gid(0);
for (size_t jedge = 0; jedge < edge_sort.size(); ++jedge) {
if (jedge == 0) {
++gid;
}
else if (edge_sort[jedge].g != edge_sort[jedge - 1].g) {
++gid;
}
int iedge = edge_sort[jedge].i;
glb_edge_id(iedge) = gid;
}
// 3) Scatter renumbered back
ATLAS_TRACE_MPI(SCATTER) {
mpi::comm().scatterv(glb_edge_id.data(), recvcounts.data(), recvdispls.data(), loc_edge_id.data(),
loc_edge_id.size(), root);
}
for (int jedge = 0; jedge < nb_edges; ++jedge) {
edge_gidx(jedge) = loc_edge_id(jedge);
}
return edges.global_index();
}
//----------------------------------------------------------------------------------------------------------------------
Field& build_cells_remote_idx(mesh::Cells& cells, const mesh::Nodes& nodes) {
ATLAS_TRACE();
idx_t mypart = static_cast<idx_t>(mpi::rank());
idx_t nparts = static_cast<idx_t>(mpi::size());
UniqueLonLat compute_uid(nodes);
// This piece should be somewhere central ... could be NPROMA ?
// ---------->
std::vector<idx_t> proc(nparts);
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
proc[jpart] = jpart;
}
// <---------
auto ridx = array::make_indexview<idx_t, 1>(cells.remote_index());
auto part = array::make_view<int, 1>(cells.partition());
const auto& element_nodes = cells.node_connectivity();
idx_t nb_cells = cells.size();
idx_t varsize = 2;
std::vector<std::vector<uid_t>> send_needed(mpi::size());
std::vector<std::vector<uid_t>> recv_needed(mpi::size());
int sendcnt = 0;
std::map<uid_t, int> lookup;
for (idx_t jcell = 0; jcell < nb_cells; ++jcell) {
uid_t uid = compute_uid(element_nodes.row(jcell));
if (idx_t(part(jcell)) == mypart) {
lookup[uid] = jcell;
ridx(jcell) = jcell;
}
else {
ATLAS_ASSERT(jcell < part.shape(0));
if (part(jcell) >= static_cast<int>(proc.size())) {
std::stringstream msg;
msg << "Assertion [part(" << jcell << ") < proc.size()] failed\n"
<< "part(" << jcell << ") = " << part(jcell) << "\n"
<< "proc.size() = " << proc.size();
throw_AssertionFailed(msg.str(), Here());
}
ATLAS_ASSERT(part(jcell) < (idx_t)proc.size());
ATLAS_ASSERT((size_t)proc[part(jcell)] < send_needed.size());
send_needed[proc[part(jcell)]].push_back(uid);
send_needed[proc[part(jcell)]].push_back(jcell);
sendcnt++;
}
}
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_needed, recv_needed); }
std::vector<std::vector<int>> send_found(mpi::size());
std::vector<std::vector<int>> recv_found(mpi::size());
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<uid_t>& recv_cell = recv_needed[proc[jpart]];
const idx_t nb_recv_cells = idx_t(recv_cell.size()) / varsize;
// array::ArrayView<uid_t,2> recv_node( make_view( Array::wrap(shape,
// recv_needed[ proc[jpart] ].data()) ),
// array::make_shape(recv_needed[ proc[jpart] ].size()/varsize,varsize)
// );
for (idx_t jcell = 0; jcell < nb_recv_cells; ++jcell) {
uid_t uid = recv_cell[jcell * varsize + 0];
int icell = recv_cell[jcell * varsize + 1];
if (lookup.count(uid)) {
send_found[proc[jpart]].push_back(icell);
send_found[proc[jpart]].push_back(lookup[uid]);
}
else {
std::stringstream msg;
msg << "[" << mpi::rank() << "] "
<< "Node requested by rank [" << jpart << "] with uid [" << uid
<< "] that should be owned is not found";
throw_Exception(msg.str(), Here());
}
}
}
ATLAS_TRACE_MPI(ALLTOALL) { mpi::comm().allToAll(send_found, recv_found); }
for (idx_t jpart = 0; jpart < nparts; ++jpart) {
const std::vector<int>& recv_cell = recv_found[proc[jpart]];
const idx_t nb_recv_cells = recv_cell.size() / 2;
// array::ArrayView<int,2> recv_node( recv_found[ proc[jpart] ].data(),
// array::make_shape(recv_found[ proc[jpart] ].size()/2,2) );
for (idx_t jcell = 0; jcell < nb_recv_cells; ++jcell) {
ridx(recv_cell[jcell * 2 + 0]) = recv_cell[jcell * 2 + 1];
}
}
return cells.remote_index();
}
void build_cells_parallel_fields(Mesh& mesh) {
bool parallel = false;
mesh.cells().metadata().get("parallel", parallel);
if (!parallel) {
build_cells_remote_idx(mesh.cells(), mesh.nodes());
}
mesh.cells().metadata().set("parallel", true);
}
//----------------------------------------------------------------------------------------------------------------------
// C wrapper interfaces to C++ routines
void atlas__build_parallel_fields(Mesh::Implementation* mesh) {
ATLAS_ASSERT(mesh != nullptr, "Cannot access uninitialised atlas_Mesh");
Mesh m(mesh);
build_parallel_fields(m);
}
void atlas__build_nodes_parallel_fields(mesh::Nodes* nodes) {
ATLAS_ASSERT(nodes != nullptr, "Cannot access uninitialised atlas_mesh_Nodes");
build_nodes_parallel_fields(*nodes);
}
void atlas__build_edges_parallel_fields(Mesh::Implementation* mesh) {
ATLAS_ASSERT(mesh != nullptr, "Cannot access uninitialised atlas_Mesh");
Mesh m(mesh);
build_edges_parallel_fields(m);
}
void atlas__renumber_nodes_glb_idx(mesh::Nodes* nodes) {
ATLAS_ASSERT(nodes != nullptr, "Cannot access uninitialised atlas_mesh_Nodes");
renumber_nodes_glb_idx(*nodes);
}
//----------------------------------------------------------------------------------------------------------------------
} // namespace actions
} // namespace mesh
} // namespace atlas
| 38.929793 | 120 | 0.540357 | [
"mesh",
"shape",
"vector",
"transform"
] |
10d6898bc030310a31cbe167560427311a31d969 | 287 | cpp | C++ | 1389-create-target-array-in-the-given-order/1389-create-target-array-in-the-given-order.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 1389-create-target-array-in-the-given-order/1389-create-target-array-in-the-given-order.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 1389-create-target-array-in-the-given-order/1389-create-target-array-in-the-given-order.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> createTargetArray(vector<int>& arr, vector<int>& index) {
vector<int> v;
int n = arr.size();
int ans =0;
for(int i=0;i<n;i++){
v.insert(v.begin()+ index[i], arr[i]);
}
return v;
}
}; | 23.916667 | 73 | 0.487805 | [
"vector"
] |
10d708fdc3ca2db32016cf9216b2fb9b6fd686b1 | 5,082 | cpp | C++ | common/common.cpp | quorten/Quacks-Core | dcea7e99ae5e30b3464e56f4c202c99ee6a05ac4 | [
"Unlicense"
] | null | null | null | common/common.cpp | quorten/Quacks-Core | dcea7e99ae5e30b3464e56f4c202c99ee6a05ac4 | [
"Unlicense"
] | null | null | null | common/common.cpp | quorten/Quacks-Core | dcea7e99ae5e30b3464e56f4c202c99ee6a05ac4 | [
"Unlicense"
] | null | null | null | //Functions common to all programs
#include "common.h"
using std::vector;
using std::string;
//Function implimentions
void EncodeText(char* pData)
{
for (unsigned long i = 0; pData[i] != 0; i++)
pData[i] += 128;
}
void DecodeText(char* pData)
{
for (unsigned long i = 0; pData[i] != 0; i++)
pData[i] -= 128;
}
/*Note for out binary handling functions:
The binary data handling functions are
meant to handle unknown "chunks" of data.
The data is stored as follows:
1. A pointer points to an unsigned 32-bit integer.
2. That integer indicates the size of the preceding
unknown data.*/
void EncodeBinary(void* pData)
{
char* pData2 = (char*)pData; //All the casting to char* was moved to here
unsigned long* pDataSize = SizeofBinData(pData2);
pData2 += 4;
for (unsigned long i = 0; i < *pDataSize; i++)
pData2[i] += 128;
pData2 -= 4;
}
void DecodeBinary(void* pData)
{
char* pData2 = (char*)pData; //All the casting to char* was moved to here
unsigned long* pDataSize = SizeofBinData(pData2);
pData2 += 4;
for (unsigned long i = 0; i < *pDataSize; i++)
pData2[i] -= 128;
pData2 -= 4;
}
inline unsigned long* SizeofBinData(void* pData)
{ return reinterpret_cast<unsigned long*>(pData); }
PHEAP_DATA ReadBinaryFile(const char* pFilename)
{
//Binary file handling is done with windows API's (but it shouldn't be)
unsigned long bytesRead;
HANDLE hFile = CreateFile(pFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, NULL, NULL);
unsigned long dataSize = GetFileSize(hFile, NULL);
char* phInData = new char[dataSize];
ReadFile(hFile, phInData, dataSize, &bytesRead, NULL);
CloseHandle(hFile);
unsigned char* phOutData = new unsigned char[4+dataSize];
memcpy(phOutData, &dataSize, 4);
memcpy(phOutData + 4, phInData, dataSize);
delete []phInData;
return phOutData;
}
bool WriteBinaryFile(const char* pFilename, void* pData)
{
//Binary file handling is done with windows API's (but it shouldn't be)
unsigned long bytesWritten;
HANDLE hFile = CreateFile(pFilename, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == NULL)
return false;
WriteFile(hFile, (char*)pData + 4, *SizeofBinData(pData), &bytesWritten, NULL);
CloseHandle(hFile);
return true;
}
void IntractWebsiteFiles(HANDLE hUpdate, bool bDeleteExternal, bool bUseGuestFiles)
{
vector<string> dirContents;
unsigned short numStorageToUse;
unsigned short storageAreaToUse;
char* phText; //Temporary storage for encoding phText
if (bUseGuestFiles == true)
{
numStorageToUse = NUM_GUESTFILES;
storageAreaToUse = GUESTFILES_START;
}
else
{
numStorageToUse = NUM_WEBFILES;
storageAreaToUse = WEBFILES_START;
}
phText = new char[1000];
GetCurrentDirectory(1000, phText);
ListDirectoryContents(phText, dirContents);
delete []phText;
unsigned long numWebFiles = dirContents.size();
UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(numStorageToUse), NULL, &numWebFiles, 4);
for (unsigned long i = 0; i < dirContents.size(); i++)
{
//Do the data
PHEAP_DATA phData = ReadBinaryFile(dirContents[i].c_str());
EncodeBinary(phData);
UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(storageAreaToUse+i*2), NULL, phData, 4 + *SizeofBinData(phData));
delete []phData;
//Do the name
phText = new char[dirContents[i].size()+1];
strcpy(phText, dirContents[i].c_str());
EncodeText(phText);
UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(storageAreaToUse+i*2+1), NULL, phText, dirContents[i].size()+1);
delete []phText;
if (bDeleteExternal)
remove(dirContents[i].c_str());
}
}
bool ListDirectoryContents(char* targetDir, vector<string>& fileList)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char DirSpec[MAX_PATH + 1]; // directory specification
DWORD dwError;
//printf ("Target directory is %s.\n", targetDir);
if (strlen(targetDir) + 3 < MAX_PATH)
{
strncpy (DirSpec, targetDir, strlen(targetDir)+1);
strncat (DirSpec, "\\*", 3);
}
else
return false;
hFind = FindFirstFile(DirSpec, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
//printf ("Invalid file handle. Error is %u\n", GetLastError());
return false;
}
else
{
string filename = FindFileData.cFileName;
if (filename.find(".") != 0 && filename.find(".exe") == string::npos) //We don't want ".", "..", or logon.exe
fileList.push_back(FindFileData.cFileName);
while (FindNextFile(hFind, &FindFileData) != 0)
{
filename = FindFileData.cFileName;
if (filename.find(".") != 0 && filename.find(".exe") == string::npos) //We don't want ".", "..", or logon.exe
fileList.push_back(FindFileData.cFileName);
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
//printf ("FindNextFile error. Error is %u\n", dwError);
return false;
}
}
return true;
} | 29.375723 | 119 | 0.67198 | [
"vector"
] |
10e6a2878a6ec9f61d50781b6361ec659cc49104 | 7,374 | cpp | C++ | src/core/type/objectptrtype.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/core/type/objectptrtype.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/core/type/objectptrtype.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | /*
Copyright 2009-2021 Nicolas Colombe
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 <core/type/objectptrtype.hpp>
#include <core/type/typemanager.hpp>
#include <core/type/classtype.hpp>
#include <core/lua/luaconverter.hpp>
namespace eXl
{
#if 0
IMPLEMENT_RTTI(ObjectPtrType);
ObjectPtrType::ObjectPtrType()
:CoreType(TypeTraits::GetName<RttiOPtr>(),
0,
TypeTraits::GetSize<RttiOPtr>(),
Type_Is_CoreType)
,m_Rtti(RttiObjectRefC::StaticRtti())
{
//m_Flags |= Dynamic;
}
ObjectPtrType::ObjectPtrType(Rtti const& iRtti)
: CoreType(TypeName(TypeTraits::GetName<RttiOPtr>() + iRtti.GetName()),
0,
TypeTraits::GetSize<RttiOPtr>(),
Type_Is_CoreType)
,m_Rtti(iRtti)
{
//m_Flags |= Dynamic;
}
void* ObjectPtrType::Alloc()const
{
return TypeTraits::Alloc<RttiOPtr>();
}
void ObjectPtrType::Free(void* iObj)const
{
TypeTraits::Free<RttiOPtr>(iObj);
}
void* ObjectPtrType::Construct(void* iObj)const
{
void* obj = TypeTraits::DefaultCTor<RttiOPtr>(iObj);
ClassType const* classType = TypeManager::GetClassForRtti(m_Rtti);
if(classType)
{
void* newObj = nullptr;
classType->Build(newObj, nullptr);
if(newObj != nullptr)
{
*reinterpret_cast<RttiOPtr*>(obj) = reinterpret_cast<RttiObjectRefC*>(newObj);
}
}
return obj;
}
void ObjectPtrType::Destruct(void* iObj)const
{
TypeTraits::DTor<RttiOPtr>(iObj);
}
Err ObjectPtrType::Unstream_Uninit(void* oData, Unstreamer* iUnstreamer)const
{
Err err = iUnstreamer->BeginStruct();
if(err)
err = iUnstreamer->PushKey("ObjectPointer");
String tempVal;
if(err)
err = iUnstreamer->ReadString(&tempVal);
if(StringUtil::ToASCII(tempVal) != m_Rtti.GetName())
{
LOG_ERROR<<"Wrong pointer class : " << tempVal <<" expected "<<m_Rtti.GetName() <<"\n";
err = Err::Error;
}
if(err)
err = iUnstreamer->PopKey();
if(err)
err = iUnstreamer->PushKey("Value");
TypeTraits::DefaultCTor<RttiOPtr>(oData);
void* obj = nullptr;
if(err)
{
err = ClassType::DynamicUnstream(obj,iUnstreamer);
if(err)
{
if(obj != nullptr)
*reinterpret_cast<RttiOPtr*>(oData) = reinterpret_cast<RttiObjectRefC*>(obj);
else
err = Err::Error;
if(err)
err = iUnstreamer->PopKey();
}
}
if(err)
err = iUnstreamer->EndStruct();
return err;
}
Err ObjectPtrType::Stream(void const* iData, Streamer* iStreamer)const
{
RttiObject const* obj = reinterpret_cast<RttiOPtr const*>(iData)->get();
ClassType const* classType;
Err err = iStreamer->BeginStruct();
if(err)
err = iStreamer->PushKey("ObjectPointer");
if(err)
err = iStreamer->WriteString(StringUtil::FromASCII(m_Rtti.GetName()));
if(err)
err = iStreamer->PopKey();
if(err)
{
if(obj != nullptr)
{
classType = nullptr;
//classType = obj->GetClassType();
if(classType == nullptr)
err = Err::Error;
if(err)
err = iStreamer->PushKey("Value");
if(err)
err = classType->Stream(obj,iStreamer);
if(err)
err = iStreamer->PopKey();
}
}
if(err)
err = iStreamer->EndStruct();
return err;
}
Err ObjectPtrType::Copy_Uninit(void const* iData, void* oData) const
{
if(iData != nullptr)
{
RttiObject const* origObj = reinterpret_cast<RttiOPtr const*>(iData)->get();
if(origObj != nullptr)
{
//ClassType const* classType = origObj->GetClassType();
ClassType const* classType = nullptr;
if(classType)
{
void* obj = classType->Copy(origObj);
if(obj != nullptr)
{
TypeTraits::DefaultCTor<RttiOPtr>(oData);
*reinterpret_cast<RttiOPtr*>(oData) = reinterpret_cast<RttiObjectRefC*>(obj);
RETURN_SUCCESS;
}
}
}
}
RETURN_FAILURE;
}
#ifdef EXL_LUA
luabind::object ObjectPtrType::ConvertToLua(void const* iObj,lua_State* iState)const
{
if(iState==nullptr)
return luabind::object();
return eXl::LuaConverter<RttiOPtr>::ConvertToLua(iObj,this,iState);
}
Err ObjectPtrType::ConvertFromLua_Uninit(lua_State* iState,unsigned int& ioIndex,void* oObj)const
{
if(iState==nullptr)
RETURN_FAILURE;
if(oObj==nullptr)
RETURN_FAILURE;
eXl::LuaConverter<RttiOPtr>::ConvertFromLua(this,oObj,iState,ioIndex);
RETURN_SUCCESS;
}
#endif
Err ObjectPtrType::Compare(void const* iVal1, void const* iVal2, CompRes& oRes)const
{
if(iVal1 == nullptr || iVal2 == nullptr)
RETURN_FAILURE;
oRes = TypeTraits::Compare<RttiOPtr>(iVal1,iVal2);
RETURN_SUCCESS;
}
bool ObjectPtrType::CanAssignFrom(Type const* iOtherType) const
{
if(iOtherType == this)
return true;
else
{
ObjectPtrType const* otherObject = ObjectPtrType::DynamicCast(iOtherType);
if(otherObject)
{
if(otherObject->GetMinimalRtti().IsKindOf(m_Rtti))
{
return true;
}
}
else
{
return false;
}
}
return false;
}
Err ObjectPtrType::Assign_Uninit(Type const* inputType, void const* iData, void* oData) const
{
if(iData != nullptr && oData != nullptr && CanAssignFrom(inputType))
{
TypeTraits::Copy<RttiOPtr>(oData,iData);
RETURN_SUCCESS;
}
RETURN_FAILURE;
}
bool ObjectPtrType::Isnullptr(void const* iData) const
{
if(iData)
{
return reinterpret_cast<RttiOPtr const*>(iData)->get() == nullptr;
}
return true;
}
ClassType const* ObjectPtrType::GetObjectType(void const* iData) const
{
if(iData)
{
RttiOPtr const* ptr = reinterpret_cast<RttiOPtr const*>(iData);
if(ptr != nullptr && ptr->get() != nullptr)
{
//return ptr->get()->GetClassType();
return nullptr;
}
}
return nullptr;
}
Rtti const* ObjectPtrType::GetObjectRtti(void const* iData) const
{
if(iData)
{
RttiOPtr const& ptr = *reinterpret_cast<RttiOPtr const*>(iData);
if(ptr != nullptr)
{
return &ptr->GetRtti();
}
}
return nullptr;
}
#endif
} | 27.110294 | 460 | 0.634255 | [
"object"
] |
10e715a9bbe2bc43ae993079ad7869e1902335a8 | 559 | cc | C++ | accepted/584a.cc | cbarnson/codeforces-cpp | adf0ee2d71a8abbec1e111013bf9bfa7cda02395 | [
"MIT"
] | 1 | 2019-06-14T02:21:30.000Z | 2019-06-14T02:21:30.000Z | accepted/584a.cc | cbarnson/codeforces-cpp | adf0ee2d71a8abbec1e111013bf9bfa7cda02395 | [
"MIT"
] | null | null | null | accepted/584a.cc | cbarnson/codeforces-cpp | adf0ee2d71a8abbec1e111013bf9bfa7cda02395 | [
"MIT"
] | null | null | null | // Problem # : 584a
// Created on : 2018-10-21 13:23:26
#include <bits/stdc++.h>
#define FR(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, t;
cin >> n >> t;
if (t == 10) {
if (n < 2)
cout << -1 << endl;
else {
cout << 1 << string(n - 1, '0') << endl;
}
} else {
cout << string(n, (char)(t + '0')) << endl;
}
}
| 18.633333 | 50 | 0.468694 | [
"vector"
] |
10e74877fa9f6f785dfe0e53cb37a11195b34be1 | 6,187 | cpp | C++ | cxx/isce3/polsar/symmetrize.cpp | isce-framework/isce3 | 59cdd2c659a4879367db5537604b0ca93d26b372 | [
"Apache-2.0"
] | 64 | 2019-08-06T19:22:22.000Z | 2022-03-20T17:11:46.000Z | cxx/isce3/polsar/symmetrize.cpp | isce-framework/isce3 | 59cdd2c659a4879367db5537604b0ca93d26b372 | [
"Apache-2.0"
] | 8 | 2020-09-01T22:46:53.000Z | 2021-11-04T00:05:28.000Z | cxx/isce3/polsar/symmetrize.cpp | isce-framework/isce3 | 59cdd2c659a4879367db5537604b0ca93d26b372 | [
"Apache-2.0"
] | 29 | 2019-08-05T21:40:55.000Z | 2022-03-23T00:17:03.000Z | #include "symmetrize.h"
#include <isce3/core/DenseMatrix.h>
#include <isce3/geocode/GeocodeCov.h>
#include <isce3/geometry/RTC.h>
#include <isce3/math/ComplexMultiply.h>
namespace isce3 { namespace polsar {
static void _validate_rasters(isce3::io::Raster& raster_a,
std::string raster_a_name, int raster_a_band,
isce3::io::Raster& raster_b, std::string raster_b_name,
int raster_b_band)
{
std::string error_msg;
if (raster_a_band < 1 || raster_a_band > raster_a.numBands()) {
error_msg = " Invalid band for " + raster_a_name + ": " +
std::to_string(raster_a_band);
throw isce3::except::InvalidArgument(ISCE_SRCINFO(), error_msg);
}
if (raster_b_band < 1 || raster_b_band > raster_b.numBands()) {
error_msg = " Invalid band for " + raster_b_name + ": " +
std::to_string(raster_b_band);
throw isce3::except::InvalidArgument(ISCE_SRCINFO(), error_msg);
}
error_msg = "ERROR the ";
error_msg += raster_a_name;
error_msg += " and ";
error_msg += raster_b_name;
if (raster_a.length() != raster_b.length()) {
error_msg += " raster dimensions to not match";
throw isce3::except::InvalidArgument(ISCE_SRCINFO(), error_msg);
}
if (raster_a.width() != raster_b.width()) {
error_msg += " raster dimensions to not match";
throw isce3::except::InvalidArgument(ISCE_SRCINFO(), error_msg);
}
if (GDALDataTypeIsComplex(raster_a.dtype(raster_a_band)) xor
GDALDataTypeIsComplex(raster_b.dtype(raster_b_band))) {
error_msg += " raster data type to not match";
throw isce3::except::InvalidArgument(ISCE_SRCINFO(), error_msg);
}
}
template<typename T>
void _symmetrizeCrossPolChannels(isce3::io::Raster& hv_raster,
isce3::io::Raster& vh_raster, isce3::io::Raster& output_raster,
const long x0, const long block_width, const long y0,
const long block_length, const int hv_raster_band,
const int vh_raster_band, const int output_raster_band)
{
using namespace isce3::math::complex_multiply;
// Read HV array
isce3::core::Matrix<T> hv_array(block_length, block_width);
hv_raster.getBlock(
hv_array.data(), x0, y0, block_width, block_length, hv_raster_band);
// Read VH array
isce3::core::Matrix<T> vh_array(block_length, block_width);
vh_raster.getBlock(
vh_array.data(), x0, y0, block_width, block_length, vh_raster_band);
// Compute output
isce3::core::Matrix<T> output_array(block_length, block_width);
_Pragma("omp parallel for schedule(dynamic)") for (long i = 0;
i < block_length; ++i)
{
for (long j = 0; j < block_width; ++j) {
output_array(i, j) = 0.5 * (hv_array(i, j) + vh_array(i, j));
}
}
// Set output block
output_raster.setBlock(output_array.data(), x0, y0, block_width,
block_length, output_raster_band);
}
void symmetrizeCrossPolChannels(isce3::io::Raster& hv_raster,
isce3::io::Raster& vh_raster, isce3::io::Raster& output_raster,
isce3::core::MemoryModeBlockY memory_mode, int hv_raster_band,
int vh_raster_band, int output_raster_band)
{
pyre::journal::info_t info("isce3.polsar.symmetrizeCrossPolChannels");
info << "Symmetrizing cross-polarimetric channels (HV and VH)"
<< pyre::journal::endl;
_validate_rasters(
hv_raster, "HV", hv_raster_band, vh_raster, "VH", vh_raster_band);
_validate_rasters(hv_raster, "HV", hv_raster_band, output_raster, "output",
output_raster_band);
const long x0 = 0;
auto block_width = hv_raster.width();
int block_length, nblocks;
switch (memory_mode) {
case isce3::core::MemoryModeBlockY::SingleBlockY:
nblocks = 1;
block_length = static_cast<int>(hv_raster.length());
break;
case isce3::core::MemoryModeBlockY::AutoBlocksY: [[fallthrough]];
case isce3::core::MemoryModeBlockY::MultipleBlocksY:
const int out_nbands = 1;
isce3::geocode::getBlocksNumberAndLength(hv_raster.length(),
hv_raster.width(), out_nbands,
GDALGetDataTypeSizeBytes(hv_raster.dtype()), &info,
&block_length, &nblocks);
}
for (int block = 0; block < nblocks; ++block) {
const long y0 = block * block_length;
int this_block_length = block_length;
if ((block + 1) * block_length > hv_raster.length()) {
this_block_length = hv_raster.length() % block_length;
}
if (nblocks > 1) {
info << "symmetrizing block: " << block + 1 << "/" << nblocks
<< pyre::journal::endl;
}
if (hv_raster.dtype() == GDT_Float32)
_symmetrizeCrossPolChannels<float>(hv_raster, vh_raster,
output_raster, x0, block_width, y0, this_block_length,
hv_raster_band, vh_raster_band, output_raster_band);
else if (hv_raster.dtype() == GDT_Float64)
_symmetrizeCrossPolChannels<double>(hv_raster, vh_raster,
output_raster, x0, block_width, y0, this_block_length,
hv_raster_band, vh_raster_band, output_raster_band);
else if (hv_raster.dtype() == GDT_CFloat32)
_symmetrizeCrossPolChannels<std::complex<float>>(hv_raster,
vh_raster, output_raster, x0, block_width, y0,
this_block_length, hv_raster_band, vh_raster_band,
output_raster_band);
else if (hv_raster.dtype() == GDT_CFloat64)
_symmetrizeCrossPolChannels<std::complex<double>>(hv_raster,
vh_raster, output_raster, x0, block_width, y0,
this_block_length, hv_raster_band, vh_raster_band,
output_raster_band);
else {
std::string error_message =
"ERROR not implemented for input raster datatype";
throw isce3::except::RuntimeError(ISCE_SRCINFO(), error_message);
}
}
}
}} // namespace isce3::polsar
| 39.407643 | 80 | 0.63197 | [
"geometry"
] |
10ecbda1051421d9eca37725c169723b6ea177e9 | 2,736 | cpp | C++ | code archive/CF/894D.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/CF/894D.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/CF/894D.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | //{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<int,int> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
const ll MAXn=1e6+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
ii p[MAXn];
vector<ii> v[MAXn],dt[MAXn];
vector<ll> pre[MAXn];
void dfs(ll now)
{
dt[now].pb(ii(0,now));
for(ii &k:v[now])
{
dfs(k.X);
for(ii &tmp:dt[k.X])dt[now].pb(ii(tmp.X+k.Y,tmp.Y));
//dt[now].pb(ii(k.Y,k.X));
}
if(SZ(v[now])==2)inplace_merge(dt[now].begin()+1,dt[now].begin()+1+SZ(dt[v[now][0].X]),dt[now].end());
pre[now].pb(0);
for(ii &tmp:dt[now])pre[now].pb(pre[now].back()+tmp.X);
}
int main()
{
IOS();
ll q,n;
cin>>n>>q;
REP1(i,n-1)
{
ll t;
cin>>t;
p[i+1]=ii((i+1)/2,t);
v[(i+1)/2].pb(ii(i+1,t));
}
dfs(1);
REP1(i,n)debug(i,dt[i],pre[i]);
REP(T,q)
{
ll x,h;
cin>>x>>h;
ll ct=0,tt=0,s=0,tmph=h;
while(h>0)
{
ll a=lower_bound(ALL(dt[x]),ii(h,-1))-dt[x].begin();
tt+=pre[x][a]+a*s;ct+=a;
debug(T,dt[x],pre[x],s,h,a,ct,tt);
if(x==1)break;
ll b=lower_bound(ALL(dt[x]),ii(h-2*p[x].Y,-1))-dt[x].begin();
ct-=b;tt-=pre[x][b]+(p[x].Y)*b+b*(s+p[x].Y);
debug(T,h,b,ct,tt);
s+=p[x].Y,h-=p[x].Y;x=p[x].X;
}
cout<<ct*tmph-tt<<endl;
}
}
| 26.307692 | 129 | 0.563596 | [
"vector"
] |
10edcac128070b4684726cb92331d643888e2520 | 282 | cpp | C++ | CodeForces/Gravity Flip.cpp | Danish-Belal/CodeCollection | cd3914d3d73542dd5f20755c4b1e42906f443b03 | [
"MIT"
] | 125 | 2021-10-01T19:05:26.000Z | 2021-10-03T13:32:42.000Z | CodeForces/Gravity Flip.cpp | Danish-Belal/CodeCollection | cd3914d3d73542dd5f20755c4b1e42906f443b03 | [
"MIT"
] | 201 | 2021-10-30T20:40:01.000Z | 2022-03-22T17:26:28.000Z | CodeForces/Gravity Flip.cpp | Danish-Belal/CodeCollection | cd3914d3d73542dd5f20755c4b1e42906f443b03 | [
"MIT"
] | 294 | 2021-10-01T18:46:05.000Z | 2021-10-03T14:25:07.000Z | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,a;
vector<int>v;
cin>>n;
while(n--)
{
cin>>a;
v.push_back(a);
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
return 0;
}
| 14.1 | 31 | 0.432624 | [
"vector"
] |
10eecf8aa2bda035a6ac442a090ad5e29ed5f2f4 | 8,159 | cpp | C++ | src/cfdcore_logger.cpp | ko-matsu/cfd-core | ad07f210cfefe7838a6eaf4ce0e13a27c0d6167e | [
"MIT"
] | 5 | 2019-10-12T11:05:26.000Z | 2020-05-10T19:09:19.000Z | src/cfdcore_logger.cpp | ko-matsu/cfd-core | ad07f210cfefe7838a6eaf4ce0e13a27c0d6167e | [
"MIT"
] | 128 | 2019-10-02T06:33:49.000Z | 2022-03-20T02:14:35.000Z | src/cfdcore_logger.cpp | p2pderivatives/cfd-core | 399750cb1fa320f3b203092290ebb9f3ed4fe742 | [
"MIT"
] | 4 | 2019-10-22T07:59:43.000Z | 2020-05-29T11:06:00.000Z | // Copyright 2019 CryptoGarage
/**
* @file cfdcore_logger.cpp
* @brief implementation of logger
*/
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// clang-format off
#include "quill/LogLevel.h"
#ifdef CFDCORE_LOGGING
#include "quill/Logger.h"
#include "quill/Fmt.h"
#include "quill/Quill.h"
#include "quill/LogMacroMetadata.h"
#ifdef CFDCORE_LOG_CONSOLE
#include "quill/handlers/ConsoleHandler.h"
#endif // CFDCORE_LOG_CONSOLE
#endif // CFDCORE_LOGGING
// clang-format on
#include "cfdcore/cfdcore_exception.h"
#include "cfdcore/cfdcore_logger.h"
#include "cfdcore/cfdcore_logger_interface.h"
#include "cfdcore/cfdcore_util.h"
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
/// instance of CfdLogger class
static cfd::core::logger::CfdLogger logger_instance;
void cfd::core::InitializeLogger(void) { logger_instance.Initialize(); }
void cfd::core::FinalizeLogger(bool is_finish_process) {
logger_instance.Finalize(is_finish_process);
}
void cfd::core::SetLogger(void* function_address) {
logger_instance.SetLogger(function_address);
}
// -----------------------------------------------------------------------------
// Internal API
// -----------------------------------------------------------------------------
namespace cfd {
namespace core {
namespace logger {
/// Debug Flag
#if defined(DEBUG) || defined(CFDCORE_DEBUG)
static bool cfdcore_logger_is_debug = true;
#else
static bool cfdcore_logger_is_debug = false;
#endif
bool IsEnableLogLevel(cfd::core::logger::CfdLogLevel level) {
return logger_instance.IsEnableLogLevel(level);
}
void WriteLog(
const CfdSourceLocation& location, cfd::core::logger::CfdLogLevel level,
const std::string& log_message) {
logger_instance.WriteLog(location, level, log_message);
}
#if defined(CFDCORE_LOGGING) && (defined(DEBUG) || defined(CFDCORE_DEBUG))
/**
* @brief convert log level.
* @param[in] log_level cfd log level
* @return convert log level.
*/
static quill::LogLevel ConvertLogLevel(CfdLogLevel log_level) {
switch (log_level) {
case CfdLogLevel::kCfdLogLevelOff:
return quill::LogLevel::None;
case CfdLogLevel::kCfdLogLevelTrace:
return quill::LogLevel::TraceL1;
case CfdLogLevel::kCfdLogLevelDebug:
return quill::LogLevel::Debug;
case CfdLogLevel::kCfdLogLevelWarning:
return quill::LogLevel::Warning;
case CfdLogLevel::kCfdLogLevelError:
return quill::LogLevel::Error;
case CfdLogLevel::kCfdLogLevelCritical:
return quill::LogLevel::Critical;
case CfdLogLevel::kCfdLogLevelInfo:
default:
return quill::LogLevel::Info;
}
}
#endif // CFDCORE_LOGGING
// -----------------------------------------------------------------------------
// CfdLogger
// -----------------------------------------------------------------------------
cfd::core::logger::CfdLogger::CfdLogger(void) {
// do nothing
}
cfd::core::logger::CfdLogger::~CfdLogger(void) { Finalize(true); }
cfd::core::CfdError cfd::core::logger::CfdLogger::Initialize(void) {
if (is_initialized_) {
// do nothing
} else {
is_initialized_ = true;
is_alive_ = true;
if ((!is_extend_log_) && cfdcore_logger_is_debug) {
#if defined(CFDCORE_LOGGING) && (defined(DEBUG) || defined(CFDCORE_DEBUG))
#ifndef CFDCORE_LOG_CONSOLE
const size_t kRotateFileSize = 1024 * 1024 * 256;
const std::string filepath = "cfd_debug.txt";
#endif
std::string kDefaultLogLevel = "info";
#ifdef CFDCORE_LOG_LEVEL
int level_val = CFDCORE_LOG_LEVEL;
if (level_val == 1) {
kDefaultLogLevel = "trace";
} else if (level_val == 2) {
kDefaultLogLevel = "debug";
} else if (level_val == 4) {
kDefaultLogLevel = "warn";
}
#endif
// TODO(k-matsuzawa): only used for debugging
auto log_level = StringUtil::ToLower(kDefaultLogLevel);
if (log_level == "trace") {
log_level_ = kCfdLogLevelTrace;
} else if (log_level == "debug") {
log_level_ = kCfdLogLevelDebug;
} else if ((log_level == "warn") || (log_level == "warning")) {
log_level_ = kCfdLogLevelWarning;
} else {
log_level_ = kCfdLogLevelInfo;
}
// is_async_ = true;
is_use_default_logger_ = true;
// spdlog::init_thread_pool(1024 * 128, 5); // For Initalization
#ifdef CFDCORE_LOG_CONSOLE
// quill::enable_console_colours();
quill::ConsoleColours console_colours;
console_colours.set_default_colours();
quill::Handler* handler =
quill::stdout_handler("stdout_colours", console_colours);
handler->set_pattern(
QUILL_STRING("%(ascii_time) [%(process):%(thread)] %(level_name) "
"%(logger_name) - %(message)"), // NOLINT
"%D %H:%M:%S.%Qms", quill::Timezone::LocalTime);
quill::set_default_logger_handler(handler);
quill::start();
quill::Logger* logger = quill::get_logger();
#else
quill::start();
quill::Handler* handler =
quill::rotating_file_handler(filepath, "w", kRotateFileSize, 3);
handler->set_pattern(
QUILL_STRING("%(ascii_time) [%(process):%(thread)] %(level_name) "
"%(logger_name) - %(message)"), // NOLINT
"%D %H:%M:%S.%Qms", quill::Timezone::LocalTime);
quill::Logger* logger = quill::create_logger("cfd", handler);
#endif
logger->set_log_level(ConvertLogLevel(log_level_));
default_logger_ = logger;
#else // CFDCORE_LOGGING
std::cout << "default logger is not support on C++11." << std::endl;
#endif // CFDCORE_LOGGING
}
}
return kCfdSuccess;
}
void cfd::core::logger::CfdLogger::Finalize(bool is_finish_process) {
if (is_alive_) {
is_alive_ = false;
if (is_use_default_logger_ && (!is_finish_process)) {
// quill is not found finalize function.
}
}
}
void cfd::core::logger::CfdLogger::SetLogger(void* function_address) {
this->function_address_ = function_address;
is_extend_log_ = true;
}
bool cfd::core::logger::CfdLogger::IsEnableLogLevel(CfdLogLevel level) {
if (log_level_ == kCfdLogLevelOff) return false;
if (is_initialized_ && is_alive_ && (level <= log_level_)) return true;
return false;
}
void cfd::core::logger::CfdLogger::WriteLog(
const CfdSourceLocation& location, cfd::core::logger::CfdLogLevel level,
const std::string& log_message) {
if (is_initialized_ && is_alive_) {
if (function_address_ != nullptr) {
// extend log
} else if (default_logger_ != nullptr) {
#if defined(CFDCORE_LOGGING) && (defined(DEBUG) || defined(CFDCORE_DEBUG))
auto logger = static_cast<quill::Logger*>(default_logger_);
if (level == CfdLogLevel::kCfdLogLevelCritical) {
LOG_CRITICAL(
logger, "[{}:{}] {}", location.filename, location.line,
log_message);
} else if (level == CfdLogLevel::kCfdLogLevelError) {
LOG_ERROR(
logger, "[{}:{}] {}", location.filename, location.line,
log_message);
} else if (level == CfdLogLevel::kCfdLogLevelWarning) {
LOG_WARNING(
logger, "[{}:{}] {}", location.filename, location.line,
log_message);
} else if (level == CfdLogLevel::kCfdLogLevelInfo) {
LOG_INFO(
logger, "[{}:{}] {}: {}", location.filename, location.line,
location.funcname, log_message);
} else if (level == CfdLogLevel::kCfdLogLevelDebug) {
LOG_DEBUG(
logger, "[{}:{}] {}: {}", location.filename, location.line,
location.funcname, log_message);
} else if (level == CfdLogLevel::kCfdLogLevelTrace) {
LOG_TRACE_L1(
logger, "[{}:{}] {}: {}", location.filename, location.line,
location.funcname, log_message);
}
#else
printf(
"[%s:%d](%d) %s: %s", location.filename, location.line, level,
location.funcname, log_message.c_str());
#endif // CFDCORE_LOGGING
}
}
}
} // namespace logger
} // namespace core
} // namespace cfd
| 33.166667 | 80 | 0.620787 | [
"vector"
] |
10f05ef33997ecb32eb5ce8188d1ef0cf038134b | 11,570 | cpp | C++ | FrameTL/multiplicative_Schwarz.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | FrameTL/multiplicative_Schwarz.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | FrameTL/multiplicative_Schwarz.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for steepest_descent.h
#include <cmath>
#include <set>
#include <utils/plot_tools.h>
#include <adaptive/apply.h>
#include <numerics/corner_singularity.h>
#include <frame_evaluate.h>
#include <poisson_1d_testcase.h>
using std::set;
namespace FrameTL
{
/*!
*/
template<class VALUE = double>
class PolySolBiharmonic
: public Function<1, VALUE>
{
public:
PolySolBiharmonic() {};
virtual ~PolySolBiharmonic() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
return 16*(p[0]*p[0])*(1-p[0])*(1-p[0]);
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
template <class PROBLEM>
void GALERKIN (PROBLEM& P,
const set<typename PROBLEM::Index>& Lambda,
const InfiniteVector<double, typename PROBLEM::Index>& rhs,
Vector<double>& u)
{
typedef typename PROBLEM::Index Index;
// setup stiffness matrix
cout << "setting up full stiffness matrix..." << endl;
SparseMatrix<double> A_Lambda;
WaveletTL::setup_stiffness_matrix(P, Lambda, A_Lambda);
cout << "setting up full right hand side..." << endl;
Vector<double> F(Lambda.size());
unsigned int id = 0;
typename set<Index>::const_iterator it = Lambda.begin();
for (; it != Lambda.end(); ++it, ++id) {
F[id] = rhs.get_coefficient(*it);
}
cout << "size = " << F.size() << endl;
unsigned int iterations = 0;
CG(A_Lambda, F, u, 1.0e-15, 500, iterations);
cout << "CG done!!!!" << " Needed " << iterations << " iterations" << endl;
}
// a very quick hack, only working for ery special case
template <class PROBLEM>
void REDUCE_REDUNDANCY (PROBLEM& P, const int i,
const InfiniteVector<double, typename PROBLEM::Index>& u,
InfiniteVector<double, typename PROBLEM::Index>& u_sparse)
{
#if 1
u_sparse.clear();
typename InfiniteVector<double, typename PROBLEM::Index>::const_iterator it = u.begin();
if (i==0) {
Point<1> x(.8);
for (; it != u.end(); ++it) {
//if (it.index().p() == 1 && in_support(P.basis(), it.index(),x)) {
if (it.index().p() == 1) {
u_sparse.set_coefficient(it.index(), *it);
}
}
}
else if (i==1) {
Point<1> x(.2);
for (; it != u.end(); ++it) {
//if (it.index().p() == 0 && in_support(P.basis(), it.index(),x)) {
if (it.index().p() == 0) {
u_sparse.set_coefficient(it.index(), *it);
}
}
}
//cout << u_sparse << endl;
//u.clear();
//u -= u_bak;
//u.compress();
#endif
}
template <class PROBLEM>
bool intersect_line1 (PROBLEM& P,
const typename PROBLEM::Index& lambda)
{
typedef typename PROBLEM::WaveletBasis::Support SuppType;
const SuppType* supp = &(P.basis().all_patch_supports[lambda.number()]);
if ( (supp->a[0] < -0.7) && (-0.7 < supp->b[0]) && (supp->a[1] < 0.0)
||
(supp->a[1] < 0.0) && (0.0 < supp->b[1]) && (supp->b[0] > -0.7)
) // L-shaped with smaller overlap
//if ((supp->a[1] < 0.0) && (0.0 < supp->b[1])) // usual L-shaped
//if ((supp->a[0] < -0.3) && (-0.3 < supp->b[0]))
return true;
return false;
}
template <class PROBLEM>
bool intersect_line2 (PROBLEM& P,
const typename PROBLEM::Index& lambda)
{
typedef typename PROBLEM::WaveletBasis::Support SuppType;
const SuppType* supp = &(P.basis().all_patch_supports[lambda.number()]);
if ((supp->a[0] < 0.0) && (0.0 < supp->b[0]))
//if ((supp->a[0] < 0.3) && (0.3 < supp->b[0]))
return true;
return false;
}
template <class PROBLEM>
bool contact_with_patch2 (PROBLEM& P,
const typename PROBLEM::Index& lambda)
{
typedef typename PROBLEM::WaveletBasis::Support SuppType;
const SuppType* supp = &(P.basis().all_patch_supports[lambda.number()]);
//if ( leq(supp->b[0],0.3) )
if ( leq(supp->b[0],0.0) )
return true;
return false;
}
template <class PROBLEM>
void multiplicative_Schwarz_SOLVE(const PROBLEM& P, const double epsilon,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon_0,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon_1,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon)
{
// double o_lap = 0.7;
// typedef PBasis<3,3> Basis1D;
// //typedef SplineBasis<2,2,P_construction> Basis1D;
// typedef typename PROBLEM::WaveletBasis Frame;
// const int jmax = 15;
// typedef typename PROBLEM::Index Index;
// double a_inv = P.norm_Ainv();
// double omega_i = a_inv*P.F_norm();
// InfiniteVector<double, Index> u_k, u_k_1_2, r, help, f, Av, r_exact, u_sparse;
// map<double,double> log_10_residual_norms;
// map<double,double> degrees_of_freedom;
// map<double,double> asymptotic;
// map<double,double> time_asymptotic;
// bool exit = 0;
// double time = 0;
// clock_t tstart, tend;
// tstart = clock();
// double eta = 1.0e-15;
// const int number_patches = P.basis().n_p();
// unsigned int global_iterations = 0;
// double tmp = 5.;
// set<Index> I1;
// set<Index> I2;
// const int DIM = 1;
// // setup index sets for blocks of stiffness matrix
// for (Index lambda = FrameTL::first_generator<Basis1D,DIM,DIM,Frame>(&P.basis(), P.basis().j0());
// lambda <= FrameTL::last_wavelet<Basis1D,DIM,DIM,Frame>(&P.basis(), jmax); ++lambda) {
// if (lambda.p() == 0)
// I1.insert(lambda);
// else if (lambda.p() == 1)
// I2.insert(lambda);
// }
// // setting up the four blocks of the stiffnes matrix
// SparseMatrix<double> A11;
// SparseMatrix<double> A12;
// SparseMatrix<double> A21;
// SparseMatrix<double> A22;
// cout << "setting up A11... " << endl;
// WaveletTL::setup_stiffness_matrix(P, I1, A11);
// cout << "setting up A12... " << endl;
// WaveletTL::setup_stiffness_matrix(P, I1, I2, A12);
// //cout << A12 << endl;
// cout << "setting up A21... " << endl;
// WaveletTL::setup_stiffness_matrix(P, I2, I1, A21);
// //cout << A21 << endl;
// cout << "setting up A22... " << endl;
// WaveletTL::setup_stiffness_matrix(P, I2, A22);
// Vector<double> u_1(I1.size());
// Vector<double> u_2(I2.size());
// Vector<double> u_1_bak(I1.size());
// Vector<double> u_2_bak(I2.size());
// Vector<double> help_1(I1.size());
// Vector<double> help_2(I2.size());
// // setup full local right hand sides
// Vector<double> f_1(I1.size());
// Vector<double> f_2(I2.size());
// cout << "setting up f1... " << endl;
// WaveletTL::setup_righthand_side(P, I1, f_1);
// cout << "setting up f2... " << endl;
// WaveletTL::setup_righthand_side(P, I2, f_2);
// double res_norm = 25;
// while ( sqrt(res_norm) > 1.0e-10 && global_iterations < 100) {
// cout << "##### global iteration = " << global_iterations << endl;
// help_1 = 0;
// help_2 = 0;
// // perform the two half steps explicitely
// unsigned int iterations = 0;
// #if 1 // 1D
// // sparsen u_2
// int k = 0;
// Point<1> x(o_lap);
// for (typename set<Index>::const_iterator it = I2.begin(); it != I2.end(); it++, k++) {
// if (! in_support(P.basis(), *it, x)) {
// u_2[k] = 0;
// }
// }
// #endif
// #if 0 // 2D
// // sparsen u_2
// int k = 0;
// for (typename set<Index>::const_iterator it = I2.begin(); it != I2.end(); it++, k++) {
// if (! intersect_line1 (P,*it) ) {
// u_2[k] = 0;
// }
// }
// #endif
// //cout << "sparse u2 " << u_2 << endl;
// A12.apply(u_2,help_1);
// CG(A11, (f_1 - help_1), u_1, 1.0e-15, 500, iterations); // u_1 = A11^-1 * (f_1 - A12*u_2);
// cout << "needed " << iterations << " in CG" << endl;
// //cout << "u1 after first partial step" << u_1 << endl;
// #if 1 // 1D
// // backup u_1 now
// u_1_bak = u_1;
// // sparsen u_1
// k = 0;
// Point<1> y(1-o_lap);
// for (typename set<Index>::const_iterator it = I1.begin(); it != I1.end(); it++, k++) {
// if (! in_support(P.basis(), *it, y)) {
// u_1[k] = 0;
// }
// }
// //cout << "sparse u1 " << u_1 << endl;
// #endif
// #if 0 // 2D
// // backup u_1 now
// u_1_bak = u_1;
// // sparsen u_1
// k = 0;
// for (typename set<Index>::const_iterator it = I1.begin(); it != I1.end(); it++, k++) {
// if (! intersect_line2(P,*it) ) {
// u_1[k] = 0;
// }
// }
// //cout << "sparse u1 " << u_1 << endl;
// #endif
// A21.apply(u_1,help_2);
// CG(A22, (f_2 - help_2), u_2, 1.0e-15, 500, iterations); // u_2 = A22^-1 * (f_2 - A21*u_1);
// cout << "needed " << iterations << " in CG" << endl;
// //cout << "u2 after first partial step" << u_2 << endl;
// #if 1 //1D
// // setup the current global approximation
// // we have to remove those coefficients of u_1_bak that are contained in the closure of the second patch
// typedef typename PROBLEM::WaveletBasis::Support SuppType;
// k = 0;
// for (typename set<Index>::const_iterator it = I1.begin(); it != I1.end(); it++, k++) {
// const SuppType* supp = &(P.basis().all_patch_supports[(*it).number()]);
// //cout << "#### " << supp->a[0] << " " << leq(0.3, supp->a[0]) << endl;
// if (leq(1-o_lap, supp->a[0]) ) {
// //if (! leq(supp->b[0], 0.2) ) {
// u_1_bak[k] = 0;
// }
// }
// //cout << u_1_bak << endl;
// u_1 = u_1_bak;
// #endif
// #if 0 //2D
// // setup the current global approximation
// // we have to remove those coefficients of u_1_bak that are contained in the closure of the second patch
// typedef typename PROBLEM::WaveletBasis::Support SuppType;
// k = 0;
// for (typename set<Index>::const_iterator it = I1.begin(); it != I1.end(); it++, k++) {
// const SuppType* supp = &(P.basis().all_patch_supports[(*it).number()]);
// if (contact_with_patch2(P,*it) ) {
// u_1_bak[k] = 0;
// }
// }
// //cout << u_1_bak << endl;
// u_1 = u_1_bak;
// #endif
// // compute residual norm:
// A11.apply(u_1, help_1);
// A12.apply(u_2, help_2);
// res_norm = l2_norm_sqr(f_1-(help_1+help_2));
// A21.apply(u_1, help_1);
// A22.apply(u_2, help_2);
// res_norm += l2_norm_sqr(f_2-(help_1+help_2));
// cout << "residual norm = " << sqrt(res_norm) << " after iteration " << global_iterations << endl;
// global_iterations++;
// }
// int id = 0;
// for (typename set<Index>::const_iterator it = I1.begin(); it != I1.end(); it++, id++) {
// if (u_1[id] != 0) {
// //cout << "index1 = " << (*it).number() << " " << u_1[id] << endl;
// u_epsilon_0.set_coefficient(*it, u_1[id]);
// }
// }
// id = 0;
// for (typename set<Index>::const_iterator it = I2.begin(); it != I2.end(); it++, id++) {
// //cout << *it << endl;
// if (u_2[id] != 0) {
// //cout << "index2 = " << (*it).number() << " " << u_2[id] << endl;
// u_epsilon_1.set_coefficient(*it, u_2[id]);
// }
// }
// u_epsilon = u_epsilon_0 + u_epsilon_1;
// //cout << "degrees_of_freedom = " << u_epsilon.size() << endl;
// // SparseMatrix<double> A;
// // set<Index> Lambda_sparse;
// // u_epsilon.support(Lambda_sparse);
// // WaveletTL::setup_stiffness_matrix(P, Lambda_sparse, A);
// // A.matlab_output("stiff_sparse_1D_out", "stiff_sparse",1);
}
}
| 30.447368 | 113 | 0.554624 | [
"vector"
] |
10facba138a28c0ea794f9d391f32030921884f9 | 770 | cpp | C++ | src/test/applications/minimum_curvature_path.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 28 | 2021-11-26T16:03:33.000Z | 2022-02-21T13:51:58.000Z | src/test/applications/minimum_curvature_path.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 1 | 2022-03-01T17:10:39.000Z | 2022-03-01T17:10:39.000Z | src/test/applications/minimum_curvature_path.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 1 | 2022-02-28T12:21:04.000Z | 2022-02-28T12:21:04.000Z | #include "gtest/gtest.h"
#include "lion/thirdparty/include/cppad/cppad.hpp"
#define SKIP_TIMESERIES
using timeseries = CppAD::AD<double>;
#include "src/core/vehicles/track_by_arcs.h"
#include "src/core/applications/minimum_curvature_path.h"
TEST(Minimum_curvature_path,oval_50)
{
Xml_document track_xml("./data/ovaltrack.xml",true);
Track_by_arcs oval(track_xml,true);
Xml_document matlab_result("./data/minimum_curvature_path.xml",true);
std::vector<double> x_saved = matlab_result.get_root_element().get_child("ovaltrack_50/w").get_value(std::vector<double>());
Minimum_curvature_path result(oval,50);
EXPECT_TRUE(result.get_success());
for (size_t i = 0; i < 50; ++i)
EXPECT_NEAR(x_saved[i], result.get_x()[i],5.0e-2);
}
| 27.5 | 128 | 0.732468 | [
"vector"
] |
80001d6cfed97a57ba53138d4ebd747a475c4234 | 7,060 | cpp | C++ | ImSynth/lib/Synth/WaveTableOsc.cpp | syyePhenomenol/ImSynth | d4be0d5c707efcf826d6d49a34f3d15f0e8a23b6 | [
"MIT"
] | 2 | 2021-06-13T03:47:35.000Z | 2021-06-16T07:16:39.000Z | ImSynth/lib/Synth/WaveTableOsc.cpp | syyePhenomenol/ImSynth | d4be0d5c707efcf826d6d49a34f3d15f0e8a23b6 | [
"MIT"
] | null | null | null | ImSynth/lib/Synth/WaveTableOsc.cpp | syyePhenomenol/ImSynth | d4be0d5c707efcf826d6d49a34f3d15f0e8a23b6 | [
"MIT"
] | null | null | null | //
// Test wavetable oscillator
//
// Created by Nigel Redmon on 4/31/12
// EarLevel Engineering: earlevel.com
// Copyright 2012 Nigel Redmon
//
// For a complete explanation of the wavetable oscillator and code,
// read the series of articles by the author, starting here:
// www.earlevel.com/main/2012/05/03/a-wavetable-oscillator—introduction/
//
// License:
//
// This source code is provided as is, without warranty.
// You may copy and distribute verbatim copies of this document.
// You may modify and use this source code to create binary code for your own purposes, free or commercial.
//
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
#include "WaveTableOsc.h"
void makeAllTables(vector<vector<waveTable>>* allTables, float baseFreq) {
// run loop over every wavetable shape
for (int n = 0; n < numberOfShapes; n++) {
// calc number of harmonics where the highest harmonic baseFreq and lowest alias an octave higher would meet
int maxHarms = sampleRate / (3.0 * baseFreq) + 0.5;
// round up to nearest power of two
unsigned int v = maxHarms;
v--; // so we don't go up if already a power of 2
v |= v >> 1; // roll the highest bit into all lower bits...
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++; // and increment to power of 2
int tableLen = v * 2 * overSamp; // double for the sample rate, then oversampling
vector<myFloat> ar(tableLen), ai(tableLen); // for ifft
double topFreq = baseFreq * 2.0 / sampleRate;
for (; maxHarms >= 1; maxHarms >>= 1) {
if (n == 0) {
defineSine(tableLen, ar, ai);
}
else if (n == 1) {
defineTriangle(tableLen, maxHarms, ar, ai);
}
else if (n == 2) {
defineSawtooth(tableLen, maxHarms, ar, ai);
}
else if (n == 3) {
defineSquare(tableLen, maxHarms, ar, ai);
}
waveTable table = makeWaveTable(tableLen, ar, ai, topFreq);
(*allTables)[n].push_back(table);
topFreq *= 2;
//if (tableLen > constantRatioLimit) // variable table size (constant oversampling but with minimum table size)
// tableLen >>= 1;
}
}
}
//
// if scale is 0, auto-scales
// returns scaling factor (0.0 if failure), and wavetable in ai array
//
waveTable makeWaveTable(int len, vector<myFloat>& ar, vector<myFloat>& ai, double topFreq)
{
waveTable table;
fft(len, ar, ai);
myFloat max = 0.0;
float scale = 0.0;
for (int idx = 0; idx < len; idx++) {
myFloat temp = fabs(ai[idx]);
if (max < temp) {
max = temp;
}
}
scale = 1.0 / max * .999;
// normalize and cast to a float vector
vector<float> wave(len);
for (int idx = 0; idx < len; idx++)
wave[idx] = ai[idx] * scale;
wave.push_back(wave.front());
table.topFreq = topFreq;
table.waveTableLen = len;
table.waveTable_ = wave;
return table;
}
//
// fft
//
// I grabbed (and slightly modified) this Rabiner & Gold translation...
//
// (could modify for real data, could use a template version, blah blah--just keeping it short)
//
void fft(int N, vector<myFloat>& ar, vector<myFloat>& ai)
/*
in-place complex fft
After Cooley, Lewis, and Welch; from Rabiner & Gold (1975)
program adapted from FORTRAN
by K. Steiglitz (ken@princeton.edu)
Computer Science Dept.
Princeton University 08544 */
{
int i, j, k, L; /* indexes */
int M, TEMP, LE, LE1, ip; /* M = log N */
int NV2, NM1;
myFloat t; /* temp */
myFloat Ur, Ui, Wr, Wi, Tr, Ti;
myFloat Ur_old;
// if ((N > 1) && !(N & (N - 1))) // make sure we have a power of 2
NV2 = N >> 1;
NM1 = N - 1;
TEMP = N; /* get M = log N */
M = 0;
while (TEMP >>= 1) ++M;
/* shuffle */
j = 1;
for (i = 1; i <= NM1; i++) {
if(i<j) { /* swap a[i] and a[j] */
t = ar[j-1];
ar[j-1] = ar[i-1];
ar[i-1] = t;
t = ai[j-1];
ai[j-1] = ai[i-1];
ai[i-1] = t;
}
k = NV2; /* bit-reversed counter */
while(k < j) {
j -= k;
k /= 2;
}
j += k;
}
LE = 1.;
for (L = 1; L <= M; L++) { // stage L
LE1 = LE; // (LE1 = LE/2)
LE *= 2; // (LE = 2^L)
Ur = 1.0;
Ui = 0.;
Wr = cos(M_PI/(float)LE1);
Wi = -sin(M_PI/(float)LE1); // Cooley, Lewis, and Welch have "+" here
for (j = 1; j <= LE1; j++) {
for (i = j; i <= N; i += LE) { // butterfly
ip = i+LE1;
Tr = ar[ip-1] * Ur - ai[ip-1] * Ui;
Ti = ar[ip-1] * Ui + ai[ip-1] * Ur;
ar[ip-1] = ar[i-1] - Tr;
ai[ip-1] = ai[i-1] - Ti;
ar[i-1] = ar[i-1] + Tr;
ai[i-1] = ai[i-1] + Ti;
}
Ur_old = Ur;
Ur = Ur_old * Wr - Ui * Wi;
Ui = Ur_old * Wi + Ui * Wr;
}
}
}
void defineSine(int len, vector<myFloat>& ar, vector<myFloat>& ai)
{
// clear
for (int idx = 0; idx < len; idx++) {
ai[idx] = 0;
ar[idx] = 0;
}
// sine
ar[1] = 1.0;
}
void defineTriangle(int len, int numHarmonics, vector<myFloat>& ar, vector<myFloat>& ai)
{
if (numHarmonics > (len >> 1))
numHarmonics = (len >> 1);
// clear
for (int idx = 0; idx < len; idx++) {
ai[idx] = 0;
ar[idx] = 0;
}
// triangle
float sign = 1;
for (int idx = 1, jdx = len - 1; idx <= numHarmonics; idx++, jdx--) {
myFloat temp = idx & 0x01 ? 1.0 / (idx * idx) * (sign = -sign) : 0.0;
ar[idx] = -temp;
ar[jdx] = temp;
}
}
//
// defineSawtooth
//
// prepares sawtooth harmonics for ifft
//
void defineSawtooth(int len, int numHarmonics, vector<myFloat>& ar, vector<myFloat>& ai)
{
if (numHarmonics > (len >> 1))
numHarmonics = (len >> 1);
// clear
for (int idx = 0; idx < len; idx++) {
ai[idx] = 0;
ar[idx] = 0;
}
// sawtooth
for (int idx = 1, jdx = len - 1; idx <= numHarmonics; idx++, jdx--) {
myFloat temp = -1.0 / idx;
ar[idx] = -temp;
ar[jdx] = temp;
}
}
void defineSquare(int len, int numHarmonics, vector<myFloat> & ar, vector<myFloat> & ai)
{
if (numHarmonics > (len >> 1))
numHarmonics = (len >> 1);
// clear
for (int idx = 0; idx < len; idx++) {
ai[idx] = 0;
ar[idx] = 0;
}
// square
for (int idx = 1, jdx = len - 1; idx <= numHarmonics; idx++, jdx--) {
myFloat temp = idx & 0x01 ? 1.0 / idx : 0.0;
ar[idx] = temp;
ar[jdx] = -temp;
}
} | 27.470817 | 123 | 0.493484 | [
"shape",
"vector"
] |
800bbdd931f77f09637dd78cbb28200002f0ca03 | 1,667 | cpp | C++ | day08/day08_01/day08_01.cpp | thomasneff/advent_of_code_2020 | e662f31a181ecaf50eda9005cf916af2191d9348 | [
"MIT"
] | 1 | 2020-12-10T08:25:46.000Z | 2020-12-10T08:25:46.000Z | day08/day08_01/day08_01.cpp | thomasneff/advent_of_code_2020 | e662f31a181ecaf50eda9005cf916af2191d9348 | [
"MIT"
] | null | null | null | day08/day08_01/day08_01.cpp | thomasneff/advent_of_code_2020 | e662f31a181ecaf50eda9005cf916af2191d9348 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <deque>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "BaseInstruction.h"
#include "ProcessorRegisters.h"
class Processor
{
public:
Processor(std::vector<std::string> input_lines)
{
// Transform / parse input lines to instructions
for(const auto& line : input_lines)
{
auto space_loc = line.find(' ');
auto inst = line.substr(0, space_loc);
int arg = std::stoi(line.substr(space_loc));
instructions.push_back(BaseInstruction::getInstructionFromString(inst, arg, reg));
}
};
bool executeInstruction()
{
// simply run instruction from current isp
if(reg.isp < 0 || reg.isp >= instructions.size())
{
return false;
}
if(already_used_instructions.find(reg.isp) == already_used_instructions.end())
{
already_used_instructions[reg.isp] = true;
}
else
{
// we already executed this instruction
return false;
}
instructions[reg.isp]->execute();
return true;
}
ProcessorRegisters reg;
private:
std::vector<std::unique_ptr<BaseInstruction>> instructions;
// This is only for the challenge and wouldn't have a real use otherwise
std::map<int, bool> already_used_instructions;
};
int main()
{
std::ifstream input_file("input_simple.txt");
std::string input_line;
std::vector<std::string> input_lines;
// get all input lines from file
while(std::getline(input_file, input_line))
{
input_lines.push_back(input_line);
}
Processor p(input_lines);
while(p.executeInstruction() == true)
;
std::cout << "Value in acc is: " << p.reg.acc << "\n";
}
| 19.611765 | 85 | 0.70006 | [
"vector",
"transform"
] |
8025e0d7c4633315815130da194a6df881285ace | 3,842 | cpp | C++ | src/main.cpp | henryliuw/SEM | 93d6e24270e38cd0179d47fd94566626eec6e3a8 | [
"MIT"
] | null | null | null | src/main.cpp | henryliuw/SEM | 93d6e24270e38cd0179d47fd94566626eec6e3a8 | [
"MIT"
] | null | null | null | src/main.cpp | henryliuw/SEM | 93d6e24270e38cd0179d47fd94566626eec6e3a8 | [
"MIT"
] | null | null | null | #include "geometrycentral/surface/manifold_surface_mesh.h"
#include "geometrycentral/surface/meshio.h"
#include "geometrycentral/surface/vertex_position_geometry.h"
#include "geometrycentral/surface/direction_fields.h"
#include "SEM.h"
#include "polyscope/polyscope.h"
#include "polyscope/surface_mesh.h"
#include "args/args.hxx"
#include "imgui.h"
#include "polyscope/point_cloud.h"
using namespace geometrycentral;
using namespace geometrycentral::surface;
// == Geometry-central data
std::unique_ptr<ManifoldSurfaceMesh> mesh_uptr;
std::unique_ptr<VertexPositionGeometry> geometry_uptr;
ManifoldSurfaceMesh* mesh;
VertexPositionGeometry* geometry;
// Polyscope visualization handle, to quickly add data to the surface
polyscope::SurfaceMesh *psMesh;
// Some algorithm parameters
float param1 = 42.0;
SEM* sem_ptr;
// Example computation function -- this one computes and registers a scalar
// quantity
void GUIstep() {
static int count = 0;
std::cout << "iteration:" << count++ << "\taverage error:" << sem_ptr->step() << std::endl;
polyscope::registerSurfaceMesh(
polyscope::guessNiceNameFromPath("SEM parameterization"),
geometry->vertexPositions, mesh->getFaceVertexList(), //geometry->inputVertexPositions
polyscopePermutations(*mesh));
polyscope::requestRedraw();
}
// A user-defined callback, for creating control panels (etc)
// Use ImGUI commands to build whatever you want here, see
// https://github.com/ocornut/imgui/blob/master/imgui.h
void myCallback() {
if (ImGui::Button("step")) {
GUIstep();
}
ImGui::SliderFloat("param", ¶m1, 0., 100.);
}
void debug() {
}
int main(int argc, char **argv) {
// Configure the argument parser
args::ArgumentParser parser("geometry-central & Polyscope example project");
args::Positional<std::string> inputFilename(parser, "mesh", "a mesh file.");
// Parse args
try {
parser.ParseCLI(argc, argv);
} catch (args::Help &h) {
std::cout << parser;
return 0;
} catch (args::ParseError &e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return 1;
}
// Make sure a mesh name was given
std::string name;
if (!inputFilename) {
name = "../input/cowhead.obj";
//std::cerr << "Please specify a mesh file as argument" << std::endl;
//return EXIT_FAILURE;
}
else
{
name = args::get(inputFilename);
}
// Initialize polyscope
polyscope::init();
// Set the callback function
polyscope::state::userCallback = myCallback;
// Load mesh
std::tie(mesh_uptr, geometry_uptr) = readManifoldSurfaceMesh(name);
mesh = mesh_uptr.release();
geometry = geometry_uptr.release();
SEM sem(mesh, geometry);
sem_ptr = &sem;
// Register the mesh with polyscope
psMesh = polyscope::registerSurfaceMesh(
polyscope::guessNiceNameFromPath("original 3D"),
sem.ORIGINAL, mesh->getFaceVertexList(), //geometry->inputVertexPositions
polyscopePermutations(*mesh));
polyscope::registerSurfaceMesh(
polyscope::guessNiceNameFromPath("SEM parameterization"),
geometry->vertexPositions, mesh->getFaceVertexList(), //geometry->inputVertexPositions
polyscopePermutations(*mesh));
polyscope::requestRedraw();
// testing part
//std::cout << geometry->cotanLaplacian;
//auto L = sem.computeLaplacian();
////std::cout << L << std::endl;
//auto fB = sem.solveBoundaryLaplacian(sem.fI_save, L);
//sem.updateGeometry(fB, sem.fI_save);
//polyscope::registerSurfaceMesh(
// polyscope::guessNiceNameFromPath("SEM parameterization"),
// geometry->vertexPositions, mesh->getFaceVertexList(), //geometry->inputVertexPositions
// polyscopePermutations(*mesh));
// Give control to the polyscope gui
polyscope::show();
delete mesh;
delete geometry;
return EXIT_SUCCESS;
}
| 30.492063 | 100 | 0.701718 | [
"mesh",
"geometry",
"3d"
] |
80326394c459b1d20e82e476c1aadd73df9409f1 | 15,321 | cpp | C++ | src/apps/viblio_video_analyzer/viblio_video_analyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | src/apps/viblio_video_analyzer/viblio_video_analyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | src/apps/viblio_video_analyzer/viblio_video_analyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | /*
The entry point into the application. Parses command line options (or config files) and sets up the program
flow based on said options
Date: 01/07/2013
Author: Jason Catchpole (jason@viblio.com)
*/
#include "boost/program_options.hpp"
#include <iostream>
#include <list>
#include <vector>
#include <stdio.h>
#include <string>
#include "FileSystem/FileSystem.h"
#include "VideoSource/FileVideoSource.h"
#include "Analytics.FaceAnalyzer/AnalyzerTypes.h"
#include "Analytics.FaceAnalyzer/FaceDetector.h"
#include "JobConfiguration.h"
#include "Analytics.FaceAnalyzer/FaceAnalyzerConfiguration.h"
#include "VideoProcessor.h"
#include <fstream>
#include <boost/make_shared.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/expressions/formatters/named_scope.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/utility/empty_deleter.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/attributes/named_scope.hpp>
#include <boost/log/support/exception.hpp>
#ifdef _WIN32
//#include <vld.h> // Visual Leak Detector
#endif
#ifdef _WIN32
#include <windows.h>
void my_sleep( unsigned milliseconds ) {
Sleep( milliseconds );
}
#else
#include <unistd.h>
void my_sleep( unsigned milliseconds ) {
usleep( milliseconds * 1000 );
}
#endif
namespace po = boost::program_options;
using namespace std;
//using namespace cv;
using namespace boost;
// function prototypes
void ExtractFaceAnalysisParameters( po::variables_map variableMap, Analytics::FaceAnalyzer::FaceAnalyzerConfiguration *faceAnalyzer);
int g_verbosityLevel = 0;
string g_version = "0.75";
void InitLogging(string logfilePath)
{
typedef log::sinks::synchronous_sink< log::sinks::text_file_backend > text_file_sink;
boost::shared_ptr< text_file_sink > fileSink = boost::make_shared< text_file_sink >(
log::keywords::time_based_rotation = log::sinks::file::rotation_at_time_point(0, 0, 0), // rotate at midnight
log::keywords::file_name = logfilePath + "video_analyzer_%N.log", // file name pattern
log::keywords::auto_flush = true,
log::keywords::rotation_size = 10 * 1024 * 1024);
fileSink->set_formatter(
log::expressions::stream
//<< log::expressions::format_named_scope("Scopes", "%n")
<< "Timestamp: " << log::expressions::attr< boost::posix_time::ptime >("TimeStamp")
<< log::expressions::if_ (log::expressions::has_attr< string >("FaceID"))
[
// if "ID" is present then put it to the record
log::expressions::stream << log::expressions::attr< string >("FaceID")
]
.else_
[
// otherwise add nothing
log::expressions::stream << ""
]
<< ". Message: " << log::expressions::smessage
);
// now add the console outputter
typedef log::sinks::synchronous_sink< log::sinks::text_ostream_backend > text_console_sink;
boost::shared_ptr< text_console_sink > consoleSink = boost::make_shared< text_console_sink >();
consoleSink->locked_backend()->add_stream(
boost::shared_ptr< std::ostream >(&std::clog, log::empty_deleter()));
consoleSink->locked_backend()->auto_flush(true);
// Register the sink in the logging core
log::core::get()->add_sink(fileSink);
log::core::get()->add_sink(consoleSink);
}
int main(int argc, char* argv[])
{
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("filename,f", po::value<string>(), "specify the input video filename to analyze")
("video_rotation,r", po::value<int>()->default_value(0), "amount (in degrees) to rotate each frame prior to any processing")
("verbosity,v", po::value<int>(&g_verbosityLevel)->default_value(0), "set the verbosity level (between 0-3, 0 is off, 3 is most verbose)")
("analyzers", po::value< vector<string> >(), "analyzers to use. Options include \"FaceAnalysis\"")
("face_detector_cascade_file", po::value<string>(), "the path to the cascade file to use for face detection")
("eye_detector_cascade_file", po::value<string>(), "the path to the cascade file to use for eye detection")
("face_thumbnail_path,p", po::value<string>(), "the location to put output facial thumbnails generated")
("filename_prefix", po::value<string>(), "the filename prefix that need to be appended")
("face_detection_frequency", po::value<int>()->default_value(15), "set how often we should perform face detection, e.g. a value of 3 means we only check every third frame, lower numbers means we check more frequently but this will be slower")
("face_image_resize", po::value<float>()->default_value(1.0f), "specifies rescale factor for frames prior to performing face processing")
("lost_track_process_frequency", po::value<int>()->default_value(5), "set how often a lost face should perform processing when attempting to regain the track, e.g. a value of 5 means we only check every fifth frame, lower numbers means we check more frequently but this will be slower")
("Thumbnail_generation_frequency", po::value<int>()->default_value(1500), "set how often a thumbnail should be generated in milliseconds, e.g. a value of 1500 means we only check every frame after 1500 milliseconds and do thumbnail processing")
("discarded_tracker_frequency", po::value<int>()->default_value(90000), "set how often a track should be pushed to discarded state in milliseconds, e.g. a value of 90000 means one and half minute")
("maximum_concurrent_trackers", po::value<int>()->default_value(15), "set how many trackers are allowed to exist at one time")
("render_visualization", "determines whether visualizations will be rendered")
("log_file_path", po::value<string>(), "the path where any log files should be placed")
("face_detector", po::value<string>()->default_value("neurotech"), "specifies which detector to use. Options include \"Neurotech\", \"Orbeus\", or \"OpenCV\"")
("orbeus_api_key", po::value<string>(), "If the \"face_detector\", is set to \"Orbeus\" then this option must be provided. It specifies the API key to use in queries to the Orbeus API")
("orbeus_secret_key", po::value<string>(), "If the \"face_detector\", is set to \"Orbeus\" then this option must be provided. It specifies the secret key to use in queries to the Orbeus API")
("orbeus_namespace", po::value<string>(), "If the \"face_detector\", is set to \"Orbeus\" then this option is optional. It specifies the namespace to use in queries to the Orbeus API")
("orbeus_user_id", po::value<string>(), "If the \"face_detector\", is set to \"Orbeus\" then this option is optional. It specifies the user_id parameter to use in queries to the Orbeus API")
;
po::variables_map variableMap;
po::store(po::parse_command_line(argc, argv, desc), variableMap);
po::notify(variableMap);
// they asked for help, lets give it to them
if (variableMap.count("help"))
{
cout << desc << "\n";
return 1;
}
string logFilePath = "";
// determine if they provided a log file path, if so make sure it ends in a trailing slash
if( variableMap.count("log_file_path") )
{
logFilePath = variableMap["log_file_path"].as<string>();
if( logFilePath.back() != '\\' && logFilePath.back() != '/' )
{
cout << "Log file path provided does not contain a trailing slash, adding a backslash '\\'. If you are on linux consider adding a '/'" << endl;
logFilePath.append("\\");
}
}
InitLogging(logFilePath); // initialize the logging
log::add_common_attributes();
log::core::get()->add_global_attribute("TimeStamp", log::attributes::local_clock());
BOOST_LOG_TRIVIAL(info) << "OpenCV version: " << CV_VERSION;
// If we want to test directory creation..............
//std::string folder= "RamsriGolla";
//bool file;
//FileSystem::CreateDirectory(folder);
//Jzon::Object root;
JobConfiguration jobConfig;
if (variableMap.count("filename"))
{
BOOST_LOG_TRIVIAL(error) << "Input filename to analyze was set to "
<< variableMap["filename"].as<string>();
jobConfig.videoSourceFilename = variableMap["filename"].as<string>();
}
else
{
BOOST_LOG_TRIVIAL(error) << "Input filename not specified, nothing to do";
return 1;
}
// Analyzer config extraction from parameters and config file
if( variableMap.count("analyzers") )
{
vector<string>::const_iterator startIter = variableMap["analyzers"].as<vector<string>>().begin();
vector<string>::const_iterator endIter = variableMap["analyzers"].as<vector<string>>().end();
for(; startIter!=endIter; startIter++)
{
// convert the string to lower case first
//std::transform((*startIter).begin(), (*startIter).end(), (*startIter).begin(), ::tolower);
// check to see if this value passed in by the user is known to us
Analytics::AnalyzerType analyzerType = Analytics::ConvertStringToAnalyzerType(*startIter);
if( analyzerType == Analytics::UnknownAnalyzer )
{
BOOST_LOG_TRIVIAL(error) << "Error - The specified analyzer named " << *startIter << " is not valid";
}
else
{
// we know what kind of analyzer this is so examine the variable map for the corresponding config for this analyzer
switch(analyzerType)
{
case Analytics::Analyzer_FaceAnalysis:
{
jobConfig.isFaceAnalyzerEnabled = true;
jobConfig.faceAnalyzerConfig = new Analytics::FaceAnalyzer::FaceAnalyzerConfiguration();
ExtractFaceAnalysisParameters( variableMap, jobConfig.faceAnalyzerConfig );
} break;
default:
{
// do nothing
} break;
};
}
}
}
// now that we have all our config data nice and neat lets start processing
const NChar * components = N_T("Biometrics.FaceDetection,Biometrics.FaceExtraction,Biometrics.FaceSegmentation,Biometrics.FaceQualityAssessment");
NResult result = N_OK;
NBool available = NFalse;
int max_license_attempts = 108;
int license_wait_secs = 300;
int license_attempt = 0;
while ( !available ) {
try {
if ( license_attempt > max_license_attempts ) {
BOOST_LOG_TRIVIAL(error) << "Failed to obtain license after " << license_attempt << " attempts.";
throw runtime_error( "Failed to obtain Neurotech license after exceeding max_license_attempts." );
} else {
license_attempt++;
}
BOOST_LOG_TRIVIAL( info ) << "Attempting to acquire Neurotech licenses.";
result = NLicenseObtainComponents(N_T("/local"), N_T("5000"), components, &available);
if ( NFailed( result ) || !available ) {
BOOST_LOG_TRIVIAL( info ) << "Failed to acquire Neurotech license.";
BOOST_LOG_TRIVIAL( info ) << "Waiting " << license_wait_secs << " seconds for license.";
my_sleep( license_wait_secs * 1000 );
} else {
BOOST_LOG_TRIVIAL( info ) << "Neurotech license acquired.";
}
} catch ( int e ) {
BOOST_LOG_TRIVIAL(error) << "Exception caught while attempting to obtain Neurotech product license. Cannot continue";
if (!available)
BOOST_LOG_TRIVIAL(error) << "Neurotech Licenses for " << components << " not available";
throw e;
}
}
try {
VideoProcessor videoProcessor(jobConfig);
videoProcessor.PerformProcessing();
videoProcessor.OutputJobSummaryStatistics();
videoProcessor.DumpOutput(jobConfig);
if( jobConfig.faceAnalyzerConfig != NULL )
delete jobConfig.faceAnalyzerConfig;
} catch ( Exception e ) {
BOOST_LOG_TRIVIAL( error ) << "Exception thrown in face detection.";
if ( available ) {
NResult result2 = NLicenseReleaseComponents(components);
if (NFailed(result2)) {
BOOST_LOG_TRIVIAL(error) << "NLicenseReleaseComponents() failed (result = " << result2<< ")";
}
}
throw e;
}
if ( available ) {
NResult result2 = NLicenseReleaseComponents(components);
if (NFailed(result2)) {
BOOST_LOG_TRIVIAL(error) << "NLicenseReleaseComponents() failed (result = " << result2<< ")";
}
}
return 0;
}
void ExtractFaceAnalysisParameters( po::variables_map variableMap, Analytics::FaceAnalyzer::FaceAnalyzerConfiguration *faceAnalyzerConfig )
{
if( faceAnalyzerConfig == NULL )
return; // can't do aything
if (variableMap.count("face_detector_cascade_file"))
{
faceAnalyzerConfig->faceDetectorCascadeFile = variableMap["face_detector_cascade_file"].as<string>();
}
if (variableMap.count("eye_detector_cascade_file"))
{
faceAnalyzerConfig->eyeDetectorCascadeFile = variableMap["eye_detector_cascade_file"].as<string>();
}
if (variableMap.count("face_thumbnail_path"))
{
faceAnalyzerConfig->faceThumbnailOutputPath = variableMap["face_thumbnail_path"].as<string>();
}
if (variableMap.count("filename_prefix"))
{
faceAnalyzerConfig->filenameprefix= variableMap["filename_prefix"].as<string>();
}
if (variableMap.count("face_detection_frequency"))
{
faceAnalyzerConfig->faceDetectionFrequency = variableMap["face_detection_frequency"].as<int>();
}
if(variableMap.count("face_detector"))
{
faceAnalyzerConfig->faceDetectorType = Analytics::FaceAnalyzer::FaceDetector::ConvertStringToDetectorType(variableMap["face_detector"].as<string>());
}
if(variableMap.count("orbeus_user_id"))
{
faceAnalyzerConfig->orbeusUserId = variableMap["orbeus_user_id"].as<string>();
}
if(variableMap.count("orbeus_api_key"))
{
faceAnalyzerConfig->orbeusApiKey = variableMap["orbeus_api_key"].as<string>();
}
if(variableMap.count("orbeus_secret_key"))
{
faceAnalyzerConfig->orbeusSecretKey = variableMap["orbeus_secret_key"].as<string>();
}
if(variableMap.count("orbeus_namespace"))
{
faceAnalyzerConfig->orbeusNamespace = variableMap["orbeus_namespace"].as<string>();
}
if (variableMap.count("lost_track_process_frequency"))
{
faceAnalyzerConfig->lostFaceProcessFrequency = variableMap["lost_track_process_frequency"].as<int>();
}
if (variableMap.count("Thumbnail_generation_frequency"))
{
faceAnalyzerConfig->Thumbnail_generation_frequency = variableMap["Thumbnail_generation_frequency"].as<int>();
}
if (variableMap.count("discarded_tracker_frequency"))
{
faceAnalyzerConfig->discarded_tracker_frequency = variableMap["discarded_tracker_frequency"].as<int>();
}
if (variableMap.count("maximum_concurrent_trackers"))
{
faceAnalyzerConfig->maximumNumberActiveTrackers = variableMap["maximum_concurrent_trackers"].as<int>();
}
if (variableMap.count("face_image_resize"))
{
faceAnalyzerConfig->imageRescaleFactor = variableMap["face_image_resize"].as<float>();
}
if (variableMap.count("render_visualization"))
{
faceAnalyzerConfig->renderVisualization = true;
}
}
| 38.984733 | 289 | 0.702696 | [
"object",
"vector",
"transform"
] |
8033836363a0eddbdf67109c3e6ba3de1390fa06 | 19,393 | cc | C++ | RecoBTag/SecondaryVertex/src/GhostTrackComputer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoBTag/SecondaryVertex/src/GhostTrackComputer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoBTag/SecondaryVertex/src/GhostTrackComputer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include <iostream>
#include <cstddef>
#include <string>
#include <cmath>
#include <vector>
#include <Math/VectorUtil.h>
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/Math/interface/Vector3D.h"
#include "DataFormats/Math/interface/LorentzVector.h"
#include "DataFormats/GeometryCommonDetAlgo/interface/Measurement1D.h"
#include "DataFormats/GeometryVector/interface/GlobalPoint.h"
#include "DataFormats/GeometryVector/interface/GlobalVector.h"
#include "DataFormats/GeometryVector/interface/VectorUtil.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/BTauReco/interface/TrackIPTagInfo.h"
#include "DataFormats/BTauReco/interface/SecondaryVertexTagInfo.h"
#include "DataFormats/BTauReco/interface/TaggingVariable.h"
#include "DataFormats/BTauReco/interface/VertexTypes.h"
#include "DataFormats/BTauReco/interface/ParticleMasses.h"
#include "RecoBTag/SecondaryVertex/interface/TrackSorting.h"
#include "RecoBTag/SecondaryVertex/interface/TrackSelector.h"
#include "RecoBTag/SecondaryVertex/interface/TrackKinematics.h"
#include "RecoBTag/SecondaryVertex/interface/V0Filter.h"
#include "RecoBTag/SecondaryVertex/interface/GhostTrackComputer.h"
using namespace reco;
static edm::ParameterSet dropDeltaR(const edm::ParameterSet &pset)
{
edm::ParameterSet psetCopy(pset);
psetCopy.addParameter<double>("jetDeltaRMax", 99999.0);
return psetCopy;
}
GhostTrackComputer::GhostTrackComputer(const edm::ParameterSet ¶ms) :
charmCut(params.getParameter<double>("charmCut")),
sortCriterium(TrackSorting::getCriterium(params.getParameter<std::string>("trackSort"))),
trackSelector(params.getParameter<edm::ParameterSet>("trackSelection")),
trackNoDeltaRSelector(dropDeltaR(params.getParameter<edm::ParameterSet>("trackSelection"))),
minTrackWeight(params.getParameter<double>("minimumTrackWeight")),
trackPairV0Filter(params.getParameter<edm::ParameterSet>("trackPairV0Filter"))
{
}
const btag::TrackIPData &
GhostTrackComputer::threshTrack(const TrackIPTagInfo &trackIPTagInfo,
const btag::SortCriteria sort,
const reco::Jet &jet,
const GlobalPoint &pv) const
{
const edm::RefVector<TrackCollection> &tracks =
trackIPTagInfo.selectedTracks();
const std::vector<btag::TrackIPData> &ipData =
trackIPTagInfo.impactParameterData();
std::vector<std::size_t> indices = trackIPTagInfo.sortedIndexes(sort);
TrackKinematics kin;
for(std::vector<std::size_t>::const_iterator iter = indices.begin();
iter != indices.end(); ++iter) {
const btag::TrackIPData &data = ipData[*iter];
const Track &track = *tracks[*iter];
if (!trackNoDeltaRSelector(track, data, jet, pv))
continue;
kin.add(track);
if (kin.vectorSum().M() > charmCut)
return data;
}
static const btag::TrackIPData dummy = {
GlobalPoint(),
GlobalPoint(),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
0.
};
return dummy;
}
const btag::TrackIPData &
GhostTrackComputer::threshTrack(const CandIPTagInfo &trackIPTagInfo,
const btag::SortCriteria sort,
const reco::Jet &jet,
const GlobalPoint &pv) const
{
const CandIPTagInfo::input_container &tracks =
trackIPTagInfo.selectedTracks();
const std::vector<btag::TrackIPData> &ipData =
trackIPTagInfo.impactParameterData();
std::vector<std::size_t> indices = trackIPTagInfo.sortedIndexes(sort);
TrackKinematics kin;
for(std::vector<std::size_t>::const_iterator iter = indices.begin(); iter != indices.end(); ++iter) {
const btag::TrackIPData &data = ipData[*iter];
const CandidatePtr &track = tracks[*iter];
if (!trackNoDeltaRSelector(track, data, jet, pv))
continue;
kin.add(track);
if (kin.vectorSum().M() > charmCut)
return data;
}
static const btag::TrackIPData dummy = {
GlobalPoint(),
GlobalPoint(),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
Measurement1D(-1.0, 1.0),
0.
};
return dummy;
}
static void addMeas(std::pair<double, double> &sum, Measurement1D meas)
{
double weight = 1. / meas.error();
weight *= weight;
sum.first += weight * meas.value();
sum.second += weight;
}
TaggingVariableList
GhostTrackComputer::operator () (const TrackIPTagInfo &ipInfo,
const SecondaryVertexTagInfo &svInfo) const
{
using namespace ROOT::Math;
edm::RefToBase<Jet> jet = ipInfo.jet();
math::XYZVector jetDir = jet->momentum().Unit();
bool havePv = ipInfo.primaryVertex().isNonnull();
GlobalPoint pv;
if (havePv)
pv = GlobalPoint(ipInfo.primaryVertex()->x(),
ipInfo.primaryVertex()->y(),
ipInfo.primaryVertex()->z());
btag::Vertices::VertexType vtxType = btag::Vertices::NoVertex;
TaggingVariableList vars;
vars.insert(btau::jetPt, jet->pt(), true);
vars.insert(btau::jetEta, jet->eta(), true);
TrackKinematics allKinematics;
TrackKinematics vertexKinematics;
TrackKinematics trackKinematics;
std::pair<double, double> vertexDist2D, vertexDist3D;
std::pair<double, double> tracksDist2D, tracksDist3D;
unsigned int nVertices = 0;
unsigned int nVertexTracks = 0;
unsigned int nTracks = 0;
for(unsigned int i = 0; i < svInfo.nVertices(); i++) {
const Vertex &vertex = svInfo.secondaryVertex(i);
bool hasRefittedTracks = vertex.hasRefittedTracks();
TrackRefVector tracks = svInfo.vertexTracks(i);
unsigned int n = 0;
for(TrackRefVector::const_iterator track = tracks.begin();
track != tracks.end(); track++)
if (svInfo.trackWeight(i, *track) >= minTrackWeight)
n++;
if (n < 1)
continue;
bool isTrackVertex = (n == 1);
++*(isTrackVertex ? &nTracks : &nVertices);
addMeas(*(isTrackVertex ? &tracksDist2D : &vertexDist2D),
svInfo.flightDistance(i, true));
addMeas(*(isTrackVertex ? &tracksDist3D : &vertexDist3D),
svInfo.flightDistance(i, false));
TrackKinematics &kin = isTrackVertex ? trackKinematics
: vertexKinematics;
for(TrackRefVector::const_iterator track = tracks.begin();
track != tracks.end(); track++) {
float w = svInfo.trackWeight(i, *track);
if (w < minTrackWeight)
continue;
if (hasRefittedTracks) {
Track actualTrack =
vertex.refittedTrack(*track);
kin.add(actualTrack, w);
vars.insert(btau::trackEtaRel, reco::btau::etaRel(jetDir,
actualTrack.momentum()), true);
} else {
kin.add(**track, w);
vars.insert(btau::trackEtaRel, reco::btau::etaRel(jetDir,
(*track)->momentum()), true);
}
if (!isTrackVertex)
nVertexTracks++;
}
}
Measurement1D dist2D, dist3D;
if (nVertices) {
vtxType = btag::Vertices::RecoVertex;
if (nVertices == 1 && nTracks) {
vertexDist2D.first += tracksDist2D.first;
vertexDist2D.second += tracksDist2D.second;
vertexDist3D.first += tracksDist3D.first;
vertexDist3D.second += tracksDist3D.second;
vertexKinematics += trackKinematics;
}
dist2D = Measurement1D(
vertexDist2D.first / vertexDist2D.second,
std::sqrt(1. / vertexDist2D.second));
dist3D = Measurement1D(
vertexDist3D.first / vertexDist3D.second,
std::sqrt(1. / vertexDist3D.second));
vars.insert(btau::jetNSecondaryVertices, nVertices, true);
vars.insert(btau::vertexNTracks, nVertexTracks, true);
} else if (nTracks) {
vtxType = btag::Vertices::PseudoVertex;
vertexKinematics = trackKinematics;
dist2D = Measurement1D(
tracksDist2D.first / tracksDist2D.second,
std::sqrt(1. / tracksDist2D.second));
dist3D = Measurement1D(
tracksDist3D.first / tracksDist3D.second,
std::sqrt(1. / tracksDist3D.second));
}
if (nVertices || nTracks) {
vars.insert(btau::flightDistance2dVal, dist2D.value(), true);
vars.insert(btau::flightDistance2dSig, dist2D.significance(), true);
vars.insert(btau::flightDistance3dVal, dist3D.value(), true);
vars.insert(btau::flightDistance3dSig, dist3D.significance(), true);
vars.insert(btau::vertexJetDeltaR,
Geom::deltaR(svInfo.flightDirection(0), jetDir),true);
vars.insert(btau::jetNSingleTrackVertices, nTracks, true);
}
std::vector<std::size_t> indices = ipInfo.sortedIndexes(sortCriterium);
const std::vector<btag::TrackIPData> &ipData =
ipInfo.impactParameterData();
const edm::RefVector<TrackCollection> &tracks =
ipInfo.selectedTracks();
TrackRef trackPairV0Test[2];
for(unsigned int i = 0; i < indices.size(); i++) {
std::size_t idx = indices[i];
const btag::TrackIPData &data = ipData[idx];
const TrackRef &trackRef = tracks[idx];
const Track &track = *trackRef;
// filter track
if (!trackSelector(track, data, *jet, pv))
continue;
// add track to kinematics for all tracks in jet
allKinematics.add(track);
// check against all other tracks for V0 track pairs
trackPairV0Test[0] = tracks[idx];
bool ok = true;
for(unsigned int j = 0; j < indices.size(); j++) {
if (i == j)
continue;
std::size_t pairIdx = indices[j];
const btag::TrackIPData &pairTrackData =
ipData[pairIdx];
const TrackRef &pairTrackRef = tracks[pairIdx];
const Track &pairTrack = *pairTrackRef;
if (!trackSelector(pairTrack, pairTrackData, *jet, pv))
continue;
trackPairV0Test[1] = pairTrackRef;
if (!trackPairV0Filter(trackPairV0Test, 2)) {
ok = false;
break;
}
}
if (!ok)
continue;
// add track variables
const math::XYZVector& trackMom = track.momentum();
double trackMag = std::sqrt(trackMom.Mag2());
vars.insert(btau::trackSip3dVal, data.ip3d.value(), true);
vars.insert(btau::trackSip3dSig, data.ip3d.significance(), true);
vars.insert(btau::trackSip2dVal, data.ip2d.value(), true);
vars.insert(btau::trackSip2dSig, data.ip2d.significance(), true);
vars.insert(btau::trackJetDistVal, data.distanceToJetAxis.value(), true);
vars.insert(btau::trackGhostTrackDistVal, data.distanceToGhostTrack.value(), true);
vars.insert(btau::trackGhostTrackDistSig, data.distanceToGhostTrack.significance(), true);
vars.insert(btau::trackGhostTrackWeight, data.ghostTrackWeight, true);
vars.insert(btau::trackDecayLenVal, havePv ? (data.closestToGhostTrack - pv).mag() : -1.0, true);
vars.insert(btau::trackMomentum, trackMag, true);
vars.insert(btau::trackEta, trackMom.Eta(), true);
vars.insert(btau::trackChi2, track.normalizedChi2(), true);
vars.insert(btau::trackNPixelHits, track.hitPattern().pixelLayersWithMeasurement(), true);
vars.insert(btau::trackNTotalHits, track.hitPattern().trackerLayersWithMeasurement(), true);
vars.insert(btau::trackPtRel, VectorUtil::Perp(trackMom, jetDir), true);
vars.insert(btau::trackDeltaR, VectorUtil::DeltaR(trackMom, jetDir), true);
}
vars.insert(btau::vertexCategory, vtxType, true);
vars.insert(btau::trackSumJetDeltaR,
VectorUtil::DeltaR(allKinematics.vectorSum(), jetDir), true);
vars.insert(btau::trackSumJetEtRatio,
allKinematics.vectorSum().Et() / ipInfo.jet()->et(), true);
vars.insert(btau::trackSip3dSigAboveCharm,
threshTrack(ipInfo, reco::btag::IP3DSig, *jet, pv)
.ip3d.significance(),
true);
vars.insert(btau::trackSip2dSigAboveCharm,
threshTrack(ipInfo, reco::btag::IP2DSig, *jet, pv)
.ip2d.significance(),
true);
if (vtxType != btag::Vertices::NoVertex) {
const math::XYZTLorentzVector& allSum = allKinematics.vectorSum();
const math::XYZTLorentzVector& vertexSum = vertexKinematics.vectorSum();
vars.insert(btau::vertexMass, vertexSum.M(), true);
if (allKinematics.numberOfTracks())
vars.insert(btau::vertexEnergyRatio,
vertexSum.E() / allSum.E(), true);
else
vars.insert(btau::vertexEnergyRatio, 1, true);
}
vars.finalize();
return vars;
}
TaggingVariableList
GhostTrackComputer::operator () (const CandIPTagInfo &ipInfo,
const CandSecondaryVertexTagInfo &svInfo) const
{
using namespace ROOT::Math;
edm::RefToBase<Jet> jet = ipInfo.jet();
math::XYZVector jetDir = jet->momentum().Unit();
bool havePv = ipInfo.primaryVertex().isNonnull();
GlobalPoint pv;
if (havePv)
pv = GlobalPoint(ipInfo.primaryVertex()->x(),
ipInfo.primaryVertex()->y(),
ipInfo.primaryVertex()->z());
btag::Vertices::VertexType vtxType = btag::Vertices::NoVertex;
TaggingVariableList vars;
vars.insert(btau::jetPt, jet->pt(), true);
vars.insert(btau::jetEta, jet->eta(), true);
TrackKinematics allKinematics;
TrackKinematics vertexKinematics;
TrackKinematics trackKinematics;
std::pair<double, double> vertexDist2D, vertexDist3D;
std::pair<double, double> tracksDist2D, tracksDist3D;
unsigned int nVertices = 0;
unsigned int nVertexTracks = 0;
unsigned int nTracks = 0;
for(unsigned int i = 0; i < svInfo.nVertices(); i++) {
const reco::VertexCompositePtrCandidate &vertex = svInfo.secondaryVertex(i);
const std::vector<CandidatePtr> & tracks = vertex.daughterPtrVector();
unsigned int n = 0;
for(std::vector<CandidatePtr>::const_iterator track = tracks.begin(); track != tracks.end(); ++track)
n++;
if (n < 1)
continue;
bool isTrackVertex = (n == 1);
++*(isTrackVertex ? &nTracks : &nVertices);
addMeas(*(isTrackVertex ? &tracksDist2D : &vertexDist2D),
svInfo.flightDistance(i, true));
addMeas(*(isTrackVertex ? &tracksDist3D : &vertexDist3D),
svInfo.flightDistance(i, false));
TrackKinematics &kin = isTrackVertex ? trackKinematics : vertexKinematics;
for(std::vector<CandidatePtr>::const_iterator track = tracks.begin(); track != tracks.end(); ++track) {
kin.add(*track);
vars.insert(btau::trackEtaRel, reco::btau::etaRel(jetDir, (*track)->momentum()), true);
if (!isTrackVertex)
nVertexTracks++;
}
}
Measurement1D dist2D, dist3D;
if (nVertices) {
vtxType = btag::Vertices::RecoVertex;
if (nVertices == 1 && nTracks) {
vertexDist2D.first += tracksDist2D.first;
vertexDist2D.second += tracksDist2D.second;
vertexDist3D.first += tracksDist3D.first;
vertexDist3D.second += tracksDist3D.second;
vertexKinematics += trackKinematics;
}
dist2D = Measurement1D(
vertexDist2D.first / vertexDist2D.second,
std::sqrt(1. / vertexDist2D.second));
dist3D = Measurement1D(
vertexDist3D.first / vertexDist3D.second,
std::sqrt(1. / vertexDist3D.second));
vars.insert(btau::jetNSecondaryVertices, nVertices, true);
vars.insert(btau::vertexNTracks, nVertexTracks, true);
} else if (nTracks) {
vtxType = btag::Vertices::PseudoVertex;
vertexKinematics = trackKinematics;
dist2D = Measurement1D(
tracksDist2D.first / tracksDist2D.second,
std::sqrt(1. / tracksDist2D.second));
dist3D = Measurement1D(
tracksDist3D.first / tracksDist3D.second,
std::sqrt(1. / tracksDist3D.second));
}
if (nVertices || nTracks) {
vars.insert(btau::flightDistance2dVal, dist2D.value(), true);
vars.insert(btau::flightDistance2dSig, dist2D.significance(), true);
vars.insert(btau::flightDistance3dVal, dist3D.value(), true);
vars.insert(btau::flightDistance3dSig, dist3D.significance(), true);
vars.insert(btau::vertexJetDeltaR, Geom::deltaR(svInfo.flightDirection(0), jetDir),true);
vars.insert(btau::jetNSingleTrackVertices, nTracks, true);
}
std::vector<std::size_t> indices = ipInfo.sortedIndexes(sortCriterium);
const std::vector<btag::TrackIPData> &ipData = ipInfo.impactParameterData();
const CandIPTagInfo::input_container &tracks = ipInfo.selectedTracks();
const Track * trackPairV0Test[2];
for(unsigned int i = 0; i < indices.size(); i++) {
std::size_t idx = indices[i];
const btag::TrackIPData &data = ipData[idx];
const Track * trackPtr = reco::btag::toTrack(tracks[idx]);
const Track &track = *trackPtr;
// filter track
if (!trackSelector(track, data, *jet, pv))
continue;
// add track to kinematics for all tracks in jet
allKinematics.add(track);
// check against all other tracks for V0 track pairs
trackPairV0Test[0] = reco::btag::toTrack(tracks[idx]);
bool ok = true;
for(unsigned int j = 0; j < indices.size(); j++) {
if (i == j)
continue;
std::size_t pairIdx = indices[j];
const btag::TrackIPData &pairTrackData = ipData[pairIdx];
const Track * pairTrackPtr = reco::btag::toTrack(tracks[pairIdx]);
const Track &pairTrack = *pairTrackPtr;
if (!trackSelector(pairTrack, pairTrackData, *jet, pv))
continue;
trackPairV0Test[1] = pairTrackPtr;
if (!trackPairV0Filter(trackPairV0Test, 2)) {
ok = false;
break;
}
}
if (!ok)
continue;
// add track variables
const math::XYZVector& trackMom = track.momentum();
double trackMag = std::sqrt(trackMom.Mag2());
vars.insert(btau::trackSip3dVal, data.ip3d.value(), true);
vars.insert(btau::trackSip3dSig, data.ip3d.significance(), true);
vars.insert(btau::trackSip2dVal, data.ip2d.value(), true);
vars.insert(btau::trackSip2dSig, data.ip2d.significance(), true);
vars.insert(btau::trackJetDistVal, data.distanceToJetAxis.value(), true);
vars.insert(btau::trackGhostTrackDistVal, data.distanceToGhostTrack.value(), true);
vars.insert(btau::trackGhostTrackDistSig, data.distanceToGhostTrack.significance(), true);
vars.insert(btau::trackGhostTrackWeight, data.ghostTrackWeight, true);
vars.insert(btau::trackDecayLenVal, havePv ? (data.closestToGhostTrack - pv).mag() : -1.0, true);
vars.insert(btau::trackMomentum, trackMag, true);
vars.insert(btau::trackEta, trackMom.Eta(), true);
vars.insert(btau::trackChi2, track.normalizedChi2(), true);
vars.insert(btau::trackNPixelHits, track.hitPattern().pixelLayersWithMeasurement(), true);
vars.insert(btau::trackNTotalHits, track.hitPattern().trackerLayersWithMeasurement(), true);
vars.insert(btau::trackPtRel, VectorUtil::Perp(trackMom, jetDir), true);
vars.insert(btau::trackDeltaR, VectorUtil::DeltaR(trackMom, jetDir), true);
}
vars.insert(btau::vertexCategory, vtxType, true);
vars.insert(btau::trackSumJetDeltaR, VectorUtil::DeltaR(allKinematics.vectorSum(), jetDir), true);
vars.insert(btau::trackSumJetEtRatio, allKinematics.vectorSum().Et() / ipInfo.jet()->et(), true);
vars.insert(btau::trackSip3dSigAboveCharm, threshTrack(ipInfo, reco::btag::IP3DSig, *jet, pv).ip3d.significance(), true);
vars.insert(btau::trackSip2dSigAboveCharm, threshTrack(ipInfo, reco::btag::IP2DSig, *jet, pv).ip2d.significance(), true);
if (vtxType != btag::Vertices::NoVertex) {
const math::XYZTLorentzVector& allSum = allKinematics.vectorSum();
const math::XYZTLorentzVector& vertexSum = vertexKinematics.vectorSum();
vars.insert(btau::vertexMass, vertexSum.M(), true);
if (allKinematics.numberOfTracks())
vars.insert(btau::vertexEnergyRatio, vertexSum.E() / allSum.E(), true);
else
vars.insert(btau::vertexEnergyRatio, 1, true);
}
vars.finalize();
return vars;
}
| 35.324226 | 122 | 0.694787 | [
"vector"
] |
80362d9a249d41f572f40bb0984cc9ede061e723 | 4,640 | cpp | C++ | src/runtime/rpc/dbus/CDBusChannelFactory.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 6 | 2018-05-08T10:08:21.000Z | 2021-11-13T13:22:58.000Z | src/runtime/rpc/dbus/CDBusChannelFactory.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 1 | 2018-05-08T10:20:17.000Z | 2018-07-23T05:19:19.000Z | src/runtime/rpc/dbus/CDBusChannelFactory.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 4 | 2018-03-13T06:21:11.000Z | 2021-06-19T02:48:07.000Z | //=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) 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 "ccmrpc.h"
#include "CDBusChannelFactory.h"
#include "CDBusChannel.h"
#include "CDBusParcel.h"
#include "CProxy.h"
#include "CStub.h"
#include "InterfacePack.h"
#include "registry.h"
#include "util/ccmautoptr.h"
namespace ccm {
CCM_INTERFACE_IMPL_LIGHT_1(CDBusChannelFactory, LightRefBase, IRPCChannelFactory);
CDBusChannelFactory::CDBusChannelFactory(
/* [in] */ RPCType type)
: mType(type)
{}
ECode CDBusChannelFactory::CreateInterfacePack(
/* [out] */ IInterfacePack** ipack)
{
VALIDATE_NOT_NULL(ipack);
*ipack = new InterfacePack();
REFCOUNT_ADD(*ipack);
return NOERROR;
}
ECode CDBusChannelFactory::CreateParcel(
/* [out] */ IParcel** parcel)
{
VALIDATE_NOT_NULL(parcel)
*parcel = new CDBusParcel();
REFCOUNT_ADD(*parcel);
return NOERROR;
}
ECode CDBusChannelFactory::CreateChannel(
/* [in] */ RPCPeer peer,
/* [out] */ IRPCChannel** channel)
{
VALIDATE_NOT_NULL(channel);
*channel = (IRPCChannel*)new CDBusChannel(mType, peer);
REFCOUNT_ADD(*channel);
return NOERROR;
}
ECode CDBusChannelFactory::MarshalInterface(
/* [in] */ IInterface* object,
/* [out] */ IInterfacePack** ipack)
{
VALIDATE_NOT_NULL(ipack);
InterfaceID iid;
object->GetInterfaceID(object, &iid);
InterfacePack* pack = new InterfacePack();
AutoPtr<IStub> stub;
ECode ec = FindExportObject(mType, IObject::Probe(object), &stub);
if (SUCCEEDED(ec)) {
CDBusChannel* channel = CDBusChannel::GetStubChannel(stub);
pack->SetDBusName(channel->mName);
pack->SetCoclassID(((CStub*)stub.Get())->GetTargetCoclassID());
pack->SetInterfaceID(iid);
}
else {
IProxy* proxy = IProxy::Probe(object);
if (proxy != nullptr) {
CDBusChannel* channel = CDBusChannel::GetProxyChannel(proxy);
pack->SetDBusName(channel->mName);
pack->SetCoclassID(((CProxy*)proxy)->GetTargetCoclassID());
pack->SetInterfaceID(iid);
}
else {
ec = CoCreateStub(object, mType, &stub);
if (FAILED(ec)) {
Logger::E("CDBusChannel", "Marshal interface failed.");
*ipack = nullptr;
return ec;
}
CDBusChannel* channel = CDBusChannel::GetStubChannel(stub);
pack->SetDBusName(channel->mName);
pack->SetCoclassID(((CStub*)stub.Get())->GetTargetCoclassID());
pack->SetInterfaceID(iid);
RegisterExportObject(mType, IObject::Probe(object), stub);
}
}
*ipack = (IInterfacePack*)pack;
REFCOUNT_ADD(*ipack);
return NOERROR;
}
ECode CDBusChannelFactory::UnmarshalInterface(
/* [in] */ IInterfacePack* ipack,
/* [out] */ IInterface** object)
{
VALIDATE_NOT_NULL(object);
AutoPtr<IObject> iobject;
ECode ec = FindImportObject(mType, ipack, &iobject);
if (SUCCEEDED(ec)) {
InterfaceID iid;
ipack->GetInterfaceID(&iid);
*object = iobject->Probe(iid);
REFCOUNT_ADD(*object);
return NOERROR;
}
AutoPtr<IStub> stub;
ec = FindExportObject(mType, ipack, &stub);
if (SUCCEEDED(ec)) {
CStub* stubObj = (CStub*)stub.Get();
InterfaceID iid;
ipack->GetInterfaceID(&iid);
*object = stubObj->GetTarget()->Probe(iid);
REFCOUNT_ADD(*object);
return NOERROR;
}
CoclassID cid;
ipack->GetCoclassID(&cid);
AutoPtr<IProxy> proxy;
ec = CoCreateProxy(cid, mType, &proxy);
if (FAILED(ec)) {
*object = nullptr;
return ec;
}
CDBusChannel* channel = CDBusChannel::GetProxyChannel(proxy);
channel->mName = ((InterfacePack*)ipack)->GetDBusName();
RegisterImportObject(mType, ipack, IObject::Probe(proxy));
proxy.MoveTo((IProxy**)object);
return NOERROR;
}
}
| 29.55414 | 82 | 0.621552 | [
"object",
"model"
] |
80379f3929287da70470023a1713e766c6068568 | 3,869 | cc | C++ | bridge/bindings/jsc/DOM/text_node.cc | jeromehan/kraken | cbc4977de5f3a9ac62b3e6cb5aa0383988d8178a | [
"Apache-2.0"
] | 1 | 2021-03-14T06:34:02.000Z | 2021-03-14T06:34:02.000Z | bridge/bindings/jsc/DOM/text_node.cc | jeromehan/kraken | cbc4977de5f3a9ac62b3e6cb5aa0383988d8178a | [
"Apache-2.0"
] | 1 | 2021-05-08T08:43:08.000Z | 2021-05-08T08:43:08.000Z | bridge/bindings/jsc/DOM/text_node.cc | jeromehan/kraken | cbc4977de5f3a9ac62b3e6cb5aa0383988d8178a | [
"Apache-2.0"
] | 1 | 2021-09-13T03:51:47.000Z | 2021-09-13T03:51:47.000Z | /*
* Copyright (C) 2020 Alibaba Inc. All rights reserved.
* Author: Kraken Team.
*/
#include "text_node.h"
namespace kraken::binding::jsc {
void bindTextNode(std::unique_ptr<JSContext> &context) {
auto textNode = JSTextNode::instance(context.get());
JSC_GLOBAL_SET_PROPERTY(context, "Text", textNode->classObject);
}
std::unordered_map<JSContext *, JSTextNode *> JSTextNode::instanceMap{};
JSTextNode *JSTextNode::instance(JSContext *context) {
if (instanceMap.count(context) == 0) {
instanceMap[context] = new JSTextNode(context);
}
return instanceMap[context];
}
JSTextNode::~JSTextNode() {
instanceMap.erase(context);
}
JSTextNode::JSTextNode(JSContext *context) : JSNode(context, "Text") {}
JSObjectRef JSTextNode::instanceConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount,
const JSValueRef *arguments, JSValueRef *exception) {
const JSValueRef dataValueRef = arguments[0];
auto textNode = new TextNodeInstance(this, JSValueToStringCopy(ctx, dataValueRef, exception));
return textNode->object;
}
JSTextNode::TextNodeInstance::TextNodeInstance(JSTextNode *jsTextNode, JSStringRef data)
: NodeInstance(jsTextNode, NodeType::TEXT_NODE), nativeTextNode(new NativeTextNode(nativeNode)) {
m_data.setString(data);
NativeString args_01{};
buildUICommandArgs(data, args_01);
foundation::UICommandBuffer::instance(_hostClass->contextId)
->addCommand(eventTargetId, UICommand::createTextNode, args_01, nativeTextNode);
}
JSValueRef JSTextNode::TextNodeInstance::getProperty(std::string &name, JSValueRef *exception) {
auto &propertyMap = getTextNodePropertyMap();
if (propertyMap.count(name) == 0) {
return NodeInstance::getProperty(name, exception);
}
auto &property = propertyMap[name];
switch (property) {
case TextNodeProperty::nodeValue:
case TextNodeProperty::textContent:
case TextNodeProperty::data: {
return m_data.makeString();
}
case TextNodeProperty::nodeName: {
JSStringRef nodeName = JSStringCreateWithUTF8CString("#text");
return JSValueMakeString(_hostClass->ctx, nodeName);
}
}
}
bool JSTextNode::TextNodeInstance::setProperty(std::string &name, JSValueRef value, JSValueRef *exception) {
if (name == "data" || name == "nodeValue") {
JSStringRef data = JSValueToStringCopy(_hostClass->ctx, value, exception);
m_data.setString(data);
std::string dataString = JSStringToStdString(data);
NativeString args_01{};
NativeString args_02{};
buildUICommandArgs(name, dataString, args_01, args_02);
foundation::UICommandBuffer::instance(_hostClass->contextId)
->addCommand(eventTargetId, UICommand::setProperty, args_01, args_02, nullptr);
return true;
} else {
return NodeInstance::setProperty(name, value, exception);
}
}
void JSTextNode::TextNodeInstance::getPropertyNames(JSPropertyNameAccumulatorRef accumulator) {
NodeInstance::getPropertyNames(accumulator);
for (auto &property : getTextNodePropertyNames()) {
JSPropertyNameAccumulatorAddName(accumulator, property);
}
}
std::string JSTextNode::TextNodeInstance::internalGetTextContent() {
return m_data.string();
}
JSTextNode::TextNodeInstance::~TextNodeInstance() {
foundation::UICommandCallbackQueue::instance()->registerCallback([](void *ptr) {
delete reinterpret_cast<NativeTextNode *>(ptr);
}, nativeTextNode);
}
void JSTextNode::TextNodeInstance::internalSetTextContent(JSStringRef content, JSValueRef *exception) {
m_data.setString(content);
std::string key = "data";
NativeString args_01{};
NativeString args_02{};
buildUICommandArgs(key, content, args_01, args_02);
foundation::UICommandBuffer::instance(context->getContextId())
->addCommand(eventTargetId, UICommand::setProperty, args_01, args_02, nullptr);
}
} // namespace kraken::binding::jsc
| 33.643478 | 108 | 0.74412 | [
"object"
] |
803bef091ca9ee0e507114eca7ddf6bd0a49c0cf | 971 | cpp | C++ | time/time.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | 1 | 2020-12-15T20:25:21.000Z | 2020-12-15T20:25:21.000Z | time/time.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | time/time.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n, m, c;
int b[1005][1005];
int mn[1005];
vector<int> g[1005];
int dfs(int f, int d)
{
if (b[f][d])
{
return b[f][d];
}
if (f == 1 && d == 0)
{
return 0;
}
if (d == 0)
{
return -1000000000;
}
int tmp = -1000000000;
for (int i = 0; i < g[f].size(); i++)
{
tmp = max(tmp, dfs(g[f][i], d - 1));
}
b[f][d] = tmp + mn[f];
return b[f][d];
}
int main()
{
cin >> n >> m >> c;
for (int i = 1; i <= n; i++)
{
cin >> mn[i];
}
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
g[b].push_back(a);
}
for (int i = 0; i <= 1001; i++)
{
for (int j = 1; j <= n; j++)
{
dfs(j, i);
}
}
int ans = 0;
for (int i = 0; i <= 1001; i++)
{
ans = max(ans, b[1][i] - c * i * i);
}
cout << ans << endl;
return 0;
} | 17.339286 | 44 | 0.359423 | [
"vector"
] |
d9a40062061c12aa6e7a8b3fd87cc3b816c7eb5e | 5,675 | cpp | C++ | src/caffe/layers/core/attention_crop_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | 7 | 2018-02-06T13:48:17.000Z | 2019-04-08T13:56:22.000Z | src/caffe/layers/core/attention_crop_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/core/attention_crop_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #ifdef USE_OPENCV
#include <vector>
#include <opencv2/core/core.hpp>
#include "caffe/layers/attention_crop_layer.hpp"
#include "caffe/util/math_functions.hpp"
#include "opencv2/opencv.hpp"
#include "caffe/util/rng.hpp"
#define ek 0.05
#define core 3
namespace caffe {
template<typename Dtype>
void AttentionCropLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// nothing should be done here
}
template<typename Dtype>
void AttentionCropLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// then assign the shape of the top blob
vector<int> top_shape = bottom[0]->shape();
top_shape[2] = out_size;
top_shape[3] = out_size;
top[0]->Reshape(top_shape);
}
template<typename Dtype>
void AttentionCropLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
Dtype mean_value[3] = { mean_value1, mean_value2, mean_value3 };
Dtype* top_data_cpu = top[0]->mutable_cpu_data();
const Dtype* bottom_data_0 = bottom[0]->cpu_data();
const Dtype* bottom_data_1 = bottom[1]->cpu_data();
cv::Mat cv_img = cv::Mat(bottom[0]->shape(2), bottom[0]->shape(2), CV_8UC3);
cv::Mat out_cv_img = cv::Mat(out_size, out_size, CV_8UC3);
int bottom_index;
int in_size = bottom[0]->shape(2);
for (int n = 0; n<bottom[0]->shape(0); n++)
{
Dtype a = bottom_data_1[n * 3];
Dtype b = bottom_data_1[n * 3 + 1];
Dtype c = bottom_data_1[n * 3 + 2];
c = c>0.01 * in_size ? c : 0.01 * in_size;
int w_off = int(a - c > 0 ? a - c : 0);
int h_off = int(b - c > 0 ? b - c : 0);
int w_end = int((a + c) < in_size ? (a + c) : in_size);
int h_end = int((b + c) < in_size ? (b + c) : in_size);
for (int i = 0; i < bottom[0]->shape(2); i++)
{
uchar* ptr = cv_img.ptr<uchar>(i);
int img_index = 0;
for (int j = 0; j < bottom[0]->shape(2); j++)
{
for (int k = 0; k < 3; k++)
{
bottom_index = n * bottom[0]->count(1) + (k * bottom[0]->shape(2) + i) * bottom[0]->shape(2) + j;
ptr[img_index++] = bottom_data_0[bottom_index] + mean_value[k];
}
}
}
cv::Rect roi(w_off, h_off, w_end - w_off, h_end - h_off);
cv::Mat cv_cropped_img = cv_img(roi);
cv::resize(cv_cropped_img, out_cv_img, out_cv_img.size(), 0, 0, cv::INTER_LINEAR);
int top_index;
for (int i = 0; i < out_size; i++)
{
const uchar* ptr = out_cv_img.ptr<uchar>(i);
int img_index = 0;
for (int j = 0; j < out_size; j++)
{
for (int k = 0; k < 3; k++)
{
Dtype pixel = static_cast<Dtype>(ptr[img_index++]);
top_index = n * top[0]->count(1) + (k * out_size + i) * out_size + j;
top_data_cpu[top_index] = pixel - mean_value[k];
}
}
}
}
}
template<typename Dtype>
Dtype H(Dtype x){
return 1 / (1 + exp(-ek*x));
}
template<typename Dtype>
Dtype diff_H(Dtype x){
return ek * exp(-ek*x) / ((1 + exp(-ek*x))*(1 + exp(-ek*x)));
}
template<typename Dtype>
Dtype F(Dtype a, Dtype b, Dtype c, Dtype x, Dtype y) {
return (H(x - (a - c)) - H(x - (a + c)))*(H(y - (b - c)) - H(y - (b + c)));
}
template<typename Dtype>
Dtype diff_F_a(Dtype a, Dtype b, Dtype c, Dtype x, Dtype y) {
return (diff_H(x - (a - c)) - diff_H(x - (a + c)))*(H(y - (b - c)) - H(y - (b + c)));
}
template<typename Dtype>
Dtype diff_F_b(Dtype a, Dtype b, Dtype c, Dtype x, Dtype y) {
return (diff_H(y - (b - c)) - diff_H(y - (b + c)))*(H(x - (a - c)) - H(x - (a + c)));
}
template<typename Dtype>
Dtype diff_F_c(Dtype a, Dtype b, Dtype c, Dtype x, Dtype y) {
return -((diff_H(y - (b - c)) + diff_H(y - (b + c)))*(H(x - (a - c)) - H(x - (a + c))) + (diff_H(x - (a - c)) + diff_H(x - (a + c)))*(H(y - (b - c)) - H(y - (b + c)))) + 0.005;
}
template<typename Dtype>
void AttentionCropLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* top_data = top[0]->cpu_data();
Dtype* bottom_diff_cpu = bottom[1]->mutable_cpu_diff();
const Dtype* bottom_data = bottom[1]->cpu_data();
int in_size = bottom[0]->shape(2);
caffe_set(bottom[1]->count(), Dtype(0.0), bottom_diff_cpu);
int count_1 = top[0]->count(1);
int count_2 = top[0]->count(2);
int count_3 = top[0]->count(3);
Dtype a;
Dtype b;
Dtype c;
for (int i = 0; i < top[0]->shape(0); i++)
{
a = bottom_data[i * 3];
b = bottom_data[i * 3 + 1];
c = bottom_data[i * 3 + 2];
for (int j = 0; j < top[0]->shape(1); j++)
{
Dtype max_diff = 0;
for (int k = 0; k < top[0]->shape(2); k++)
{
for (int l = 0; l < top[0]->shape(3); l++)
{
int top_index = i * count_1 + j * count_2 + k * count_3 + l;
Dtype top = top_diff[top_index]>0 ? top_diff[top_index] : -top_diff[top_index];
if (top > max_diff)
{
max_diff = top;
}
}
}
for (int k = 0; k < top[0]->shape(2); k++)
{
for (int l = 0; l < top[0]->shape(3); l++)
{
int top_index = i * count_1 + j * count_2 + k * count_3 + l;
Dtype top = top_diff[top_index]>0 ? top_diff[top_index] : -top_diff[top_index];
if (max_diff > 0)
{
top = top / max_diff * 0.0000001;
}
Dtype x = a - c + 2 * l * c / out_size;
Dtype y = b - c + 2 * k * c / out_size;
bottom_diff_cpu[3 * i + 0] += top * diff_F_a(a, b, c, x, y);
bottom_diff_cpu[3 * i + 1] += top * diff_F_b(a, b, c, x, y);
bottom_diff_cpu[3 * i + 2] += top * diff_F_c(a, b, c, x, y);
}
}
}
}
}
#ifndef USE_CUDA
STUB_GPU(AttentionCropLayer);
#endif
INSTANTIATE_CLASS(AttentionCropLayer);
REGISTER_LAYER_CLASS(AttentionCrop);
} // namespace caffe
#endif | 29.252577 | 177 | 0.587841 | [
"shape",
"vector"
] |
d9a6c222d64a8f126d9f86f297187ab93c435ada | 2,986 | hpp | C++ | boost/boost_1_56_0/libs/numeric/odeint/performance/openmp/osc_chain_1d_system.hpp | cooparation/caffe-android | cd91078d1f298c74fca4c242531989d64a32ba03 | [
"BSD-2-Clause-FreeBSD"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | boost/boost_1_56_0/libs/numeric/odeint/performance/openmp/osc_chain_1d_system.hpp | cooparation/caffe-android | cd91078d1f298c74fca4c242531989d64a32ba03 | [
"BSD-2-Clause-FreeBSD"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | boost/boost_1_56_0/libs/numeric/odeint/performance/openmp/osc_chain_1d_system.hpp | cooparation/caffe-android | cd91078d1f298c74fca4c242531989d64a32ba03 | [
"BSD-2-Clause-FreeBSD"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | /* Boost libs/numeric/odeint/performance/openmp/osc_chain_1d_system.hpp
Copyright 2013 Karsten Ahnert
Copyright 2013 Mario Mulansky
Copyright 2013 Pascal Germroth
stronlgy nonlinear hamiltonian lattice
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)
*/
#ifndef SYSTEM_HPP
#define SYSTEM_HPP
#include <vector>
#include <cmath>
#include <iostream>
#include <omp.h>
#include <boost/math/special_functions/sign.hpp>
#include <boost/numeric/odeint/external/openmp/openmp.hpp>
namespace checked_math {
inline double pow( double x , double y )
{
if( x==0.0 )
// 0**y = 0, don't care for y = 0 or NaN
return 0.0;
using std::pow;
using std::abs;
return pow( abs(x) , y );
}
}
double signed_pow( double x , double k )
{
using boost::math::sign;
return checked_math::pow( x , k ) * sign(x);
}
struct osc_chain {
const double m_kap, m_lam;
osc_chain( const double kap , const double lam )
: m_kap( kap ) , m_lam( lam )
{ }
// Simple case with openmp_range_algebra
void operator()( const std::vector<double> &q ,
std::vector<double> &dpdt ) const
{
const size_t N = q.size();
double coupling_lr = 0;
size_t last_i = N;
#pragma omp parallel for firstprivate(coupling_lr, last_i) lastprivate(coupling_lr) schedule(runtime)
for(size_t i = 0 ; i < N - 1 ; ++i)
{
if(i > 0 && i != last_i + 1)
coupling_lr = signed_pow( q[i-1]-q[i] , m_lam-1 );
dpdt[i] = -signed_pow( q[i] , m_kap-1 ) + coupling_lr;
coupling_lr = signed_pow( q[i] - q[i+1] , m_lam-1 );
dpdt[i] -= coupling_lr;
last_i = i;
}
dpdt[N-1] = -signed_pow( q[N-1] , m_kap-1 ) + coupling_lr;
}
// Split case with openmp_algebra
void operator()( const boost::numeric::odeint::openmp_state<double> &q ,
boost::numeric::odeint::openmp_state<double> &dpdt ) const
{
const size_t M = q.size();
#pragma omp parallel for schedule(runtime)
for(size_t i = 0 ; i < M ; ++i)
{
const std::vector<double> &_q = q[i];
std::vector<double> &_dpdt = dpdt[i];
const size_t N = q[i].size();
double coupling_lr = 0;
if(i > 0) coupling_lr = signed_pow( q[i-1].back() - _q[0] , m_lam-1 );
for(size_t j = 0 ; j < N-1 ; ++j)
{
_dpdt[j] = -signed_pow( _q[j] , m_kap-1 ) + coupling_lr;
coupling_lr = signed_pow( _q[j] - _q[j+1] , m_lam-1 );
_dpdt[j] -= coupling_lr;
}
_dpdt[N-1] = -signed_pow( _q[N-1] , m_kap-1 ) + coupling_lr;
if(i + 1 < M) _dpdt[N-1] -= signed_pow( _q[N-1] - q[i+1].front() , m_lam-1 );
}
}
};
#endif
| 30.161616 | 109 | 0.556263 | [
"vector"
] |
d9aa1c11772d88db77731a030835bb80d68e6b74 | 9,934 | cpp | C++ | src/latex/LatexDocument.cpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | 15 | 2017-10-20T07:53:03.000Z | 2021-09-23T15:54:54.000Z | src/latex/LatexDocument.cpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | null | null | null | src/latex/LatexDocument.cpp | dholzmueller/sfcpp | b929419b13c35fff199c6c65e87ecffae9963cfc | [
"Apache-2.0"
] | 3 | 2017-10-20T20:02:29.000Z | 2020-12-02T12:47:53.000Z | /* Copyright 2017 The sfcpp Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "LatexDocument.hpp"
#include <boost/filesystem.hpp>
#include <files/files.hpp>
#include <cstdlib>
namespace sfcpp {
namespace latex {
extern std::string documentHeader;
std::string LatexDocument::getCode() const {
return "\\documentclass[tikz,border=0.1cm]{standalone}\n" + documentHeader +
"\n\\begin{document}\n" + container.getCode() + "\\end{document}\n"; // TODO
}
void LatexDocument::addElement(std::shared_ptr<LatexElement> element) {
container.addElement(element);
}
void LatexDocument::saveAndCompile(std::string filename) {
sfcpp::files::writeToFile(filename, getCode());
std::string command;
boost::filesystem::path p(filename);
auto parentPath = p.parent_path();
if (!parentPath.empty()) {
command += "cd " + parentPath.native() + "; ";
}
command += "pdflatex -interaction=batchmode " + p.filename().native();
system(command.c_str());
}
std::string documentHeader = R"package(
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[ngerman]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{mathtools}
\usepackage{IEEEtrantools}
\usepackage{microtype}
\usepackage{amsopn}
\usepackage{varwidth}
\usepackage{xcolor,colortbl}
\usepackage{tabu}
\usepackage{comment}
\usepackage{enumerate}
\usepackage{array}
\usepackage{csquotes}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage{tikz-3dplot}
\usepackage{nicefrac}
\usetikzlibrary{trees,positioning,shapes,calc,patterns,angles,quotes}
%\usepackage[squaren]{SIunits}
\usepackage{pgfplots}
\usepackage{algpseudocode}
\usepackage{algorithm}
%\usepackage{hyperref}
\usepackage{booktabs}
\usepackage{amsfonts}
\usepackage{color}
\usepackage{stmaryrd}
\usepackage[shortlabels]{enumitem}
\usepackage{todonotes}
\usepackage{mathdots}
\usepackage{empheq}
\usepgfplotslibrary{fillbetween}
\pgfplotsset{compat=1.11}
\usepackage[caption=false]{subfig}
\usepackage{etoolbox}
\makeatletter
\providerobustcmd*{\bigcupdot}{%
\mathop{%
\mathpalette\bigop@dot\bigcup
}%
}
\newrobustcmd*{\bigop@dot}[2]{%
\setbox0=\hbox{$\m@th#1#2$}%
\vbox{%
\lineskiplimit=\maxdimen
\lineskip=-0.7\dimexpr\ht0+\dp0\relax
\ialign{%
\hfil##\hfil\cr
$\m@th\cdot$\cr
\box0\cr
}%
}%
}
\makeatother
\newcommand*\widefbox[1]{\fbox{\hspace{2em}#1\hspace{2em}}}
\newlength\Origarrayrulewidth
% horizontal rule equivalent to \cline but with 2pt width
\newcommand{\Cline}[1]{%
\noalign{\global\setlength\Origarrayrulewidth{\arrayrulewidth}}%
\noalign{\global\setlength\arrayrulewidth{2pt}}\cline{#1}%
\noalign{\global\setlength\arrayrulewidth{\Origarrayrulewidth}}%
}
% draw a vertical rule of width 2pt on both sides of a cell
\newcommand\Thickvrule[1]{%
\multicolumn{1}{!{\vrule width 2pt}c!{\vrule width 2pt}}{#1}%
}
% draw a vertical rule of width 2pt on the left side of a cell
\newcommand\Thickvrulel[1]{%
\multicolumn{1}{!{\vrule width 2pt}c|}{#1}%
}
% draw a vertical rule of width 2pt on the right side of a cell
\newcommand\Thickvruler[1]{%
\multicolumn{1}{|c!{\vrule width 2pt}}{#1}%
}
\theoremstyle{plain}
\newtheorem{theorem}{Satz}
\newtheorem{satz}{Satz}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{Theorem}[theorem]{Theorem}
\newtheorem{corollary}[theorem]{Korollar}
\theoremstyle{definition}
\newtheorem{defi}[theorem]{Definition}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{algorithmThm}[theorem]{Algorithmus}
\newtheorem{remark}[theorem]{Bemerkung}
\newtheorem{bem}[theorem]{Bemerkung}
\newtheorem{example}[theorem]{Beispiel}
\newtheorem{bsp}[theorem]{Beispiel}
\newtheorem{outlook}[theorem]{Ausblick}
\newtheorem{notation}[theorem]{Notation}
%\newenvironment{bsp}{\par\noindent\textbf{\thechapter. Beispiel}}{}
\newcommand{\myworries}[1]{\textcolor{red}{#1}}
\newtheorem{exercise}{Aufgabe}
\numberwithin{exercise}{section}
\numberwithin{equation}{section}
\numberwithin{theorem}{section}
\newcommand{\bbA}{\mathbb{A}}
\newcommand{\bbB}{\mathbb{B}}
\newcommand{\bbC}{\mathbb{C}}
\newcommand{\bbD}{\mathbb{D}}
\newcommand{\bbE}{\mathbb{E}}
\newcommand{\bbF}{\mathbb{F}}
\newcommand{\bbG}{\mathbb{G}}
\newcommand{\bbH}{\mathbb{H}}
\newcommand{\bbI}{\mathbb{I}}
\newcommand{\bbJ}{\mathbb{J}}
\newcommand{\bbK}{\mathbb{K}}
\newcommand{\bbL}{\mathbb{L}}
\newcommand{\bbM}{\mathbb{M}}
\newcommand{\bbN}{\mathbb{N}}
\newcommand{\bbO}{\mathbb{O}}
\newcommand{\bbP}{\mathbb{P}}
\newcommand{\bbQ}{\mathbb{Q}}
\newcommand{\bbR}{\mathbb{R}}
\newcommand{\bbS}{\mathbb{S}}
\newcommand{\bbT}{\mathbb{T}}
\newcommand{\bbU}{\mathbb{U}}
\newcommand{\bbV}{\mathbb{V}}
\newcommand{\bbW}{\mathbb{W}}
\newcommand{\bbX}{\mathbb{X}}
\newcommand{\bbY}{\mathbb{Y}}
\newcommand{\bbZ}{\mathbb{Z}}
\newcommand{\calA}{\mathcal{A}}
\newcommand{\calB}{\mathcal{B}}
\newcommand{\calC}{\mathcal{C}}
\newcommand{\calD}{\mathcal{D}}
\newcommand{\calE}{\mathcal{E}}
\newcommand{\calF}{\mathcal{F}}
\newcommand{\calG}{\mathcal{G}}
\newcommand{\calH}{\mathcal{H}}
\newcommand{\calI}{\mathcal{I}}
\newcommand{\calJ}{\mathcal{J}}
\newcommand{\calK}{\mathcal{K}}
\newcommand{\calL}{\mathcal{L}}
\newcommand{\calM}{\mathcal{M}}
\newcommand{\calN}{\mathcal{N}}
\newcommand{\calO}{\mathcal{O}}
\newcommand{\calP}{\mathcal{P}}
\newcommand{\calQ}{\mathcal{Q}}
\newcommand{\calR}{\mathcal{R}}
\newcommand{\calS}{\mathcal{S}}
\newcommand{\calT}{\mathcal{T}}
\newcommand{\calU}{\mathcal{U}}
\newcommand{\calV}{\mathcal{V}}
\newcommand{\calW}{\mathcal{W}}
\newcommand{\calX}{\mathcal{X}}
\newcommand{\calY}{\mathcal{Y}}
\newcommand{\calZ}{\mathcal{Z}}
%Miscellaneous
\newcommand{\diff}{d} %{\,\mathrm{d}}
\newcommand{\ddx}{\frac{\diff}{\diff x}}
\newcommand{\quot}[1]{\enquote{#1}}
\newcommand{\setof}[1]{\widehat{#1}} %die Menge einer Algebra
\newcommand{\WLOG}{without loss of generality}
\DeclareMathOperator{\fst}{fst}
\DeclareMathOperator{\snd}{snd}
%Functions
\newcommand{\successor}[1]{s(#1)}
\newcommand{\predecessor}[1]{p(#1)}
\newcommand{\successors}[1]{S_{#1}}
\newcommand{\predecessors}[1]{P_{#1}}
\newcommand{\innerSet}[1]{\widehat{#1}}
%Operators for Relations
\newcommand{\equalDef}{\coloneqq}
\newcommand{\defEqual}{\eqqcolon}
\newcommand{\equivDef}{:\Leftrightarrow}
%Operators for Functions
\newcommand{\dProd}[2]{\left\langle #1, #2 \right\rangle}
\newcommand{\revdProd}[2]{\,\overleftrightarrow{\!\dProd{#1}{#2}\!}\,}
\newcommand{\revrevdProd}[2]{\,\overleftrightarrow{\overleftrightarrow{\!\dProd{#1}{#2}\!}}\,}
\newcommand{\dProdFunc}{\dProd{\cdot}{\cdot}}
\newcommand{\revdProdFunc}{\revdProd{\cdot}{\cdot}}
\newcommand{\revrevdProdFunc}{\revrevdProd{\cdot}{\cdot}}
\newcommand{\norm}[1]{\| #1 \|}
\newcommand{\logtwo}{\log_2}
%Operators for Sets
\newcommand{\powerset}[1]{\calP(#1)}
\newcommand{\card}[1]{|#1|}
\DeclareMathOperator{\Hom}{Hom}
\DeclareMathOperator{\Kern}{Kern}
\DeclareMathOperator{\Bild}{Bild}
\DeclareMathOperator{\im}{im}
\DeclareMathOperator{\id}{id}
\DeclareMathOperator{\cod}{cod}
\DeclareMathOperator{\dom}{dom}
\DeclareMathOperator*{\argmax}{argmax}
%Concrete Set Identifiers
\newcommand{\steadyOn}[1]{C(#1)}
\newcommand{\natOne}{\bbZ^+}
\newcommand{\natZero}{\bbN_0}
\newcommand{\oneToN}[1]{\bbN^{(#1)}}
\newcommand{\integers}{\bbZ}
\newcommand{\rationals}{\bbQ}
\newcommand{\reals}{\bbR}
\newcommand{\complex}{\bbC}
\newcommand{\posReals}{\bbR^+}
\newcommand{\nonNegReals}{\bbR_0^+}
\newcommand{\negReals}{\bbR^-}
\newcommand{\nonPosReals}{\bbR_0^-}
\newcommand{\domain}[1]{\dom \left( #1 \right)}
\newcommand{\codomain}[1]{\cod \left( #1 \right)}
\newcommand{\image}[1]{\im \left( #1 \right)}
\DeclareMathOperator{\rePart}{Re}
\DeclareMathOperator{\imPart}{Im}
%Complexity Sets
%\newcommand{\compEq}[2][]{\Theta_{#1} \left( #2 \right)}
%\newcommand{\compLess}[2][]{o_{#1} \left( #2 \right)}
%\newcommand{\compLeq}[2][]{\calO_{#1} \left( #2 \right)}
%\newcommand{\compGreater}[2][]{\omega_{#1} \left( #2 \right)}
%\newcommand{\compGeq}[2][]{\Omega_{#1} \left( #2 \right)}
\newcommand{\compEq}[1]{\Theta \left( #1 \right)}
\newcommand{\compLess}[1]{o\left( #1 \right)}
\newcommand{\compLeq}[1]{O\left( #1 \right)}
\newcommand{\compGreater}[1]{\omega\left( #1 \right)}
\newcommand{\compGeq}[1]{\Omega\left( #1 \right)}
\newcommand{\subsEq}{\subseteq}
\newcommand{\subsNeq}{\subsetneq}
\newcommand{\assign}{\coloneqq}
\newcommand{\mybracketl}[1]{[}
\newcommand{\mybracketr}[1]{]}
\providecommand{\piValue}{3.1415926535897932384626433832795028841}
\pgfplotscreateplotcyclelist{custom black white}{%
solid, every mark/.append style={solid, fill=gray}, mark=*\\%
dotted, every mark/.append style={solid, fill=gray}, mark=square*\\%
densely dotted, every mark/.append style={solid, fill=gray}, mark=triangle*\\%
dashdotted, every mark/.append style={solid, fill=gray}, mark=star\\%
dashed, every mark/.append style={solid, fill=gray},mark=diamond*\\%
loosely dashed, every mark/.append style={solid, fill=gray},mark=*\\%
densely dashed, every mark/.append style={solid, fill=gray},mark=square*\\%
dashdotted, every mark/.append style={solid, fill=gray},mark=otimes*\\%
dashdotdotted, every mark/.append style={solid},mark=star\\%
densely dashdotted,every mark/.append style={solid, fill=gray},mark=diamond*\\%
}
)package";
} /* namespace latex */
} /* namespace utils */
| 30.10303 | 94 | 0.7121 | [
"solid"
] |
d9ab54462afec355b137d48f4d90213994f30253 | 842 | cpp | C++ | src/RandomizePlayerIds.cpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | 1 | 2018-12-28T00:06:30.000Z | 2018-12-28T00:06:30.000Z | src/RandomizePlayerIds.cpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | 1 | 2020-02-07T17:46:26.000Z | 2020-02-07T18:12:07.000Z | src/RandomizePlayerIds.cpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | null | null | null | #include "RandomizePlayerIds.hpp"
RandomizePlayerIds::RandomizePlayerIds(IPlayerRegistry& registry)
: mPlayerRegistry(registry)
{
spdlog::get("console")->debug("RandomizePlayerIds::RandomizePlayerIds()");
}
RandomizePlayerIds::~RandomizePlayerIds()
{
spdlog::get("console")->debug("RandomizePlayerIds::~RandomizePlayerIds()");
}
void RandomizePlayerIds::Randomize()
{
spdlog::get("console")->debug("RandomizePlayerIds::Process() - Start");
std::vector<std::shared_ptr<Player>> players = mPlayerRegistry.GetListOfPlayers();
unsigned int numberOfPlayers = players.size();
std::random_shuffle(players.begin(), players.end());
for( unsigned int x = 0; x < numberOfPlayers; x++ )
{
players[x]->AssignPlayerID(x + 1);
}
spdlog::get("console")->debug("RandomizePlayerIds::Process() - Done");
}
| 30.071429 | 86 | 0.7019 | [
"vector"
] |
d9b0ff184e8510040cf3e3865f70254cc9980b8c | 7,815 | hpp | C++ | vpd-manager/editor_impl.hpp | geissonator/openpower-vpd-parser | 8be4334fd9515897bed6247159edb9004ba49939 | [
"Apache-2.0"
] | 3 | 2021-02-23T15:34:17.000Z | 2022-03-23T09:57:59.000Z | vpd-manager/editor_impl.hpp | geissonator/openpower-vpd-parser | 8be4334fd9515897bed6247159edb9004ba49939 | [
"Apache-2.0"
] | 14 | 2019-09-16T12:27:41.000Z | 2022-03-30T04:07:04.000Z | vpd-manager/editor_impl.hpp | geissonator/openpower-vpd-parser | 8be4334fd9515897bed6247159edb9004ba49939 | [
"Apache-2.0"
] | 11 | 2019-09-09T03:32:08.000Z | 2022-02-22T05:04:02.000Z | #pragma once
#include "const.hpp"
#include "types.hpp"
#include <cstddef>
#include <fstream>
#include <nlohmann/json.hpp>
#include <tuple>
namespace openpower
{
namespace vpd
{
namespace manager
{
namespace editor
{
/** @class EditorImpl */
class EditorImpl
{
public:
EditorImpl() = delete;
EditorImpl(const EditorImpl&) = delete;
EditorImpl& operator=(const EditorImpl&) = delete;
EditorImpl(EditorImpl&&) = delete;
EditorImpl& operator=(EditorImpl&&) = delete;
~EditorImpl()
{
}
/** @brief Construct EditorImpl class
*
* @param[in] record - Record Name
* @param[in] kwd - Keyword
* @param[in] vpd - Vpd Vector
*/
EditorImpl(const std::string& record, const std::string& kwd,
Binary&& vpd) :
startOffset(0),
thisRecord(record, kwd), vpdFile(std::move(vpd))
{
}
/** @brief Construct EditorImpl class
*
* @param[in] path - Path to the vpd file
* @param[in] json - Parsed inventory json
* @param[in] record - Record name
* @param[in] kwd - Keyword
* @param[in] inventoryPath - Inventory path of the vpd
*/
EditorImpl(const inventory::Path& path, const nlohmann::json& json,
const std::string& record, const std::string& kwd,
const sdbusplus::message::object_path& inventoryPath) :
vpdFilePath(path),
objPath(inventoryPath), startOffset(0), jsonFile(json),
thisRecord(record, kwd)
{
}
/** @brief Construct EditorImpl class
*
* @param[in] path - EEPROM path
* @param[in] json - Parsed inventory json object
* @param[in] record - Record name
* @param[in] kwd - Keyword name
*/
EditorImpl(const inventory::Path& path, const nlohmann::json& json,
const std::string& record, const std::string& kwd) :
vpdFilePath(path),
jsonFile(json), thisRecord(record, kwd)
{
}
/**
* @brief Update data for keyword
* The method looks for the record name to update in VTOC and then
* looks for the keyword name in that record. when found it updates the data
* of keyword with the given data. It does not block keyword data update in
* case the length of new data is greater than or less than the current data
* length. If the new data length is more than the length alotted to that
* keyword the new data will be truncated to update only the allotted
* length. Similarly if the new data length is less then only that much data
* will be updated for the keyword and remaining bits will be left
* unchanged.
*
* Following is the algorithm used to update keyword:
* 1) Look for the record name in the given VPD file
* 2) Look for the keyword name for which data needs to be updated
* which is the table of contents record.
* 3) update the data for that keyword with the new data
*
* @param[in] kwdData - data to update
* @param[in] updCache - Flag which tells whether to update Cache or not.
*/
void updateKeyword(const Binary& kwdData, const bool& updCache);
/** @brief Expands location code on DBUS
* @param[in] locationCodeType - "fcs" or "mts"
*/
void expandLocationCode(const std::string& locationCodeType);
private:
/** @brief read VTOC record from the vpd file
*/
void readVTOC();
/** @brief validate ecc data for the VTOC record
* @param[in] itrToRecData -iterator to the record data
* @param[in] itrToECCData - iterator to the ECC data
* @param[in] recLength - Length of the record
* @param[in] eccLength - Length of the record's ECC
*/
void checkECC(Binary::const_iterator& itrToRecData,
Binary::const_iterator& itrToECCData,
openpower::vpd::constants::RecordLength recLength,
openpower::vpd::constants::ECCLength eccLength);
/** @brief reads value at the given offset
* @param[in] offset - offset value
* @return value at that offset in bigendian
*/
auto getValue(openpower::vpd::constants::offsets::Offsets offset);
/** @brief Checks if required record name exist in the VPD file
* @param[in] iterator - pointing to start of PT kwd
* @param[in] ptLength - length of the PT kwd
*/
void checkPTForRecord(Binary::const_iterator& iterator, Byte ptLength);
/** @brief Checks for required keyword in the record */
void checkRecordForKwd();
/** @brief update data for given keyword
* @param[in] kwdData- data to be updated
*/
void updateData(const Binary& kwdData);
/** @brief update record ECC */
void updateRecordECC();
/** @brief method to update cache once the data for keyword has been updated
*/
void updateCache();
/** @brief method to process and update CI in case required
* @param[in] - objectPath - path of the object to introspect
*/
void processAndUpdateCI(const std::string& objectPath);
/** @brief method to process and update extra interface
* @param[in] Inventory - single inventory json subpart
* @param[in] objPath - path of the object to introspect
*/
void processAndUpdateEI(const nlohmann::json& Inventory,
const inventory::Path& objPath);
/** @brief method to make busctl call
*
* @param[in] object - bus object path
* @param[in] interface - bus interface
* @param[in] property - property to update on BUS
* @param[in] data - data to be updated on Bus
*
*/
template <typename T>
void makeDbusCall(const std::string& object, const std::string& interface,
const std::string& property, const std::variant<T>& data);
// path to the VPD file to edit
inventory::Path vpdFilePath;
// inventory path of the vpd fru to update keyword
const inventory::Path objPath;
// stream to perform operation on file
std::fstream vpdFileStream;
// offset to get vpd data from EEPROM
uint32_t startOffset;
// file to store parsed json
const nlohmann::json jsonFile;
// structure to hold info about record to edit
struct RecInfo
{
Binary kwdUpdatedData; // need access to it in case encoding is needed
const std::string recName;
const std::string recKWd;
openpower::vpd::constants::RecordOffset recOffset;
openpower::vpd::constants::ECCOffset recECCoffset;
std::size_t recECCLength;
std::size_t kwdDataLength;
openpower::vpd::constants::RecordSize recSize;
openpower::vpd::constants::DataOffset kwDataOffset;
// constructor
RecInfo(const std::string& rec, const std::string& kwd) :
recName(rec), recKWd(kwd), recOffset(0), recECCoffset(0),
recECCLength(0), kwdDataLength(0), recSize(0), kwDataOffset(0)
{
}
} thisRecord;
Binary vpdFile;
// If requested Interface is common Interface
bool isCI;
/** @brief This API will be used to find out Parent FRU of Module/CPU
*
* @param[in] - moduleObjPath, object path of that FRU
* @param[in] - fruType, Type of Parent FRU
* for Module/CPU Parent Type- FruAndModule
*
* @return returns vpd file path of Parent Fru of that Module
*/
std::string getSysPathForThisFruType(const std::string& moduleObjPath,
const std::string& fruType);
/** @brief This API will search for correct EEPROM path for asked CPU
* and will init vpdFilePath
*/
void getVpdPathForCpu();
}; // class EditorImpl
} // namespace editor
} // namespace manager
} // namespace vpd
} // namespace openpower
| 33.397436 | 80 | 0.636596 | [
"object",
"vector"
] |
d9bfa7b50408c8d043a19a20041bd8e26c27e463 | 2,085 | cpp | C++ | all/native/graphics/BitmapCanvas.cpp | ArtronicsGame/mobile-sdk | 492afb38fbf372d2e76534b8f92e433b7cfb69b5 | [
"BSD-3-Clause"
] | null | null | null | all/native/graphics/BitmapCanvas.cpp | ArtronicsGame/mobile-sdk | 492afb38fbf372d2e76534b8f92e433b7cfb69b5 | [
"BSD-3-Clause"
] | null | null | null | all/native/graphics/BitmapCanvas.cpp | ArtronicsGame/mobile-sdk | 492afb38fbf372d2e76534b8f92e433b7cfb69b5 | [
"BSD-3-Clause"
] | null | null | null | #include "BitmapCanvas.h"
#if defined(_WIN32)
#define CARTO_BITMAP_CANVAS_IMPL UWPImpl
#include "graphics/BitmapCanvasUWPImpl.h"
#elif defined(__APPLE__)
#define CARTO_BITMAP_CANVAS_IMPL IOSImpl
#include "graphics/BitmapCanvasIOSImpl.h"
#elif defined(__ANDROID__)
#define CARTO_BITMAP_CANVAS_IMPL AndroidImpl
#include "graphics/BitmapCanvasAndroidImpl.h"
#else
#error "Unsupported platform"
#endif
namespace carto {
BitmapCanvas::BitmapCanvas(int width, int height) :
_impl(new CARTO_BITMAP_CANVAS_IMPL(width, height))
{
}
BitmapCanvas::~BitmapCanvas() {
}
void BitmapCanvas::setDrawMode(DrawMode mode) {
_impl->setDrawMode(mode);
}
void BitmapCanvas::setColor(const Color& color) {
_impl->setColor(color);
}
void BitmapCanvas::setStrokeWidth(float width) {
_impl->setStrokeWidth(width);
}
void BitmapCanvas::setFont(const std::string& name, float size) {
_impl->setFont(name, size);
}
void BitmapCanvas::pushClipRect(const ScreenBounds& clipRect) {
_impl->pushClipRect(clipRect);
}
void BitmapCanvas::popClipRect() {
_impl->popClipRect();
}
void BitmapCanvas::drawText(const std::string& text, const ScreenPos& pos, int maxWidth, bool breakLines) {
_impl->drawText(text, pos, maxWidth, breakLines);
}
void BitmapCanvas::drawPolygon(const std::vector<ScreenPos>& poses) {
_impl->drawPolygon(poses);
}
void BitmapCanvas::drawRoundRect(const ScreenBounds& rect, float radius) {
_impl->drawRoundRect(rect, radius);
}
void BitmapCanvas::drawBitmap(const ScreenBounds& rect, const std::shared_ptr<Bitmap>& bitmap) {
_impl->drawBitmap(rect, bitmap);
}
ScreenBounds BitmapCanvas::measureTextSize(const std::string& text, int maxWidth, bool breakLines) const {
return _impl->measureTextSize(text, maxWidth, breakLines);
}
std::shared_ptr<Bitmap> BitmapCanvas::buildBitmap() const {
return _impl->buildBitmap();
}
BitmapCanvas::Impl::~Impl() {
}
}
| 26.730769 | 111 | 0.690647 | [
"vector"
] |
d9ca8aff490e39b8c01244f935c9c813240dcc66 | 8,848 | cpp | C++ | src/CefWing/CefRenderApp/RenderDelegates/CefViewClient.cpp | klarso-gmbh/CefView_CefViewCore | 18958c0dbcc44e851ce8569909b098a13ea37953 | [
"MIT"
] | 25 | 2021-04-12T06:10:56.000Z | 2022-03-07T13:31:12.000Z | src/CefWing/CefRenderApp/RenderDelegates/CefViewClient.cpp | klarso-gmbh/CefView_CefViewCore | 18958c0dbcc44e851ce8569909b098a13ea37953 | [
"MIT"
] | 2 | 2021-08-03T08:29:43.000Z | 2022-02-11T08:33:15.000Z | src/CefWing/CefRenderApp/RenderDelegates/CefViewClient.cpp | klarso-gmbh/CefView_CefViewCore | 18958c0dbcc44e851ce8569909b098a13ea37953 | [
"MIT"
] | 13 | 2021-04-23T00:36:29.000Z | 2022-03-08T07:18:17.000Z | #pragma region projet_headers
#include "CefViewClient.h"
#pragma endregion projet_headers
// bool CefViewClient::Accessor::Get(const CefString& name,
// const CefRefPtr<CefV8Value> object,
// CefRefPtr<CefV8Value>& retval,
// CefString& exception)
//{
// return true;
//}
//
// bool CefViewClient::Accessor::Set(const CefString& name,
// const CefRefPtr<CefV8Value> object,
// const CefRefPtr<CefV8Value> value,
// CefString& exception)
//{
// return true;
//}
//////////////////////////////////////////////////////////////////////////
CefViewClient::V8Handler::V8Handler(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefViewClient::EventListenerListMap& eventListenerListMap)
: browser_(browser)
, frame_(frame)
, eventListenerListMap_(eventListenerListMap)
{}
bool
CefViewClient::V8Handler::Execute(const CefString& function,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (function == CEFVIEW_INVOKEMETHOD)
ExecuteInvokeMethod(function, object, arguments, retval, exception);
else if (function == CEFVIEW_ADDEVENTLISTENER)
ExecuteAddEventListener(function, object, arguments, retval, exception);
else if (function == CEFVIEW_REMOVEEVENTLISTENER)
ExecuteRemoveEventListener(function, object, arguments, retval, exception);
else
return false;
return true;
}
void
CefViewClient::V8Handler::ExecuteInvokeMethod(const CefString& function,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
CefRefPtr<CefProcessMessage> msg = CefProcessMessage::Create(INVOKEMETHOD_NOTIFY_MESSAGE);
CefRefPtr<CefListValue> args = msg->GetArgumentList();
int frameId = (int)frame_->GetIdentifier();
int idx = 0;
args->SetInt(idx++, frameId);
args->SetString(idx++, function);
for (std::size_t i = 0; i < arguments.size(); i++) {
if (arguments[i]->IsBool())
args->SetBool(idx++, arguments[i]->GetBoolValue());
else if (arguments[i]->IsInt())
args->SetInt(idx++, arguments[i]->GetIntValue());
else if (arguments[i]->IsDouble())
args->SetDouble(idx++, arguments[i]->GetDoubleValue());
else if (arguments[i]->IsString())
args->SetString(idx++, arguments[i]->GetStringValue());
else
args->SetNull(idx++);
}
if (browser_)
frame_->SendProcessMessage(PID_BROWSER, msg);
retval = CefV8Value::CreateUndefined();
}
void
CefViewClient::V8Handler::ExecuteAddEventListener(const CefString& function,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
bool bRet = false;
if (arguments.size() == 2) {
if (arguments[0]->IsString()) {
if (arguments[1]->IsFunction()) {
CefString eventName = arguments[0]->GetStringValue();
EventListener listener;
listener.callback_ = arguments[1];
listener.context_ = CefV8Context::GetCurrentContext();
auto itListenerList = eventListenerListMap_.find(eventName);
if (itListenerList == eventListenerListMap_.end()) {
EventListenerList eventListenerList;
eventListenerList.push_back(listener);
eventListenerListMap_[eventName] = eventListenerList;
} else {
EventListenerList& eventListenerList = itListenerList->second;
// does this listener exist?
bool found = false;
for (auto item : eventListenerList) {
if (item.callback_->IsSame(listener.callback_)) {
found = true;
break;
}
}
if (!found)
eventListenerList.push_back(listener);
}
bRet = true;
} else
exception = "Invalid parameters; parameter 2 should be a function";
} else
exception = "Invalid parameters; parameter 1 should be a string";
} else
exception = "Invalid parameters; expecting 2 parameters";
retval = CefV8Value::CreateBool(bRet);
}
void
CefViewClient::V8Handler::ExecuteRemoveEventListener(const CefString& function,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
bool bRet = false;
if (arguments.size() == 2) {
if (arguments[0]->IsString()) {
if (arguments[1]->IsFunction()) {
CefString eventName = arguments[0]->GetStringValue();
EventListener listener;
listener.callback_ = arguments[1];
listener.context_ = CefV8Context::GetCurrentContext();
auto itListenerList = eventListenerListMap_.find(eventName);
if (itListenerList != eventListenerListMap_.end()) {
EventListenerList& eventListenerList = itListenerList->second;
for (auto itListener = eventListenerList.begin(); itListener != eventListenerList.end(); itListener++) {
if (itListener->callback_->IsSame(listener.callback_))
eventListenerList.erase(itListener);
}
}
} else
exception = "Invalid parameters; parameter 2 is expecting a function";
} else
exception = "Invalid parameters; parameter 1 is expecting a string";
} else
exception = "Invalid parameters; expecting 2 parameters";
retval = CefV8Value::CreateBool(bRet);
}
//////////////////////////////////////////////////////////////////////////
CefViewClient::CefViewClient(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame)
: object_(CefV8Value::CreateObject(nullptr, nullptr))
, browser_(browser)
, frame_(frame)
{
// create function handler
CefRefPtr<V8Handler> handler = new V8Handler(browser_, frame_, eventListenerListMap_);
// create function "InvokeMethod"
CefRefPtr<CefV8Value> funcInvokeMethod = CefV8Value::CreateFunction(CEFVIEW_INVOKEMETHOD, handler);
// add this function to window object
object_->SetValue(CEFVIEW_INVOKEMETHOD, funcInvokeMethod, V8_PROPERTY_ATTRIBUTE_READONLY);
// create function addEventListener
CefRefPtr<CefV8Value> funcAddEventListener = CefV8Value::CreateFunction(CEFVIEW_ADDEVENTLISTENER, handler);
// add this function to window object
object_->SetValue(CEFVIEW_ADDEVENTLISTENER, funcAddEventListener, V8_PROPERTY_ATTRIBUTE_READONLY);
// create function removeListener
CefRefPtr<CefV8Value> funcRemoveEventListener = CefV8Value::CreateFunction(CEFVIEW_REMOVEEVENTLISTENER, handler);
// add this function to window object
object_->SetValue(CEFVIEW_REMOVEEVENTLISTENER, funcRemoveEventListener, V8_PROPERTY_ATTRIBUTE_READONLY);
}
CefRefPtr<CefV8Value>
CefViewClient::GetObject()
{
return object_;
}
void
CefViewClient::ExecuteEventListener(const CefString eventName, CefRefPtr<CefDictionaryValue> dict)
{
auto itListenerList = eventListenerListMap_.find(eventName);
if (itListenerList != eventListenerListMap_.end()) {
EventListenerList& eventListenerList = itListenerList->second;
for (auto listener : eventListenerList) {
listener.context_->Enter();
CefRefPtr<CefV8Value> eventObject = CefV8Value::CreateObject(nullptr, nullptr);
CefDictionaryValue::KeyList kyes;
dict->GetKeys(kyes);
CefRefPtr<CefValue> value;
CefRefPtr<CefV8Value> v8Value;
for (const CefString& key : kyes) {
value = dict->GetValue(key);
if (VTYPE_BOOL == value->GetType())
v8Value = CefV8Value::CreateBool(value->GetBool());
else if (VTYPE_INT == value->GetType())
v8Value = CefV8Value::CreateInt(value->GetInt());
else if (VTYPE_DOUBLE == value->GetType())
v8Value = CefV8Value::CreateDouble(value->GetDouble());
else if (VTYPE_STRING == value->GetType())
v8Value = CefV8Value::CreateString(value->GetString());
else
continue;
eventObject->SetValue(key, v8Value, V8_PROPERTY_ATTRIBUTE_READONLY);
}
CefV8ValueList arguments;
arguments.push_back(eventObject);
listener.callback_->ExecuteFunction(object_, arguments);
listener.context_->Exit();
}
}
}
| 37.333333 | 115 | 0.629069 | [
"object"
] |
d9d3ecebe7434248ed4522289e5ab8c838bffd78 | 4,909 | cpp | C++ | test/greedy/knapsack_two_app_long_test.cpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | null | null | null | test/greedy/knapsack_two_app_long_test.cpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | null | null | null | test/greedy/knapsack_two_app_long_test.cpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | 1 | 2021-02-24T06:23:56.000Z | 2021-02-24T06:23:56.000Z | //=======================================================================
// Copyright (c)
//
// 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)
//=======================================================================
/**
* @file knapsack_two_app_long_test.cpp
* @brief
* @author Piotr Wygocki
* @version 1.0
* @date 2013-09-20
*/
#include "test_utils/logger.hpp"
#include "test_utils/read_knapsack.hpp"
#include "test_utils/test_result_check.hpp"
#include "test_utils/get_test_dir.hpp"
#include "test_utils/system.hpp"
#include "paal/greedy/knapsack_0_1_two_app.hpp"
#include "paal/greedy/knapsack_unbounded_two_app.hpp"
#include "paal/utils/floating.hpp"
#include "paal/utils/parse_file.hpp"
#include <boost/test/unit_test.hpp>
#include <fstream>
using namespace paal;
using namespace paal::utils;
BOOST_AUTO_TEST_CASE(KnapsackTwoAppLong) {
std::string test_dir = paal::system::get_test_data_dir("KNAPSACK");
using paal::system::build_path;
parse(build_path(test_dir, "cases.txt"), [&](const std::string & line, std::istream &) {
int testId = std::stoi(line);
LOGLN("test >>>>>>>>>>>>>>>>>>>>>>>>>>>> " << testId);
int capacity;
std::vector<std::pair<int, int>> sizes_values;
std::vector<int> optimal;
auto size = [](std::pair<int, int> object) { return object.first; }
;
auto value = [](std::pair<int, int> object) { return object.second; }
;
read(build_path(test_dir, "cases/"), testId, capacity, sizes_values, optimal);
LOGLN("capacity " << capacity);
// LOGLN("size - value pairs ");
// LOG_COPY_RANGE_DEL(sizes_values, " ");
LOGLN("");
// KNAPSACK 0/1
{
std::vector<std::pair<int, int>> result;
auto value_sum = [&](int sum, int i) {
return sum + sizes_values[i].second;
}
;
auto opt = boost::accumulate(optimal, 0, value_sum);
LOGLN("Knapsack 0/1");
auto maxValue =
knapsack_0_1_two_app(sizes_values, capacity,
std::back_inserter(result), value, size);
LOGLN("Max value " << maxValue.first << ", Total size "
<< maxValue.second);
// LOG_COPY_RANGE_DEL(result, " ");
LOGLN("");
LOGLN("OPT");
LOG_COPY_RANGE_DEL(optimal, " ");
LOGLN("");
BOOST_CHECK(maxValue.second <= capacity);
check_result(maxValue.first, opt, 0.5, greater_equal{});
}
// KNAPSACK
{
std::vector<std::pair<int, int>> result;
LOGLN("Knapsack unbounded");
auto maxValue = knapsack_unbounded_two_app(
sizes_values, capacity, std::back_inserter(result), value,
size);
LOGLN("Max value " << maxValue.first << ", Total size "
<< maxValue.second);
// LOG_COPY_RANGE_DEL(result, " ");
LOGLN("");
BOOST_CHECK(maxValue.second <= capacity);
}
});
}
#include <iostream>
BOOST_AUTO_TEST_CASE(KnapsackTwoAppLongPerf) {
std::srand(42);
const int OBJECTS_NR = static_cast<int>(1e7);
const int MAX = static_cast<int>(1e2);
using Objects = std::vector<std::pair<int, int>>;
Objects objects(OBJECTS_NR);
auto rand_from_range = [ = ]() { return (std::rand() % MAX) + 1; }
;
auto rand_pair = [ = ]() {
return std::make_pair(rand_from_range(), rand_from_range());
}
;
std::generate_n(objects.begin(), OBJECTS_NR, rand_pair);
auto total_size =
boost::accumulate(objects, 0, [&](int sum, std::pair<int, int> p) {
return sum + p.first;
});
auto size = [](std::pair<int, int> object) { return object.first; }
;
auto value = [](std::pair<int, int> object) { return object.second; }
;
auto capacity = total_size / 2;
LOGLN("capacity = " << capacity);
// KNAPSACK
{
Objects result;
LOGLN("Knapsack unbounded");
auto maxValue = knapsack_unbounded_two_app(
objects, capacity, std::back_inserter(result), value, size);
LOGLN("Max value " << maxValue.first << ", Total size "
<< maxValue.second);
BOOST_CHECK(maxValue.second <= capacity);
}
// KNAPSACK 0/1
{
Objects result;
LOGLN("Knapsack 0/1");
auto maxValue = knapsack_0_1_two_app(
objects, capacity, std::back_inserter(result), value, size);
LOGLN("Max value " << maxValue.first << ", Total size "
<< maxValue.second);
BOOST_CHECK(maxValue.second <= capacity);
}
}
| 32.296053 | 92 | 0.55001 | [
"object",
"vector"
] |
d9e366844aae1d7ff9571a5eefc9300257bd9fba | 8,522 | cc | C++ | ash/wm/maximize_mode/maximize_mode_controller.cc | lauer3912/chromium.src | 969c559f5e43b329295b68c49ae9bf46a833395c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-16T03:57:28.000Z | 2021-01-23T15:29:45.000Z | ash/wm/maximize_mode/maximize_mode_controller.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/wm/maximize_mode/maximize_mode_controller.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-03-15T13:21:38.000Z | 2017-03-15T13:21:38.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 "ash/wm/maximize_mode/maximize_mode_controller.h"
#include "ash/accelerometer/accelerometer_controller.h"
#include "ash/display/display_manager.h"
#include "ash/shell.h"
#include "ui/gfx/vector3d_f.h"
namespace ash {
namespace {
// The hinge angle at which to enter maximize mode.
const float kEnterMaximizeModeAngle = 200.0f;
// The angle at which to exit maximize mode, this is specifically less than the
// angle to enter maximize mode to prevent rapid toggling when near the angle.
const float kExitMaximizeModeAngle = 160.0f;
// When the lid is fully open 360 degrees, the accelerometer readings can
// occasionally appear as though the lid is almost closed. If the lid appears
// near closed but the device is on we assume it is an erroneous reading from
// it being open 360 degrees.
const float kFullyOpenAngleErrorTolerance = 10.0f;
// When the device approaches vertical orientation (i.e. portrait orientation)
// the accelerometers for the base and lid approach the same values (i.e.
// gravity pointing in the direction of the hinge). When this happens we cannot
// compute the hinge angle reliably and must turn ignore accelerometer readings.
// This is the angle from vertical under which we will not compute a hinge
// angle.
const float kHingeAxisAlignedThreshold = 15.0f;
// The angle which the screen has to be rotated past before the display will
// rotate to match it (i.e. 45.0f is no stickiness).
const float kDisplayRotationStickyAngleDegrees = 60.0f;
// The minimum acceleration in a direction required to trigger screen rotation.
// This prevents rapid toggling of rotation when the device is near flat and
// there is very little screen aligned force on it.
const float kMinimumAccelerationScreenRotation = 0.3f;
const float kRadiansToDegrees = 180.0f / 3.14159265f;
// Returns the angle between |base| and |other| in degrees.
float AngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
const gfx::Vector3dF& other) {
return acos(gfx::DotProduct(base, other) /
base.Length() / other.Length()) * kRadiansToDegrees;
}
// Returns the clockwise angle between |base| and |other| where |normal| is the
// normal of the virtual surface to measure clockwise according to.
float ClockwiseAngleBetweenVectorsInDegrees(const gfx::Vector3dF& base,
const gfx::Vector3dF& other,
const gfx::Vector3dF& normal) {
float angle = AngleBetweenVectorsInDegrees(base, other);
gfx::Vector3dF cross(base);
cross.Cross(other);
// If the dot product of this cross product is normal, it means that the
// shortest angle between |base| and |other| was counterclockwise with respect
// to the surface represented by |normal| and this angle must be reversed.
if (gfx::DotProduct(cross, normal) > 0.0f)
angle = 360.0f - angle;
return angle;
}
} // namespace
MaximizeModeController::MaximizeModeController() {
Shell::GetInstance()->accelerometer_controller()->AddObserver(this);
}
MaximizeModeController::~MaximizeModeController() {
Shell::GetInstance()->accelerometer_controller()->RemoveObserver(this);
}
void MaximizeModeController::OnAccelerometerUpdated(
const gfx::Vector3dF& base,
const gfx::Vector3dF& lid) {
// Responding to the hinge rotation can change the maximize mode state which
// affects screen rotation, so we handle hinge rotation first.
HandleHingeRotation(base, lid);
HandleScreenRotation(lid);
}
void MaximizeModeController::HandleHingeRotation(const gfx::Vector3dF& base,
const gfx::Vector3dF& lid) {
static const gfx::Vector3dF hinge_vector(0.0f, 1.0f, 0.0f);
bool maximize_mode_engaged =
Shell::GetInstance()->IsMaximizeModeWindowManagerEnabled();
// As the hinge approaches a vertical angle, the base and lid accelerometers
// approach the same values making any angle calculations highly inaccurate.
// Bail out early when it is too close.
float hinge_angle = AngleBetweenVectorsInDegrees(base, hinge_vector);
if (hinge_angle < kHingeAxisAlignedThreshold ||
hinge_angle > 180.0f - kHingeAxisAlignedThreshold) {
return;
}
// Compute the angle between the base and the lid.
float angle = ClockwiseAngleBetweenVectorsInDegrees(base, lid, hinge_vector);
// Toggle maximize mode on or off when corresponding thresholds are passed.
// TODO(flackr): Make MaximizeModeController own the MaximizeModeWindowManager
// such that observations of state changes occur after the change and shell
// has fewer states to track.
if (maximize_mode_engaged &&
angle > kFullyOpenAngleErrorTolerance &&
angle < kExitMaximizeModeAngle) {
Shell::GetInstance()->EnableMaximizeModeWindowManager(false);
} else if (!maximize_mode_engaged &&
angle > kEnterMaximizeModeAngle) {
Shell::GetInstance()->EnableMaximizeModeWindowManager(true);
}
}
void MaximizeModeController::HandleScreenRotation(const gfx::Vector3dF& lid) {
bool maximize_mode_engaged =
Shell::GetInstance()->IsMaximizeModeWindowManagerEnabled();
internal::DisplayManager* display_manager =
Shell::GetInstance()->display_manager();
gfx::Display::Rotation current_rotation = display_manager->GetDisplayInfo(
gfx::Display::InternalDisplayId()).rotation();
// If maximize mode is not engaged, ensure the screen is not rotated and
// do not rotate to match the current device orientation.
if (!maximize_mode_engaged) {
if (current_rotation != gfx::Display::ROTATE_0) {
// TODO(flackr): Currently this will prevent setting a manual rotation on
// the screen of a device with an accelerometer, this should only set it
// back to ROTATE_0 if it was last set by the accelerometer.
// Also, SetDisplayRotation will save the setting to the local store,
// this should be stored in a way that we can distinguish what the
// rotation was set by.
display_manager->SetDisplayRotation(gfx::Display::InternalDisplayId(),
gfx::Display::ROTATE_0);
}
return;
}
// After determining maximize mode state, determine if the screen should
// be rotated.
gfx::Vector3dF lid_flattened(lid.x(), lid.y(), 0.0f);
float lid_flattened_length = lid_flattened.Length();
// When the lid is close to being flat, don't change rotation as it is too
// sensitive to slight movements.
if (lid_flattened_length < kMinimumAccelerationScreenRotation)
return;
// The reference vector is the angle of gravity when the device is rotated
// clockwise by 45 degrees. Computing the angle between this vector and
// gravity we can easily determine the expected display rotation.
static gfx::Vector3dF rotation_reference(-1.0f, 1.0f, 0.0f);
// Set the down vector to match the expected direction of gravity given the
// last configured rotation. This is used to enforce a stickiness that the
// user must overcome to rotate the display and prevents frequent rotations
// when holding the device near 45 degrees.
gfx::Vector3dF down(0.0f, 0.0f, 0.0f);
if (current_rotation == gfx::Display::ROTATE_0)
down.set_x(-1.0f);
else if (current_rotation == gfx::Display::ROTATE_90)
down.set_y(1.0f);
else if (current_rotation == gfx::Display::ROTATE_180)
down.set_x(1.0f);
else
down.set_y(-1.0f);
// Don't rotate if the screen has not passed the threshold.
if (AngleBetweenVectorsInDegrees(down, lid_flattened) <
kDisplayRotationStickyAngleDegrees) {
return;
}
float angle = ClockwiseAngleBetweenVectorsInDegrees(rotation_reference,
lid_flattened, gfx::Vector3dF(0.0f, 0.0f, -1.0f));
gfx::Display::Rotation new_rotation = gfx::Display::ROTATE_90;
if (angle < 90.0f)
new_rotation = gfx::Display::ROTATE_0;
else if (angle < 180.0f)
new_rotation = gfx::Display::ROTATE_270;
else if (angle < 270.0f)
new_rotation = gfx::Display::ROTATE_180;
// When exiting maximize mode return rotation to 0. When entering, rotate to
// match screen orientation.
if (new_rotation == gfx::Display::ROTATE_0 ||
maximize_mode_engaged) {
display_manager->SetDisplayRotation(gfx::Display::InternalDisplayId(),
new_rotation);
}
}
} // namespace ash
| 42.188119 | 80 | 0.723891 | [
"vector"
] |
d9ee8c9efc7b112e620e42afbb839f1b16a40700 | 22,241 | cpp | C++ | src/chem/ewald3D.cpp | markdellostritto/AtomNN | 763aa2ca12916638fcca14d5bddafe1112d603cd | [
"MIT"
] | null | null | null | src/chem/ewald3D.cpp | markdellostritto/AtomNN | 763aa2ca12916638fcca14d5bddafe1112d603cd | [
"MIT"
] | null | null | null | src/chem/ewald3D.cpp | markdellostritto/AtomNN | 763aa2ca12916638fcca14d5bddafe1112d603cd | [
"MIT"
] | null | null | null | // c libraries
#if (defined(__GNUC__) || defined(__GNUG__)) && !(defined(__clang__) || defined(__INTEL_COMPILER))
#include <cmath>
#elif defined __ICC || defined __INTEL_COMPILER
#include <mathimf.h> //intel math library
#endif
// c++ libraries
#include <iostream>
// ann - math
#include "src/math/const.hpp"
// ann - structure
#include "src/struc/structure.hpp"
// ann - str
#include "src/str/print.hpp"
// ann - chem
#include "src/chem/units.hpp"
#include "src/chem/ewald3D.hpp"
namespace Ewald3D{
//**********************************************************************************************************
//Utility Class
//**********************************************************************************************************
//operators
/**
* print class
* @param out - output stream
* @param u - object
*/
std::ostream& operator<<(std::ostream& out, const Utility& u){
out<<"PREC = "<<u.prec_<<"\n";
out<<"ALPHA = "<<u.alpha_<<"\n";
out<<"EPSILON = "<<u.eps_<<"\n";
out<<"WEIGHT = "<<u.weight_<<"\n";
out<<"R_MAX = "<<u.rMax_<<"\n";
out<<"K_MAX = "<<u.kMax_;
return out;
}
//member functions
/**
* set defaults
*/
void Utility::defaults(){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Utility::defaults():\n";
//calculation parameters
prec_=1E-6;
rMax_=0;
kMax_=0;
weight_=1;
alpha_=0;
//electrostatics
eps_=1;//vacuum boundary conditions
}
/**
* initialize object
* @param prec - precision of ewald calculation
*/
void Utility::init(double prec){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Utility::init(const Cell&, int, double):\n";
//set the precision
if(EWALD_PRINT_STATUS>1) std::cout<<"setting precision\n";
if(prec-1>=math::constant::ZERO || prec<=0) throw std::invalid_argument("Utility::init(double): Precision must be in (0,1)");
else prec_=prec;
}
//**********************************************************************************************************
//Coulomb Class
//**********************************************************************************************************
//operators
std::ostream& operator<<(std::ostream& out, const Coulomb& c){
char* str=new char[print::len_buf];
out<<print::buf(str)<<"\n";
out<<print::title("EWALD - COULOMB",str)<<"\n";
out<<static_cast<const Utility&>(c)<<"\n";
out<<print::title("EWALD - COULOMB",str)<<"\n";
out<<print::buf(str);
delete[] str;
return out;
}
//member functions
/**
* set defaults
*/
void Coulomb::defaults(){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::defaults():\n";
Utility::defaults();
vSelfR_=0;
vSelfK_=0;
vSelfC_=0;
}
/**
* initialiize
* @param struc - structure
* @param prec - precision of ewald calculation
*/
void Coulomb::init(const Structure& struc, double prec){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::init(const Cell&, int, double):\n";
Utility::init(prec);
//local function variables
const double pi=math::constant::PI;
//compute the limits
if(EWALD_PRINT_STATUS>0) std::cout<<"computing the limits\n";
alpha_=std::pow(struc.nAtoms()*weight_*pi*pi*pi/(struc.vol()*struc.vol()),1.0/6.0);
rMax_=std::sqrt(-1.0*std::log(prec))/alpha_;
kMax_=2.0*alpha_*std::sqrt(-1.0*std::log(prec));
if(EWALD_PRINT_DATA>0) std::cout<<"ALPHA = "<<alpha_<<" R_MAX = "<<rMax_<<" K_MAX = "<<kMax_<<"\n";
//find the lattice vectors
if(EWALD_PRINT_STATUS>0) std::cout<<"finding the lattice vectors\n";
const int rNMaxX=std::ceil(rMax_/struc.R().row(0).lpNorm<Eigen::Infinity>());//max of row - max abs x the lattice vectors
const int rNMaxY=std::ceil(rMax_/struc.R().row(1).lpNorm<Eigen::Infinity>());//max of row - max abs y the lattice vectors
const int rNMaxZ=std::ceil(rMax_/struc.R().row(2).lpNorm<Eigen::Infinity>());//max of row - max abs z the lattice vectors
const int kNMaxX=std::ceil(kMax_/struc.K().row(0).lpNorm<Eigen::Infinity>());//max of row - max abs x the lattice vectors
const int kNMaxY=std::ceil(kMax_/struc.K().row(1).lpNorm<Eigen::Infinity>());//max of row - max abs y the lattice vectors
const int kNMaxZ=std::ceil(kMax_/struc.K().row(2).lpNorm<Eigen::Infinity>());//max of row - max abs z the lattice vectors
if(EWALD_PRINT_DATA>0) std::cout<<"RN = ("<<rNMaxX<<","<<rNMaxY<<","<<rNMaxZ<<") - "<<(2*rNMaxX+1)*(2*rNMaxY+1)*(2*rNMaxZ+1)<<"\n";
if(EWALD_PRINT_DATA>0) std::cout<<"KN = ("<<kNMaxX<<","<<kNMaxY<<","<<kNMaxZ<<") - "<<(2*kNMaxX+1)*(2*kNMaxY+1)*(2*kNMaxZ+1)<<"\n";
const double f=1.05;
R.resize((2*rNMaxX+1)*(2*rNMaxY+1)*(2*rNMaxZ+1));
int rCount=0;
for(int i=-rNMaxX; i<=rNMaxX; ++i){
for(int j=-rNMaxY; j<=rNMaxY; ++j){
for(int k=-rNMaxZ; k<=rNMaxZ; ++k){
//note: don't skip R=0
const Eigen::Vector3d vtemp=i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2);
if(vtemp.norm()<f*rMax_) R[rCount++].noalias()=vtemp;
}
}
}
R.resize(rCount);
K.resize((2*kNMaxX+1)*(2*kNMaxY+1)*(2*kNMaxZ+1));
int kCount=0;
for(int i=-kNMaxX; i<=kNMaxX; ++i){
for(int j=-kNMaxY; j<=kNMaxY; ++j){
for(int k=-kNMaxZ; k<=kNMaxZ; ++k){
//note: skip K=0
const Eigen::Vector3d vtemp=i*struc.K().col(0)+j*struc.K().col(1)+k*struc.K().col(2);
const double norm=vtemp.norm();
if(norm>0 && norm<f*kMax_) K[kCount++].noalias()=vtemp;
}
}
}
K.resize(kCount);
if(EWALD_PRINT_DATA>0) std::cout<<"rCount = "<<rCount<<", kCount = "<<kCount<<"\n";
//compute the k sum amplitudes
if(EWALD_PRINT_STATUS>0) std::cout<<"computing the K-amplitudes\n";
kAmp.resize(kCount);
for(int i=0; i<kCount; ++i){
kAmp[i]=4.0*math::constant::PI/struc.vol()*exp(-K[i].dot(K[i])/(4.0*alpha_*alpha_))/(K[i].dot(K[i]));
}
//compute the self-interaction strength
if(EWALD_PRINT_STATUS>0) std::cout<<"computing self-interaction strength\n";
vSelfR_=0; vSelfK_=0;
for(int i=0; i<R.size(); ++i){
const double RN=R[i].norm();
if(RN!=0) vSelfR_+=std::erfc(alpha_*RN)/RN;
}
for(int i=0; i<kAmp.size(); ++i){
vSelfK_+=kAmp[i];
}
vSelfC_=2.0*alpha_/math::constant::RadPI;
}
void Coulomb::init_alpha(const Structure& struc, double prec){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::init_alpha(const Structure&,double):\n";
if(prec>0) prec_=prec;
alpha_=std::pow(struc.nAtoms()*weight_*math::constant::PI*math::constant::PI*math::constant::PI/(struc.vol()*struc.vol()),1.0/6.0);
rMax_=std::sqrt(-1.0*std::log(prec_))/alpha_;
kMax_=2.0*alpha_*std::sqrt(-1.0*std::log(prec_));
if(EWALD_PRINT_DATA>0) std::cout<<"ALPHA = "<<alpha_<<" R_MAX = "<<rMax_<<" K_MAX = "<<kMax_<<"\n";
}
//calculation - energy
/**
* compute the energy of a structure
* @param struc - structure
* @return the coulombic energy of the structure
*/
double Coulomb::energy(const Structure& struc)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::energy(const Structure&,int,int*):\n";
//local function variables
double energyT=0,q2s=0;
const std::complex<double> I(0,1);
Eigen::Vector3d vec;
if(EWALD_PRINT_DATA==0){
//r-space
for(int i=0; i<struc.nAtoms(); ++i){
for(int j=0; j<i; ++j){
Cell::diff(struc.posn(i),struc.posn(j),vec,struc.R(),struc.RInv());
double energyS=0;
for(int n=0; n<R.size(); ++n){
const double dist=(vec+R[n]).norm();
energyS+=erfc(alpha_*dist)/dist;
}
energyT+=struc.charge(i)*struc.charge(j)*energyS;
}
}
//k-space
for(int n=0; n<K.size(); ++n){
std::complex<double> sf(0,0);
for(int i=0; i<struc.nAtoms(); ++i){
sf+=struc.charge(i)*exp(-I*K[n].dot(struc.posn(i)));
}
energyT+=0.5*kAmp[n]*std::norm(sf);
}
//total charge and dipole
//vec.setZero();
for(int i=0; i<struc.nAtoms(); ++i){
q2s+=struc.charge(i)*struc.charge(i);
//vec.noalias()+=struc.charge(i)*struc.posn(i);
}
//self-energy
energyT+=0.5*q2s*(vSelfR_-vSelfC_);
//polarization energy
//energyT+=2.0*math::constant::PI/(2.0*eps_+1.0)*vec.dot(vec)/struc.vol();
} else {
double energyR=0,energyK=0,energyS,energyP;
//r-space
for(int i=0; i<struc.nAtoms(); ++i){
for(int j=0; j<i; ++j){
Cell::diff(struc.posn(i),struc.posn(j),vec,struc.R(),struc.RInv());
energyS=0;
for(int n=0; n<R.size(); ++n){
const double dist=(vec+R[n]).norm();
energyS+=erfc(alpha_*dist)/dist;
}
energyR+=struc.charge(i)*struc.charge(j)*energyS;
}
}
//k-space
for(int n=0; n<K.size(); ++n){
std::complex<double> sf(0,0);
for(int i=0; i<struc.nAtoms(); ++i){
sf+=struc.charge(i)*exp(-I*K[n].dot(struc.posn(i)));
}
energyK+=0.5*kAmp[n]*std::norm(sf);
}
//self-energy
for(int i=0; i<struc.nAtoms(); ++i) q2s+=struc.charge(i)*struc.charge(i);
energyS=0.5*q2s*(vSelfR_-vSelfC_);
//polarization energy
vec.setZero();
for(int i=0; i<struc.nAtoms(); ++i) vec.noalias()+=struc.charge(i)*struc.posn(i);
energyP=2.0*math::constant::PI/(2.0*eps_+1.0)*vec.dot(vec)/struc.vol();
std::cout<<"==============================\n";
std::cout<<"dipole = "<<vec.transpose()<<"\n";
std::cout<<"ke = "<<units::consts::ke()<<"\n";
std::cout<<"energy-r = "<<energyR<<"\n";
std::cout<<"energy-k = "<<energyK<<"\n";
std::cout<<"energy-s = "<<energyS<<"\n";
std::cout<<"energy-p = "<<energyP<<"\n";
std::cout<<"energy-t = "<<energyR+energyK+energyS+energyP<<"\n";
std::cout<<"==============================\n";
//energyT=energyR+energyK+energyS+energyP;
energyT=energyR+energyK+energyS;
}
return units::consts::ke()*energyT;
}
/**
* compute the energy of a structure - no initialization
* @param struc - structure
* @return the coulombic energy of the structure
*/
double Coulomb::energy_single(const Structure& struc){
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::energy(const Structure&,int,int*):\n";
//local function variables
int shellx,shelly,shellz,count=0;
double energyR=0,energyK=0,energyS,energyP,q2s=0;
const std::complex<double> I(0,1);
Eigen::Vector3d vec;
//init alpha
init_alpha(struc);
//r-space
shellx=std::ceil(rMax_/struc.R().row(0).lpNorm<Eigen::Infinity>());//max of row - max abs x the lattice vectors
shelly=std::ceil(rMax_/struc.R().row(1).lpNorm<Eigen::Infinity>());//max of row - max abs y the lattice vectors
shellz=std::ceil(rMax_/struc.R().row(2).lpNorm<Eigen::Infinity>());//max of row - max abs z the lattice vectors
if(EWALD_PRINT_DATA>0) std::cout<<"R_SHELL = ("<<shellx<<","<<shelly<<","<<shellz<<")\n";
R.resize((2*shellx+1)*(2*shelly+1)*(2*shellz+1));
count=0;
for(int i=-shellx; i<=shellx; ++i){
for(int j=-shelly; j<=shelly; ++j){
for(int k=-shellz; k<=shellz; ++k){
//note: don't skip R=0
const Eigen::Vector3d vtemp=i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2);
if(vtemp.norm()<1.05*rMax_) R[count++].noalias()=vtemp;
}
}
}
R.resize(count);
for(int i=0; i<struc.nAtoms(); ++i){
for(int j=0; j<i; ++j){
Cell::diff(struc.posn(i),struc.posn(j),vec,struc.R(),struc.RInv());
energyS=0;
for(int n=0; n<R.size(); ++n){
double dist=(vec+R[n]).norm();
energyS+=erfc(alpha_*dist)/dist;
}
energyR+=struc.charge(i)*struc.charge(j)*energyS;
}
}
//k-space
shellx=std::ceil(kMax_/struc.K().row(0).lpNorm<Eigen::Infinity>());//max of row - max abs x the lattice vectors
shelly=std::ceil(kMax_/struc.K().row(1).lpNorm<Eigen::Infinity>());//max of row - max abs y the lattice vectors
shellz=std::ceil(kMax_/struc.K().row(2).lpNorm<Eigen::Infinity>());//max of row - max abs z the lattice vectors
if(EWALD_PRINT_DATA>0) std::cout<<"K_SHELL = ("<<shellx<<","<<shelly<<","<<shellz<<")\n";
K.resize((2*shellx+1)*(2*shelly+1)*(2*shellz+1));
count=0;
for(int i=-shellx; i<=shellx; ++i){
for(int j=-shelly; j<=shelly; ++j){
for(int k=-shellz; k<=shellz; ++k){
const Eigen::Vector3d vtemp=i*struc.K().col(0)+j*struc.K().col(1)+k*struc.K().col(2);
const double norm=vtemp.norm();//note: skip K=0
if(norm>0 && norm<1.05*kMax_) K[count++].noalias()=vtemp;
}
}
}
K.resize(count);
for(int n=0; n<K.size(); ++n){
std::complex<double> sf(0,0);
const double kdot=K[n].dot(K[n]);
const double kamp=4.0*math::constant::PI/struc.vol()*std::exp(-kdot/(4.0*alpha_*alpha_))/kdot;
for(int i=0; i<struc.nAtoms(); ++i){
sf+=struc.charge(i)*exp(-I*K[n].dot(struc.posn(i)));
}
energyK+=0.5*kamp*std::norm(sf);
}
//total charge, dipole
vec.setZero();
for(int i=0; i<struc.nAtoms(); ++i){
q2s+=struc.charge(i)*struc.charge(i);
vec.noalias()+=struc.charge(i)*struc.posn(i);
}
//self-energy
double vSelfR=0;
for(int i=0; i<R.size(); ++i){
if(R[i].norm()!=0) vSelfR+=erfc(alpha_*R[i].norm())/R[i].norm();
}
energyS=0.5*q2s*(vSelfR-2.0*alpha_/math::constant::RadPI);
//polarization energy
if(EWALD_PRINT_DATA>0) std::cout<<"dipole = "<<vec.transpose()<<"\n";
energyP=2.0*math::constant::PI/(2.0*eps_+1.0)*vec.dot(vec)/struc.vol();
if(EWALD_PRINT_DATA>0){
std::cout<<"==============================\n";
std::cout<<"dipole = "<<vec.transpose()<<"\n";
std::cout<<"energy-r = "<<energyR<<"\n";
std::cout<<"energy-k = "<<energyK<<"\n";
std::cout<<"energy-s = "<<energyS<<"\n";
std::cout<<"energy-p = "<<energyP<<"\n";
std::cout<<"energy-t = "<<energyR+energyK+energyS+energyP<<"\n";
std::cout<<"==============================\n";
}
//return units::consts::ke()*(energyR+energyK+energyS+energyP);
return units::consts::ke()*(energyR+energyK+energyS);
}
/**
* compute the energy of a structure - brute force
* @param struc - structure
* @return the coulombic energy of the structure
*/
double Coulomb::energy_brute(const Structure& struc, int N)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::energy_brute(const Structure&,int,int*):\n";
//local function variables
double interEnergy=0,energySelf=0,chargeSum=0;
Eigen::Vector3d dr;
if(EWALD_PRINT_STATUS>0) std::cout<<"interaction energy\n";
for(int n=0; n<struc.nAtoms(); ++n){
for(int m=n+1; m<struc.nAtoms(); ++m){
if(EWALD_PRINT_DATA>1) std::cout<<"Pair ("<<n<<","<<m<<")\n";
//find the zeroth cell distance and energy
Cell::diff(struc.posn(n),struc.posn(m),dr,struc.R(),struc.RInv());
const double chgProd=struc.charge(n)*struc.charge(m);
for(int i=-N; i<=N; ++i){
for(int j=-N; j<=N; ++j){
for(int k=-N; k<=N; ++k){
interEnergy+=chgProd/(dr+i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2)).norm();
}
}
}
}
}
if(EWALD_PRINT_STATUS>0) std::cout<<"self-energy\n";
for(int n=0; n<struc.nAtoms(); ++n){
chargeSum+=struc.charge(n)*struc.charge(n);
}
energySelf=0;
for(int i=-N; i<=N; ++i){
for(int j=-N; j<=N; ++j){
for(int k=-N; k<=N; ++k){
const double norm=(i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2)).norm();
energySelf+=(norm>0)?1.0/norm:0;
}
}
}
energySelf*=0.5*chargeSum;
if(EWALD_PRINT_DATA>0){
std::cout<<"energy-s = "<<energySelf<<"\n";
std::cout<<"energy-i = "<<interEnergy<<"\n";
std::cout<<"energy-t = "<<interEnergy+energySelf<<"\n";
}
return units::consts::ke()*(interEnergy+energySelf);
}
//calculation - potential
/**
* compute the electrostatic potential at a given point
* @param struc - structure
* @param r - position
* @return the electrostatic potential at r
*/
double Coulomb::phi(const Structure& struc, const Eigen::Vector3d& r)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::phi(const Structure&,const Eigen::Vector3d&)const:\n";
double vTot=0,r2=0,chgsum=0;
Eigen::Vector3d dr;
if(EWALD_PRINT_DATA==0){
for(int i=0; i<struc.nAtoms(); ++i){
double vLoc=0;
//compute difference
Cell::diff(r,struc.posn(i),dr,struc.R(),struc.RInv());
//real-space contribution
for(int n=0; n<R.size(); ++n){
const double dist=(dr+R[n]).norm();
if(dist>math::constant::ZERO){
vLoc+=erfc(alpha_*dist)/dist;
}
}
//k-space contribution
for(int n=0; n<K.size(); ++n){
vLoc+=kAmp[n]*cos(K[n].dot(dr));
}
vTot+=vLoc*struc.charge(i);
r2+=dr.squaredNorm()*struc.charge(i);
chgsum+=struc.charge(i);
}
//polarization contribution
vTot+=-2.0*math::constant::PI/(2.0*eps_+1.0)*r2/struc.vol();
//constant contribution
vTot+=-math::constant::PI/(alpha_*alpha_*struc.vol())*chgsum;
} else {
double vR=0,vK=0,vP,vC;
Eigen::Vector3d dr;
for(int i=0; i<struc.nAtoms(); ++i){
Cell::diff(r,struc.posn(i),dr,struc.R(),struc.RInv());
for(int n=0; n<R.size(); ++n){
const double dist=(dr+R[n]).norm();
if(dist>math::constant::ZERO){
vR+=erfc(alpha_*dist)/dist*struc.charge(i);
}
}
for(int n=0; n<K.size(); ++n){
vK+=kAmp[n]*cos(K[n].dot(dr))*struc.charge(i);
}
r2+=dr.squaredNorm()*struc.charge(i);
chgsum+=struc.charge(i);
}
//polarization contribution
vP=-2.0*math::constant::PI/(2.0*eps_+1.0)*r2/struc.vol();
//constant contribution
vC=-math::constant::PI/(alpha_*alpha_*struc.vol())*chgsum;
std::cout<<"==============================\n";
std::cout<<"chg-t = "<<chgsum<<"\n";
std::cout<<"pot-r = "<<vR<<"\n";
std::cout<<"pot-k = "<<vK<<"\n";
std::cout<<"pot-p = "<<vP<<"\n";
std::cout<<"pot-c = "<<vC<<"\n";
std::cout<<"pot-t = "<<vR+vK+vP+vC<<"\n";
std::cout<<"==============================\n";
vTot=vR+vK+vP+vC;
}
return units::consts::ke()*vTot;
}
double Coulomb::phi(const Structure& struc, int nn)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::phi(const Structure&,int)const:\n";
return phi(struc,struc.posn(nn))+units::consts::ke()*((vSelfR_-vSelfC_)*struc.charge(nn));
}
double Coulomb::phis()const{
return units::consts::ke()*(vSelfR_+vSelfK_-vSelfC_);
}
double Coulomb::potentialBrute(const Structure& struc, int n, int N)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"Ewald3D::Coulomb::potentialBrute(const Structure&,int,const Eigen::Vector3d&)const:\n";
double v=0;
Eigen::Vector3d dr;
for(int ii=0; ii<struc.nAtoms(); ++ii){
if(ii==n) continue;
Cell::diff(struc.posn(ii),struc.posn(n),dr,struc.R(),struc.RInv());
for(int i=-N; i<=N; ++i){
for(int j=-N; j<=N; ++j){
for(int k=-N; k<=N; ++k){
v+=1.0/(dr+i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2)).norm()*struc.charge(ii);
}
}
}
}
return units::consts::ke()*v;
}
//calculation - electric field
/**
* compute the electric field at a given atom
* @param struc - structure
* @param n - index of atom
* @param field - the electric field
* @return the electric field
*/
Eigen::Vector3d& Coulomb::efield(const Structure& struc, int n, Eigen::Vector3d& field)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"field(const Structure&,int,Eigen::Vector3d&)const:\n";
const double aa=2.0*alpha_/std::sqrt(math::constant::PI);
const double bb=4.0*math::constant::PI/(2.0*eps_+1.0);
Eigen::Vector3d dr;
//zero field
field.setZero();
//compute real/reciprocal space contributions
for(int i=0; i<struc.nAtoms(); ++i){
if(i==n) continue;
Cell::diff(struc.posn(i),struc.posn(n),dr,struc.R(),struc.RInv());
field.noalias()+=bb*dr*struc.charge(i);
for(int n=0; n<R.size(); ++n){
const double dist=(dr+R[n]).norm();
field.noalias()+=(dr+R[n])*(aa*std::exp(-alpha_*alpha_*dist*dist)
+std::erfc(alpha_*dist)/dist)*struc.charge(i)/(dist*dist);
}
for(int n=0; n<K.size(); ++n){
field.noalias()+=K[n]*kAmp[n]*std::sin(K[n].dot(dr))*struc.charge(i);
}
}
return field;
}
/**
* compute the electric field at a given atom - brute force
* @param struc - structure
* @param n - index of atom
* @param field - the electric field
* @return the electric field
*/
Eigen::Vector3d& Coulomb::efieldBrute(const Structure& struc, int n, Eigen::Vector3d& field, int N)const{
if(EWALD_PRINT_FUNC>0) std::cout<<"potentialBrute(const Structure&,int,Eigen::Vector3d&,int)const:\n";
Eigen::Vector3d dr;
//zero field
field.setZero();
for(int ii=0; ii<struc.nAtoms(); ++ii){
Cell::diff(struc.posn(ii),struc.posn(n),dr,struc.R(),struc.RInv());
for(int i=-N; i<=N; ++i){
for(int j=-N; j<=N; ++j){
for(int k=-N; k<=N; ++k){
const double drn=(dr+i*struc.R().col(0)+j*struc.R().col(1)+k*struc.R().col(2)).norm();
if(drn>math::constant::ZERO) field.noalias()+=dr/(drn*drn*drn)*struc.charge(ii);
}
}
}
}
return field;
}
//potential
}
namespace serialize{
//**********************************************
// byte measures
//**********************************************
template <> int nbytes(const Ewald3D::Utility& obj){
int size=0;
size+=sizeof(double);//prec_
size+=sizeof(double);//weight_
size+=sizeof(double);//eps_
return size;
}
template <> int nbytes(const Ewald3D::Coulomb& obj){
return nbytes(static_cast<const Ewald3D::Utility&>(obj));
}
//**********************************************
// packing
//**********************************************
template <> int pack(const Ewald3D::Utility& obj, char* arr){
int pos=0;
const double prec=obj.prec();
std::memcpy(arr+pos,&prec,sizeof(double)); pos+=sizeof(double);//prec_
std::memcpy(arr+pos,&obj.weight(),sizeof(double)); pos+=sizeof(double);//weight_
std::memcpy(arr+pos,&obj.eps(),sizeof(double)); pos+=sizeof(double);//eps_
return pos;
}
template <> int pack(const Ewald3D::Coulomb& obj, char* arr){
return pack(static_cast<const Ewald3D::Utility&>(obj),arr);
}
//**********************************************
// unpacking
//**********************************************
template <> int unpack(Ewald3D::Utility& obj, const char* arr){
int pos=0;
double prec=0;
std::memcpy(&prec,arr+pos,sizeof(double)); pos+=sizeof(double);//prec_
std::memcpy(&obj.weight(),arr+pos,sizeof(double)); pos+=sizeof(double);//weight_
std::memcpy(&obj.eps(),arr+pos,sizeof(double)); pos+=sizeof(double);//eps_
obj.init(prec);
return pos;
}
template <> int unpack(Ewald3D::Coulomb& obj, const char* arr){
return unpack(static_cast<Ewald3D::Utility&>(obj),arr);
}
}
| 34.059724 | 133 | 0.590936 | [
"object"
] |
d9f6ba9178670a898a15aa710c50e9b8dc92fbcf | 1,139 | cpp | C++ | codes/FZU/fzu2038.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/FZU/fzu2038.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/FZU/fzu2038.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
const int N = 100005;
typedef long long ll;
struct node {
int next;
ll val;
ll size;
node() { next = 0, val = size = 0; };
node(int next, ll val) {
this->next = next;
this->val = val;
this->size = 0;
}
};
int vis[N];
ll n;
vector<node> v[N];
void init() {
scanf("%lld", &n);
for (int i = 0; i < n; i++) v[i].clear();
memset(vis, 0, sizeof(vis));
int a, b;
ll c;
for (int i = 1; i < n; i++) {
scanf("%d%d%lld", &a, &b, &c);
v[a].push_back(node(b, c));
v[b].push_back(node(a, c));
}
}
ll dfs(int s) {
ll cnt = 0;
vis[s] = 1;
for (int i = 0; i < v[s].size(); i++) {
int u = v[s][i].next;
if (vis[u]) continue;
ll t = dfs(u);
v[s][i].size = (n - t) * t;
cnt += t;
}
return cnt + 1;
}
ll solve() {
dfs(0);
ll ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < v[i].size(); j++)
ans += v[i][j].val * v[i][j].size;
}
return ans * 2;
}
int main () {
int cas;
scanf("%d", &cas);
for (int i = 1; i <= cas; i++) {
init();
printf("Case %d: %lld\n", i, solve());
}
return 0;
}
| 14.986842 | 42 | 0.495171 | [
"vector"
] |
8a046121241a77f772ce862ff3c8e645e7c507da | 24,185 | cpp | C++ | vk_video_decoder/libs/VulkanVideoFrameBuffer/VulkanVideoFrameBuffer.cpp | Jasper-Bekkers/vk_video_samples | c851b02743574def866c593fe66d1dff93354e6d | [
"Apache-2.0"
] | null | null | null | vk_video_decoder/libs/VulkanVideoFrameBuffer/VulkanVideoFrameBuffer.cpp | Jasper-Bekkers/vk_video_samples | c851b02743574def866c593fe66d1dff93354e6d | [
"Apache-2.0"
] | null | null | null | vk_video_decoder/libs/VulkanVideoFrameBuffer/VulkanVideoFrameBuffer.cpp | Jasper-Bekkers/vk_video_samples | c851b02743574def866c593fe66d1dff93354e6d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 NVIDIA Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <atomic>
#include <chrono>
#include <iostream>
#include <mutex>
#include <queue>
#include <sstream>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include "PictureBufferBase.h"
#include "VkCodecUtils/HelpersDispatchTable.h"
#include "VkCodecUtils/VulkanVideoUtils.h"
#include "VulkanVideoFrameBuffer.h"
#include "vk_enum_string_helper.h"
#include "vulkan_interfaces.h"
#define MAX_FRAMEBUFFER_IMAGES 32
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#define CLOCK_MONOTONIC 0
extern int clock_gettime(int dummy, struct timespec* ct);
#endif
class NvPerFrameDecodeImage : public vkPicBuffBase {
public:
NvPerFrameDecodeImage()
: m_picDispInfo()
, m_frameImage()
, m_currentImageLayout(VK_IMAGE_LAYOUT_UNDEFINED)
, m_frameCompleteFence()
, m_frameCompleteSemaphore()
, m_frameConsumerDoneFence()
, m_frameConsumerDoneSemaphore()
, m_hasFrameCompleteSignalFence(false)
, m_hasFrameCompleteSignalSemaphore(false)
, m_hasConsummerSignalFence(false)
, m_hasConsummerSignalSemaphore(false)
, m_inDecodeQueue(false)
, m_inDisplayQueue(false)
, m_ownedByDisplay(false)
{
}
void Deinit();
~NvPerFrameDecodeImage()
{
Deinit();
}
VkParserDecodePictureInfo m_picDispInfo;
vulkanVideoUtils::ImageObject m_frameImage;
VkImageLayout m_currentImageLayout;
VkFence m_frameCompleteFence;
VkSemaphore m_frameCompleteSemaphore;
VkFence m_frameConsumerDoneFence;
VkSemaphore m_frameConsumerDoneSemaphore;
uint32_t m_hasFrameCompleteSignalFence : 1;
uint32_t m_hasFrameCompleteSignalSemaphore : 1;
uint32_t m_hasConsummerSignalFence : 1;
uint32_t m_hasConsummerSignalSemaphore : 1;
uint32_t m_inDecodeQueue : 1;
uint32_t m_inDisplayQueue : 1;
uint32_t m_ownedByDisplay : 1;
};
class NvPerFrameDecodeImageSet {
public:
NvPerFrameDecodeImageSet()
: m_size(0)
, m_frameDecodeImages()
{
}
int32_t init(uint32_t numImages,
vulkanVideoUtils::VulkanDeviceInfo* deviceInfo,
const VkImageCreateInfo* pImageCreateInfo,
VkMemoryPropertyFlags requiredMemProps = 0,
int initWithPattern = -1,
VkExternalMemoryHandleTypeFlagBitsKHR exportMemHandleTypes = VkExternalMemoryHandleTypeFlagBitsKHR(),
vulkanVideoUtils::NativeHandle& importHandle = vulkanVideoUtils::NativeHandle::InvalidNativeHandle);
void Deinit();
~NvPerFrameDecodeImageSet()
{
Deinit();
}
NvPerFrameDecodeImage& operator[](unsigned int index)
{
assert(index < m_size);
return m_frameDecodeImages[index];
}
size_t size()
{
return m_size;
}
private:
size_t m_size;
NvPerFrameDecodeImage m_frameDecodeImages[MAX_FRAMEBUFFER_IMAGES];
};
static uint64_t getNsTime(bool resetTime = false)
{
static bool initStart = false;
static struct timespec start_;
if (!initStart || resetTime) {
clock_gettime(CLOCK_MONOTONIC, &start_);
initStart = true;
}
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
constexpr long one_sec_in_ns = 1000 * 1000 * 1000;
time_t secs = now.tv_sec - start_.tv_sec;
uint64_t nsec;
if (now.tv_nsec > start_.tv_nsec) {
nsec = now.tv_nsec - start_.tv_nsec;
} else {
if(secs > 1) {
secs--;
} else if (secs < 0) {
secs = 0;
}
nsec = one_sec_in_ns - (start_.tv_nsec - now.tv_nsec);
}
return (secs * one_sec_in_ns) + nsec;
}
class NvVulkanVideoFrameBuffer : public VulkanVideoFrameBuffer {
public:
NvVulkanVideoFrameBuffer(vulkanVideoUtils::VulkanDeviceInfo* pVideoRendererDeviceInfo)
: m_pVideoRendererDeviceInfo(pVideoRendererDeviceInfo)
, m_refCount(1)
, m_displayQueueMutex()
, m_perFrameDecodeImageSet()
, m_displayFrames()
, m_queryPool()
, m_ownedByDisplayMask(0)
, m_frameNumInDecodeOrder(0)
, m_frameNumInDisplayOrder(0)
, m_extent { 0, 0 }
, m_debug()
{
}
virtual int32_t AddRef();
virtual int32_t Release();
VkResult CreateVideoQueries(uint32_t numSlots, vulkanVideoUtils::VulkanDeviceInfo* deviceInfo, const VkVideoProfileKHR* pDecodeProfile)
{
VkPhysicalDeviceFeatures2 coreFeatures;
VkPhysicalDeviceSamplerYcbcrConversionFeatures ycbcrFeatures;
memset(&coreFeatures, 0, sizeof(coreFeatures));
memset(&ycbcrFeatures, 0, sizeof(ycbcrFeatures));
coreFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
coreFeatures.pNext = &ycbcrFeatures;
ycbcrFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
vk::GetPhysicalDeviceFeatures2(deviceInfo->physDevice_, &coreFeatures);
VkQueryPoolCreateInfo queryPoolCreateInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
queryPoolCreateInfo.pNext = pDecodeProfile;
queryPoolCreateInfo.queryType = VK_QUERY_TYPE_RESULT_STATUS_ONLY_KHR;
queryPoolCreateInfo.queryCount = numSlots; // m_numDecodeSurfaces frames worth
return vk::CreateQueryPool(deviceInfo->device_, &queryPoolCreateInfo, NULL, &m_queryPool);
}
virtual int32_t InitImagePool(uint32_t numImages, const VkImageCreateInfo* pImageCreateInfo, const VkVideoProfileKHR* pDecodeProfile = NULL)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
while (!m_displayFrames.empty()) {
int8_t pictureIndex = m_displayFrames.front();
assert((pictureIndex >= 0) && ((uint32_t)pictureIndex < m_perFrameDecodeImageSet.size()));
m_displayFrames.pop();
assert(m_perFrameDecodeImageSet[(uint32_t)pictureIndex].IsAvailable());
m_perFrameDecodeImageSet[(uint32_t)pictureIndex].Release();
}
if (m_queryPool != VkQueryPool()) {
vk::DestroyQueryPool(m_pVideoRendererDeviceInfo->device_, m_queryPool, NULL);
m_queryPool = VkQueryPool();
}
m_ownedByDisplayMask = 0;
m_frameNumInDecodeOrder = 0;
m_frameNumInDisplayOrder = 0;
if (numImages && pDecodeProfile) {
VkResult result = CreateVideoQueries(numImages, m_pVideoRendererDeviceInfo, pDecodeProfile);
if (result != VK_SUCCESS) {
return 0;
}
}
if (numImages && pImageCreateInfo) {
m_extent.width = pImageCreateInfo->extent.width;
m_extent.height = pImageCreateInfo->extent.height;
return m_perFrameDecodeImageSet.init(numImages, m_pVideoRendererDeviceInfo, pImageCreateInfo,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
0 /* No ColorPatternColorBars */,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
} else {
m_perFrameDecodeImageSet.Deinit();
}
return 0;
}
virtual int32_t QueueDecodedPictureForDisplay(int8_t picId, VulkanVideoDisplayPictureInfo* pDispInfo)
{
assert((uint32_t)picId < m_perFrameDecodeImageSet.size());
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
m_perFrameDecodeImageSet[picId].m_displayOrder = m_frameNumInDisplayOrder++;
m_perFrameDecodeImageSet[picId].m_timestamp = pDispInfo->timestamp;
m_perFrameDecodeImageSet[picId].m_inDisplayQueue = true;
m_perFrameDecodeImageSet[picId].AddRef();
m_displayFrames.push((uint8_t)picId);
if (m_debug) {
std::cout << "==> Queue Display Picture picIdx: " << (uint32_t)picId
<< "\t\tdisplayOrder: " << m_perFrameDecodeImageSet[picId].m_displayOrder << "\tdecodeOrder: " << m_perFrameDecodeImageSet[picId].m_decodeOrder
<< "\ttimestamp " << m_perFrameDecodeImageSet[picId].m_timestamp << std::endl;
}
return picId;
}
virtual int32_t QueuePictureForDecode(int8_t picId, VkParserDecodePictureInfo* pDecodePictureInfo, FrameSynchronizationInfo* pFrameSynchronizationInfo)
{
assert((uint32_t)picId < m_perFrameDecodeImageSet.size());
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
m_perFrameDecodeImageSet[picId].m_picDispInfo = *pDecodePictureInfo;
m_perFrameDecodeImageSet[picId].m_decodeOrder = m_frameNumInDecodeOrder++;
m_perFrameDecodeImageSet[picId].m_inDecodeQueue = true;
if (m_debug) {
std::cout << "==> Queue Decode Picture picIdx: " << (uint32_t)picId
<< "\t\tdisplayOrder: " << m_perFrameDecodeImageSet[picId].m_displayOrder << "\tdecodeOrder: " << m_perFrameDecodeImageSet[picId].m_decodeOrder
<< "\ttimestamp " << getNsTime() << "\tFrameType " << m_perFrameDecodeImageSet[picId].m_picDispInfo.videoFrameType << std::endl;
}
if (pFrameSynchronizationInfo->hasFrameCompleteSignalFence) {
pFrameSynchronizationInfo->frameCompleteFence = m_perFrameDecodeImageSet[picId].m_frameCompleteFence;
if (pFrameSynchronizationInfo->frameCompleteFence) {
m_perFrameDecodeImageSet[picId].m_hasFrameCompleteSignalFence = true;
}
}
if (m_perFrameDecodeImageSet[picId].m_hasConsummerSignalFence) {
pFrameSynchronizationInfo->frameConsumerDoneFence = m_perFrameDecodeImageSet[picId].m_frameConsumerDoneFence;
m_perFrameDecodeImageSet[picId].m_hasConsummerSignalFence = false;
}
if (pFrameSynchronizationInfo->hasFrameCompleteSignalSemaphore) {
pFrameSynchronizationInfo->frameCompleteSemaphore = m_perFrameDecodeImageSet[picId].m_frameCompleteSemaphore;
if (pFrameSynchronizationInfo->frameCompleteSemaphore) {
m_perFrameDecodeImageSet[picId].m_hasFrameCompleteSignalSemaphore = true;
}
}
if (m_perFrameDecodeImageSet[picId].m_hasConsummerSignalSemaphore) {
pFrameSynchronizationInfo->frameConsumerDoneSemaphore = m_perFrameDecodeImageSet[picId].m_frameConsumerDoneSemaphore;
m_perFrameDecodeImageSet[picId].m_hasConsummerSignalSemaphore = false;
}
pFrameSynchronizationInfo->queryPool = m_queryPool;
pFrameSynchronizationInfo->startQueryId = picId;
pFrameSynchronizationInfo->numQueries = 1;
return picId;
}
// dequeue
virtual int32_t DequeueDecodedPicture(DecodedFrame* pDecodedFrame)
{
int numberofPendingFrames = 0;
int pictureIndex = -1;
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
if (!m_displayFrames.empty()) {
numberofPendingFrames = (int)m_displayFrames.size();
pictureIndex = m_displayFrames.front();
assert((pictureIndex >= 0) && ((uint32_t)pictureIndex < m_perFrameDecodeImageSet.size()));
assert(!(m_ownedByDisplayMask & (1 << pictureIndex)));
m_ownedByDisplayMask |= (1 << pictureIndex);
m_displayFrames.pop();
m_perFrameDecodeImageSet[pictureIndex].m_inDisplayQueue = false;
m_perFrameDecodeImageSet[pictureIndex].m_ownedByDisplay = true;
}
if ((uint32_t)pictureIndex < m_perFrameDecodeImageSet.size()) {
pDecodedFrame->pictureIndex = pictureIndex;
pDecodedFrame->pDecodedImage = &m_perFrameDecodeImageSet[pictureIndex].m_frameImage;
if (m_perFrameDecodeImageSet[pictureIndex].m_hasFrameCompleteSignalFence) {
pDecodedFrame->frameCompleteFence = m_perFrameDecodeImageSet[pictureIndex].m_frameCompleteFence;
m_perFrameDecodeImageSet[pictureIndex].m_hasFrameCompleteSignalFence = false;
} else {
pDecodedFrame->frameCompleteFence = VkFence();
}
if (m_perFrameDecodeImageSet[pictureIndex].m_hasFrameCompleteSignalSemaphore) {
pDecodedFrame->frameCompleteSemaphore = m_perFrameDecodeImageSet[pictureIndex].m_frameCompleteSemaphore;
m_perFrameDecodeImageSet[pictureIndex].m_hasFrameCompleteSignalSemaphore = false;
} else {
pDecodedFrame->frameCompleteSemaphore = VkSemaphore();
}
pDecodedFrame->frameConsumerDoneFence = m_perFrameDecodeImageSet[pictureIndex].m_frameConsumerDoneFence;
pDecodedFrame->frameConsumerDoneSemaphore = m_perFrameDecodeImageSet[pictureIndex].m_frameConsumerDoneSemaphore;
pDecodedFrame->timestamp = m_perFrameDecodeImageSet[pictureIndex].m_timestamp;
pDecodedFrame->decodeOrder = m_perFrameDecodeImageSet[pictureIndex].m_decodeOrder;
pDecodedFrame->displayOrder = m_perFrameDecodeImageSet[pictureIndex].m_displayOrder;
pDecodedFrame->queryPool = m_queryPool;
pDecodedFrame->startQueryId = pictureIndex;
pDecodedFrame->numQueries = 1;
}
if (m_debug) {
std::cout << "<<<<<<<<<<< Dequeue from Display: " << pictureIndex << " out of "
<< numberofPendingFrames << " ===========" << std::endl;
}
return numberofPendingFrames;
}
virtual int32_t ReleaseDisplayedPicture(DecodedFrameRelease** pDecodedFramesRelease, uint32_t numFramesToRelease)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
for (uint32_t i = 0; i < numFramesToRelease; i++) {
const DecodedFrameRelease* pDecodedFrameRelease = pDecodedFramesRelease[i];
int pictureIndex = pDecodedFrameRelease->pictureIndex;
assert((pictureIndex >= 0) && ((uint32_t)pictureIndex < m_perFrameDecodeImageSet.size()));
assert(m_perFrameDecodeImageSet[pictureIndex].m_decodeOrder == pDecodedFrameRelease->decodeOrder);
assert(m_perFrameDecodeImageSet[pictureIndex].m_displayOrder == pDecodedFrameRelease->displayOrder);
assert(m_ownedByDisplayMask & (1 << pictureIndex));
m_ownedByDisplayMask &= ~(1 << pictureIndex);
m_perFrameDecodeImageSet[pictureIndex].m_ownedByDisplay = false;
m_perFrameDecodeImageSet[pictureIndex].Release();
m_perFrameDecodeImageSet[pictureIndex].m_hasConsummerSignalFence = pDecodedFrameRelease->hasConsummerSignalFence;
m_perFrameDecodeImageSet[pictureIndex].m_hasConsummerSignalSemaphore = pDecodedFrameRelease->hasConsummerSignalSemaphore;
}
return 0;
}
virtual int32_t GetImageResourcesByIndex(uint32_t numResources, const int8_t* referenceSlotIndexes,
VkVideoPictureResourceKHR* pictureResources,
PictureResourceInfo* pictureResourcesInfo,
VkImageLayout newImageLayout = VK_IMAGE_LAYOUT_MAX_ENUM)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
for (unsigned int resId = 0; resId < numResources; resId++) {
if ((uint32_t)referenceSlotIndexes[resId] < m_perFrameDecodeImageSet.size()) {
pictureResources[resId].imageViewBinding = m_perFrameDecodeImageSet[referenceSlotIndexes[resId]].m_frameImage.view;
assert(pictureResources[resId].sType == VK_STRUCTURE_TYPE_VIDEO_PICTURE_RESOURCE_KHR);
pictureResources[resId].codedOffset = { 0, 0 }; // FIXME: This parameter must to be adjusted based on the interlaced mode.
pictureResources[resId].codedExtent = m_extent;
pictureResources[resId].baseArrayLayer = 0;
if (pictureResourcesInfo) {
pictureResourcesInfo[resId].currentImageLayout = m_perFrameDecodeImageSet[referenceSlotIndexes[resId]].m_currentImageLayout;
}
if (VK_IMAGE_LAYOUT_MAX_ENUM != newImageLayout) {
m_perFrameDecodeImageSet[referenceSlotIndexes[resId]].m_currentImageLayout = newImageLayout;
if (pictureResourcesInfo) {
pictureResourcesInfo[resId].image = m_perFrameDecodeImageSet[referenceSlotIndexes[resId]].m_frameImage.image;
}
}
}
}
return numResources;
}
virtual int32_t ReleaseImageResources(uint32_t numResources, const uint32_t* indexes)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
for (unsigned int resId = 0; resId < numResources; resId++) {
if ((uint32_t)indexes[resId] < m_perFrameDecodeImageSet.size()) {
m_perFrameDecodeImageSet[indexes[resId]].Deinit();
}
}
return (int32_t)m_perFrameDecodeImageSet.size();
}
virtual int32_t SetPicNumInDecodeOrder(int32_t picId, int32_t picNumInDecodeOrder)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
if ((uint32_t)picId < m_perFrameDecodeImageSet.size()) {
int32_t oldPicNumInDecodeOrder = m_perFrameDecodeImageSet[picId].m_decodeOrder;
m_perFrameDecodeImageSet[picId].m_decodeOrder = picNumInDecodeOrder;
return oldPicNumInDecodeOrder;
}
assert(false);
return -1;
}
virtual int32_t SetPicNumInDisplayOrder(int32_t picId, int32_t picNumInDisplayOrder)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
if ((uint32_t)picId < m_perFrameDecodeImageSet.size()) {
int32_t oldPicNumInDisplayOrder = m_perFrameDecodeImageSet[picId].m_displayOrder;
m_perFrameDecodeImageSet[picId].m_displayOrder = picNumInDisplayOrder;
return oldPicNumInDisplayOrder;
}
assert(false);
return -1;
}
virtual const vulkanVideoUtils::ImageObject* GetImageResourceByIndex(int8_t picId)
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
if ((uint32_t)picId < m_perFrameDecodeImageSet.size()) {
return &m_perFrameDecodeImageSet[picId].m_frameImage;
}
assert(false);
return NULL;
}
virtual vkPicBuffBase* ReservePictureBuffer()
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
int32_t foundPicId = -1;
for (uint32_t picId = 0; picId < m_perFrameDecodeImageSet.size(); picId++) {
if (m_perFrameDecodeImageSet[picId].IsAvailable()) {
foundPicId = picId;
break;
}
}
if (foundPicId >= 0) {
m_perFrameDecodeImageSet[foundPicId].Reset();
m_perFrameDecodeImageSet[foundPicId].AddRef();
m_perFrameDecodeImageSet[foundPicId].m_picIdx = foundPicId;
return &m_perFrameDecodeImageSet[foundPicId];
}
assert(foundPicId >= 0);
return NULL;
}
virtual size_t GetSize()
{
std::lock_guard<std::mutex> lock(m_displayQueueMutex);
return m_perFrameDecodeImageSet.size();
}
VkResult Initialize() { return VK_SUCCESS; }
void Deinitialize() {};
virtual ~NvVulkanVideoFrameBuffer()
{
if (m_queryPool != VkQueryPool()) {
vk::DestroyQueryPool(m_pVideoRendererDeviceInfo->device_, m_queryPool, NULL);
m_queryPool = VkQueryPool();
}
}
struct PpsEntry {
};
struct SpsEntry {
std::map<uint8_t, PpsEntry> ppsMap;
};
private:
vulkanVideoUtils::VulkanDeviceInfo* m_pVideoRendererDeviceInfo;
std::atomic<int32_t> m_refCount;
std::mutex m_displayQueueMutex;
NvPerFrameDecodeImageSet m_perFrameDecodeImageSet;
std::queue<uint8_t> m_displayFrames;
VkQueryPool m_queryPool;
uint32_t m_ownedByDisplayMask;
int32_t m_frameNumInDecodeOrder;
int32_t m_frameNumInDisplayOrder;
VkExtent2D m_extent;
uint32_t m_debug : 1;
std::map<uint8_t, SpsEntry> spsMap;
};
VulkanVideoFrameBuffer* VulkanVideoFrameBuffer::CreateInstance(vulkanVideoUtils::VulkanDeviceInfo* pVideoRendererDeviceInfo)
{
NvVulkanVideoFrameBuffer* pVulkanVideoFrameBuffer = new NvVulkanVideoFrameBuffer(pVideoRendererDeviceInfo);
if (!pVulkanVideoFrameBuffer) {
return pVulkanVideoFrameBuffer;
}
VkResult err = pVulkanVideoFrameBuffer->Initialize();
if (err != VK_SUCCESS) {
pVulkanVideoFrameBuffer->Release();
pVulkanVideoFrameBuffer = NULL;
}
return pVulkanVideoFrameBuffer;
}
int32_t NvVulkanVideoFrameBuffer::AddRef()
{
return ++m_refCount;
}
int32_t NvVulkanVideoFrameBuffer::Release()
{
uint32_t ret;
ret = --m_refCount;
// Destroy the device if refcount reaches zero
if (ret == 0) {
Deinitialize();
delete this;
}
return ret;
}
void NvPerFrameDecodeImage::Deinit()
{
if (m_frameImage.m_device == VkDevice()) {
return;
}
if (m_frameCompleteFence != VkFence()) {
vk::DestroyFence(m_frameImage.m_device, m_frameCompleteFence, nullptr);
m_frameCompleteFence = VkFence();
}
if (m_frameConsumerDoneFence != VkFence()) {
vk::DestroyFence(m_frameImage.m_device, m_frameConsumerDoneFence, nullptr);
m_frameConsumerDoneFence = VkFence();
}
if (m_frameCompleteSemaphore != VkSemaphore()) {
vk::DestroySemaphore(m_frameImage.m_device, m_frameCompleteSemaphore, nullptr);
m_frameCompleteSemaphore = VkSemaphore();
}
if (m_frameConsumerDoneSemaphore != VkSemaphore()) {
vk::DestroySemaphore(m_frameImage.m_device, m_frameConsumerDoneSemaphore, nullptr);
m_frameConsumerDoneSemaphore = VkSemaphore();
}
m_frameImage.DestroyImage();
Reset();
}
int32_t NvPerFrameDecodeImageSet::init(uint32_t numImages,
vulkanVideoUtils::VulkanDeviceInfo* deviceInfo,
const VkImageCreateInfo* pImageCreateInfo,
VkMemoryPropertyFlags requiredMemProps,
int initWithPattern,
VkExternalMemoryHandleTypeFlagBitsKHR exportMemHandleTypes,
vulkanVideoUtils::NativeHandle& importHandle)
{
Deinit();
m_size = numImages;
VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
VkFenceCreateInfo fenceFrameCompleteInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
// The fence waited on for the first frame should be signaled.
fenceFrameCompleteInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
VkSemaphoreCreateInfo semInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
for (unsigned imageIndex = 0; imageIndex < numImages; imageIndex++) {
VkResult result = m_frameDecodeImages[imageIndex].m_frameImage.CreateImage(deviceInfo, pImageCreateInfo,
requiredMemProps,
initWithPattern,
exportMemHandleTypes, importHandle);
assert(result == VK_SUCCESS);
result = vk::CreateFence(deviceInfo->device_, &fenceFrameCompleteInfo, nullptr, &m_frameDecodeImages[imageIndex].m_frameCompleteFence);
result = vk::CreateFence(deviceInfo->device_, &fenceInfo, nullptr, &m_frameDecodeImages[imageIndex].m_frameConsumerDoneFence);
assert(result == VK_SUCCESS);
assert(result == VK_SUCCESS);
result = vk::CreateSemaphore(deviceInfo->device_, &semInfo, nullptr, &m_frameDecodeImages[imageIndex].m_frameCompleteSemaphore);
assert(result == VK_SUCCESS);
result = vk::CreateSemaphore(deviceInfo->device_, &semInfo, nullptr, &m_frameDecodeImages[imageIndex].m_frameConsumerDoneSemaphore);
assert(result == VK_SUCCESS);
}
return (int32_t)m_size;
}
void NvPerFrameDecodeImageSet::Deinit()
{
for (uint32_t ndx = 0; ndx < m_size; ndx++) {
m_frameDecodeImages[ndx].Deinit();
}
m_size = 0;
}
| 38.758013 | 165 | 0.688857 | [
"vector"
] |
8a0bc11027a1341001386ef22535f19dbe26bd16 | 680 | cpp | C++ | Examples/PUBCpp/ConvertPUBFiles/PUBToPDF.cpp | aspose-pub/Aspose.PUB-for-C | cad609c01b8a6201392391244df18a7b2caa215d | [
"MIT"
] | null | null | null | Examples/PUBCpp/ConvertPUBFiles/PUBToPDF.cpp | aspose-pub/Aspose.PUB-for-C | cad609c01b8a6201392391244df18a7b2caa215d | [
"MIT"
] | null | null | null | Examples/PUBCpp/ConvertPUBFiles/PUBToPDF.cpp | aspose-pub/Aspose.PUB-for-C | cad609c01b8a6201392391244df18a7b2caa215d | [
"MIT"
] | null | null | null | #include "..\Aspose.PUB.h"
using namespace System;
using namespace Aspose::Pub;
void ConvertPubToPdf()
{
// Initialize license object
auto license = System::MakeObject<Aspose::Pub::License>();
// Set license
license->SetLicense(dataDir() + u"License\\Aspose.PUB.C++.lic");
System::String filePub = dataDir() + u"1.pub";
System::String filePdf = dataDir() + u"1.pdf";
System::Console::WriteLine(u"Convert starting...");
System::SharedPtr<IPubParser> parser = PubFactory::CreateParser(filePub);
System::SharedPtr<Document> document = parser->Parse();
PubFactory::CreatePdfConverter()->ConvertToPdf(document, filePdf);
System::Console::WriteLine(u"Convert done.");
} | 29.565217 | 74 | 0.722059 | [
"object"
] |
8a1d04ce1d2b418a1f902400815a4b1d6d3f4f22 | 318 | cpp | C++ | soln/search-insert-position/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | soln/search-insert-position/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | soln/search-insert-position/Solution.cpp | yungweezy/leetcode | 070605351a0a05b80360b9a55326b03224e46bbe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for (int i=0; i< nums.size(); i++) {
if (nums[i] >= target) return i;
}
return nums.size();
}
};
// https://leetcode.com/problems/search-insert-position/ | 26.5 | 56 | 0.581761 | [
"vector"
] |
8a1f324782f9fa30ff8aea9d8f8e6d2d7196e29a | 18,635 | cxx | C++ | src/pdencp.cxx | iamholger/ccz5 | 31e8ed262e1a065ad91381306859162e76402120 | [
"MIT"
] | null | null | null | src/pdencp.cxx | iamholger/ccz5 | 31e8ed262e1a065ad91381306859162e76402120 | [
"MIT"
] | null | null | null | src/pdencp.cxx | iamholger/ccz5 | 31e8ed262e1a065ad91381306859162e76402120 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include "Constants.h"
using namespace examples::exahype2::ccz4;
#pragma omp declare target
void pdencp_(double* BgradQ, const double* const Q, const double* const gradQSerialised, const int normal)
{
const double alpha = std::exp(std::fmax(-20., std::fmin(20.,Q[16])));
const double alpha2 = alpha*alpha;
double fa = 1.0;
double faa = 0.0;
if (CCZ4LapseType==1)
{
fa = 2./alpha;
faa = -fa/alpha;
}
constexpr int nVar(59);
// First model parameter ds here (ds == CCZ4ds)
double gradQin[59][3] ={0};
// De-serialise input data and fill static array
// FIXME the use of 2D arrays can be avoided: all terms not in the normal are 0
for (int i=0; i<nVar; i++) gradQin[i][normal] = gradQSerialised[i+normal*nVar];
// Note g_cov is symmetric
const double g_cov[3][3] = { {Q[0], Q[1], Q[2]}, {Q[1], Q[3], Q[4]}, {Q[2], Q[4], Q[5]} };
const double invdet = 1./( Q[0]*Q[3]*Q[5] - Q[0]*Q[4]*Q[4] - Q[1]*Q[1]*Q[5] + 2*Q[1]*Q[2]*Q[4] -Q[2]*Q[2]*Q[3]);
const double g_contr[3][3] = {
{ ( Q[3]*Q[5]-Q[4]*Q[4])*invdet, -( Q[1]*Q[5]-Q[2]*Q[4])*invdet, -(-Q[1]*Q[4]+Q[2]*Q[3])*invdet},
{-( Q[1]*Q[5]-Q[4]*Q[2])*invdet, ( Q[0]*Q[5]-Q[2]*Q[2])*invdet, -( Q[0]*Q[4]-Q[2]*Q[1])*invdet},
{-(-Q[1]*Q[4]+Q[3]*Q[2])*invdet, -( Q[0]*Q[4]-Q[1]*Q[2])*invdet, ( Q[0]*Q[3]-Q[1]*Q[1])*invdet}
};
// NOTE Aex is symmetric
double Aex[3][3] = { {Q[6], Q[7], Q[8]}, {Q[7], Q[9], Q[10]}, {Q[8], Q[10], Q[11]} };
double traceA = 0;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) traceA+=g_contr[i][j]*Aex[i][j];
traceA *= 1./3;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) Aex[i][j] -= traceA * g_cov[i][j];
// Matrix multiplications Amix = matmul(g_contr, Aex) Aup = matmul(g_contr, mytranspose(Amix))
double Amix[3][3]={0};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int u = 0; u < 3; u++) Amix[i][j] += g_contr[i][u] * Aex[u][j];
double Aup[3][3]={0};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int u = 0; u < 3; u++) Aup[i][j] += g_contr[i][u] * Amix[j][u]; // Note the transposition is in the indices
const double DD[3][3][3] = {
{{Q[35], Q[36], Q[37]}, {Q[36], Q[38], Q[39]}, {Q[37], Q[39], Q[40]}},
{{Q[41], Q[42], Q[43]}, {Q[42], Q[44], Q[45]}, {Q[43], Q[45], Q[46]}},
{{Q[47], Q[48], Q[49]}, {Q[48], Q[50], Q[51]}, {Q[49], Q[51], Q[52]}}
};
double dgup[3][3][3] {0};
for (int k = 0; k < 3; k++)
for (int m = 0; m < 3; m++)
for (int l = 0; l < 3; l++)
for (int n = 0; n < 3; n++)
for (int j = 0; j < 3; j++) dgup[k][m][l] -= g_contr[m][n]*g_contr[j][l]*2*DD[k][n][j];
const double PP[3] = {Q[55], Q[56], Q[57]};
double Christoffel[3][3][3] = {0};
double Christoffel_tilde[3][3][3] = {0};
double Christoffel_kind1[3][3][3] = {0};
for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++)
{
Christoffel_kind1[i][j][k] = DD[k][i][j] + DD[j][i][k] - DD[i][j][k];
for (int l = 0; l < 3; l++)
{
Christoffel_tilde[i][j][k] += g_contr[k][l] * ( DD[i][j][l] + DD[j][i][l] - DD[l][i][j] );
Christoffel[i][j][k] += g_contr[k][l] * ( DD[i][j][l] + DD[j][i][l] - DD[l][i][j] ) - g_contr[k][l] * ( g_cov[j][l] * PP[i] + g_cov[i][l] * PP[j] - g_cov[i][j] * PP[l] );
}
}
double Gtilde[3] = {0};
for (int l = 0; l < 3; l++)
for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++) Gtilde[i] += g_contr[j][l] * Christoffel_tilde[j][l][i];
const double Ghat[3] = {Q[13], Q[14], Q[15]};
const double phi = std::exp(std::fmax(-20., std::fmin(20.,Q[54])));
const double phi2 = phi*phi;
double Z[3] = {0};
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) Z[i] += ( g_cov[i][j]* (Ghat[j] - Gtilde[j]));
double Zup[3] = {0};
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) Zup[i] += phi2 * g_contr[i][j] * Z[j];
const double dDD[3][3][3][3] = {
{
{
{gradQin[35][0],gradQin[36][0],gradQin[37][0]}, {gradQin[36][0],gradQin[38][0],gradQin[39][0]}, {gradQin[37][0],gradQin[39][0],gradQin[40][0]},
},
{
{gradQin[41][0],gradQin[42][0],gradQin[43][0]}, {gradQin[42][0],gradQin[44][0],gradQin[45][0]}, {gradQin[43][0],gradQin[45][0],gradQin[46][0]},
},
{
{gradQin[47][0],gradQin[48][0],gradQin[49][0]}, {gradQin[48][0],gradQin[50][0],gradQin[51][0]}, {gradQin[49][0],gradQin[51][0],gradQin[52][0]}
}
},
{
{
{gradQin[35][1],gradQin[36][1],gradQin[37][1]}, {gradQin[36][1],gradQin[38][1],gradQin[39][1]}, {gradQin[37][1],gradQin[39][1],gradQin[40][1]},
},
{
{gradQin[41][1],gradQin[42][1],gradQin[43][1]}, {gradQin[42][1],gradQin[44][1],gradQin[45][1]}, {gradQin[43][1],gradQin[45][1],gradQin[46][1]},
},
{
{gradQin[47][1],gradQin[48][1],gradQin[49][1]}, {gradQin[48][1],gradQin[50][1],gradQin[51][1]}, {gradQin[49][1],gradQin[51][1],gradQin[52][1]}
}
},
{
{
{gradQin[35][2],gradQin[36][2],gradQin[37][2]}, {gradQin[36][2],gradQin[38][2],gradQin[39][2]}, {gradQin[37][2],gradQin[39][2],gradQin[40][2]},
},
{
{gradQin[41][2],gradQin[42][2],gradQin[43][2]}, {gradQin[42][2],gradQin[44][2],gradQin[45][2]}, {gradQin[43][2],gradQin[45][2],gradQin[46][2]},
},
{
{gradQin[47][2],gradQin[48][2],gradQin[49][2]}, {gradQin[48][2],gradQin[50][2],gradQin[51][2]}, {gradQin[49][2],gradQin[51][2],gradQin[52][2]}
}
}
};
const double dPP[3][3] = {
{gradQin[55][0],gradQin[56][0],gradQin[57][0]},
{gradQin[55][1],gradQin[56][1],gradQin[57][1]},
{gradQin[55][2],gradQin[56][2],gradQin[57][2]}
};
double dChristoffelNCP[3][3][3][3] = {0};
double dChristoffel_tildeNCP[3][3][3][3] = {0};
for (int i = 0; i < 3; i++)
for (int ip = 0; ip < 3; ip++)
for (int m = 0; m < 3; m++)
for (int k = 0; k < 3; k++)
{
dChristoffelNCP[k][i][ip][m] = 0;
dChristoffel_tildeNCP[k][i][ip][m] = 0;
for (int l = 0; l < 3; l++)
{
dChristoffelNCP[k][i][ip][m] += 0.5*g_contr[m][l] * (
dDD[k][i][ip][l] + dDD[i][k][ip][l] + dDD[k][ip][i][l] + dDD[ip][k][i][l] - dDD[k][l][i][ip] + dDD[l][k][i][ip]
- g_cov[ip][l]*(dPP[k][i] + dPP[i][k]) - g_cov[i][l]*(dPP[k][ip]+dPP[ip][k]) + g_cov[i][ip]*(dPP[k][l]+dPP[l][k]) );
dChristoffel_tildeNCP[k][i][ip][m] += 0.5*g_contr[m][l]*(dDD[k][i][ip][l] + dDD[i][k][ip][l] + dDD[k][ip][i][l] + dDD[ip][k][i][l] - dDD[k][l][i][ip] - dDD[l][k][i][ip]);
}
}
double RiemannNCP[3][3][3][3] = {0};
for (int i = 0; i < 3; i++)
for (int ip = 0; ip < 3; ip++)
for (int m = 0; m < 3; m++)
for (int k = 0; k < 3; k++) RiemannNCP[i][k][ip][m] = dChristoffelNCP[k][i][ip][m] - dChristoffelNCP[ip][i][k][m];
double RicciNCP[3][3] = {0};
for (int m = 0; m < 3; m++)
for (int n = 0; n < 3; n++)
for (int l = 0; l < 3; l++) RicciNCP[m][n] += RiemannNCP[m][l][n][l];
double dGtildeNCP[3][3] = {0};
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++)
for (int j = 0; j < 3; j++)
for (int l = 0; l < 3; l++) dGtildeNCP[k][i] += g_contr[j][l]*dChristoffel_tildeNCP[k][j][l][i];
const double dGhat[3][3] = {
{gradQin[13][0],gradQin[14][0],gradQin[15][0]},
{gradQin[13][1],gradQin[14][1],gradQin[15][1]},
{gradQin[13][2],gradQin[14][2],gradQin[15][2]}
};
double dZNCP[3][3] = {0};
for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++) dZNCP[k][i] += CCZ4ds*0.5*g_cov[i][j]*(dGhat[k][j]-dGtildeNCP[k][j]);
double RicciPlusNablaZNCP[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) RicciPlusNablaZNCP[i][j] = RicciNCP[i][j] + dZNCP[i][j] + dZNCP[j][i];
double RPlusTwoNablaZNCP = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) RPlusTwoNablaZNCP += g_contr[i][j]*RicciPlusNablaZNCP[i][j]; // TODO fuse these steps
RPlusTwoNablaZNCP*=phi2;
const double AA[3] = {Q[23], Q[24], Q[25]};
const double dAA[3][3] = {
{gradQin[23][0],gradQin[24][0],gradQin[25][0]},
{gradQin[23][1],gradQin[24][1],gradQin[25][1]},
{gradQin[23][2],gradQin[24][2],gradQin[25][2]}
};
double nablaijalphaNCP[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) nablaijalphaNCP[i][j] = alpha*0.5*( dAA[i][j] + dAA[j][i] );
double nablanablaalphaNCP = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) nablanablaalphaNCP += g_contr[i][j]*nablaijalphaNCP[i][j];
nablanablaalphaNCP*=phi2;
double SecondOrderTermsNCP[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) SecondOrderTermsNCP[i][j] = -nablaijalphaNCP[i][j] + alpha*RicciPlusNablaZNCP[i][j];
double traceNCP = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) traceNCP += g_contr[i][j]*SecondOrderTermsNCP[i][j];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) SecondOrderTermsNCP[i][j] -= 1./3 * traceNCP * g_cov[i][j];
const double beta[3] = {Q[17], Q[18], Q[19]};
const double dAex[3][3][3] = {
{{gradQin[6][0],gradQin[7][0],gradQin[8][0]}, {gradQin[7][0], gradQin[9][0], gradQin[10][0]}, {gradQin[8][0], gradQin[10][0], gradQin[11][0]}},
{{gradQin[6][1],gradQin[7][1],gradQin[8][1]}, {gradQin[7][1], gradQin[9][1], gradQin[10][1]}, {gradQin[8][1], gradQin[10][1], gradQin[11][1]}},
{{gradQin[6][2],gradQin[7][2],gradQin[8][2]}, {gradQin[7][2], gradQin[9][2], gradQin[10][2]}, {gradQin[8][2], gradQin[10][2], gradQin[11][2]}}
};
//! Now assemble all this terrible stuff...
//!
//! Main variables of the CCZ4 system
double dtK[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) dtK[i][j] = phi2*SecondOrderTermsNCP[i][j] + beta[0] * dAex[0][i][j] + beta[1] * dAex[1][i][j] + beta[2] * dAex[2][i][j]; // extrinsic curvature
const double dtraceK[3] = {gradQin[53][0], gradQin[53][1], gradQin[53][1]};
double dtTraceK = -nablanablaalphaNCP + alpha*RPlusTwoNablaZNCP + beta[0]*dtraceK[0] + beta[1]*dtraceK[1] + beta[2]*dtraceK[2];
const double BB[3][3] = {
{Q[26], Q[27], Q[28]}, {Q[29], Q[30], Q[31]}, {Q[32], Q[33], Q[34]}
};
double traceB = BB[0][0] + BB[1][1] + BB[2][2]; // TODO direct from Q!
double Aupdown = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) Aupdown += Aex[i][j]*Aup[i][j];
const double dTheta[3] = {gradQin[13][0],gradQin[13][1],gradQin[13][2]};
const double dtTheta = 0.5*alpha*CCZ4e*CCZ4e*( RPlusTwoNablaZNCP ) + beta[0]*dTheta[0] + beta[1]*dTheta[1] + beta[2]*dTheta[2]; // *** original cleaning ***
double divAupNCP[3] = {0};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int l = 0; l < 3; l++)
for (int k = 0; k < 3; k++) divAupNCP[i] += g_contr[i][l]*g_contr[j][k]*dAex[j][l][k];
const double dBB[3][3][3] = {
{
{CCZ4sk*gradQin[26][0],CCZ4sk*gradQin[27][0],CCZ4sk*gradQin[28][0]}, {CCZ4sk*gradQin[29][0],CCZ4sk*gradQin[30][0],CCZ4sk*gradQin[31][0]}, {CCZ4sk*gradQin[32][0],CCZ4sk*gradQin[33][0],CCZ4sk*gradQin[34][0]}
},
{
{CCZ4sk*gradQin[26][1],CCZ4sk*gradQin[27][1],CCZ4sk*gradQin[28][1]}, {CCZ4sk*gradQin[29][1],CCZ4sk*gradQin[30][1],CCZ4sk*gradQin[31][1]}, {CCZ4sk*gradQin[32][1],CCZ4sk*gradQin[33][1],CCZ4sk*gradQin[34][1]}
},
{
{CCZ4sk*gradQin[26][2],CCZ4sk*gradQin[27][2],CCZ4sk*gradQin[28][2]}, {CCZ4sk*gradQin[29][2],CCZ4sk*gradQin[30][2],CCZ4sk*gradQin[31][2]}, {CCZ4sk*gradQin[32][2],CCZ4sk*gradQin[33][2],CCZ4sk*gradQin[34][2]}
}
};
double dtGhat[3];
for (int i = 0; i < 3; i++)
{
double temp=0, temp2=0;
for (int j = 0; j < 3; j++)
{
temp +=g_contr[i][j]*dtraceK[j];
temp2 +=g_contr[j][i]*dTheta[j];
}
dtGhat[i] = -4./3.*alpha*temp + 2*alpha*temp2 + beta[0]*dGhat[0][i] + beta[1]*dGhat[1][i] + beta[2]*dGhat[2][i];
for (int l = 0; l < 3; l++)
for (int k = 0; k < 3; k++) dtGhat[i] += g_contr[k][l]*0.5*(dBB[k][l][i] + dBB[l][k][i]) + 1./3.*g_contr[i][k]*0.5*(dBB[k][l][l] + dBB[l][k][l]);
}
double ov[3];
for (int k = 0; k < 3; k++)
{
double temp=0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) temp += g_contr[i][j]*dAex[k][i][j];
ov[k] = 2*alpha*temp;
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) dtGhat[i] += CCZ4sk*g_contr[i][j]*ov[j];
double dtbb[3];
for (int i = 0; i < 3; i++)
{
dtbb[i] = CCZ4xi*dtGhat[i] + CCZ4bs * ( beta[0]*gradQin[20+i][0] + beta[1]*gradQin[20+i][1] + beta[2]*gradQin[20+i][2] - beta[0]*gradQin[13+i][0] - beta[1]*gradQin[13+i][1] - beta[2]*gradQin[13+i][2]);
dtbb[i] *= CCZ4sk;
}
// Auxiliary variables
double dtA[3];
double dK0[3] = {0}; // FIXME we just add 0 all the time???
for (int i = 0; i < 3; i++)
{
dtA[i] = -alpha*fa*(dtraceK[i] - dK0[i] - CCZ4c*2*dTheta[i]) + beta[0]*dAA[0][i] + beta[1]*dAA[1][i] + beta[2]*dAA[2][i];
}
for (int k = 0; k < 3; k++)
{
double temp=0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) temp += g_contr[i][j]*dAex[k][i][j]; // TODO we computed this quantity few lines earlier alrady
dtA[k] -= CCZ4sk*alpha*fa*temp;
}
double dtB[3][3] = {
{CCZ4f*gradQin[20][0],CCZ4f*gradQin[21][0],CCZ4f*gradQin[22][0]},
{CCZ4f*gradQin[20][1],CCZ4f*gradQin[21][1],CCZ4f*gradQin[22][1]},
{CCZ4f*gradQin[20][2],CCZ4f*gradQin[21][2],CCZ4f*gradQin[22][2]}
};
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++)
for (int j = 0; j < 3; j++)
{
dtB[k][i] += CCZ4mu*alpha2 * g_contr[i][j]*( dPP[k][j] - dPP[j][k]);
for (int n = 0; n < 3; n++)
for (int l = 0; l < 3; l++) dtB[k][i] -= CCZ4mu*alpha2 * g_contr[i][j]*g_contr[n][l]*( dDD[k][l][j][n] - dDD[l][k][j][n]);
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) dtB[i][j] += CCZ4bs*(beta[0]*dBB[0][i][j] + beta[1]*dBB[1][i][j] + beta[2]*dBB[2][i][j]);
// NOTE 0 value param
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) dtB[i][j] *= CCZ4sk;
double dtD[3][3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++) dtD[i][j][k] = -alpha*dAex[i][j][k];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++)
for (int m = 0; m < 3; m++)
{
dtD[k][i][j] += ( 0.25*(g_cov[m][i]*(dBB[k][j][m] + dBB[j][k][m]) + g_cov[m][j]*(dBB[k][i][m]+dBB[i][k][m])) - 1./6.*g_cov[i][j]*(dBB[k][m][m]+dBB[m][k][m]) );
for (int n = 0; n < 3; n++)
dtD[k][i][j] += 1./3*alpha*g_cov[i][j]*g_contr[n][m]*dAex[k][n][m]; // explicitly remove the trace of tilde A again
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++) dtD[i][j][k] += beta[0]*dDD[0][i][j][k] + beta[1]*dDD[1][i][j][k] + beta[2]*dDD[2][i][j][k];
double dtP[3];
for (int i = 0; i < 3; i++) dtP[i] = beta[0]*dPP[0][i] + beta[1]*dPP[1][i] + beta[2]*dPP[2][i];
// NOTE test for non zero params
for (int k = 0; k < 3; k++)
{
double temp=0;
for (int m = 0; m < 3; m++)
for (int n = 0; n < 3; n++) temp += g_contr[m][n]*dAex[k][m][n]; // TODO we computed this quantity few lines earlier alrady
dtP[k] += 1./3*alpha*(dtraceK[k] + CCZ4sk*temp);
for (int i = 0; i < 3; i++) dtP[k] -= 1./6*(dBB[k][i][i] + dBB[i][k][i]);
}
double dtgamma[3][3] = {0};
double dtalpha = 0;
double dtbeta[3] = {0};
double dtphi = 0;
BgradQ[0] = -dtgamma[0][0];
BgradQ[1] = -dtgamma[0][1];
BgradQ[2] = -dtgamma[0][2];
BgradQ[3] = -dtgamma[1][1];
BgradQ[4] = -dtgamma[1][2];
BgradQ[5] = -dtgamma[2][2];
BgradQ[6] = -dtK[0][0];
BgradQ[7] = -dtK[0][1];
BgradQ[8] = -dtK[0][2];
BgradQ[9] = -dtK[1][1];
BgradQ[10] = -dtK[1][2];
BgradQ[11] = -dtK[2][2]; // ok
BgradQ[12] = -dtTheta; // ok
for (int i = 0; i < 3; i++) BgradQ[13+i] = -dtGhat[i]; // buggy
BgradQ[16] = -dtalpha;
for (int i = 0; i < 3; i++) BgradQ[17+i] = -dtbeta[i];
for (int i = 0; i < 3; i++) BgradQ[20+i] = -dtbb[i];
for (int i = 0; i < 3; i++) BgradQ[23+i] = -dtA[i];
BgradQ[26] = -dtB[0][0]; // note: thes are all 0 for default CCZ4sk=0
BgradQ[27] = -dtB[1][0];
BgradQ[28] = -dtB[2][0];
BgradQ[29] = -dtB[0][1];
BgradQ[30] = -dtB[1][1];
BgradQ[31] = -dtB[2][1];
BgradQ[32] = -dtB[0][2];
BgradQ[33] = -dtB[1][2];
BgradQ[34] = -dtB[2][2];
BgradQ[35] = -dtD[0][0][0];
BgradQ[36] = -dtD[0][0][1];
BgradQ[37] = -dtD[0][0][2];
BgradQ[38] = -dtD[0][1][1];
BgradQ[39] = -dtD[0][1][2];
BgradQ[40] = -dtD[0][2][2];
BgradQ[41] = -dtD[1][0][0];
BgradQ[42] = -dtD[1][0][1];
BgradQ[43] = -dtD[1][0][2];
BgradQ[44] = -dtD[1][1][1];
BgradQ[45] = -dtD[1][1][2];
BgradQ[46] = -dtD[1][2][2];
BgradQ[47] = -dtD[2][0][0];
BgradQ[48] = -dtD[2][0][1];
BgradQ[49] = -dtD[2][0][2];
BgradQ[50] = -dtD[2][1][1];
BgradQ[51] = -dtD[2][1][2];
BgradQ[52] = -dtD[2][2][2];
BgradQ[53] = -dtTraceK;
BgradQ[54] = -dtphi;
for (int i = 0; i < 3; i++) BgradQ[55+i] = -dtP[i];
BgradQ[58] = 0;
}
#pragma omp end declare target
int main()
{
#pragma omp target
{
const int nVar(59);
double gradQSerialised[nVar*3], BgradQ[nVar]={2}, Q[nVar]={4};
// Set up initial test data
for (int i=0;i<nVar;i++)
{
Q[i] = 1;
BgradQ[i] = 1;
gradQSerialised[i]=1;
gradQSerialised[i +nVar]=1;
gradQSerialised[i +nVar + nVar]=1;
}
//The initial data for Q is chosen such that we do not divide by 0 in the inverse determinant
Q[0]=2;
Q[1]=3;
//for (int i=0;i<1000000;i++)
pdencp_(BgradQ, Q, gradQSerialised, 0);
for (int i=0;i<nVar;i++) printf("%d %.30f\n", i+1, BgradQ[i]);
}
return 0;
}
| 38.42268 | 217 | 0.481889 | [
"model"
] |
8a21dc2cf98831b8ef7bad4b167fbf0c3c7541df | 2,082 | cpp | C++ | engines/basic/src/main.cpp | WilliamLewww/vulkan_research_kit | 7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc | [
"Apache-2.0"
] | null | null | null | engines/basic/src/main.cpp | WilliamLewww/vulkan_research_kit | 7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc | [
"Apache-2.0"
] | 2 | 2021-12-06T01:56:35.000Z | 2022-03-07T06:47:38.000Z | engines/basic/src/main.cpp | WilliamLewww/vulkan_research_kit | 7f055329c25b16dc52e10ee50e64e5e3a2d6dfdc | [
"Apache-2.0"
] | null | null | null | #include "basic/engine.h"
int main() {
Display *displayPtr = XOpenDisplay(NULL);
int screen = DefaultScreen(displayPtr);
Window window = XCreateSimpleWindow(
displayPtr, RootWindow(displayPtr, screen), 10, 10, 100, 100, 1,
BlackPixel(displayPtr, screen), WhitePixel(displayPtr, screen));
XSelectInput(displayPtr, window, ExposureMask | KeyPressMask);
XMapWindow(displayPtr, window);
std::shared_ptr<Engine> engine =
std::shared_ptr<Engine>(new Engine("Demo Application", true, {}, {}));
engine->selectWindow(displayPtr, std::make_shared<Window>(window));
std::vector<std::string> physicalDeviceNameList =
engine->getPhysicalDeviceNameList();
for (std::string physicalDeviceName : physicalDeviceNameList) {
printf("%s\n", physicalDeviceName.c_str());
}
engine->selectPhysicalDevice(physicalDeviceNameList[0], {});
std::shared_ptr<Scene> scene = engine->createScene("my-scene");
std::shared_ptr<Material> material = scene->createMaterial(
"my-material", "resources/shaders/material.vert.spv",
"resources/shaders/material.frag.spv");
std::shared_ptr<Model> model = scene->createModel(
"my-model", "resources/models/color_cube/color_cube.obj", material);
std::shared_ptr<Light> light =
scene->createLight("my-light", Light::LIGHT_TYPE_POINT);
std::shared_ptr<Camera> camera = engine->createCamera("my-camera");
XEvent event;
while (true) {
XNextEvent(displayPtr, &event);
if (event.type == KeyPress) {
// escape
if (event.xkey.keycode == 9) {
break;
}
// left
if (event.xkey.keycode == 113) {
camera->updateRotation(-0.05, 0.0, 0.0);
}
// down
if (event.xkey.keycode == 116) {
camera->updatePosition(0.0, 0.0, -0.05);
}
// up
if (event.xkey.keycode == 111) {
camera->updatePosition(0.0, 0.0, 0.05);
}
// right
if (event.xkey.keycode == 114) {
camera->updateRotation(0.05, 0.0, 0.0);
}
}
engine->render(scene, camera);
}
return 0;
}
| 28.520548 | 76 | 0.641691 | [
"render",
"vector",
"model"
] |
8a21e9df78d52e9325f672adb8028c2a47b0e2a0 | 8,630 | cpp | C++ | source/BenchmarkSimplex.cpp | Michaelangel007/BenchSimplex | 1ee70d51b91631535b9a9c6436786c6505e1148f | [
"MIT"
] | 3 | 2015-02-04T03:23:34.000Z | 2017-03-19T23:38:40.000Z | source/BenchmarkSimplex.cpp | Michaelangel007/BenchSimplex | 1ee70d51b91631535b9a9c6436786c6505e1148f | [
"MIT"
] | null | null | null | source/BenchmarkSimplex.cpp | Michaelangel007/BenchSimplex | 1ee70d51b91631535b9a9c6436786c6505e1148f | [
"MIT"
] | null | null | null | /*
* OpenSimplex (Simplectic) Noise Test in C++
* Original Java version
* Converted to C by Arthur Tombs * Modified 2014-09-22
* Cleaned up version by Michaelangel007 * Removed PNG & C++ bloat, added glsl and reference simplex
*
* This file is intended to test the function of OpenSimplexNoise.hh.
*
* Compile with:
* g++ -o BenchmarkSimplex -O2 OpenSimplexNoiseTest.cpp
*
* Additional optimization can be obtained with:
*
* GCC: -Ofast (at the cost of accuracy)
* -msse4 (or the highest level of SSE your CPU supports).
*
* MSVC: /fp:fast /arch:SSE2
*/
#ifndef SIMPLEX_SHADER
#define SIMPLEX_SHADER 1
#endif
#ifdef _MSC_VER // Shutup Microsoft Visual C++ warnings about fopen()
#define _CRT_SECURE_NO_WARNINGS
#else
#include <sys/time.h> // gettimeofday() // Linux, OSX but NOT on Windows
#endif
#include <stdio.h> // fopen()
//#include <stdlib.h> // rand(), srand() // Optimization: Removed useless randomization
#include <stdint.h> // uint8_t
#include <string.h> // memset()
#include <stdint.h> // int8_t
#include <time.h> // time()
#include <math.h> // floor()
#include "OpenSimplexNoise.hh"
#include "SimplexNoise1234.h"
#if SIMPLEX_SHADER
#include "glsl_to_cpp.h"
#include "SimplexPerlin3D.glsl" // See note about <math.h> and Windows.h -> WinDef.h min() max()
#endif
#include "PerlinNoise1234.h"
#include "util_targa.h"
#include "util_timer.h"
const int WIDTH = 512;
const int HEIGHT = 512;
const float FEATURE_SIZE = 24.0f;
// calls Noise() WIDTH*HEIGHT number of times
void make_open( OpenSimplexNoise & simplex, float *values )
{
for (int yi = 0; yi < HEIGHT; yi++)
{
float y = (-0.5f + yi / (float)(HEIGHT-1)) * (HEIGHT / FEATURE_SIZE);
for (int xi = 0; xi < WIDTH; xi++)
{
float x = (-0.5f + xi / (float)(WIDTH-1)) * (WIDTH / FEATURE_SIZE);
values[ xi+yi*WIDTH ] = simplex.eval( x, y, 0.0f );
}
}
}
void make_ref( SimplexNoise1234 & simplex, float *values )
{
for (int yi = 0; yi < HEIGHT; yi++)
{
float y = (-0.5f + yi / (float)(HEIGHT-1)) * (HEIGHT / FEATURE_SIZE);
for (int xi = 0; xi < WIDTH; xi++)
{
float x = (-0.5f + xi / (float)(WIDTH-1)) * (WIDTH / FEATURE_SIZE);
values[ xi+yi*WIDTH ] = simplex.noise( x, y, 0.0f );
}
}
}
#if SIMPLEX_SHADER
void make_shader( float *values )
{
for (int yi = 0; yi < HEIGHT; yi++)
{
float y = (-0.5f + yi / (float)(HEIGHT-1)) * (HEIGHT / FEATURE_SIZE);
for (int xi = 0; xi < WIDTH; xi++)
{
float x = (-0.5f + xi / (float)(WIDTH-1)) * (WIDTH / FEATURE_SIZE);
values[ xi+yi*WIDTH ] = SimplexPerlin3D( x, y, 0.0f );
}
}
}
#endif
void quantize( float *values, uint8_t *texels )
{
float *pSrc = values;
uint8_t *pDst = texels;
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
int8_t i = (uint8_t) floor( ((*pSrc++ * 0.5f) + 0.5f) * 255.0f ); // BUGFIX: remove +0.5 bias so final 0 .. 255
*pDst++ = i; // r
*pDst++ = i; // g
*pDst++ = i; // b
}
}
}
void DefaultOpenSimplex( float *values, uint8_t *texels )
{
// Default Seed
OpenSimplexNoise noise;
make_open( noise , values ); // generate float array
quantize ( values, texels ); // convert to 24-bit grayscale
Targa_Save( "opensimplex_noise_default.tga", WIDTH, HEIGHT, texels, 24 );
}
void BenchmarkOpenSimplex( bool bSaveNoise, float *values, uint8_t *texels )
{
Timer timer;
timer.Start();
uint64_t samples = 0;
for( uint32_t seed = 0; seed < 256; seed++ )
{
if( bSaveNoise )
printf( "Seed: %d\n", seed );
OpenSimplexNoise noise( seed );
make_open( noise , values ); // generate float array
quantize ( values, texels ); // convert to 24-bit grayscale
if( bSaveNoise )
{
char filename[ 64 ];
sprintf( filename, "opensimplex_noise_seed_%d.tga", seed );
Targa_Save( filename, WIDTH, HEIGHT, texels, 24 );
}
samples += (WIDTH * HEIGHT);
}
timer.Stop();
timer.Throughput( samples );
// Throughput = Total samples / Time
printf( "Open Simplex: %.f seconds = %d:%d, %2d %cnoise/s\n"
// , (uint32_t)samples
, timer.elapsed
, timer.mins
, timer.secs
, (uint32_t)timer.throughput.per_sec
, timer.throughput.prefix
);
}
void DefaultReferenceSimplex( float *values, uint8_t *texels )
{
SimplexNoise1234 noise;
make_ref( noise , values ); // generate float array
quantize ( values, texels ); // convert to 24-bit grayscale
Targa_Save( "refsimplex_noise_default.tga", WIDTH, HEIGHT, texels, 24 );
}
void BenchmarkReferenceSimplex( bool bSaveNoise, float *values, uint8_t *texels )
{
Timer timer;
timer.Start();
uint64_t samples = 0;
for( uint32_t seed = 0; seed < 256; seed++ )
{
if( bSaveNoise )
printf( "Seed: %d\n", seed );
SimplexNoise1234 simplex; // doesn't support a permutation seed
make_ref( simplex , values ); // generate float array
quantize( values, texels ); // convert to 24-bit grayscale
if( bSaveNoise )
{
char filename[ 64 ];
sprintf( filename, "refsimplex_noise_seed_%d.tga", seed );
Targa_Save( filename, WIDTH, HEIGHT, texels, 24 );
}
samples += (WIDTH * HEIGHT);
}
timer.Stop();
timer.Throughput( samples );
// Throughput = Total samples / Time
printf( "Ref. Simplex: %.f seconds = %d:%d, %2d %cnoise/s\n"
// , (uint32_t)samples
, timer.elapsed
, timer.mins
, timer.secs
, (uint32_t)timer.throughput.per_sec
, timer.throughput.prefix
);
}
#if SIMPLEX_SHADER
void DefaultShaderSimplex( float *values, uint8_t *texels )
{
make_shader( values ); // generate float array
quantize ( values, texels ); // convert to 24-bit grayscale
Targa_Save( "glslsimplex_noise_default.tga", WIDTH, HEIGHT, texels, 24 );
}
void BenchmarkShaderSimplex( bool bSaveNoise, float *values, uint8_t *texels )
{
Timer timer;
timer.Start();
uint64_t samples = 0;
for( uint32_t seed = 0; seed < 256; seed++ )
{
if( bSaveNoise )
printf( "Seed: %d\n", seed );
make_shader( values ); // generate float array
quantize ( values , texels ); // convert to 24-bit grayscale
samples += (WIDTH * HEIGHT);
}
timer.Stop();
timer.Throughput( samples );
// Throughput = Total samples / Time
printf( "GLSL Simplex: %.f seconds = %d:%d, %2d %cnoise/s\n"
// , (uint32_t)samples
, timer.elapsed
, timer.mins
, timer.secs
, (uint32_t)timer.throughput.per_sec
, timer.throughput.prefix
);
}
#endif
/*
Microsoft VS 2010
Properties, Code Generation,
Floating Point Model: /fp:fast
Enable Enhanced Instruction Set: /arch:sse2
Samples: 67108864
Mnoise/s w/ sse2 fp:fast w/o sse2 w/o fp:fast
Open Simplex: 12 9 6
Ref. Simplex: 21 16 10
GLSL Simplex: 8 5 4
*/
int main( int nArg, char *aArg[] )
{
float *values = new float [WIDTH * HEIGHT ]; // intensity
uint8_t *texels = new uint8_t [ WIDTH * HEIGHT * 3 ]; // rgb
// Open Simplex Seed specified
bool bBenchmark = (nArg > 1); // TODO: -bench
bool bSaveNoise = (nArg > 2); // TODO: -save
bBenchmark = 1;
DefaultOpenSimplex ( values, texels );
DefaultReferenceSimplex( values, texels );
#if SIMPLEX_SHADER
DefaultShaderSimplex ( values, texels );
#endif
if( bBenchmark )
{
BenchmarkOpenSimplex ( bSaveNoise, values, texels );
BenchmarkReferenceSimplex( bSaveNoise, values, texels );
#if SIMPLEX_SHADER
BenchmarkShaderSimplex ( bSaveNoise, values, texels );
#endif
// Repeat the benchmark but in reverse
#if SIMPLEX_SHADER
BenchmarkShaderSimplex ( bSaveNoise, values, texels );
#endif
BenchmarkReferenceSimplex( bSaveNoise, values, texels );
BenchmarkOpenSimplex ( bSaveNoise, values, texels );
}
#if _WIN32
getchar();
#endif
delete [] texels;
delete [] values;
return 0;
}
| 28.202614 | 124 | 0.578679 | [
"model"
] |
8a28b974c002ec6815f7520700575f6cf54ac33c | 2,665 | hxx | C++ | OCC/opencascade-7.2.0/x64/debug/inc/SelectBasics_EntityOwner.hxx | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | OCC/opencascade-7.2.0/x64/debug/inc/SelectBasics_EntityOwner.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | OCC/opencascade-7.2.0/x64/debug/inc/SelectBasics_EntityOwner.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2021-11-21T13:03:26.000Z | 2021-11-21T13:03:26.000Z | // Created on: 1995-02-09
// Created by: Mister rmi
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _SelectBasics_EntityOwner_HeaderFile
#define _SelectBasics_EntityOwner_HeaderFile
#include <Standard.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Type.hxx>
#include <TopLoc_Location.hxx>
//! defines an abstract owner of sensitive primitives.
//! Owners are typically used to establish a connection
//! between sensitive entities and high-level objects (e.g. presentations).
//!
//! Priority : It's possible to give a priority:
//! the scale : [0-9] ; the default priority is 0
//! it allows the predominance of one selected object upon
//! another one if many objects are selected at the same time
//!
//! example : Selection of shapes : the owners are
//! selectable objects (presentations)
//!
//! a user can give vertex priority [3], edges [2] faces [1] shape [0],
//! so that if during selection one vertex one edge and one face are
//! simultaneously detected, the vertex will only be hilighted.
class SelectBasics_EntityOwner : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(SelectBasics_EntityOwner, Standard_Transient)
public:
//! sets the selectable priority of the owner
void SetPriority (const Standard_Integer thePriority) { mypriority = thePriority; }
Standard_Integer Priority() const { return mypriority; }
Standard_EXPORT virtual Standard_Boolean HasLocation() const = 0;
Standard_EXPORT virtual void SetLocation (const TopLoc_Location& aLoc) = 0;
Standard_EXPORT virtual void ResetLocation() = 0;
Standard_EXPORT virtual TopLoc_Location Location() const = 0;
public:
//! sets the selectable priority of the owner
void Set (const Standard_Integer thePriority) { SetPriority (thePriority); }
protected:
Standard_EXPORT SelectBasics_EntityOwner (const Standard_Integer thePriority = 0);
protected:
Standard_Integer mypriority;
};
DEFINE_STANDARD_HANDLE(SelectBasics_EntityOwner, Standard_Transient)
#endif // _SelectBasics_EntityOwner_HeaderFile
| 35.065789 | 85 | 0.774859 | [
"object",
"shape"
] |
8a2e339f98939df6fde597950140a97dec2f4e33 | 1,755 | hpp | C++ | include/ssGUI/EventCallbacks/ChildRemovedEventCallback.hpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | 15 | 2022-01-21T10:48:04.000Z | 2022-03-27T17:55:11.000Z | include/ssGUI/EventCallbacks/ChildRemovedEventCallback.hpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | null | null | null | include/ssGUI/EventCallbacks/ChildRemovedEventCallback.hpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | 4 | 2022-01-21T10:48:05.000Z | 2022-01-22T15:42:34.000Z | #ifndef CHILD_REMOVED_EVENT_CALLBACK
#define CHILD_REMOVED_EVENT_CALLBACK
#include "ssGUI/EventCallbacks/BaseEventCallback.hpp"
//namespace: ssGUI::EventCallbacks
namespace ssGUI::EventCallbacks
{
//class: ssGUI::EventCallbacks::ChildRemovedEventCallback
//This event callback is triggered *after* a child is removed on this GUI object
//The child object being removed will be the source for triggering this event callback.
class ChildRemovedEventCallback : public BaseEventCallback
{
public:
friend class ssGUI::Factory;
protected:
ChildRemovedEventCallback() = default;
ChildRemovedEventCallback(ChildRemovedEventCallback const&) = default;
ChildRemovedEventCallback& operator=(ChildRemovedEventCallback const&) = default;
static void* operator new(size_t size) {return ::operator new(size);};
static void* operator new[](size_t size) {return ::operator new(size);};
static void operator delete(void* p) {free(p);};
static void operator delete[](void* p) {free(p);};
public:
//function: GetEventCallbackName
//See <BaseEventCallback::GetEventCallbackName>
virtual std::string GetEventCallbackName() const override;
//function: Clone
//See <BaseEventCallback::Clone>
virtual ChildRemovedEventCallback* Clone(ssGUI::GUIObject* newContainer, bool copyListeners) override;
//const: EVENT_NAME
//See <BaseEventCallback::EVENT_NAME>
static const std::string EVENT_NAME;
};
}
#endif | 39.886364 | 115 | 0.631909 | [
"object"
] |
8a4b1db6a3d273df2497aa1f5c8bc2614914cae1 | 2,688 | hpp | C++ | docker/d-streamon-master/d-streamon/streamon/usr/app_streamon/blocks/Metric_Block.hpp | ferrarimarco/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 2 | 2017-12-02T10:38:05.000Z | 2018-04-22T17:15:01.000Z | docker/d-streamon-master/d-streamon/streamon/usr/app_streamon/blocks/Metric_Block.hpp | scissor-project/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 67 | 2017-11-11T15:22:34.000Z | 2018-04-24T06:44:59.000Z | docker/d-streamon-master/d-streamon/streamon/usr/app_streamon/blocks/Metric_Block.hpp | ferrarimarco/open-scissor | d54718a1969701798f3e2d57f3db68d829da1cc0 | [
"Apache-2.0"
] | 1 | 2017-12-07T08:18:49.000Z | 2017-12-07T08:18:49.000Z |
#pragma once
#include <Block.hpp>
#include <BlockFactory.hpp>
#include <Packet.hpp>
#include <ClassId.hpp>
#include <arpa/inet.h>
#include <sstream>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include "bloom/bloompair.h"
#include "bloom/tewma.h"
#include "PacketPlus.hpp"
#include <unordered_map>
#include <list>
#include <streamon/pptags.h>
#include <streamon/ICounter.hpp>
namespace bm
{
// extern std::unordered_map<std::string, int> TokenMap;
#define MAX_METRICS_NUM 16
class Metric_Block : public Block
{
public:
Metric_Block(const std::string &name, bool): Block(name, false),
id_ingate(register_input_gate("in_Metric_Block")),
id_outgate(register_output_gate("out_Metric_Block"))
{
variation_detector = false;
variation_monitor = false;
swap_bf_size = 16;
swap_bf_nhash = 4;
swap_bf_reset_after = 0;
tewma_bf_size = 18;
tewma_bf_nhash = 4;
time_window = 60;
life = 1;
reset_window_end = 0;
IndexValue = -1;
InsertValue = 1;
}
Metric_Block(const Metric_Block &) = delete;
Metric_Block& operator=(const Metric_Block &) = delete;
Metric_Block(Metric_Block &&) = delete;
Metric_Block& operator=(Metric_Block &&) = delete;
virtual ~Metric_Block() {}
/*
* questo blocco ha parametri di configurazione
*/
virtual void _configure(const xml_node& n );
virtual void _receive_msg(std::shared_ptr<const Msg>&& m, int /* index */);
uint32_t string_to_int(std::string& val)
{
uint32_t num;
std::istringstream ss(val);
ss >> num;
return num;
}
protected:
int id_ingate;
int id_outgate;
int pkt_count;
int swap_bf_size;
int swap_bf_nhash;
uint64_t swap_bf_reset_after;
int tewma_bf_size;
int tewma_bf_nhash;
int life;
int metric_id;
int isPresent;
uint64_t reset_window_end;
double beta;
double time_window;
std::string configuration;
std::string det_flowkey;
std::string mon_flowkey;
bool variation_detector;
bool variation_monitor;
std::list<req_tuple> req_map;
std::vector<int> var_detect_flowkey;
std::vector<int> var_monitor_flowkey;
double InsertValue;
int IndexValue;
BloomPair* bloom;
// TEWMA* tewma_bloom;
ICounter* counter;
public:
static BloomPair* det_instances[MAX_METRICS_NUM];
static ICounter* counter_instances[MAX_METRICS_NUM];
static struct reset_action reset_ops[MAX_METRICS_NUM];
};
}
| 20.837209 | 79 | 0.643229 | [
"vector"
] |
a438abd29657b6d233eccfe9bcdfd38c0911bc94 | 716 | cpp | C++ | 21mt/src/sigcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 3 | 2015-08-26T17:14:02.000Z | 2015-11-17T04:18:56.000Z | 21mt/src/sigcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 10 | 2015-08-20T00:51:05.000Z | 2016-11-16T19:14:48.000Z | 21mt/src/sigcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 3 | 2016-11-16T00:52:23.000Z | 2021-09-10T02:17:40.000Z | #include "par_treg.h"
extern ofstream clogf;
#define TRACE(object) clogf << "line " << __LINE__ << ", file "\
<< __FILE__ << ", " << #object " = " << object << endl;
void par_t_reg::sigma_comp(dmatrix& sigma, year_month& ym)
{
int season = get_season(ym);
//clogf << "sigma_comp for " << ym << "; season = " << season << endl;
gridpartype_vector& ug = usergrid[season];
for (int i=1; i<=m; i++)
{
int j1 = jlb(i);
int jn = jub(i);
for (int j=j1; j<=jn; j++)
{
int k = gridmap[i][j];
sigma[i][j] = ug[k].sigma;
}//forj
// sigma[i][j1-1] = sigma[i][j1]; // <-- and
// sigma[i][jn+1] = sigma[i][jn]; // <--
}//fori
}//sigma_comp(dmatrix&,year_month&)
| 25.571429 | 72 | 0.526536 | [
"object"
] |
a443b308d4e92673ba9896280c0b9d6f1afa48ab | 10,653 | cpp | C++ | source/Core/Castor3D/Scene/Background/Image.cpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | source/Core/Castor3D/Scene/Background/Image.cpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | source/Core/Castor3D/Scene/Background/Image.cpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | #include "Castor3D/Scene/Background/Image.hpp"
#include "Castor3D/Engine.hpp"
#include "Castor3D/Event/Frame/FrameListener.hpp"
#include "Castor3D/Material/Texture/Sampler.hpp"
#include "Castor3D/Material/Texture/TextureLayout.hpp"
#include "Castor3D/Miscellaneous/makeVkType.hpp"
#include "Castor3D/Render/RenderModule.hpp"
#include "Castor3D/Render/RenderPipeline.hpp"
#include "Castor3D/Render/EnvironmentMap/EnvironmentMap.hpp"
#include "Castor3D/Scene/Camera.hpp"
#include "Castor3D/Scene/Scene.hpp"
#include "Castor3D/Scene/SceneNode.hpp"
#include "Castor3D/Scene/Background/Visitor.hpp"
#include "Castor3D/Shader/Program.hpp"
#include "Castor3D/Shader/Shaders/GlslUtils.hpp"
#include "Castor3D/Shader/Ubos/ModelUbo.hpp"
#include <ashespp/RenderPass/FrameBuffer.hpp>
#include <ashespp/RenderPass/RenderPass.hpp>
#include <ashespp/RenderPass/RenderPassCreateInfo.hpp>
#include <ashespp/Shader/ShaderModule.hpp>
#include <ShaderWriter/Source.hpp>
using namespace castor;
using namespace sdw;
namespace castor3d
{
//************************************************************************************************
namespace
{
ashes::ImageCreateInfo doGetImageCreate( VkFormat format
, Size const & dimensions
, bool attachment
, uint32_t mipLevel = 1u )
{
return ashes::ImageCreateInfo
{
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT,
VK_IMAGE_TYPE_2D,
format,
{ dimensions.getWidth(), dimensions.getHeight(), 1u },
mipLevel,
6u,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
( VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VkImageUsageFlags( attachment
? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
: VkImageUsageFlagBits( 0u ) ) ),
};
}
}
//************************************************************************************************
ImageBackground::ImageBackground( Engine & engine
, Scene & scene
, castor::String const & name )
: SceneBackground{ engine, scene, name + cuT( "Image" ), BackgroundType::eImage }
{
m_texture = std::make_shared< TextureLayout >( *engine.getRenderSystem()
, doGetImageCreate( VK_FORMAT_R8G8B8A8_UNORM, { 16u, 16u }, false )
, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
, cuT( "ImageBackground_Dummy" ) );
}
bool ImageBackground::loadImage( Path const & folder, Path const & relative )
{
bool result = false;
try
{
ashes::ImageCreateInfo image
{
0u,
VK_IMAGE_TYPE_2D,
VK_FORMAT_UNDEFINED,
{ 1u, 1u, 1u },
1u,
1u,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
( VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_SRC_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT ),
};
auto texture = std::make_shared< TextureLayout >( *getEngine()->getRenderSystem()
, image
, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
, cuT( "ImageBackground_Colour" ) );
texture->setSource( folder, relative, false, false );
m_2dTexture = texture;
m_2dTexturePath = castor::Path( m_2dTexture->getDefaultView().toString() );
notifyChanged();
result = true;
}
catch ( castor::Exception & p_exc )
{
log::error << p_exc.what() << std::endl;
}
return result;
}
void ImageBackground::accept( BackgroundVisitor & visitor )
{
visitor.visit( *this );
}
bool ImageBackground::doInitialise( RenderDevice const & device )
{
auto data = device.graphicsData();
doInitialise2DTexture( device, *data );
m_hdr = m_texture->getPixelFormat() == VK_FORMAT_R32_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R32G32_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R32G32B32_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R32G32B32A32_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R16_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R16G16_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R16G16B16_SFLOAT
|| m_texture->getPixelFormat() == VK_FORMAT_R16G16B16A16_SFLOAT;
return m_texture->initialise( device, *data );
}
void ImageBackground::doCleanup()
{
}
void ImageBackground::doCpuUpdate( CpuUpdater & updater )const
{
auto & viewport = *updater.viewport;
viewport.resize( updater.camera->getSize() );
viewport.setOrtho( -1.0f
, 1.0f
, -m_ratio
, m_ratio
, 0.1f
, 2.0f );
viewport.update();
auto node = updater.camera->getParent();
Matrix4x4f view;
matrix::lookAt( view
, node->getDerivedPosition()
, node->getDerivedPosition() + Point3f{ 0.0f, 0.0f, 1.0f }
, Point3f{ 0.0f, 1.0f, 0.0f } );
updater.bgMtxView = view;
updater.bgMtxProj = updater.isSafeBanded
? viewport.getSafeBandedProjection()
: viewport.getProjection();
}
void ImageBackground::doGpuUpdate( GpuUpdater & updater )const
{
}
void ImageBackground::doInitialise2DTexture( RenderDevice const & device
, QueueData const & queueData )
{
m_2dTexture->initialise( device, queueData );
VkExtent3D extent{ m_2dTexture->getWidth(), m_2dTexture->getHeight(), 1u };
auto dim = std::max( m_2dTexture->getWidth(), m_2dTexture->getHeight() );
// create the cube texture if needed.
if ( m_texture->getDimensions().width != dim
|| m_texture->getDimensions().height != dim )
{
m_ratio = float( m_2dTexture->getHeight() ) / float( m_2dTexture->getWidth() );
auto xOffset = ( dim - extent.width ) / 2u;
auto yOffset = ( dim - extent.height ) / 2u;
VkOffset3D const srcOffset{ 0, 0, 0 };
VkOffset3D const dstOffset{ int32_t( xOffset ), int32_t( yOffset ), 0 };
m_textureId = { device
, getEngine()->getGraphResourceHandler()
, cuT( "ImageBackgroundCube" )
, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT
, { dim, dim, 1u }
, 6u
, 1u
, m_2dTexture->getPixelFormat()
, ( VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) };
m_textureId.create();
m_texture = std::make_shared< TextureLayout >( device.renderSystem
, m_textureId.image
, m_textureId.wholeViewId );
VkImageSubresourceLayers srcSubresource
{
m_2dTexture->getDefaultView().getTargetView()->subresourceRange.aspectMask,
0,
0,
1,
};
VkImageSubresourceLayers dstSubresource
{
m_texture->getDefaultView().getTargetView()->subresourceRange.aspectMask,
0,
0,
1,
};
VkImageCopy copyInfos[6];
copyInfos[uint32_t( CubeMapFace::ePositiveX )].extent = extent;
copyInfos[uint32_t( CubeMapFace::ePositiveX )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveX )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::ePositiveX )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveX )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::ePositiveX );
copyInfos[uint32_t( CubeMapFace::ePositiveX )].dstOffset = dstOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeX )].extent = extent;
copyInfos[uint32_t( CubeMapFace::eNegativeX )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeX )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeX )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeX )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::eNegativeX );
copyInfos[uint32_t( CubeMapFace::eNegativeX )].dstOffset = dstOffset;
copyInfos[uint32_t( CubeMapFace::ePositiveY )].extent = extent;
copyInfos[uint32_t( CubeMapFace::ePositiveY )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveY )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::ePositiveY )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveY )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::ePositiveY );
copyInfos[uint32_t( CubeMapFace::ePositiveY )].dstOffset = dstOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeY )].extent = extent;
copyInfos[uint32_t( CubeMapFace::eNegativeY )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeY )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeY )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeY )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::eNegativeY );
copyInfos[uint32_t( CubeMapFace::eNegativeY )].dstOffset = dstOffset;
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].extent = extent;
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::ePositiveZ );
copyInfos[uint32_t( CubeMapFace::ePositiveZ )].dstOffset = dstOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].extent = extent;
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].srcSubresource = srcSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].srcOffset = srcOffset;
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].dstSubresource = dstSubresource;
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].dstSubresource.baseArrayLayer = uint32_t( CubeMapFace::eNegativeZ );
copyInfos[uint32_t( CubeMapFace::eNegativeZ )].dstOffset = dstOffset;
auto commandBuffer = queueData.commandPool->createCommandBuffer( "ImageBackground" );
commandBuffer->begin();
commandBuffer->memoryBarrier( VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
, VK_PIPELINE_STAGE_TRANSFER_BIT
, m_2dTexture->getDefaultView().getTargetView().makeTransferSource( VK_IMAGE_LAYOUT_UNDEFINED ) );
uint32_t index{ 0u };
for ( auto & copyInfo : copyInfos )
{
commandBuffer->memoryBarrier( VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
, VK_PIPELINE_STAGE_TRANSFER_BIT
, m_texture->getLayerCubeFaceView( 0, CubeMapFace( index ) ).getTargetView().makeTransferDestination( VK_IMAGE_LAYOUT_UNDEFINED ) );
commandBuffer->copyImage( copyInfo
, m_2dTexture->getTexture()
, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
, m_texture->getTexture()
, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL );
commandBuffer->memoryBarrier( VK_PIPELINE_STAGE_TRANSFER_BIT
, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
, m_texture->getLayerCubeFaceView( 0, CubeMapFace( index ) ).getTargetView().makeShaderInputResource( VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) );
++index;
}
commandBuffer->end();
queueData.queue->submit( *commandBuffer, nullptr );
queueData.queue->waitIdle();
m_2dTexture->cleanup();
}
}
//************************************************************************************************
}
| 37.378947 | 148 | 0.715385 | [
"render"
] |
a4494ac608f11b2687998618ecf10ab3f5624723 | 6,162 | cpp | C++ | YAX/src/Graphics/GraphicsAdapter.cpp | Swillis57/YAX | cc366b99af9bbce1d1a3a3580fad9f6c50bbfb4e | [
"MS-PL"
] | 1 | 2015-01-29T01:58:56.000Z | 2015-01-29T01:58:56.000Z | YAX/src/Graphics/GraphicsAdapter.cpp | Swillis57/YAX | cc366b99af9bbce1d1a3a3580fad9f6c50bbfb4e | [
"MS-PL"
] | 1 | 2015-03-27T11:21:08.000Z | 2015-03-27T11:21:08.000Z | YAX/src/Graphics/GraphicsAdapter.cpp | Swillis57/YAX | cc366b99af9bbce1d1a3a3580fad9f6c50bbfb4e | [
"MS-PL"
] | null | null | null | #include "Graphics/DepthFormat.h"
#include "Graphics/GraphicsAdapter.h"
#include "Graphics/GraphicsProfile.h"
#include "Graphics/SurfaceFormat.h"
#include "Rectangle.h"
#include "../../../external/glew/include/GL/glew.h"
#include "../../../external/glfw/include/GLFW/glfw3.h"
#ifdef _WIN32
# define GLFW_EXPOSE_NATIVE_WIN32
# define GLFW_EXPOSE_NATIVE_WGL
#elif __linux__
# define GLFW_EXPOSE_NATIVE_X11
# define GLFW_EXPOSE_NATIVE_GLX
#else
# define GLFW_EXPOSE_NATIVE_COCOA
# define GLFW_EXPOSE_NATIVE_NSGL
#endif
#include "../../../external/glfw/include/GLFW/glfw3native.h"
//Takes the const GLchar* from glGetString and casts it into an std::string
#define glGetActualString(enum) (std::string{reinterpret_cast<const char*>(glGetString(enum))} + "\0")
namespace YAX
{
struct GraphicsAdapter::Impl
{
DisplayModeCollection _supportedModes;
std::string _name, _desc, _vendor;
GLFWmonitor* _handle;
ui32 _monitorIdx;
Impl(std::string name, std::string desc, std::string vend, GLFWmonitor* hnd)
: _name(name), _desc(desc), _vendor(vend), _handle(hnd)
{
//Find and add the supported display modes for this monitor
i32 modeCount;
auto modes = glfwGetVideoModes(hnd, &modeCount);
size_t fixedModeCount = static_cast<size_t>(modeCount);
for (size_t j = 0; j < fixedModeCount; j++)
{
auto vMode = modes[j];
_supportedModes.emplace_back(DisplayMode(
{ vMode.redBits, vMode.blueBits, vMode.greenBits },
Rectangle(0, 0, vMode.width, vMode.height)
));
}
}
~Impl() = default;
bool IsProfileSupported(GraphicsProfile profile)
{
GLint majV;
glGetIntegerv(GL_MAJOR_VERSION, &majV);
//Core profile is always available,
//Compat is available for versions >= 3.0
return (profile == GraphicsProfile::HiDef || majV >= 3);
}
DisplayMode CurrentDisplayMode() const
{
//Don't need to delete this, GLFW manages the memory
auto vMode = glfwGetVideoMode(_handle);
return DisplayMode(
{vMode->redBits, vMode->blueBits, vMode->greenBits},
Rectangle(0, 0, vMode->width, vMode->height)
);
}
bool IsDefault() const
{
return _handle == _defaultAdapter->MonitorHandle();
}
bool IsWideScreen() const
{
//A widescreen aspect ratio is either 16:9 or 16:10
float aspRat = CurrentDisplayMode().AspectRatio();
return aspRat == 1.77f || aspRat == 1.6f;
}
};
GraphicsAdapter* GraphicsAdapter::_defaultAdapter;
std::vector<std::unique_ptr<GraphicsAdapter>> GraphicsAdapter::_adapters;
GraphicsAdapter::GraphicsAdapter(std::string name, std::string desc, std::string vend, GLFWmonitor* hnd)
{
_impl = std::make_unique<Impl>(name, desc, vend, hnd);
}
GraphicsAdapter::~GraphicsAdapter() = default;
GraphicsAdapter::GraphicsAdapter(GraphicsAdapter&& old)
: _impl(std::move(old._impl))
{}
GraphicsAdapter::GraphicsAdapter(const GraphicsAdapter& old)
: _impl(new Impl(*old._impl))
{}
GraphicsAdapter& GraphicsAdapter::operator=(const GraphicsAdapter& old)
{
this->_impl = std::unique_ptr<Impl>(new Impl(*old._impl));
return *this;
}
GraphicsAdapter& GraphicsAdapter::operator=(GraphicsAdapter&& old)
{
this->_impl = std::move(old._impl);
return *this;
}
const std::vector<std::unique_ptr<GraphicsAdapter>>* GraphicsAdapter::Adapters()
{
return &_adapters;
}
GraphicsAdapter* GraphicsAdapter::DefaultAdapter()
{
return _defaultAdapter;
}
void GraphicsAdapter::FindAdapters()
{
//A graphics adapter is essentially a connection to a
//monitor, so we just find all the monitors on the system
//and add them to the Adapters vector
GLFWmonitor* defaultMonitor = glfwGetPrimaryMonitor();
i32 monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
ui32 fixedMonitorCount = static_cast<ui32>(monitorCount);
//These shouldn't change between adapters unless the monitors
//are connected to different graphics cards (rare)
std::string desc = glGetActualString(GL_RENDERER);
std::string vend = glGetActualString(GL_VENDOR);
for (ui32 i = 0; i < fixedMonitorCount; i++)
{
#ifdef GLFW_EXPOSE_NATIVE_WIN32
std::string name = glfwGetWin32Adapter(monitors[i]);
#else
std::string name = glfwGetMonitorName(monitors[i]);
#endif
_adapters.emplace_back(std::make_unique<GraphicsAdapter>(GraphicsAdapter { name, desc, vend, monitors[i] }));
_adapters[_adapters.size() - 1]->_impl->_monitorIdx = i;
if (monitors[i] == defaultMonitor)
_defaultAdapter = _adapters[_adapters.size() - 1].get();
}
}
std::string GraphicsAdapter::Description() const
{
return _impl->_desc;
}
std::string GraphicsAdapter::DeviceName() const
{
return _impl->_name;
}
bool GraphicsAdapter::IsDefaultAdapter() const
{
return _impl->IsDefault();
}
bool GraphicsAdapter::IsWideScreen() const
{
return _impl->IsWideScreen();
}
GLFWmonitor* GraphicsAdapter::MonitorHandle() const
{
return _impl->_handle;
}
ui32 GraphicsAdapter::MonitorIndex() const
{
return _impl->_monitorIdx;
}
bool GraphicsAdapter::IsProfileSupported(GraphicsProfile profile) const
{
return _impl->IsProfileSupported(profile);
}
DisplayMode GraphicsAdapter::CurrentDisplayMode() const
{
return _impl->CurrentDisplayMode();
}
const DisplayModeCollection& GraphicsAdapter::SupportedDisplayModes() const
{
return _impl->_supportedModes;
}
} | 30.50495 | 121 | 0.627556 | [
"vector"
] |
a449e63eaa3a3b30a0195194eea2fd5dd352b371 | 1,432 | cpp | C++ | src/Rule.cpp | butitsnotme/funky-math-problem-solver | 01a38099735d9d93c406f2c99becad715f811c32 | [
"MIT"
] | null | null | null | src/Rule.cpp | butitsnotme/funky-math-problem-solver | 01a38099735d9d93c406f2c99becad715f811c32 | [
"MIT"
] | null | null | null | src/Rule.cpp | butitsnotme/funky-math-problem-solver | 01a38099735d9d93c406f2c99becad715f811c32 | [
"MIT"
] | null | null | null | #include "Rule.h"
#include <cstdlib>
#include <sstream>
using namespace std;
Rule::Rule() {
}
Rule::~Rule() {
}
void Rule::set(int x1, int y1, int x2, int y2, int diff) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
this->diff = diff;
this->num = true;
}
void Rule::set(int x1, int y1, int x2, int y2, bool greater) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
this->greater = greater;
this->num = false;
}
bool Rule::check(vector<vector<int>> matrix) const {
if (num) {
return (diff == (abs(matrix[x1][y1] - matrix[x2][y2])));
} else if(greater) {
return (matrix[x1][y1] > matrix[x2][y2]);
} else {
return (matrix[x1][y1] < matrix[x2][y2]);
}
}
bool Rule::valid(int x, int y, int sx, int sy) const {
int cp = y * sx + x;
int p1 = y1 * sx + x1;
int p2 = y2 * sx + x2;
return (p1 <= cp) && (p2 <= cp);
}
string Rule::to_string() const {
stringstream ss;
ss << "Rule: ";
if (num) {
ss << diff << endl;
} else {
ss << (greater ? ">" : "<") << endl;
}
ss << "Box 1: (" << x1 << "," << y1 << ")" << endl;
ss << "Box 2: (" << x2 << "," << y2 << ")" << endl;
return ss.str();
}
float Rule::xpos() const {
return ((x1 + x2) / 2.0);
}
float Rule::ypos() const {
return ((y1 + y2) / 2.0);
}
string Rule::rule() const {
if (num) {
return std::to_string(diff);
} else {
return (greater ? ">" : "<");
}
}
| 18.126582 | 62 | 0.513268 | [
"vector"
] |
a450af35643ebed17abcd76ec1837607d75e1d67 | 17,938 | cpp | C++ | LeanRays.cpp | mld2443/LeanCppRays | 0672c3e0bdbec720b10f766148cd2eb17e20968b | [
"MIT"
] | null | null | null | LeanRays.cpp | mld2443/LeanCppRays | 0672c3e0bdbec720b10f766148cd2eb17e20968b | [
"MIT"
] | null | null | null | LeanRays.cpp | mld2443/LeanCppRays | 0672c3e0bdbec720b10f766148cd2eb17e20968b | [
"MIT"
] | null | null | null | ///////////////
// RayTracer //
///////////////
#include <iostream>
#include <math.h>
#include <list>
#include <optional>
#include <random>
#include <png.h>
#define DTOR(x) x * 3.1415926535897932/180.0
using decimal = double;
//////////////////////
// Global Variables //
//////////////////////
std::random_device device;
std::mt19937 gen(device());
std::normal_distribution<decimal> nDist(0.0, 1.0);
std::uniform_real_distribution<decimal> uDist(0.0, 1.0);
//////////////////////////
// Forward Declarations //
//////////////////////////
class Material;
class Lambertian;
class Metallic;
class Dielectric;
class Shape;
class Plane;
class Sphere;
class Scene;
class Camera;
///////////////////
// MARK: Structs //
///////////////////
struct Range {
decimal lower, upper;
bool contains(const decimal& value) const { return lower <= value && value < upper; }
};
struct Vec3 {
decimal x, y, z;
decimal length() const;
Vec3 normalize() const;
bool isZero() const { return x == 0.0 && y == 0.0 && z == 0.0; }
};
Vec3 randomVector() { return Vec3{nDist(gen), nDist(gen), nDist(gen)}; }
Vec3 randomUnitVector() { return randomVector().normalize(); }
Vec3 operator+(const Vec3& lhs, const Vec3& rhs) { return Vec3{lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z}; }
Vec3 operator-(const Vec3& lhs, const Vec3& rhs) { return Vec3{lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z}; }
Vec3 operator-(const Vec3& v) { return Vec3{-v.x, -v.y, -v.z}; }
Vec3 operator*(const Vec3& lhs, const decimal rhs) { return Vec3{lhs.x * rhs, lhs.y * rhs, lhs.z * rhs}; }
Vec3 operator*(const decimal lhs, const Vec3& rhs) { return Vec3{lhs * rhs.x, lhs * rhs.y, lhs * rhs.z}; }
std::ostream& operator<<(std::ostream& str, const Vec3& v) { return str << "<" << v.x << ", " << v.y << ", " << v.z << ">"; }
Vec3 operator*(const Vec3& lhs, const Vec3& rhs) { return Vec3{lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z}; }
decimal dot(const Vec3& lhs, const Vec3& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; }
Vec3 cross(const Vec3& lhs, const Vec3& rhs) { return Vec3{lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x}; }
Vec3 reflect(const Vec3& incoming, const Vec3& normal) { return incoming - (normal * (2.0 * dot(incoming, normal))); }
Vec3 refract(const Vec3& incoming, const Vec3& normal, const decimal eta) {
const decimal cosI = -dot(incoming, normal), sinT2 = eta * eta * (1.0 - cosI * cosI);
if (sinT2 > 1.0)
return Vec3{};
const decimal cosT = sqrt(1.0 - sinT2);
return (incoming * eta) + (normal * (eta * cosI - cosT));
}
decimal Vec3::length() const { return sqrt(dot(*this, *this)); }
Vec3 Vec3::normalize() const { return *this * (1.0/length()); }
struct Ray {
Vec3 origin, direction;
Ray(const Vec3& o, const Vec3& d): origin(o), direction(d.normalize()) {}
Vec3 project(const decimal dist) const { return origin + (direction * dist); }
};
struct Color {
decimal r, g, b;
Color(const decimal r = 0.0, const decimal g = 0.0, const decimal b = 0.0): r(r), g(g), b(b) {}
Color(const char* desc) {
unsigned int rr = 0, gg = 0, bb = 0;
sscanf(desc, "#%2x%2x%2x", &rr, &gg, &bb);
r = ((decimal)rr) / 255.0, g = ((decimal)gg) / 255.0, b = ((decimal)bb) / 255.0;
}
Color transform(const std::function<decimal(decimal)>& t) const { return Color{t(r), t(g), t(b)}; }
};
Color operator+(const Color& lhs, const Color& rhs) { return Color{lhs.r + rhs.r, lhs.g + rhs.g, lhs.b + rhs.b}; }
Color operator-(const Color& lhs, const Color& rhs) { return Color{lhs.r - rhs.r, lhs.g - rhs.g, lhs.b - rhs.b}; }
Color operator*(const Color& lhs, const Color& rhs) { return Color{lhs.r * rhs.r, lhs.g * rhs.g, lhs.b * rhs.b}; }
Color operator/(const Color& lhs, const decimal rhs) { return Color{lhs.r / rhs, lhs.g / rhs, lhs.b / rhs}; }
Color operator*(const Color& lhs, const decimal rhs) { return Color{lhs.r * rhs, lhs.g * rhs, lhs.b * rhs}; }
Color operator*(const decimal lhs, const Color& rhs) { return Color{lhs * rhs.r, lhs * rhs.g, lhs * rhs.b}; }
struct Pixel {
png_byte r, g, b;
Pixel(const png_byte r = 0, const png_byte g = 0, const png_byte b = 0): r(r), g(g), b(b) {}
Pixel(const Color& c): r(clamp(c.r)), g(clamp(c.g)), b(clamp(c.b)) {}
private:
static png_byte clamp(const decimal f) { return (png_byte) std::min(std::max((int) (f * 255.0), 0), 255); }
};
struct Intersection {
decimal distance;
Vec3 point;
Vec3 normal;
Material *material;
};
void abort_(const char * s, ...) {
va_list args;
va_start(args, s);
vfprintf(stderr, s, args);
fprintf(stderr, "\n");
va_end(args);
abort();
}
/////////////////////
// MARK: Materials //
/////////////////////
class Material {
public:
Material(Color c): m_color(c) {}
virtual Ray interact(const Ray&, const Vec3&, const Vec3&, const decimal) const=0;
const Color m_color;
};
class Lambertian : public Material {
public:
Lambertian(Color c): Material(c) {}
Ray interact(const Ray& incoming, const Vec3& collision, const Vec3& normal, const decimal) const override {
Vec3 target = collision + normal + randomUnitVector() * 0.999;
return Ray{collision, target - collision};
}
};
class Metallic : public Material {
public:
Metallic(const Color c, const decimal f): Material(c), m_fuzz(f) {}
Ray interact(const Ray& incoming, const Vec3& collision, const Vec3& normal, const decimal) const override {
Vec3 reflected = reflect(incoming.direction, normal);
if (m_fuzz > 0.0) {
Vec3 fuzziness = randomUnitVector() * m_fuzz;
decimal product = dot(fuzziness, normal);
if (product < 0.0)
fuzziness = fuzziness - (2.0 * product * normal);
reflected = reflected + fuzziness;
}
return Ray{collision, reflected};
}
private:
decimal m_fuzz;
};
class Dielectric : public Material {
public:
Dielectric(const Color c, const decimal i): Material(c.transform(sqrtl)), m_refractionIndex(i) {}
Ray interact(const Ray& incoming, const Vec3& collision, const Vec3& normal, const decimal sceneIndex) const override {
const decimal entering = dot(incoming.direction, normal);
Vec3 refracted;
if (entering > 0.0)
refracted = refract(incoming.direction, -normal, m_refractionIndex / sceneIndex);
else
refracted = refract(incoming.direction, normal, sceneIndex / m_refractionIndex);
if (refracted.isZero() || uDist(gen) < schlickApproximation(abs(entering), sceneIndex))
return Ray{collision, reflect(incoming.direction, normal)};
return Ray{collision, refracted};
}
private:
decimal m_refractionIndex;
decimal schlickApproximation(const decimal cosX, const decimal sceneIndex) const {
decimal r0 = (sceneIndex - m_refractionIndex) / (sceneIndex + m_refractionIndex);
r0 *= r0;
const decimal x = 1.0 - cosX;
return r0 + (1.0 - r0) * x * x * x * x * x;
}
};
//////////////////
// MARK: Shapes //
//////////////////
class Shape {
public:
Shape(Material* m, const Vec3& p): m_position(p), m_material(m) {}
std::optional<Intersection> intersectRay(const Ray& ray, const Range& window) {
std::optional<decimal> distance = computeNearestIntersection(ray, window);
if (!distance)
return std::nullopt;
Vec3 point = ray.project(*distance), normal = computeNormalAt(point);
if (dot(ray.direction, normal) >= 0.0)
return std::nullopt;
return Intersection{*distance, point, normal, m_material};
}
protected:
virtual std::optional<decimal> computeNearestIntersection(const Ray&, const Range&) const=0;
virtual Vec3 computeNormalAt(const Vec3&) const=0;
const Vec3 m_position;
Material *m_material;
};
class Plane : public Shape {
public:
Plane(Material* m, const Vec3& p, const Vec3& n): Shape(m, p), m_normal(n.normalize()), m_normDotPos(dot(m_normal, p)) {}
protected:
std::optional<decimal> computeNearestIntersection(const Ray& ray, const Range& window) const override {
const decimal denominator = dot(m_normal, ray.direction);
if (denominator == 0.0)
return std::nullopt;
const decimal distance = (m_normDotPos - dot(m_normal, ray.origin)) / denominator;
if (window.contains(distance))
return distance;
return std::nullopt;
}
Vec3 computeNormalAt(const Vec3&) const override {
return m_normal;
}
private:
const Vec3 m_normal;
const decimal m_normDotPos;
};
class Sphere : public Shape {
public:
Sphere(Material* m, const Vec3& p, const decimal r): Shape(m, p), m_radius(r * r) {}
protected:
std::optional<decimal> computeNearestIntersection(const Ray& ray, const Range& window) const override {
const Vec3 rCam = ray.origin - m_position;
const Vec3 rRay = ray.direction;
const decimal A = dot(rRay, rRay);
const decimal B = dot(rCam, rRay);
const decimal C = dot(rCam, rCam) - m_radius;
const decimal square = B * B - A * C;
if (square < 0.0)
return std::nullopt;
const decimal root = sqrt(square);
const decimal D1 = (-B - root) / A;
const decimal D2 = (-B + root) / A;
if (window.contains(D1))
return D1;
if (window.contains(D2))
return D2;
return std::nullopt;
}
Vec3 computeNormalAt(const Vec3& point) const override {
return (point - m_position).normalize();
}
private:
const decimal m_radius;
};
/////////////////
// MARK: Scene //
/////////////////
class Scene {
public:
Scene(const Color h = "#4C7FFF",
const Color s = "#FFFFFF",
const decimal r = 1.0):
m_horizon(h),
m_sky(s),
m_refractionIndex(r) {}
~Scene() {
for (Shape* s : m_things) {
if (s) {
free(s);
}
}
}
void addShape(Shape* s) {
m_things.push_back(s);
}
Color castRay(const Ray& start, const Range& frustum, const unsigned int depth) const {
Ray ray = start;
Range window = frustum;
std::list<Color> colors{};
while (true) {
if (colors.size() >= depth)
return Color{};
std::optional<Intersection> nearest = findNearest(ray, window);
if (!nearest)
break;
colors.push_back(nearest->material->m_color);
ray = nearest->material->interact(ray, nearest->point, nearest->normal, m_refractionIndex);
window = {window.lower, window.upper - nearest->distance};
}
Color result = skyBox(ray.direction);
for (Color c : colors)
result = result * c;
return result;
}
private:
const Color m_horizon;
const Color m_sky;
const decimal m_refractionIndex;
std::list<Shape*> m_things;
std::optional<Intersection> findNearest(const Ray& ray, const Range& window) const {
std::optional<Intersection> nearest = std::nullopt;
Range currentWindow = window;
for (Shape* s : m_things) {
if (nearest)
currentWindow = {window.lower, nearest->distance};
std::optional<Intersection> candidate = s->intersectRay(ray, currentWindow);
if (candidate) {
nearest = candidate;
}
}
return nearest;
}
Color skyBox(const Vec3& direction) const {
const decimal interpolate = (0.5 * (direction.z + 1.0));
return (m_horizon * (1.0 - interpolate)) + (m_sky * interpolate);
}
};
//////////////////
// MARK: Camera //
//////////////////
class Camera {
public:
Camera(const Vec3& position,
const unsigned int width, const unsigned int height,
const unsigned int sampling, const unsigned int depth,
const Vec3& direction,
const decimal FOV,
const Vec3& up = Vec3{0.0, 0.0, 1.0}):
m_position(position),
m_width(width), m_height(height),
m_sampling(sampling), m_depth(depth),
m_frustum(Range{0.1, 1000.0}) {
const Vec3 unitDirection = direction.normalize();
const decimal screenWidth = tan(DTOR(FOV / 2.0));
const decimal screenHeight = (((decimal) height) / ((decimal) width)) * screenWidth;
const Vec3 iStar = cross(up, unitDirection).normalize();
const Vec3 jStar = cross(iStar, unitDirection).normalize();
m_iHat = iStar * (2.0 * screenWidth / (decimal) width);
m_jHat = jStar * (2.0 * screenHeight / (decimal) height);
m_origin = unitDirection + (iStar * -screenWidth) + (jStar * -screenHeight);
m_film = new Pixel*[height];
for (unsigned int y = 0u; y < height; ++y)
m_film[y] = new Pixel[width];
}
~Camera() {
for (unsigned int y = 0u; y < m_height; ++y)
free(m_film[y]);
free(m_film);
}
void captureScene(const Scene& scene) {
for (unsigned int y = 0u; y < m_height; y++) {
for (unsigned int x = 0u; x < m_width; x++)
this->m_film[y][x] = this->getPixel(scene, x, y);
std::cout << ".";
}
std::cout << std::endl;
}
void developFilm(FILE* file) const {
if (!file)
abort_("[write_png_file] File could not be opened for writing");
png_byte** image = (png_byte**) m_film;
png_struct* negative = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!negative)
abort_("[write_png_file] png_create_write_struct failed");
png_info* info = png_create_info_struct(negative);
if (!info)
abort_("[write_png_file] png_create_info_struct failed");
if (setjmp(png_jmpbuf(negative)))
abort_("[write_png_file] Error during init_io");
png_init_io(negative, file);
if (setjmp(png_jmpbuf(negative)))
abort_("[write_png_file] Error during writing header");
png_set_IHDR(negative, info, m_width, m_height, 8, 2, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(negative, info);
if (setjmp(png_jmpbuf(negative)))
abort_("[write_png_file] Error during writing bytes");
png_write_image(negative, image);
if (setjmp(png_jmpbuf(negative)))
abort_("[write_png_file] Error during end of write");
png_write_end(negative, NULL);
}
private:
const Vec3 m_position;
const unsigned int m_width, m_height, m_sampling, m_depth;
const Range m_frustum;
Vec3 m_iHat, m_jHat, m_origin;
Pixel** m_film;
Pixel getPixel(const Scene& scene, const unsigned int x, const unsigned int y) const {
Color sample{};
for (unsigned int s = 0u; s < m_sampling; ++s) {
const decimal xCoord = x + uDist(gen);
const decimal yCoord = y + uDist(gen);
const Vec3 screenSpacePosition = m_origin + (m_iHat * xCoord) + (m_jHat * yCoord);
const Ray cast{m_position, screenSpacePosition};
sample = sample + scene.castRay(cast, m_frustum, m_depth);
}
sample = sample / m_sampling;
// Post-processing, makes the result brighter
//sample = sample.transform(sqrt);
return Pixel(sample);
}
};
/////////////////////////
// MARK: Program Entry //
/////////////////////////
int main(int argc, const char * argv[]) {
// Lights
Scene s{}; // Daytime lighting
//Scene s{"#AA00AA", "#100460"}; // Nighttime lighting
// Make-up
Material* white = new Lambertian{"#FFFFFF"};
Material* glass = new Dielectric{"#F0FFF0", 1.37};
Material* matteCyan = new Lambertian{"#00FFFF"};
Material* shinyYellow = new Metallic{"#FFFF00", 0.0};
Material* gunmetal = new Metallic{"#808080", 0.1};
Material* matteMagenta = new Lambertian{"#FF00FF"};
// Actors
s.addShape(new Plane{white, Vec3{}, Vec3{0.0,0.0,1.0}});
s.addShape(new Sphere{glass, Vec3{9.0,0.0,6.0}, 6.0});
s.addShape(new Sphere{matteCyan, Vec3{19.0,-5.0,3.0}, 3.0});
s.addShape(new Sphere{shinyYellow, Vec3{20.0,5.0,4.0}, 4.0});
s.addShape(new Sphere{gunmetal, Vec3{30.0,-16.0,16.0}, 16.0});
s.addShape(new Sphere{matteMagenta, Vec3{100.0,170.0,30.0}, 30.0});
// Camera
//const unsigned int width = 320, height = 180, sampling = 100, depth = 10;
const unsigned int width = 1920, height = 1080, sampling = 5000, depth = 10;
Camera c = Camera(Vec3{0.0,0.0,7.0}, width, height, sampling, depth, Vec3{18.0,0.0,-1.0}, 100.0);
// Action
clock_t cycles = clock(); {
c.captureScene(s);
} cycles = clock() - cycles;
std::cout << "Capture took " << cycles << " clocks, " << ((decimal)cycles)/CLOCKS_PER_SEC << " seconds." << std::endl;
// Cut!
FILE *file = fopen("Output.png", "wb");
c.developFilm(file);
fclose(file);
// That's a wrap
free(white);
free(glass);
free(matteCyan);
free(shinyYellow);
free(gunmetal);
free(matteMagenta);
return 0;
}
| 31.918149 | 154 | 0.57604 | [
"shape",
"transform"
] |
a45fccdb80798ba338f8a2fb10815cba2b1875ba | 42,246 | cxx | C++ | HLT/MUON/OfflineInterface/AliHLTMUONDigitPublisherComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | HLT/MUON/OfflineInterface/AliHLTMUONDigitPublisherComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | HLT/MUON/OfflineInterface/AliHLTMUONDigitPublisherComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: *
* Artur Szostak <artursz@iafrica.com> *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id: AliHLTMUONDigitPublisherComponent.cxx 26179 2008-05-29 22:27:27Z aszostak $
///
/// @file AliHLTMUONDigitPublisherComponent.cxx
/// @author Artur Szostak <artursz@iafrica.com>
/// @date 29 May 2008
/// @brief Implementation of the dHLT digit publisher component.
///
/// This component is used to publish simulated or reconstructed digits from
/// the digits trees as DDL raw data. The data is converted into DDL format
/// on the fly.
///
#include "AliHLTMUONDigitPublisherComponent.h"
#include "AliHLTMUONConstants.h"
#include "AliHLTMUONUtils.h"
#include "AliHLTLogging.h"
#include "AliHLTSystem.h"
#include "AliHLTDefinitions.h"
#include "AliRawDataHeaderV3.h"
#include "AliMUONTrackerDDLDecoderEventHandler.h"
#include "AliMUONConstants.h"
#include "AliMUONMCDataInterface.h"
#include "AliMUONDataInterface.h"
#include "AliMUONVDigitStore.h"
#include "AliMUONVTriggerStore.h"
#include "AliMpExMap.h"
#include "AliMpCDB.h"
#include "AliMpDDL.h"
#include "AliMpDDLStore.h"
#include "AliMpDEManager.h"
#include "AliMpTriggerCrate.h"
#include "AliMpConstants.h"
#include "AliBitPacking.h"
#include "AliMUONBlockHeader.h"
#include "AliMUONBusStruct.h"
#include "AliMUONConstants.h"
#include "AliMUONDarcHeader.h"
#include "AliMUONVDigit.h"
#include "AliMUONDspHeader.h"
#include "AliMUONGlobalTrigger.h"
#include "AliMUONLocalStruct.h"
#include "AliMUONLocalTrigger.h"
#include "AliMUONLocalTriggerBoard.h"
#include "AliMUONRegionalTrigger.h"
#include "AliMUONRegHeader.h"
#include "AliRunLoader.h"
#include "AliCentralTrigger.h"
#include "AliLog.h"
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cerrno>
#include <cassert>
ClassImp(AliHLTMUONDigitPublisherComponent)
AliHLTMUONDigitPublisherComponent::AliHLTMUONDigitPublisherComponent() :
AliHLTOfflineDataSource(),
fDDL(-1),
fCurrentEventIndex(0),
fMakeScalars(false),
fMCDataInterface(NULL),
fDataInterface(NULL),
fChamberExclusionList(0),
fDetElemExclusionList(0)
{
/// Default constructor.
}
AliHLTMUONDigitPublisherComponent::~AliHLTMUONDigitPublisherComponent()
{
/// Default destructor.
if (fMCDataInterface != NULL) delete fMCDataInterface;
if (fDataInterface != NULL) delete fDataInterface;
}
const char* AliHLTMUONDigitPublisherComponent::GetComponentID()
{
/// Inherited from AliHLTComponent. Returns the component ID.
return AliHLTMUONConstants::DigitPublisherId();
}
AliHLTComponentDataType AliHLTMUONDigitPublisherComponent::GetOutputDataType()
{
/// Inherited from AliHLTComponent. Returns the raw DDL data type.
return AliHLTMUONConstants::DDLRawDataType();
}
void AliHLTMUONDigitPublisherComponent::GetOutputDataSize(
unsigned long& constBase, double& inputMultiplier
)
{
/// Inherited from AliHLTComponent.
/// Returns an estimate of the expected output data size.
// estimated as max number of channels * raw data word size + max headers size.
constBase = sizeof(AliRawDataHeaderV3) + 65536*sizeof(UInt_t)
+ sizeof(AliMUONBlockHeaderStruct)*2 + sizeof(AliMUONDSPHeaderStruct)*10
+ sizeof(AliMUONBusPatchHeaderStruct) * 50;
inputMultiplier = 0;
}
AliHLTComponent* AliHLTMUONDigitPublisherComponent::Spawn()
{
/// Inherited from AliHLTComponent. Creates a new object instance.
return new AliHLTMUONDigitPublisherComponent;
}
int AliHLTMUONDigitPublisherComponent::ParseChamberString(const char* str)
{
/// Parses a string with the following format:
/// <number>|<number>-<number>[,<number>|<number>-<number>,...]
/// For example: 1 1,2,3 1-2 1,2-4,5 etc...
/// Chamber numbers must be in the range [1..10] for tracking chambers.
/// All valid tracking chamber numbers will added to fChamberExclusionList.
/// @param str The string to parse.
/// @return Zero on success and EINVAL if there is a parse error.
char* end = const_cast<char*>(str);
long lastChamber = -1;
do
{
// Parse the next number.
char* current = end;
long chamber = strtol(current, &end, 0);
// Check for parse errors of the number.
if (current == end)
{
HLTError("Expected a number in the range [1..%d] but got '%s'.",
AliMUONConstants::NTrackingCh(), current
);
return -EINVAL;
}
if (chamber < 1 or AliMUONConstants::NTrackingCh() < chamber)
{
HLTError("Received the chamber number %d, which is outside the valid range of [1..%d].",
chamber, AliMUONConstants::NTrackingCh()
);
return -EINVAL;
}
// Skip any whitespace after the number
while (*end != '\0' and (*end == ' ' or *end == '\t' or *end == '\r' or *end == '\n')) end++;
// Check if we are dealing with a list or range, or if we are at
// the end of the string.
if (*end == '-')
{
lastChamber = chamber;
end++;
continue;
}
else if (*end == ',')
{
assert( 1 <= chamber and chamber <= AliMUONConstants::NTrackingCh() );
Int_t size = fChamberExclusionList.GetSize();
fChamberExclusionList.Set(size+1);
fChamberExclusionList[size] = chamber-1;
end++;
}
else if (*end == '\0')
{
assert( 1 <= chamber and chamber <= AliMUONConstants::NTrackingCh() );
Int_t size = fChamberExclusionList.GetSize();
fChamberExclusionList.Set(size+1);
fChamberExclusionList[size] = chamber-1;
}
else
{
HLTError("Could not understand parameter list '%s'. Expected '-', ','"
" or end of line, but received '%c' at character %d.",
str, *end, (int)(end - str) +1
);
return -EINVAL;
}
// Set the range of chambers to publish for.
if (lastChamber > 0)
{
Int_t min, max;
if (lastChamber < chamber)
{
min = lastChamber;
max = chamber;
}
else
{
min = chamber;
max = lastChamber;
}
assert( min >= 1 );
assert( max <= AliMUONConstants::NTrackingCh() );
for (Int_t i = min; i <= max; i++)
{
Int_t size = fChamberExclusionList.GetSize();
fChamberExclusionList.Set(size+1);
fChamberExclusionList[size] = i-1;
}
}
lastChamber = -1;
}
while (*end != '\0');
return 0;
}
int AliHLTMUONDigitPublisherComponent::ParseDetElemString(const char* str)
{
/// Parses a string with the following format:
/// <number>|<number>-<number>[,<number>|<number>-<number>,...]
/// For example: 100 100,201,208 100-104 105,202-204,503 etc...
/// Detector element numbers must be in the range [100..1099] for tracking stations.
/// All valid detector element numbers will added to fDetElemExclusionList.
/// @param str The string to parse.
/// @return Zero on success and EINVAL if there is a parse error.
char* end = const_cast<char*>(str);
long lastDetElem = -1;
do
{
// Parse the next number.
char* current = end;
long detElem = strtol(current, &end, 0);
// Check for parse errors of the number.
if (current == end)
{
HLTError("Expected a number in the range [100..1099] but got '%s'.",
current
);
return -EINVAL;
}
if (detElem < 100 or 1099 < detElem)
{
HLTError("Received the detector element ID number of %d,"
" which is outside the valid range of [100..1099].",
detElem
);
return -EINVAL;
}
// Skip any whitespace after the number
while (*end != '\0' and (*end == ' ' or *end == '\t' or *end == '\r' or *end == '\n')) end++;
// Check if we are dealing with a list or range, or if we are at
// the end of the string.
if (*end == '-')
{
lastDetElem = detElem;
end++;
continue;
}
else if (*end == ',')
{
assert( 100 <= detElem and detElem <= 1099 );
Int_t size = fDetElemExclusionList.GetSize();
fDetElemExclusionList.Set(size+1);
fDetElemExclusionList[size] = detElem-1;
end++;
}
else if (*end == '\0')
{
assert( 100 <= detElem and detElem <= 1099 );
Int_t size = fDetElemExclusionList.GetSize();
fDetElemExclusionList.Set(size+1);
fDetElemExclusionList[size] = detElem-1;
}
else
{
HLTError("Could not understand parameter list '%s'. Expected '-', ','"
" or end of line, but received '%c' at character %d.",
str, *end, (int)(end - str) +1
);
return -EINVAL;
}
// Set the range of detector elements to publish for.
if (lastDetElem > 0)
{
Int_t min, max;
if (lastDetElem < detElem)
{
min = lastDetElem;
max = detElem;
}
else
{
min = detElem;
max = lastDetElem;
}
assert( min >= 100 );
assert( max <= 1099 );
for (Int_t i = min; i <= max; i++)
{
Int_t size = fDetElemExclusionList.GetSize();
fDetElemExclusionList.Set(size+1);
fDetElemExclusionList[size] = i-1;
}
}
lastDetElem = -1;
}
while (*end != '\0');
return 0;
}
int AliHLTMUONDigitPublisherComponent::DoInit(int argc, const char** argv)
{
/// Inherited from AliHLTComponent.
/// Parses the command line parameters and initialises the component.
HLTInfo("Initialising dHLT digit publisher component.");
if (fMCDataInterface != NULL)
{
delete fMCDataInterface;
fMCDataInterface = NULL;
}
if (fDataInterface != NULL)
{
delete fDataInterface;
fDataInterface = NULL;
}
// Initialise with default values.
fDDL = -1;
fCurrentEventIndex = 0;
fMakeScalars = false;
fChamberExclusionList.Set(0);
fDetElemExclusionList.Set(0);
bool simdata = false;
bool recdata = false;
bool firstEventSet = false;
bool eventNumLitSet = false;
for (int i = 0; i < argc; i++)
{
if (strcmp(argv[i], "-makescalars") == 0)
{
fMakeScalars = true;
continue;
}
if (strcmp(argv[i], "-simdata") == 0)
{
simdata = true;
continue;
}
if (strcmp(argv[i], "-recdata") == 0)
{
recdata = true;
continue;
}
if (strcmp(argv[i], "-ddl") == 0)
{
if (argc <= i+1)
{
HLTError("DDL number not specified. It must be in the range [1..22]" );
return -EINVAL;
}
char* cpErr = NULL;
unsigned long num = strtoul(argv[i+1], &cpErr, 0);
if (cpErr == NULL or *cpErr != '\0')
{
HLTError("Cannot convert '%s' to a DDL number.", argv[i+1]);
return -EINVAL;
}
if (num < 1 or 22 < num)
{
HLTError("The DDL number must be in the range [1..22].");
return -EINVAL;
}
fDDL = num - 1; // Convert to DDL number in the range 0..21
i++;
continue;
}
if (strcmp(argv[i], "-ddlid") == 0)
{
if (argc <= i+1)
{
HLTError("DDL equipment ID number not specified."
" It must be in the range [2560..2579] or [2816..2817]."
);
return -EINVAL;
}
char* cpErr = NULL;
unsigned long num = strtoul(argv[i+1], &cpErr, 0);
if (cpErr == NULL or *cpErr != '\0')
{
HLTError("Cannot convert '%s' to a DDL equipment ID number.", argv[i+1]);
return -EINVAL;
}
fDDL = AliHLTMUONUtils::EquipIdToDDLNumber(num); // Convert to DDL number in the range 0..21
if (fDDL < 0 or 21 < fDDL)
{
HLTError("The DDL equipment ID number must be in the range"
" [2560..2579] or [2816..2817]."
);
return -EINVAL;
}
i++;
continue;
}
if (strcmp(argv[i], "-firstevent") == 0)
{
if (eventNumLitSet)
{
HLTWarning("The -firstevent flag is overridden by a"
" previous use of -event_number_literal."
);
}
if (++i >= argc)
{
HLTError("Expected a positive number after -firstevent.");
return -EINVAL;
}
char* end = NULL;
long num = strtol(argv[i], &end, 0);
if ((end != NULL and *end != '\0') or num < 0) // Check if the conversion is OK.
{
HLTError("Expected a positive number after -firstevent"
" but got: %s", argv[i]
);
return -EINVAL;
}
fCurrentEventIndex = Int_t(num);
firstEventSet = true;
continue;
}
if (strcmp(argv[i], "-event_number_literal") == 0)
{
if (firstEventSet)
{
HLTWarning("The -event_number_literal option will"
" override -firstevent."
);
}
fCurrentEventIndex = -1;
eventNumLitSet = true;
continue;
}
if (strcmp(argv[i], "-exclude_chamber") == 0)
{
if (argc <= i+1)
{
HLTError("Expected a chamber number, a range eg. '1-10', or a list eg."
" '1,2,3' after '-exclude_chamber'."
);
return -EINVAL;
}
int result = ParseChamberString(argv[i+1]);
if (result != 0) return result;
i++;
continue;
}
if (strcmp(argv[i], "-exclude_detelem") == 0)
{
if (argc <= i+1)
{
HLTError("Expected a detector element ID number, a range eg. '100-108',"
" or a list eg. '100,102,301' after '-exclude_detelem'."
);
return -EINVAL;
}
int result = ParseDetElemString(argv[i+1]);
if (result != 0) return result;
i++;
continue;
}
HLTError("Unknown option '%s'.", argv[i]);
return -EINVAL;
}
if (fDDL == -1)
{
HLTError("DDL number must be set with the -ddl option, but it was not.");
return -EINVAL;
}
// Must load the mapping data if it is not already loaded.
if (AliMpDDLStore::Instance(false) == NULL)
{
AliMpCDB::LoadDDLStore();
if (AliMpDDLStore::Instance(false) == NULL)
{
HLTError("Could not load the DDL mapping store from CDB.");
return -EFAULT;
}
}
// Now we can initialise the data interface objects and loaders.
if (simdata)
{
HLTDebug("Loading simulated digits with AliMUONMCDataInterface.");
try
{
fMCDataInterface = new AliMUONMCDataInterface("galice.root");
}
catch (const std::bad_alloc&)
{
HLTError("Not enough memory to allocate AliMUONMCDataInterface.");
return -ENOMEM;
}
}
else if (recdata)
{
HLTDebug("Loading reconstructed digits with AliMUONDataInterface.");
try
{
fDataInterface = new AliMUONDataInterface("galice.root");
}
catch (const std::bad_alloc&)
{
HLTError("Not enough memory to allocate AliMUONDataInterface.");
return -ENOMEM;
}
}
// Check that the fCurrentEventIndex number falls within the correct range.
UInt_t maxevent = 0;
if (fMCDataInterface != NULL)
maxevent = UInt_t(fMCDataInterface->NumberOfEvents());
else if (fDataInterface != NULL)
maxevent = UInt_t(fDataInterface->NumberOfEvents());
if (fCurrentEventIndex != -1 and UInt_t(fCurrentEventIndex) >= maxevent and maxevent != 0)
{
fCurrentEventIndex = 0;
HLTWarning("The selected first event number (%d) was larger than"
" the available number of events (%d). Resetting the event"
" counter to zero.", fCurrentEventIndex, maxevent
);
}
return 0;
}
int AliHLTMUONDigitPublisherComponent::DoDeinit()
{
/// Inherited from AliHLTComponent. Performs a cleanup of the component.
HLTInfo("Deinitialising dHLT digit publisher component.");
if (fMCDataInterface != NULL)
{
delete fMCDataInterface;
fMCDataInterface = NULL;
}
if (fDataInterface != NULL)
{
delete fDataInterface;
fDataInterface = NULL;
}
return 0;
}
int AliHLTMUONDigitPublisherComponent::GetEvent(
const AliHLTComponentEventData& evtData,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
AliHLTComponentBlockDataList& outputBlocks
)
{
/// Inherited from AliHLTOfflineDataSource.
assert( fMCDataInterface != NULL or fDataInterface != NULL );
if (not IsDataEvent()) return 0; // ignore non data events.
// Check the size of the event descriptor structure.
if (evtData.fStructSize < sizeof(AliHLTComponentEventData))
{
HLTError(kHLTLogError,
"The event descriptor (AliHLTComponentEventData) size is"
" smaller than expected. It claims to be %d bytes, but"
" we expect it to be %d bytes.",
evtData.fStructSize,
sizeof(AliHLTComponentEventData)
);
size = 0; // Important to tell framework that nothing was generated.
return -EINVAL;
}
// Use the fEventID as the event number to load if fCurrentEventIndex == -1,
// check it and load that event with the runloader.
// If fCurrentEventIndex is a positive number then use it instead and
// increment it.
UInt_t eventnumber = UInt_t(evtData.fEventID);
UInt_t maxevent = 0;
if (fMCDataInterface != NULL)
maxevent = UInt_t(fMCDataInterface->NumberOfEvents());
else if (fDataInterface != NULL)
maxevent = UInt_t(fDataInterface->NumberOfEvents());
if (fCurrentEventIndex != -1)
{
eventnumber = UInt_t(fCurrentEventIndex);
fCurrentEventIndex++;
if (UInt_t(fCurrentEventIndex) >= maxevent)
fCurrentEventIndex = 0;
}
if ( eventnumber >= maxevent )
{
HLTError("The event number (%d) is larger than the available number"
" of events on file (%d).",
eventnumber, maxevent
);
size = 0; // Important to tell framework that nothing was generated.
return -EINVAL;
}
const AliMUONVDigitStore* digitStore = NULL;
const AliMUONVTriggerStore* triggerStore = NULL;
if (fMCDataInterface != NULL)
{
HLTDebug("Filling data block with simulated digits for event %d.", eventnumber);
if (fDDL < 20)
{
digitStore = fMCDataInterface->DigitStore(eventnumber);
}
else
{
triggerStore = fMCDataInterface->TriggerStore(eventnumber);
}
}
else if (fDataInterface != NULL)
{
HLTDebug("Filling data block with reconstructed digits for event %d.", eventnumber);
if (fDDL < 20)
{
digitStore = fDataInterface->DigitStore(eventnumber);
}
else
{
triggerStore = fDataInterface->TriggerStore(eventnumber);
}
}
else
{
HLTError("Neither AliMUONDataInterface nor AliMUONMCDataInterface were created.");
size = 0; // Important to tell framework that nothing was generated.
return -EFAULT;
}
// Make sure we have the correct CTP trigger loaded.
AliRunLoader* runloader = AliRunLoader::Instance();
if (runloader != NULL)
{
if (runloader->GetTrigger() == NULL)
runloader->LoadTrigger();
runloader->GetEvent(eventnumber);
}
if (fDDL < 20 and digitStore != NULL)
{
int result = WriteTrackerDDL(digitStore, fDDL, outputPtr, size);
if (result != 0)
{
size = 0; // Important to tell framework that nothing was generated.
return result;
}
}
else if (triggerStore != NULL)
{
int result = WriteTriggerDDL(triggerStore, fDDL-20, outputPtr, size, fMakeScalars);
if (result != 0)
{
size = 0; // Important to tell framework that nothing was generated.
return result;
}
}
else
{
size = 0; // Important to tell framework that nothing was generated.
return 0;
}
AliHLTComponentBlockData bd;
FillBlockData(bd);
bd.fPtr = outputPtr;
bd.fOffset = 0;
bd.fSize = size;
bd.fDataType = AliHLTMUONConstants::DDLRawDataType();
bd.fSpecification = AliHLTMUONUtils::DDLNumberToSpec(fDDL);
outputBlocks.push_back(bd);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Methods copied from AliMUONRawWriter.
//TODO: This is not ideal. We should have AliMUONRawWriter re-factored so that
// we can have raw data generated into a memory resident buffer, rather than
// always written to a file on disk, as it is now. But this will take some time
// since people need to be convinced of this fact.
//____________________________________________________________________
void AliHLTMUONDigitPublisherComponent::LocalWordPacking(UInt_t& word, UInt_t locId, UInt_t locDec,
UInt_t trigY, UInt_t posY, UInt_t posX,
UInt_t sdevX, UInt_t devX)
{
/// pack local trigger word
AliBitPacking::PackWord(locId,word,19,22); //card id number in crate
AliBitPacking::PackWord(locDec,word,15,18);
AliBitPacking::PackWord(trigY,word,14,14);
AliBitPacking::PackWord(posY,word,10,13);
AliBitPacking::PackWord(sdevX,word,9,9);
AliBitPacking::PackWord(devX,word,5,8);
AliBitPacking::PackWord(posX,word,0,4);
}
//______________________________________________________________________________
void
AliHLTMUONDigitPublisherComponent::Digits2BusPatchMap(
const AliMUONVDigitStore& digitStore,
AliMpExMap& busPatchMap, Int_t iDDL
)
{
/// Create bus patch structures corresponding to digits in the store
AliMpDDLStore* ddlStore = AliMpDDLStore::Instance();
assert(ddlStore != NULL);
AliMpDDL* ddl = ddlStore->GetDDL(iDDL);
busPatchMap.SetSize(ddl->GetNofBusPatches());
if (ddl->GetNofDEs() <= 0) return;
Int_t minDetElem = ddl->GetDEId(0);
Int_t maxDetElem = ddl->GetDEId(0);
for (Int_t i = 1; i < ddl->GetNofDEs(); i++)
{
if (ddl->GetDEId(i) < minDetElem) minDetElem = ddl->GetDEId(i);
if (ddl->GetDEId(i) > maxDetElem) maxDetElem = ddl->GetDEId(i);
}
static const Int_t kMAXADC = (1<<12)-1; // We code the charge on a 12 bits ADC.
// DDL event one per half chamber
// raw data
Char_t parity = 0x4;
UShort_t manuId = 0;
UChar_t channelId = 0;
UShort_t charge = 0;
Int_t busPatchId = 0;
Int_t currentBusPatchId = -1;
UInt_t word;
AliMUONBusStruct* busStruct(0x0);
TIter next(digitStore.CreateIterator(minDetElem, maxDetElem));
AliMUONVDigit* digit;
while ( ( digit = static_cast<AliMUONVDigit*>(next()) ) )
{
// Check if we should exclude digits from a particular chamber or detector element.
bool excludeDigit = false;
for (Int_t i = 0; i < fDetElemExclusionList.GetSize(); i++)
{
if (digit->DetElemId() == fDetElemExclusionList[i])
{
excludeDigit = true;
break;
}
}
for (Int_t i = 0; i < fChamberExclusionList.GetSize(); i++)
{
if (AliMpDEManager::GetChamberId(digit->DetElemId()) == fChamberExclusionList[i])
{
excludeDigit = true;
break;
}
}
if (excludeDigit) continue;
charge = digit->ADC();
if ( charge > kMAXADC )
{
// This is most probably an error in the digitizer (which should insure
// the adc is below kMAXADC), so make it a (non-fatal) error indeed.
HLTError("ADC value %d above 0x%x for DE %d . Setting to 0x%x. Digit is:",
charge,kMAXADC,digit->DetElemId(),kMAXADC);
charge = kMAXADC;
}
// inverse mapping
busPatchId = ddlStore->GetBusPatchId(digit->DetElemId(), digit->ManuId());
if (busPatchId<0) continue;
if ( digit->ManuId() > 0x7FF ||
digit->ManuChannel() > 0x3F )
{
HLTFatal("<%s>: ID %12u DE %4d Cath %d (Ix,Iy)=(%3d,%3d) (Manu,Channel)=(%4d,%2d)"
", Charge=%7.2f\nManuId,ManuChannel are invalid for this digit.",
digit->ClassName(), digit->GetUniqueID(),
digit->DetElemId(), digit->Cathode(), digit->PadX(), digit->PadY(),
digit->ManuId(), digit->ManuChannel(), digit->Charge()
);
}
manuId = ( digit->ManuId() & 0x7FF ); // 11 bits
channelId = ( digit->ManuChannel() & 0x3F ); // 6 bits
//packing word
word = 0;
AliBitPacking::PackWord((UInt_t)manuId,word,18,28);
AliBitPacking::PackWord((UInt_t)channelId,word,12,17);
AliBitPacking::PackWord((UInt_t)charge,word,0,11);
// parity word
parity = word & 0x1;
for (Int_t i = 1; i <= 30; ++i)
{
parity ^= ((word >> i) & 0x1);
}
AliBitPacking::PackWord((UInt_t)parity,word,31,31);
if ( currentBusPatchId != busPatchId )
{
busStruct =
static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(busPatchId));
currentBusPatchId = busPatchId;
}
if (!busStruct)
{
busStruct = new AliMUONBusStruct;
busStruct->SetDataKey(busStruct->GetDefaultDataKey());
busStruct->SetBusPatchId(busPatchId);
busStruct->SetLength(0);
busPatchMap.Add(busPatchId,busStruct);
}
// set sub Event
busStruct->AddData(word);
}
}
//______________________________________________________________________________
int AliHLTMUONDigitPublisherComponent::WriteTrackerDDL(
const AliMUONVDigitStore* digitStore, Int_t iDDL,
AliHLTUInt8_t* outBuffer, AliHLTUInt32_t& outBufferSize
)
{
/// Write DDL file for one tracker DDL
assert(0 <= iDDL and iDDL <= 19);
AliMpDDLStore* ddlStore = AliMpDDLStore::Instance();
assert(ddlStore != NULL);
if (ddlStore->GetDDL(iDDL) == NULL)
{
HLTError("Could not find DDL mapping for DDL %d.", iDDL+1);
return -EFAULT;
}
AliMpExMap busPatchMap;
Digits2BusPatchMap(*digitStore,busPatchMap,iDDL);
AliMUONBlockHeader blockHeader;
AliMUONDspHeader dspHeader;
blockHeader.SetDataKey(blockHeader.GetDefaultDataKey());
dspHeader.SetDataKey(dspHeader.GetDefaultDataKey());
if (outBufferSize < sizeof(AliRawDataHeaderV3))
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize, sizeof(AliRawDataHeaderV3)
);
return -ENOBUFS;
}
AliRawDataHeaderV3* header = reinterpret_cast<AliRawDataHeaderV3*>(outBuffer);
// Fill header with default values.
*header = AliRawDataHeaderV3();
AliRunLoader* runloader = AliRunLoader::Instance();
if (runloader != NULL)
{
if (runloader->GetTrigger() != NULL)
{
AliCentralTrigger *aCTP = runloader->GetTrigger();
ULong64_t mask = aCTP->GetClassMask();
header->SetTriggerClass(mask);
mask = aCTP->GetClassMaskNext50();
header->SetTriggerClassNext50(mask);
}
}
Int_t* buffer = reinterpret_cast<Int_t*>(header+1);
Int_t endOfBuffer = (outBufferSize - sizeof(AliRawDataHeaderV3)) / sizeof(Int_t);
// buffer size (max'ed out)
// (((43 manus max per bus patch *64 channels + 4 bus patch words) * 5 bus patch
// + 10 dsp words)*5 dsps + 8 block words)*2 blocks
AliMpDDL* ddl = ddlStore->GetDDL(iDDL);
Int_t iDspMax = ddl->GetMaxDsp();
Int_t iBusPerDSP[5]; //number of bus patches per DSP
ddl->GetBusPerDsp(iBusPerDSP);
Int_t busIter = 0;
Int_t totalDDLLength = 0;
Int_t index = 0;
// two blocks A and B per DDL
for (Int_t iBlock = 0; iBlock < 2; ++iBlock)
{
Int_t length = blockHeader.GetHeaderLength();
if (index + length >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+length)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// block header
memcpy(&buffer[index],blockHeader.GetHeader(),length*4);
Int_t indexBlk = index;
index += length;
// 5 DSP's max per block
for (Int_t iDsp = 0; iDsp < iDspMax; ++iDsp)
{
Int_t dspHeaderLength = dspHeader.GetHeaderLength();
if (index + dspHeaderLength >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+dspHeaderLength)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// DSP header
memcpy(&buffer[index],dspHeader.GetHeader(),dspHeaderLength*4);
Int_t indexDsp = index;
index += dspHeaderLength;
// 5 buspatches max per DSP
for (Int_t i = 0; i < iBusPerDSP[iDsp]; ++i)
{
Int_t iBusPatch = ddl->GetBusPatchId(busIter++);
// iteration over bus patch in DDL
if (iBusPatch == -1)
{
AliWarning(Form("Error in bus itr in DDL %d\n", iDDL));
continue;
}
AliMUONBusStruct* busStructPtr = static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(iBusPatch));
Int_t busHeaderLength = busStructPtr->GetHeaderLength();
if (index + busHeaderLength >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+busHeaderLength)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// check if buspatchid has digit
if (busStructPtr)
{
// add bus patch structure header
memcpy(&buffer[index],busStructPtr->GetHeader(),busHeaderLength*4);
index += busHeaderLength;
Int_t busLength = busStructPtr->GetLength();
if (index + busLength >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+busLength)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// add bus patch data
memcpy(&buffer[index],busStructPtr->GetData(),busLength*4);
index += busLength;
}
else
{
// writting anyhow buspatch structure (empty ones)
buffer[index++] = busStructPtr->GetDefaultDataKey(); // fill it also for empty data size
buffer[index++] = busStructPtr->GetHeaderLength(); // header length
buffer[index++] = 0; // raw data length
buffer[index++] = iBusPatch; // bus patch
}
} // bus patch
if (index + 1 >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+1)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// check if totalLength even
// set padding word in case
// Add one word 0xBEEFFACE at the end of DSP structure
Int_t totalDspLength = index - indexDsp;
if ((totalDspLength % 2) == 1)
{
buffer[indexDsp + dspHeader.GetHeaderLength() - 2] = 1;
buffer[index++] = dspHeader.GetDefaultPaddingWord();
totalDspLength++;
}
Int_t dspLength = totalDspLength - dspHeader.GetHeaderLength();
buffer[indexDsp+1] = totalDspLength; // dsp total length
buffer[indexDsp+2] = dspLength; // data length
} // dsp
Int_t totalBlkLength = index - indexBlk;
Int_t blkLength = totalBlkLength - blockHeader.GetHeaderLength();
totalDDLLength += totalBlkLength;
buffer[indexBlk+1] = totalBlkLength; // total block length
buffer[indexBlk+2] = blkLength;
} // block
if (index + 2 >= endOfBuffer)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize,
sizeof(AliRawDataHeaderV3) + (index+2)*sizeof(UInt_t)
);
return -ENOBUFS;
}
// add twice the end of CRT structure data key
// hope it's good placed (ChF)
buffer[index++] = blockHeader.GetDdlDataKey();
buffer[index++] = blockHeader.GetDdlDataKey();
totalDDLLength += 2;
header->fSize = (totalDDLLength) * sizeof(Int_t) + sizeof(AliRawDataHeaderV3);
outBufferSize = header->fSize;
return 0;
}
//______________________________________________________________________________
int AliHLTMUONDigitPublisherComponent::WriteTriggerDDL(
const AliMUONVTriggerStore* triggerStore, Int_t iDDL,
AliHLTUInt8_t* outBuffer, AliHLTUInt32_t& outBufferSize,
bool scalarEvent
)
{
/// Write trigger DDL
assert(0 <= iDDL and iDDL <= 19);
AliMpDDLStore* ddlStore = AliMpDDLStore::Instance();
assert(ddlStore != NULL);
if (outBufferSize < sizeof(AliRawDataHeaderV3))
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize, sizeof(AliRawDataHeaderV3)
);
return -ENOBUFS;
}
AliRawDataHeaderV3* header = reinterpret_cast<AliRawDataHeaderV3*>(outBuffer);
// Fill header with default values.
*header = AliRawDataHeaderV3();
AliRunLoader* runloader = AliRunLoader::Instance();
if (runloader != NULL)
{
if (runloader->GetTrigger() != NULL)
{
AliCentralTrigger *aCTP = runloader->GetTrigger();
ULong64_t mask = aCTP->GetClassMask();
header->SetTriggerClass(mask);
}
}
// global trigger for trigger pattern
AliMUONGlobalTrigger* gloTrg = triggerStore->Global();
if (!gloTrg)
{
return 0;
}
Int_t gloTrigResp = gloTrg->GetGlobalResponse();
UInt_t word;
Int_t* buffer = reinterpret_cast<Int_t*>(header+1);
Int_t index;
//Int_t locCard;
UChar_t locDec, trigY, posY, posX, regOut;
UInt_t regInpLpt;
UInt_t regInpHpt;
UInt_t devX;
UChar_t sdevX;
UInt_t version = 1; // software version
UInt_t eventPhys = 1; // trigger type: 1 for physics, 0 for software
UInt_t serialNb = 0xF; // serial nb of card: all bits on for the moment
Int_t globalFlag = 0; // set to 1 if global info present in DDL else set to 0
AliMUONDarcHeader darcHeader;
AliMUONRegHeader regHeader;
AliMUONLocalStruct localStruct;
// size of headers
static const Int_t kDarcHeaderLength = darcHeader.GetDarcHeaderLength();
static const Int_t kGlobalHeaderLength = darcHeader.GetGlobalHeaderLength();
static const Int_t kDarcScalerLength = darcHeader.GetDarcScalerLength();
static const Int_t kGlobalScalerLength = darcHeader.GetGlobalScalerLength();
static const Int_t kRegHeaderLength = regHeader.GetHeaderLength();
static const Int_t kRegScalerLength = regHeader.GetScalerLength();
static const Int_t kLocHeaderLength = localStruct.GetLength();
static const Int_t kLocScalerLength = localStruct.GetScalerLength();
// [16(local)*6 words + 6 words]*8(reg) + 8 words = 824
static const Int_t kBufferSize = (16 * (kLocHeaderLength+1) + (kRegHeaderLength+1))* 8
+ kDarcHeaderLength + kGlobalHeaderLength + 2;
// [16(local)*51 words + 16 words]*8(reg) + 8 + 10 + 8 words scaler event 6682 words
static const Int_t kScalerBufferSize = (16 * (kLocHeaderLength + kLocScalerLength +1) +
(kRegHeaderLength + kRegScalerLength +1))* 8 +
(kDarcHeaderLength + kDarcScalerLength +
kGlobalHeaderLength + kGlobalScalerLength + 2);
if(scalarEvent) {
eventPhys = 0; //set to generate scaler events
header->fWord2 |= (0x1 << 14); // set L1SwC bit on
}
if(scalarEvent)
{
if (outBufferSize < sizeof(AliRawDataHeaderV3) + kScalerBufferSize)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize, sizeof(AliRawDataHeaderV3) + kScalerBufferSize
);
return -ENOBUFS;
}
}
else
{
if (outBufferSize < sizeof(AliRawDataHeaderV3) + kBufferSize)
{
HLTError("The output buffer size is too small to write output."
" It is only %d bytes, but we need at least %d bytes.",
outBufferSize, sizeof(AliRawDataHeaderV3) + kBufferSize
);
return -ENOBUFS;
}
}
index = 0;
if (iDDL == 0) // suppose global info in DDL one
globalFlag = 1;
else
globalFlag = 0;
word = 0;
// set darc status word
// see AliMUONDarcHeader.h for details
AliBitPacking::PackWord((UInt_t)eventPhys,word,30,30);
AliBitPacking::PackWord((UInt_t)serialNb,word,20,23);
AliBitPacking::PackWord((UInt_t)globalFlag,word,10,10);
AliBitPacking::PackWord((UInt_t)version,word,12,19);
darcHeader.SetWord(word);
memcpy(&buffer[index], darcHeader.GetHeader(), (kDarcHeaderLength)*4);
index += kDarcHeaderLength;
// no global input for the moment....
if (iDDL == 0)
darcHeader.SetGlobalOutput(gloTrigResp);
else
darcHeader.SetGlobalOutput(0);
if (scalarEvent) {
// 6 DARC scaler words
memcpy(&buffer[index], darcHeader.GetDarcScalers(),kDarcScalerLength*4);
index += kDarcScalerLength;
}
// end of darc word
buffer[index++] = darcHeader.GetEndOfDarc();
// 4 words of global board input + Global board output
memcpy(&buffer[index], darcHeader.GetGlobalInput(), (kGlobalHeaderLength)*4);
index += kGlobalHeaderLength;
if (scalarEvent) {
// 10 Global scaler words
memcpy(darcHeader.GetGlobalScalers(), &buffer[index], kGlobalScalerLength*4);
index += kGlobalScalerLength;
}
// end of global word
buffer[index++] = darcHeader.GetEndOfGlobal();
const AliMpRegionalTrigger* reg = ddlStore->GetRegionalTrigger();
Int_t nCrate = reg->GetNofTriggerCrates()/2;
// 8 regional cards per DDL
for (Int_t iReg = 0; iReg < nCrate; ++iReg) {
// crate info
AliMpTriggerCrate* crate = ddlStore->GetTriggerCrate(iDDL, iReg);
if (!crate)
{
AliWarning(Form("Missing crate number %d in DDL %d\n", iReg, iDDL));
continue;
}
// regional info tree, make sure that no reg card missing
AliMUONRegionalTrigger* regTrg = triggerStore->FindRegional(crate->GetId());
if (!regTrg)
{
AliError(Form("Missing regional board %d in trigger Store\n", crate->GetId()));
continue;
}
// Regional card header
word = 0;
// set darc status word
regHeader.SetDarcWord(word);
regOut = regTrg->GetOutput();
regInpHpt = regTrg->GetLocalOutput(0);
regInpLpt = regTrg->GetLocalOutput(1);
// fill darc word, not darc status for the moment (empty)
//see AliMUONRegHeader.h for details
AliBitPacking::PackWord((UInt_t)eventPhys,word,31,31);
AliBitPacking::PackWord((UInt_t)serialNb,word,20,25);
AliBitPacking::PackWord((UInt_t)version,word,8,15);
AliBitPacking::PackWord((UInt_t)crate->GetId(),word,16,19);
AliBitPacking::PackWord((UInt_t)regOut,word,0,7);
regHeader.SetWord(word);
// fill header later, need local response
Int_t indexReg = index;
index += kRegHeaderLength;
// 11 regional scaler word
if (scalarEvent) {
memcpy(&buffer[index], regHeader.GetScalers(), kRegScalerLength*4);
index += kRegScalerLength;
}
// end of regional word
buffer[index++] = regHeader.GetEndOfReg();
// 16 local card per regional board
// UShort_t localMask = 0x0;
Int_t nLocalBoard = AliMpConstants::LocalBoardNofChannels();
for (Int_t iLoc = 0; iLoc < nLocalBoard; iLoc++) {
// slot zero for Regional card
Int_t localBoardId = crate->GetLocalBoardId(iLoc);
if (localBoardId) { // if not empty slot
AliMpLocalBoard* localBoard = ddlStore->GetLocalBoard(localBoardId);
if (localBoard->IsNotified()) {// if notified board
AliMUONLocalTrigger* locTrg = triggerStore->FindLocal(localBoardId);
//locCard = locTrg->LoCircuit();
locDec = locTrg->GetLoDecision();
trigY = locTrg->LoTrigY();
posY = locTrg->LoStripY();
posX = locTrg->LoStripX();
devX = locTrg->LoDev();
sdevX = locTrg->LoSdev();
AliDebug(4,Form("loctrg %d, posX %d, posY %d, devX %d\n",
locTrg->LoCircuit(),locTrg->LoStripX(),locTrg->LoStripY(),locTrg->LoDev()));
//packing word
word = 0;
LocalWordPacking(word, (UInt_t)iLoc, (UInt_t)locDec, (UInt_t)trigY, (UInt_t)posY,
(UInt_t)posX, (UInt_t)sdevX, (UInt_t)devX);
buffer[index++] = (locTrg->GetX1Pattern() | (locTrg->GetX2Pattern() << 16));
buffer[index++] = (locTrg->GetX3Pattern() | (locTrg->GetX4Pattern() << 16));
buffer[index++] = (locTrg->GetY1Pattern() | (locTrg->GetY2Pattern() << 16));
buffer[index++] = (locTrg->GetY3Pattern() | (locTrg->GetY4Pattern() << 16));
buffer[index++] = (Int_t)word; // data word
}
// fill copy card X-Y inputs from the notified cards
if (localBoard->GetInputXfrom() && localBoard->GetInputYfrom())
{
// not triggered
locDec = 0; trigY = 1; posY = 15;
posX = 0; devX = 0; sdevX = 1;
LocalWordPacking(word, (UInt_t)iLoc, (UInt_t)locDec, (UInt_t)trigY, (UInt_t)posY,
(UInt_t)posX, (UInt_t)sdevX, (UInt_t)devX);
Int_t localFromId = localBoard->GetInputXfrom();
AliMUONLocalTrigger* locTrgfrom = triggerStore->FindLocal(localFromId);
buffer[index++] = 0; // copy only X3-4 & Y1-4
buffer[index++] = (locTrgfrom->GetX3Pattern() | (locTrgfrom->GetX4Pattern() << 16));
buffer[index++] = (locTrgfrom->GetY1Pattern() | (locTrgfrom->GetY2Pattern() << 16));
buffer[index++] = (locTrgfrom->GetY3Pattern() | (locTrgfrom->GetY4Pattern() << 16));
buffer[index++] = word;
}
} else {
// fill with 10CDEAD word for empty slots
for (Int_t i = 0; i < localStruct.GetLength(); i++)
buffer[index++] = localStruct.GetDisableWord();
}// condition localBoard
// 45 regional scaler word
if (scalarEvent) {
memcpy(&buffer[index], localStruct.GetScalers(), kLocScalerLength*4);
index += kLocScalerLength;
}
// end of local structure words
buffer[index++] = localStruct.GetEndOfLocal();
} // local card
// fill regional header with local output
regHeader.SetInput(regInpHpt, 0);
regHeader.SetInput(regInpLpt, 1);
memcpy(&buffer[indexReg],regHeader.GetHeader(),kRegHeaderLength*4);
} // Regional card
header->fSize = index * sizeof(Int_t) + sizeof(AliRawDataHeaderV3);
outBufferSize = header->fSize;
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
| 30.068327 | 105 | 0.643114 | [
"object",
"3d"
] |
a4629ea085dfcbdef1272f6b8ce2263c8df4904a | 6,854 | cpp | C++ | ds4/code/4_router_cli/command/group_command.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 132 | 2017-03-22T03:46:38.000Z | 2022-03-08T15:08:16.000Z | ds4/code/4_router_cli/command/group_command.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 4 | 2017-04-06T17:46:10.000Z | 2018-08-08T18:27:59.000Z | ds4/code/4_router_cli/command/group_command.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 30 | 2017-03-26T22:38:17.000Z | 2021-11-21T20:50:17.000Z | //
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#define _ENABLE_ATOMIC_ALIGNMENT_FIX
#include <algorithm>
#include <vector>
#include "command/group_command.h"
#include "component/mute_component.h"
#include "component/client/client_component.h"
#include "component/group/group_component.h"
#include "component/router/router_acceptor_component.h"
#include "entity/entity.h"
#include "entity/entity_factory.h"
#include "entity/entity_util.h"
#include "factory/router_factory.h"
#include "message/request/client_request_message.h"
#include "security/filter/exclusive.h"
#include "security/filter/hex.h"
namespace eja
{
// Interface
void group_command::execute(const entity::ptr& entity, const group_request_message::ptr& request_message) const
{
// Validate
if (!validate(entity, request_message))
return;
// Group
const auto client = entity->get<client_component>();
const auto group_entity = get_group(entity);
if (likely(group_entity))
{
// Id
if (request_message->has_id())
{
const auto message_map = group_entity->get<message_map_component>();
{
const auto e = entity_factory::create_timeout(entity);
const auto pair = std::make_pair(request_message->get_id(), e);
// NOTE: Allow reuse
thread_lock(message_map);
message_map->insert(pair);
}
}
// Copy
std::vector<entity::ptr> clients;
if (!request_message->has_clients())
{
if (!request_message->has_room())
{
// Copy
clients = entity_util::transform<client_map_component>(group_entity);
}
else
{
const auto room_entity = get_room(group_entity, request_message->get_room());
if (likely(room_entity))
{
// Copy
clients = entity_util::transform<client_map_component>(room_entity);
// NOTE: Add if not in room
const auto client_map = room_entity->get<client_map_component>();
{
thread_lock(client_map);
const auto it = client_map->find(client->get_id());
if (it == client_map->end())
{
const auto pair = std::make_pair(client->get_id(), entity);
const auto result = client_map->insert(pair);
assert(result.second);
}
}
}
}
}
else
{
const auto client_map = group_entity->get<client_map_component>();
clients.reserve(request_message->get_clients().size());
for (const auto& id : request_message->get_clients())
{
// XOR: Don't really need this
//const auto idx = exclusive::compute(id, client->get_seed());
thread_lock(client_map);
const auto it = client_map->find(id);
if (it != client_map->end())
{
const auto& e = it->second;
clients.push_back(e);
}
}
}
// Remove
if (!request_message->is_share())
{
// Muted
clients.erase(std::remove_if(clients.begin(), clients.end(), [&](const entity::ptr e)
{
if (entity != e)
{
// Muted?
const auto ms = e->get<mute_set_component>();
{
thread_lock(ms);
return ms->find(e) != ms->end();
}
}
// Send to self?
return !request_message->is_self();
}), clients.end());
}
else
{
// Muted or not sharing
clients.erase(std::remove_if(clients.begin(), clients.end(), [&](const entity::ptr e)
{
// Sharing?
const auto c = e->get<client_component>();
if (!c->is_share())
return true;
if (entity != e)
{
// Muted?
const auto ms = e->get<mute_set_component>();
{
thread_lock(ms);
return ms->find(e) != ms->end();
}
}
// Send to self?
return !request_message->is_self();
}), clients.end());
}
// Empty?
if (!clients.empty())
{
// Request
const auto client_request = client_request_message::create();
client_request->set_id(request_message->get_id());
client_request->set_data(request_message->get_data());
client_request->set_room(request_message->get_room());
client_request->set_origin(client->get_id());
// Write
const auto acceptor = m_entity->get<router_acceptor_component>();
for (const auto& e : clients)
{
// XOR: Don't really need this
//const auto client_request = client_request_message::create();
//client_request->set_id(request_message->get_id());
//client_request->set_data(request_message->get_data());
//client_request->set_room(request_message->get_room());
//const auto c = e->get<client_component>();
///*const*/ auto idx = exclusive::compute(client->get_id(), c->get_seed());
//client_request->set_origin(std::move(idx));
acceptor->async_write(e, client_request);
}
}
}
}
// Utility
bool group_command::validate(const entity::ptr& entity, const group_request_message::ptr& request_message) const
{
// Id
const auto& id = request_message->get_id();
if (unlikely(id.size() > io::max_id_size))
return false;
// Clients
for (const auto& client : request_message->get_clients())
{
if (unlikely(client.size() > security::get_max_size()))
return false;
}
// Origin
if (unlikely(request_message->has_origin()))
return false;
// Room
const auto& room = request_message->get_room();
if (unlikely(room.size() > io::max_id_size))
return false;
// Data
if (request_message->has_data())
{
// Verified
const auto client = entity->get<client_component>();
if (client->is_verified())
return true;
// PM, Browse, Search, & Transfer (Don't spam)
if (request_message->has_clients() || request_message->is_share())
return true;
// Group (Don't spam)
const auto group = entity->get<group_component>();
if (group->has_id())
return true;
}
return false;
}
}
| 27.748988 | 113 | 0.656551 | [
"vector",
"transform"
] |
a462df61d5615dbeb2ffc8b0db4a72374d372e21 | 40,031 | cpp | C++ | Visual Mercutio/zBaseLib/PSS_PlanFinObjects.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zBaseLib/PSS_PlanFinObjects.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zBaseLib/PSS_PlanFinObjects.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_PlanFinObjects --------------------------------------------------*
****************************************************************************
* Description : Provides financial plan objects *
* Developer : Processsoft *
****************************************************************************/
#include "stdafx.h"
#include "PSS_PlanFinObjects.h"
// std
#include <float.h>
// processsoft
#include "PSS_Document.h"
#include "PSS_View.h"
#include "PSS_MathParser.h"
#include "PSS_DrawFunctions.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNRect, PSS_PLFNGraphic, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNRect
//---------------------------------------------------------------------------
PSS_PLFNRect::PSS_PLFNRect(BOOL round) :
PSS_PLFNGraphic(),
m_Round(round),
m_ArcOffset(5)
{}
//---------------------------------------------------------------------------
PSS_PLFNRect::PSS_PLFNRect(const PSS_PLFNRect& other) :
PSS_PLFNGraphic(),
m_Round(FALSE),
m_ArcOffset(0)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNRect::~PSS_PLFNRect()
{}
//---------------------------------------------------------------------------
const PSS_PLFNRect& PSS_PLFNRect::operator = (const PSS_PLFNRect* pOther)
{
PSS_PLFNGraphic::operator = ((inherited*)pOther);
if (!pOther)
{
// set default values
m_Round = 0;
m_ArcOffset = 5;
}
else
{
m_Round = pOther->m_Round;
m_ArcOffset = pOther->m_ArcOffset;
}
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNRect& PSS_PLFNRect::operator = (const PSS_PLFNRect& other)
{
PSS_PLFNGraphic::operator = ((inherited&)other);
m_Round = other.m_Round;
m_ArcOffset = other.m_ArcOffset;
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNRect::Clone() const
{
return new PSS_PLFNRect(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNRect::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNRect*>(pSrc));
}
//---------------------------------------------------------------------------
void PSS_PLFNRect::Serialize(CArchive& ar)
{
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 5)
PSS_PLFNGraphic::Serialize(ar);
else
PSS_PlanFinObject::Serialize(ar);
if (ar.IsStoring())
{
// write the elements
ar << m_ArcOffset;
ar << WORD(m_Round);
}
else
{
// read the elements
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 5)
{
ar >> m_ArcOffset;
WORD wValue;
ar >> wValue;
m_Round = BOOL(wValue);
}
else
m_Round = FALSE;
}
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNRect::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNRect::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
void PSS_PLFNRect::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
CPen pen;
CPen* pOldPen = pDC->SelectObject(&GetGraphicPen(pen));
if (m_Round)
{
// draw the square
pDC->MoveTo(m_ObjectRect.left + GetArcOffset(), m_ObjectRect.top);
pDC->LineTo(m_ObjectRect.right - GetArcOffset() + 1, m_ObjectRect.top);
pDC->Arc (m_ObjectRect.left, m_ObjectRect.top,
m_ObjectRect.left + (GetArcOffset() * 2), m_ObjectRect.top + (GetArcOffset() * 2),
m_ObjectRect.left + GetArcOffset(), m_ObjectRect.top,
m_ObjectRect.left, m_ObjectRect.top + GetArcOffset() + 1);
pDC->MoveTo(m_ObjectRect.right, m_ObjectRect.top + GetArcOffset());
pDC->LineTo(m_ObjectRect.right, m_ObjectRect.bottom - GetArcOffset() + 1);
pDC->Arc (m_ObjectRect.right - (GetArcOffset() * 2), m_ObjectRect.top,
m_ObjectRect.right, m_ObjectRect.top + (GetArcOffset() * 2),
m_ObjectRect.right, m_ObjectRect.top + GetArcOffset(),
m_ObjectRect.right - GetArcOffset(), m_ObjectRect.top);
pDC->MoveTo(m_ObjectRect.right - GetArcOffset(), m_ObjectRect.bottom);
pDC->LineTo(m_ObjectRect.left + GetArcOffset() - 1, m_ObjectRect.bottom);
pDC->Arc (m_ObjectRect.right - (GetArcOffset() * 2), m_ObjectRect.bottom - (GetArcOffset() * 2),
m_ObjectRect.right, m_ObjectRect.bottom,
m_ObjectRect.right - GetArcOffset() - 1, m_ObjectRect.bottom,
m_ObjectRect.right, m_ObjectRect.bottom - GetArcOffset());
pDC->MoveTo(m_ObjectRect.left, m_ObjectRect.bottom - GetArcOffset());
pDC->LineTo(m_ObjectRect.left, m_ObjectRect.top + GetArcOffset() - 1);
pDC->Arc (m_ObjectRect.left, m_ObjectRect.bottom - (GetArcOffset() * 2),
m_ObjectRect.left + (GetArcOffset() * 2), m_ObjectRect.bottom,
m_ObjectRect.left, m_ObjectRect.bottom - GetArcOffset(),
m_ObjectRect.left + GetArcOffset() + 1, m_ObjectRect.bottom);
}
else
{
// draw the square
pDC->MoveTo(m_ObjectRect.left, m_ObjectRect.top);
pDC->LineTo(m_ObjectRect.right, m_ObjectRect.top);
pDC->LineTo(m_ObjectRect.right, m_ObjectRect.bottom);
pDC->LineTo(m_ObjectRect.left, m_ObjectRect.bottom);
pDC->LineTo(m_ObjectRect.left, m_ObjectRect.top);
}
// draw the shadow only on the screen
if (!pDC->IsPrinting())
{
CPen lightGrayPen(PS_SOLID, 1, defCOLOR_LTLTGRAY);
pDC->SelectObject(&lightGrayPen);
if (!m_Round)
{
pDC->MoveTo(m_ObjectRect.right + 1, m_ObjectRect.top + 1);
pDC->LineTo(m_ObjectRect.right + 1, m_ObjectRect.bottom + 1);
pDC->LineTo(m_ObjectRect.left - 1, m_ObjectRect.bottom + 1);
}
}
pDC->SelectObject(pOldPen);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNLine, PSS_PLFNGraphic, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNLine
//---------------------------------------------------------------------------
PSS_PLFNLine::PSS_PLFNLine() :
PSS_PLFNGraphic(),
m_StartPoint(0, 0),
m_EndPoint(0, 0)
{}
//---------------------------------------------------------------------------
PSS_PLFNLine::PSS_PLFNLine(const PSS_PLFNLine& other) :
PSS_PLFNGraphic()
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNLine::~PSS_PLFNLine()
{}
//---------------------------------------------------------------------------
const PSS_PLFNLine& PSS_PLFNLine::operator = (const PSS_PLFNLine* pOther)
{
PSS_PLFNGraphic::operator = ((inherited*)pOther);
if (!pOther)
{
m_StartPoint = PSS_Point(0, 0);
m_EndPoint = PSS_Point(0, 0);
}
else
{
m_StartPoint = pOther->m_StartPoint;
m_EndPoint = pOther->m_EndPoint;
}
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNLine& PSS_PLFNLine::operator = (const PSS_PLFNLine& other)
{
PSS_PLFNGraphic::operator = ((inherited&)other);
m_StartPoint = other.m_StartPoint;
m_EndPoint = other.m_EndPoint;
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNLine::Clone() const
{
return new PSS_PLFNLine(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNLine::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNLine*>(pSrc));
}
//---------------------------------------------------------------------------
void PSS_PLFNLine::SizePositionHasChanged()
{
PSS_PlanFinObject::SizePositionHasChanged();
// recalculate all element positions
m_StartPoint.x = m_ObjectRect.left;
m_StartPoint.y = m_ObjectRect.top;
m_EndPoint.x = m_ObjectRect.right;
m_EndPoint.y = m_ObjectRect.bottom;
}
//---------------------------------------------------------------------------
void PSS_PLFNLine::Serialize(CArchive& ar)
{
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 5)
PSS_PLFNGraphic::Serialize(ar);
else
PSS_PlanFinObject::Serialize(ar);
if (ar.IsStoring())
{
// write the elements
ar << m_StartPoint;
ar << m_EndPoint;
}
else
{
// read the elements. If the version is before the version 0, then the line rect should be modified
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() < 0)
m_ObjectRect.bottom = m_ObjectRect.top;
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 2)
{
ar >> m_StartPoint;
ar >> m_EndPoint;
}
else
{
m_StartPoint.x = m_ObjectRect.left;
m_StartPoint.y = m_ObjectRect.top;
m_EndPoint.x = m_ObjectRect.right;
m_EndPoint.y = m_ObjectRect.bottom;
}
}
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNLine::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNLine::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
void PSS_PLFNLine::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
CPen pen;
CPen* pOldPen = pDC->SelectObject(&GetGraphicPen(pen));
pDC->MoveTo(m_ObjectRect.left, m_ObjectRect.top);
pDC->LineTo(m_ObjectRect.right, m_ObjectRect.bottom);
// draw the shadow only on the screen
if (!pDC->IsPrinting())
{
CPen lightGrayPen(PS_SOLID, 1, defCOLOR_LTLTGRAY);
pDC->SelectObject(&lightGrayPen);
pDC->MoveTo(m_ObjectRect.left + 1, m_ObjectRect.top + 1);
pDC->LineTo(m_ObjectRect.right + 1, m_ObjectRect.bottom + 1);
}
pDC->SelectObject(pOldPen);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNStatic, PSS_PLFNText, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNStatic
//---------------------------------------------------------------------------
PSS_PLFNStatic::PSS_PLFNStatic() :
PSS_PLFNText()
{
// set as static
SetIsStatic(TRUE);
}
//---------------------------------------------------------------------------
PSS_PLFNStatic::PSS_PLFNStatic(const PSS_PLFNStatic& other) :
PSS_PLFNText()
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNStatic::~PSS_PLFNStatic()
{}
//---------------------------------------------------------------------------
const PSS_PLFNStatic& PSS_PLFNStatic::operator = (const PSS_PLFNStatic* pOther)
{
PSS_PLFNText::operator = ((inherited*)pOther);
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNStatic& PSS_PLFNStatic::operator = (const PSS_PLFNStatic& other)
{
PSS_PLFNText::operator = ((inherited&)other);
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNStatic::Clone() const
{
return new PSS_PLFNStatic(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNStatic::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNStatic*>(pSrc));
}
//---------------------------------------------------------------------------
void PSS_PLFNStatic::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
CFont* pOldFont = pDC->SelectObject(GetFont(pView));
pDC->SetBkMode(TRANSPARENT);
CSize sizeText;
CPoint orgText;
// text color
pDC->SetTextColor(GetColor(pView));
GetTextExtentOrg(pDC, m_Str, sizeText, orgText, GetAngle());
m_ObjectRect.right = m_ObjectRect.left + sizeText.cx;
// the alignment to bottom should be changed to remove the alignement issue with different fonts,
// then the calculation of the text area should be changed
m_ObjectRect.top = m_ObjectRect.bottom - sizeText.cy;
pDC->SetTextAlign(TA_LEFT | TA_BOTTOM);
pDC->TextOut(m_ObjectRect.left + orgText.x, m_ObjectRect.bottom - orgText.y, m_Str);
pDC->SelectObject(pOldFont);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
void PSS_PLFNStatic::OnAngleChanged(PSS_Document* pDoc)
{
// rotate the font
RotateFont(pDoc);
}
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNTime, PSS_PLFNAscii, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNTime
//---------------------------------------------------------------------------
PSS_PLFNTime::PSS_PLFNTime() :
PSS_PLFNAscii(),
m_Time(g_ZeroTime)
{}
//---------------------------------------------------------------------------
PSS_PLFNTime::PSS_PLFNTime(const PSS_PLFNTime& other) :
PSS_PLFNAscii()
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNTime::~PSS_PLFNTime()
{}
//---------------------------------------------------------------------------
const PSS_PLFNTime& PSS_PLFNTime::operator = (const PSS_PLFNTime* pOther)
{
PSS_PLFNAscii::operator = ((inherited*)pOther);
if (!pOther)
m_Time = g_ZeroTime;
else
m_Time = pOther->m_Time;
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNTime& PSS_PLFNTime::operator = (const PSS_PLFNTime& other)
{
PSS_PLFNAscii::operator = ((inherited&)other);
m_Time = other.m_Time;
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNTime::Clone() const
{
return new PSS_PLFNTime(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNTime::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNTime*>(pSrc));
}
//---------------------------------------------------------------------------
BOOL PSS_PLFNTime::IsSelected(const CPoint& point) const
{
return(m_ObjectRect.PtInRect(point));
}
//---------------------------------------------------------------------------
CString PSS_PLFNTime::GetFormattedObject()
{
FormatObject(&m_Time);
return GetFormattedBuffer();
}
//---------------------------------------------------------------------------
CString PSS_PLFNTime::GetUnformattedObject()
{
if (IsEmpty())
// empty the string
m_FormatBuffer[0] = 0x00;
else
std::sprintf(m_FormatBuffer, "%d.%d.%04d", m_Time.GetDay(), m_Time.GetMonth(), m_Time.GetYear());
return GetFormattedBuffer();
}
//---------------------------------------------------------------------------
BOOL PSS_PLFNTime::ConvertFormattedObject(const CString& value, BOOL locateFormat, BOOL emptyWhenZero)
{
// set the flag for empty or not
if (value.IsEmpty())
EmptyObject();
else
ClearEmptyObjectFlag();
// save the old value to know if the value has changed
#ifndef _WIN32
CTime oldTime = m_Time;
#else
COleDateTime oldTime = m_Time;
#endif
CString temp = value;
int index;
// get the day
if ((index = temp.FindOneOf("./")) == -1)
{
EmptyObject();
// changed?
return (oldTime != m_Time);
}
CString param = temp.Left(index);
const int day = std::atoi((const char *)param);
if (day <= 0)
return FALSE;
// get the month
temp = temp.Right(temp.GetLength() - index - 1);
if ((index = temp.FindOneOf("./")) == -1)
{
EmptyObject();
// changed?
return (oldTime != m_Time);
}
param = temp.Left(index);
const int month = std::atoi((const char *)param);
if (month <= 0)
return FALSE;
// get the year
param = temp.Right(temp.GetLength() - index - 1);
int year = std::atoi((const char *)param);
// 1900 Based date
if (year < 1900)
year += 1900;
#ifndef _WIN32
CTime time(year, month, day, 12, 00, 00);
#else
COleDateTime time(year, month, day, 12, 00, 00);
#endif
m_Time = time;
// changed?
return (oldTime != m_Time);
}
//---------------------------------------------------------------------------
CStringArray& PSS_PLFNTime::GetFormatChoice() const
{
m_FormatChoice.RemoveAll();
// read the number and format it. Create a copy of the current object and modify the format
PSS_PLFNTime tmpTime = *this;
tmpTime.SetFormatType(E_FT_Standard);
tmpTime.FormatObject(&tmpTime.m_Time);
m_FormatChoice.Add(CString(tmpTime.GetFormattedBuffer()));
tmpTime.SetFormatType(E_FT_Date);
tmpTime.FormatObject(&tmpTime.m_Time);
m_FormatChoice.Add(CString(tmpTime.GetFormattedBuffer()));
tmpTime.SetFormatType(E_FT_Date1);
tmpTime.FormatObject(&tmpTime.m_Time);
m_FormatChoice.Add(CString(tmpTime.GetFormattedBuffer()));
tmpTime.SetFormatType(E_FT_Date2);
tmpTime.FormatObject(&tmpTime.m_Time);
m_FormatChoice.Add(CString(tmpTime.GetFormattedBuffer()));
return m_FormatChoice;
}
//---------------------------------------------------------------------------
void PSS_PLFNTime::SetFormatWithChoice(const CString& value)
{
const INT_PTR formatChoiceCount = m_FormatChoice.GetSize();
INT_PTR index = 0;
// iterate through the array and compare which one is the same
for (INT_PTR i = 0; i < formatChoiceCount; ++i)
if (m_FormatChoice[i] == value)
{
index = i;
break;
}
// found a format?
if (index < formatChoiceCount)
switch (index)
{
case 0: m_FormatType = E_FT_Standard; break;
case 1: m_FormatType = E_FT_Date; break;
case 2: m_FormatType = E_FT_Date1; break;
case 3: m_FormatType = E_FT_Date2; break;
}
}
//---------------------------------------------------------------------------
void PSS_PLFNTime::Serialize(CArchive& ar)
{
PSS_PlanFinObject::Serialize(ar);
if (ar.IsStoring())
// write the elements
ar << m_Time;
else
{
// read the elements. Before version 13
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() < 13)
{
CTime time;
ar >> time;
if (time.GetTime() >= 0)
m_Time.SetDateTime(time.GetYear(),
time.GetMonth(),
time.GetDay(),
time.GetHour(),
time.GetMinute(),
time.GetSecond());
// before version 12
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() < 12)
{
#ifdef _WIN32
// build a CTime for comparison
CTime zeroTime(g_ZeroTime.GetYear(),
g_ZeroTime.GetMonth(),
g_ZeroTime.GetDay(),
g_ZeroTime.GetHour(),
g_ZeroTime.GetMinute(),
g_ZeroTime.GetSecond());
m_IsEmpty = (time == zeroTime);
#else
m_IsEmpty = (time == g_ZeroTime);
#endif
}
}
else
ar >> m_Time;
}
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNTime::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNTime::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
void PSS_PLFNTime::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
CFont* pOldFont = pDC->SelectObject(GetFont(pView));
if (IsEmpty())
DrawEmpty(pDC, pView);
else
{
pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(GetColor(pView));
// before drawing the object, format it
FormatObject(&m_Time);
pDC->SetTextAlign(0);
pDC->DrawText(GetFormattedBuffer(), -1, &m_ObjectRect, GetJustify(pView->GetDocument()));
}
pDC->SelectObject(pOldFont);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNLong, PSS_PLFNAscii, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNLong
//---------------------------------------------------------------------------
PSS_PLFNLong::PSS_PLFNLong() :
PSS_PLFNAscii(),
m_Long(0.0),
m_IconDisplayType(IE_DT_NoIcon),
m_Rounded(0.0),
m_IsCalculatedField(FALSE),
m_KeepTheValue(FALSE),
m_IsRounded(FALSE)
{}
//---------------------------------------------------------------------------
PSS_PLFNLong::PSS_PLFNLong(const PSS_PLFNLong& other) :
PSS_PLFNAscii(),
m_Long(0.0),
m_IconDisplayType(IE_DT_NoIcon),
m_Rounded(0.0),
m_IsCalculatedField(FALSE),
m_KeepTheValue(FALSE),
m_IsRounded(FALSE)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNLong::~PSS_PLFNLong()
{}
//---------------------------------------------------------------------------
const PSS_PLFNLong& PSS_PLFNLong::operator = (const PSS_PLFNLong* pOther)
{
PSS_PLFNAscii::operator = ((inherited*)pOther);
if (!pOther)
{
// set default values
m_Long = 0.0;
m_IconDisplayType = IE_DT_NoIcon;
m_Rounded = 0.0;
m_IsCalculatedField = FALSE;
m_KeepTheValue = FALSE;
m_IsRounded = FALSE;
}
else
{
m_Long = pOther->m_Long;
m_IconDisplayType = pOther->m_IconDisplayType;
m_Rounded = pOther->m_Rounded;
m_IsCalculatedField = pOther->m_IsCalculatedField;
m_KeepTheValue = pOther->m_KeepTheValue;
m_IsRounded = pOther->m_IsRounded;
m_Associations.AssignContents(pOther->m_Associations);
}
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNLong& PSS_PLFNLong::operator = (const PSS_PLFNLong& other)
{
PSS_PLFNAscii::operator = ((inherited&)other);
m_Long = other.m_Long;
m_IconDisplayType = other.m_IconDisplayType;
m_Rounded = other.m_Rounded;
m_IsCalculatedField = other.m_IsCalculatedField;
m_KeepTheValue = other.m_KeepTheValue;
m_IsRounded = other.m_IsRounded;
m_Associations.AssignContents(other.m_Associations);
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNLong::Clone() const
{
return new PSS_PLFNLong(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNLong*>(pSrc));
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::GetContains(const CString& line)
{
int index;
// get the object name
if ((index = line.ReverseFind(',')) == -1)
return;
// get the value string
CString str;
int pos = line.GetLength() - index - 2;
if (pos > 0)
str = line.Right(pos);
m_Long = std::atof(str);
}
//---------------------------------------------------------------------------
CString PSS_PLFNLong::GetFormattedObject()
{
if (IsEmpty())
return "";
FormatObject(m_Long);
return GetFormattedBuffer();
}
//---------------------------------------------------------------------------
CString PSS_PLFNLong::GetUnformattedObject()
{
if (IsEmpty())
return "";
std::sprintf(m_FormatBuffer, "%lf", m_Long);
return GetFormattedBuffer();
}
//---------------------------------------------------------------------------
BOOL PSS_PLFNLong::ConvertFormattedObject(const CString& value, BOOL locateFormat, BOOL emptyWhenZero)
{
if (value.IsEmpty())
{
EmptyObject();
return TRUE;
}
// save the old value to make comparison
const double oldValue = m_Long;
// convert the string to a double and assign the result to the value. Check if the % char exists.
// If it's the case remove it and divide the number by 100. If the % char exists, the ' char can't
// exists at the same time
char* pCpPos = const_cast<char*>(std::strchr((const char*)value, '%'));
if (pCpPos)
{
// check if char ' exists at the same time
if (std::strchr((const char*)value, '\''))
{
AfxMessageBox(IDS_WZFORMATNUMBERERROR);
return FALSE;
}
// replace the percentage symbol
*pCpPos = 0x00;
m_Long = std::atof((const char*)value) / 100;
if (locateFormat)
SetFormatType(E_FT_Percentage);
// check if it's necessary to empty the object when zeros
if (emptyWhenZero && !m_Long)
EmptyObject();
// has changed?
return (oldValue != m_Long);
}
// detect dash or double-dash
bool b1Dash = false;
bool b2Dash = false;
if (std::strstr((const char*)value, ".--"))
b2Dash = true;
else
if (std::strstr((const char*)value, ".-"))
b1Dash = true;
// test if amounts contain a ' char
if (std::strchr((const char*)value, '\''))
{
// remove the ' char
const char* pBuffer = (const char*)value;
char valueBuf[100];
std::size_t index = 0;
for (int i = 0; *pBuffer; ++pBuffer)
if (*pBuffer != '\'')
{
valueBuf[i] = *pBuffer;
++i;
index = i;
}
valueBuf[index] = 0x00;
// if dash or double-dash, remove it before converting to number
if (b2Dash)
// set artificial end of buffer
valueBuf[index - 2] = 0x00;
else
if (b1Dash)
// set artificial end of buffer
valueBuf[index - 1] = 0x00;
m_Long = std::atof(valueBuf);
if (locateFormat)
if (std::strchr((const char*)value, ',') || std::strchr((const char*)value, '.'))
{
if (b2Dash)
SetFormatType(E_FT_Amount2DashTrail);
else
if (b1Dash)
SetFormatType(E_FT_Amount1DashTrail);
else
SetFormatType(E_FT_Amount2);
}
else
SetFormatType(E_FT_Amount);
}
else
{
char temp[100];
const int i = value.GetLength() - 1;
std::strcpy(temp, (const char*)value);
// if dahs or double-dash, remove it before converting to number
if (b2Dash)
// set artificial end of buffer
temp[i - 2] = 0x00;
else
if (b1Dash)
// set artificial end of buffer
temp[i - 1] = 0x00;
m_Long = std::atof(temp);
if (locateFormat && (std::strchr((const char*)value, ',') || std::strchr((const char*)value, '.')))
if (b2Dash)
SetFormatType(E_FT_Amount2Dash);
else
if (b1Dash)
SetFormatType(E_FT_Amount1Dash);
else
SetFormatType(E_FT_Amount1);
}
// check if it's necessary to empty the object when zeros
if (emptyWhenZero && !m_Long)
EmptyObject();
else
ClearEmptyObjectFlag();
// has changed?
return (oldValue != m_Long);
}
//---------------------------------------------------------------------------
CStringArray& PSS_PLFNLong::GetFormatChoice()
{
m_FormatChoice.RemoveAll();
// read the number and format it. Create a copy of the current object and modify the format
bool wasEmpty = false;
PSS_PLFNLong tmpLong = *this;
// bug on empty number, set 0 if empty
if (tmpLong.IsEmpty())
{
wasEmpty = true;
tmpLong.SetValue(1035.25);
}
tmpLong.SetFormatType(E_FT_Standard);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount1);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount2);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount1Dash);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount2Dash);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount1DashTrail);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
tmpLong.SetFormatType(E_FT_Amount2DashTrail);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
if (wasEmpty)
tmpLong.SetValue(0.5845);
tmpLong.SetFormatType(E_FT_Percentage);
tmpLong.FormatObject(tmpLong.m_Long);
m_FormatChoice.Add(CString(tmpLong.GetFormattedBuffer()));
return m_FormatChoice;
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::SetFormatWithChoice(const CString& value)
{
const INT_PTR formatChoiceCount = m_FormatChoice.GetSize();
INT_PTR index = 0;
// iterate through the array and search for matching value
for (INT_PTR i = 0; i < formatChoiceCount; ++i)
if (m_FormatChoice[i] == value)
{
index = i;
break;
}
// found something?
if (index < m_FormatChoice.GetSize())
switch (index)
{
case 0: m_FormatType = E_FT_Standard; break;
case 1: m_FormatType = E_FT_Amount; break;
case 2: m_FormatType = E_FT_Amount1; break;
case 3: m_FormatType = E_FT_Amount2; break;
case 4: m_FormatType = E_FT_Amount1Dash; break;
case 5: m_FormatType = E_FT_Amount2Dash; break;
case 6: m_FormatType = E_FT_Amount1DashTrail; break;
case 7: m_FormatType = E_FT_Amount2DashTrail; break;
case 8: m_FormatType = E_FT_Percentage; break;
}
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::Recalculate(PSS_Document* pDoc)
{
if (!pDoc)
return;
PSS_Formula* pFormula = pDoc->GetFormula(GetObjectName());
if (!pFormula)
return;
PSS_FormulaParser parser;
m_Long = parser.StringParser((const char*)pFormula->GetExtractedFormula(), &(pDoc->GetObjectList()));
if (GetRoundedValue() && IsRounded())
m_Long = std::ceil(m_Long / GetRoundedValue()) * GetRoundedValue();
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::DrawCalculatedSymbol(CDC* pDC)
{
if (pDC->IsPrinting())
return;
HINSTANCE hInst = ::AfxFindResourceHandle(MAKEINTRESOURCE(IDB_CALCBACKASSC), RT_BITMAP);
if (GetCurrentAssociation())
{
if (IsCalculatedField())
{
PSS_PlanFinObject::DrawBoundRect(pDC);
// show calculator icon in association mode
ShowBitmapFile(MAKEINTRESOURCE(IDB_CALCBACKASSC),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom);
}
else
{
// show icon in association mode
ShowBitmapFile(MAKEINTRESOURCE(IDB_BACKASSC),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom);
PSS_PlanFinObject::DrawRightCorner(pDC);
}
}
else
{
if (m_IconDisplayType == IE_DT_AssociationIcon)
{
PSS_PlanFinObject::DrawBoundRect(pDC);
// show the field as calculate with association
ShowBitmapFile(MAKEINTRESOURCE(IDB_CALCWITHASSC),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom);
}
else
if (IsCalculatedField())
{
PSS_PlanFinObject::DrawBoundRect(pDC);
// show the field as protected
if (KeepTheValue())
ShowBitmapFileExtent(MAKEINTRESOURCE(IDB_LOCKED),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom,
SRCAND);
else
if (GetAssociations().GetCount())
// show calculator icon for association mode
ShowBitmapFile(MAKEINTRESOURCE(IDB_CALCSHOWASSC),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom);
else
// show the field as calculate
ShowBitmapFile(MAKEINTRESOURCE(IDB_CALCULATOR),
pDC->m_hDC,
hInst,
m_ObjectRect.right,
m_ObjectRect.bottom);
}
}
}
//---------------------------------------------------------------------------
void PSS_PLFNLong::Serialize(CArchive& ar)
{
PSS_PLFNAscii::Serialize(ar);
if (ar.IsStoring())
{
// write the elements
ar << m_Long;
ar << WORD(m_IsCalculatedField);
ar << WORD(m_KeepTheValue);
ar << WORD(m_IsRounded);
ar << m_Rounded;
ar << WORD(m_IconDisplayType);
}
else
{
// read the elements
ar >> m_Long;
WORD wValue;
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() < 1)
{
m_IsCalculatedField = FALSE;
m_KeepTheValue = FALSE;
}
else
{
ar >> wValue;
m_IsCalculatedField = wValue;
ar >> wValue;
m_KeepTheValue = wValue;
}
// since version 2
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 2 && ((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() <= 5)
{
CStringArray schemaArray;
schemaArray.Serialize(ar);
}
// since version 5
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 5)
{
ar >> wValue;
m_IsRounded = BOOL(wValue);
ar >> m_Rounded;
}
// since version 6
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 6)
{
ar >> wValue;
m_IconDisplayType = IEIconDisplayType(wValue);
}
// until version 12
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() < 12)
{
m_IsEmpty = (m_Long == FLT_MAX);
if (m_Long == FLT_MAX)
m_Long = 0;
}
}
// serialize associations (since version 6)
if (((PSS_BaseDocument*)ar.m_pDocument)->GetDocumentStamp().GetInternalVersion() >= 6)
m_Associations.Serialize(ar);
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNLong::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNLong::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
void PSS_PLFNLong::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
CFont* pOldFont = pDC->SelectObject(GetFont(pView));
if (IsEmpty())
DrawEmpty(pDC, pView);
else
{
pDC->SetBkMode(TRANSPARENT);
const COLORREF color = GetColor(pView);
pDC->SetTextColor(color);
// before drawing the object, format it
FormatObject(m_Long);
pDC->SetTextAlign(0);
pDC->DrawText(GetFormattedBuffer(), -1, &m_ObjectRect, GetJustify(pView->GetDocument()));
}
pDC->SelectObject(pOldFont);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
| 32.38754 | 179 | 0.490095 | [
"object"
] |
a46a1025c1678ce91a066d080bc3a26ea8bd4487 | 9,857 | cpp | C++ | cpp/wingchun/src/util/instrument.cpp | shu13720902/kungfu | da8101b6e4b7f08280d047c8f8c85c5e51875f15 | [
"Apache-2.0"
] | null | null | null | cpp/wingchun/src/util/instrument.cpp | shu13720902/kungfu | da8101b6e4b7f08280d047c8f8c85c5e51875f15 | [
"Apache-2.0"
] | null | null | null | cpp/wingchun/src/util/instrument.cpp | shu13720902/kungfu | da8101b6e4b7f08280d047c8f8c85c5e51875f15 | [
"Apache-2.0"
] | 1 | 2021-10-31T05:11:05.000Z | 2021-10-31T05:11:05.000Z | //
// Created by PolarAir on 2019-02-27.
//
#ifndef KUNGFU_BASIC_INFO_HPP
#define KUNGFU_BASIC_INFO_HPP
#include <string>
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <kungfu/wingchun/util/instrument.h>
#include <kungfu/wingchun/util/env.h>
using namespace kungfu::journal;
namespace kungfu
{
FutureInstrumentStorage::FutureInstrumentStorage(const std::string& file_name) : db_(file_name.c_str(), SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE)
{
create_table_if_not_exist();
}
void FutureInstrumentStorage::create_table_if_not_exist()
{
try
{
std::string sql = "CREATE TABLE IF NOT EXISTS future_instrument(\n"
" instrument_id CHAR(50),\n"
" exchange_id CHAR(50),\n"
" instrument_type CHAR(1),\n"
" product_id CHAR(50),\n"
" contract_multiplier INTEGER,\n"
" price_tick DOUBLE,\n"
" open_date CHAR(50),\n"
" create_date CHAR(50),\n"
" expire_date CHAR(50),\n"
" delivery_year INTEGER,\n"
" delivery_month INTEGER,\n"
" is_trading INTEGER,\n"
" long_margin_ratio DOUBLE,\n"
" short_margin_ratio DOUBLE)\n";
db_.exec(sql);
}
catch (std::exception& e)
{
SPDLOG_ERROR(e.what());
}
}
void FutureInstrumentStorage::set_future_instruments(const std::vector<FutureInstrument> &future_instruments)
{
db_.exec("BEGIN");
try
{
db_.exec("DELETE FROM future_instrument");
for (const auto& future_instrument : future_instruments)
{
SQLite::Statement insert(db_, "INSERT INTO future_instrument VALUES(?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?)");
insert.bind(1, future_instrument.instrument_id);
insert.bind(2, future_instrument.exchange_id);
insert.bind(3, std::string(1, future_instrument.instrument_type));
insert.bind(4, future_instrument.product_id);
insert.bind(5, future_instrument.contract_multiplier);
insert.bind(6, future_instrument.price_tick);
insert.bind(7, future_instrument.open_date);
insert.bind(8, future_instrument.create_date);
insert.bind(9, future_instrument.expire_date);
insert.bind(10, future_instrument.delivery_year);
insert.bind(11, future_instrument.delivery_month);
insert.bind(12, future_instrument.is_trading);
insert.bind(13, future_instrument.long_margin_ratio);
insert.bind(14, future_instrument.short_margin_ratio);
insert.exec();
}
db_.exec("COMMIT");
}
catch (std::exception& e)
{
SPDLOG_ERROR(e.what());
db_.exec("ROLLBACK");
}
}
void FutureInstrumentStorage::get_future_instrument(std::pair<std::string, std::string>& key, std::map<std::pair<std::string, std::string>, FutureInstrument>& future_instruments)
{
try
{
SQLite::Statement query(db_, "SELECT * FROM future_instrument WHERE instrument_id = ? and exchange_id = ?");
query.bind(1, key.first);
query.bind(2, key.second);
if (query.executeStep())
{
FutureInstrument inst = {};
strcpy(inst.instrument_id, query.getColumn(0));
strcpy(inst.exchange_id, query.getColumn(1));
inst.instrument_type = query.getColumn(2)[0];
strcpy(inst.product_id, query.getColumn(3));
inst.contract_multiplier = query.getColumn(4);
inst.price_tick = query.getColumn(5);
strcpy(inst.open_date, query.getColumn(6));
strcpy(inst.create_date, query.getColumn(7));
strcpy(inst.expire_date, query.getColumn(8));
inst.delivery_year = query.getColumn(9);
inst.delivery_month = query.getColumn(10);
inst.is_trading = (int)query.getColumn(11);
inst.long_margin_ratio = query.getColumn(12);
inst.short_margin_ratio = query.getColumn(13);
future_instruments[key] = inst;
}
}
catch (std::exception& e)
{
SPDLOG_ERROR(e.what());
}
}
void FutureInstrumentStorage::get_future_instruments(std::map<std::pair<std::string, std::string>, FutureInstrument>& future_instruments)
{
try
{
SQLite::Statement query(db_, "SELECT * FROM future_instrument");
while (query.executeStep())
{
std::pair<std::string, std::string> key = {(const char*)query.getColumn(0), (const char*)query.getColumn(1)};
FutureInstrument inst = {};
strcpy(inst.instrument_id, query.getColumn(0));
strcpy(inst.exchange_id, query.getColumn(1));
inst.instrument_type = query.getColumn(2)[0];
strcpy(inst.product_id, query.getColumn(3));
inst.contract_multiplier = query.getColumn(4);
inst.price_tick = query.getColumn(5);
strcpy(inst.open_date, query.getColumn(6));
strcpy(inst.create_date, query.getColumn(7));
strcpy(inst.expire_date, query.getColumn(8));
inst.delivery_year = query.getColumn(9);
inst.delivery_month = query.getColumn(10);
inst.is_trading = (int)query.getColumn(11);
inst.long_margin_ratio = query.getColumn(12);
inst.short_margin_ratio = query.getColumn(13);
future_instruments[key] = inst;
}
}
catch (std::exception& e)
{
SPDLOG_ERROR(e.what());
}
}
std::shared_ptr<InstrumentManager> InstrumentManager::instrument_manager_ = nullptr;
InstrumentManager::InstrumentManager()
{
memset(&default_future_instrument_, 0, sizeof(default_future_instrument_));
default_future_instrument_.contract_multiplier = 10;
default_future_instrument_.price_tick = 1.0;
default_future_instrument_.is_trading = true;
default_future_instrument_.long_margin_ratio = 0.2;
default_future_instrument_.short_margin_ratio = 0.2;
reload_from_db();
}
void InstrumentManager::reload_from_db()
{
future_instruments_.clear();
FutureInstrumentStorage storage_(fmt::format(FUTURE_INSTRUMENT_DB_FILE_FORMAT, get_base_dir()));
storage_.get_future_instruments(future_instruments_);
}
std::shared_ptr<InstrumentManager> InstrumentManager::get_instrument_manager()
{
if (instrument_manager_ == nullptr)
{
instrument_manager_ = std::shared_ptr<InstrumentManager>(new InstrumentManager());
}
return instrument_manager_;
}
const FutureInstrument* InstrumentManager::get_future_instrument(const char* instrument_id, const char* exchange_id)
{
std::pair<std::string, std::string> key = {std::string(instrument_id), std::string(exchange_id)};
auto search = future_instruments_.find(key);
if (search != future_instruments_.end())
{
return &(search->second);
}
else
{
FutureInstrumentStorage storage_(fmt::format(FUTURE_INSTRUMENT_DB_FILE_FORMAT, get_base_dir()));
storage_.get_future_instrument(key, future_instruments_);
auto search = future_instruments_.find(key);
if (search != future_instruments_.end())
{
return &(search->second);
}
}
return &default_future_instrument_;
}
int InstrumentManager::get_future_multiplier(const char* instrument_id, const char* exchange_id)
{
const auto* ins = get_future_instrument(instrument_id, exchange_id);
if (nullptr != ins)
{
return ins->contract_multiplier;
}
return default_future_instrument_.contract_multiplier;
}
double InstrumentManager::get_future_margin_ratio(const char* instrument_id, const char* exchange_id, kungfu::Direction dir)
{
const auto* ins = get_future_instrument(instrument_id, exchange_id);
if (nullptr != ins)
{
return dir == DirectionLong ? ins->long_margin_ratio : ins->short_margin_ratio;
}
return dir == DirectionLong ? default_future_instrument_.long_margin_ratio : default_future_instrument_.short_margin_ratio;
}
std::vector<const FutureInstrument*> InstrumentManager::get_future_instruments()
{
FutureInstrumentStorage storage_(fmt::format(FUTURE_INSTRUMENT_DB_FILE_FORMAT, get_base_dir()));
storage_.get_future_instruments(future_instruments_);
std::vector<const FutureInstrument*> result;
for (const auto& iter : future_instruments_)
{
result.push_back(&(iter.second));
}
return result;
}
}
#endif // KUNGFU_BASIC_INFO_HPP
| 41.590717 | 182 | 0.570863 | [
"vector"
] |
a46e5698de0d1dab7a8931d4078fb41a8db8284c | 6,094 | cpp | C++ | src/qt/qtbase/src/platformsupport/eglconvenience/qeglcompositor.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/platformsupport/eglconvenience/qeglcompositor.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/platformsupport/eglconvenience/qeglcompositor.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/private/qopengltextureblitter_p.h>
#include <qpa/qplatformbackingstore.h>
#include "qeglcompositor_p.h"
#include "qeglplatformwindow_p.h"
#include "qeglplatformscreen_p.h"
QT_BEGIN_NAMESPACE
static QEGLCompositor *compositor = 0;
QEGLCompositor::QEGLCompositor()
: m_context(0),
m_window(0),
m_blitter(0)
{
Q_ASSERT(!compositor);
m_updateTimer.setSingleShot(true);
m_updateTimer.setInterval(0);
connect(&m_updateTimer, SIGNAL(timeout()), SLOT(renderAll()));
}
QEGLCompositor::~QEGLCompositor()
{
Q_ASSERT(compositor == this);
if (m_blitter) {
m_blitter->destroy();
delete m_blitter;
}
compositor = 0;
}
void QEGLCompositor::schedule(QOpenGLContext *context, QEGLPlatformWindow *window)
{
m_context = context;
m_window = window;
if (!m_updateTimer.isActive())
m_updateTimer.start();
}
void QEGLCompositor::renderAll()
{
Q_ASSERT(m_context && m_window);
m_context->makeCurrent(m_window->window());
if (!m_blitter) {
m_blitter = new QOpenGLTextureBlitter;
m_blitter->create();
}
m_blitter->bind();
QEGLPlatformScreen *screen = static_cast<QEGLPlatformScreen *>(m_window->screen());
QList<QEGLPlatformWindow *> windows = screen->windows();
for (int i = 0; i < windows.size(); ++i)
render(windows.at(i));
m_blitter->release();
m_context->swapBuffers(m_window->window());
for (int i = 0; i < windows.size(); ++i)
windows.at(i)->composited();
}
struct BlendStateBinder
{
BlendStateBinder() : m_blend(false) {
glDisable(GL_BLEND);
}
void set(bool blend) {
if (blend != m_blend) {
if (blend) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
} else {
glDisable(GL_BLEND);
}
m_blend = blend;
}
}
~BlendStateBinder() {
if (m_blend)
glDisable(GL_BLEND);
}
bool m_blend;
};
void QEGLCompositor::render(QEGLPlatformWindow *window)
{
const QPlatformTextureList *textures = window->textures();
if (!textures)
return;
const QRect targetWindowRect(QPoint(0, 0), window->screen()->geometry().size());
glViewport(0, 0, targetWindowRect.width(), targetWindowRect.height());
float currentOpacity = 1.0f;
BlendStateBinder blend;
for (int i = 0; i < textures->count(); ++i) {
uint textureId = textures->textureId(i);
QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(textures->geometry(i),
targetWindowRect);
const float opacity = window->window()->opacity();
if (opacity != currentOpacity) {
currentOpacity = opacity;
m_blitter->setOpacity(currentOpacity);
}
if (textures->count() > 1 && i == textures->count() - 1) {
// Backingstore for a widget with QOpenGLWidget subwidgets
blend.set(true);
m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft);
} else if (textures->count() == 1) {
// A regular QWidget window
const bool translucent = window->window()->requestedFormat().alphaBufferSize() > 0;
blend.set(translucent);
m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft);
} else if (!textures->flags(i).testFlag(QPlatformTextureList::StacksOnTop)) {
// Texture from an FBO belonging to a QOpenGLWidget
blend.set(false);
m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginBottomLeft);
}
}
for (int i = 0; i < textures->count(); ++i) {
if (textures->flags(i).testFlag(QPlatformTextureList::StacksOnTop)) {
QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(textures->geometry(i), targetWindowRect);
blend.set(true);
m_blitter->blit(textures->textureId(i), target, QOpenGLTextureBlitter::OriginBottomLeft);
}
}
m_blitter->setOpacity(1.0f);
}
QEGLCompositor *QEGLCompositor::instance()
{
if (!compositor)
compositor = new QEGLCompositor;
return compositor;
}
void QEGLCompositor::destroy()
{
delete compositor;
compositor = 0;
}
QT_END_NAMESPACE
| 32.763441 | 112 | 0.643584 | [
"geometry",
"render"
] |
a4731a491c7f0212d80e4fca946fc69772ffa9e0 | 7,047 | cpp | C++ | lab4DSA/ExtendedTest.cpp | marivsteo/Data-Structures-And-Algorithms-Course | e81a9439b24ad9587f92ef1696eae02a383b3188 | [
"MIT"
] | null | null | null | lab4DSA/ExtendedTest.cpp | marivsteo/Data-Structures-And-Algorithms-Course | e81a9439b24ad9587f92ef1696eae02a383b3188 | [
"MIT"
] | null | null | null | lab4DSA/ExtendedTest.cpp | marivsteo/Data-Structures-And-Algorithms-Course | e81a9439b24ad9587f92ef1696eae02a383b3188 | [
"MIT"
] | null | null | null | #include <assert.h>
#include "Bag.h"
#include "ExtendedTest.h"
#include "BagIterator.h"
#include <iostream>
#include <vector>
#include <exception>
using namespace std;
void testCreate() {
Bag b;
assert(b.size() == 0);
assert(b.isEmpty() == true);
for (int i = -5; i < 5; i++) {
assert(b.search(i) == false);
}
for (int i = -10; i < 10; i++) {
assert(b.remove(i) == false);
}
for (int i = -10; i < 10; i++) {
assert(b.nrOccurrences(i) == 0);
}
BagIterator it = b.iterator();
assert(it.valid() == false);
}
void testAdd() {
Bag b;
for (int i = 0; i < 10; i++) {
b.add(i);
}
assert(b.isEmpty() == false);
assert(b.size() == 10);
for (int i = -10; i < 20; i++) {
b.add(i);
}
assert(b.isEmpty() == false);
assert(b.size() == 40);
for (int i = -100; i < 100; i++) {
b.add(i);
}
assert(b.isEmpty() == false);
assert(b.size() == 240);
for (int i = -200; i < 200; i++) {
int count = b.nrOccurrences(i);
if (i < -100) {
assert(count == 0);
assert(b.search(i) == false);
}
else if (i < -10) {
assert(count == 1);
assert(b.search(i) == true);
}
else if (i < 0) {
assert(count == 2);
assert(b.search(i) == true);
}
else if (i < 10) {
assert(count == 3);
assert(b.search(i) == true);
}
else if (i < 20) {
assert(count == 2);
assert(b.search(i) == true);
}
else if (i < 100) {
assert(count == 1);
assert(b.search(i) == true);
}
else {
assert(count == 0);
assert(b.search(i) == false);
}
}
for (int i = 10000; i > -10000; i--) {
b.add(i);
}
assert(b.size() == 20240);
}
void testRemove() {
Bag b;
for (int i = -100; i < 100; i++) {
assert(b.remove(i) == false);
}
assert(b.size() == 0);
for (int i = -100; i < 100; i = i + 2) {
b.add(i);
}
for (int i = -100; i < 100; i++) {
if (i % 2 == 0) {
assert(b.remove(i) == true);
}
else {
assert(b.remove(i) == false);
}
}
assert(b.size() == 0);
for (int i = -100; i <= 100; i = i + 2) {
b.add(i);
}
for (int i = 100; i > -100; i--) {
if (i % 2 == 0) {
assert(b.remove(i) == true);
}
else {
assert(b.remove(i) == false);
}
}
assert(b.size() == 1);
b.remove(-100);
for (int i = -100; i < 100; i++) {
b.add(i);
b.add(i);
b.add(i);
b.add(i);
b.add(i);
}
assert(b.size() == 1000);
for (int i = -100; i < 100; i++) {
assert(b.nrOccurrences(i) == 5);
}
for (int i = -100; i < 100; i++) {
assert(b.remove(i) == true);
}
assert(b.size() == 800);
for (int i = -100; i < 100; i++) {
assert(b.nrOccurrences(i) == 4);
}
for (int i = -200; i < 200; i++) {
if (i < -100 || i >= 100) {
assert(b.remove(i) == false);
assert(b.remove(i) == false);
assert(b.remove(i) == false);
assert(b.remove(i) == false);
assert(b.remove(i) == false);
}
else {
assert(b.remove(i) == true);
assert(b.remove(i) == true);
assert(b.remove(i) == true);
assert(b.remove(i) == true);
assert(b.remove(i) == false);
}
}
assert(b.size() == 0);
for (int i = -1000; i < 1000; i++) {
assert(b.nrOccurrences(i) == 0);
}
int min = -200;
int max = 200;
while (min < max) {
b.add(min);
b.add(max);
min++;
max--;
}
b.add(0);
b.add(0);
assert(b.size() == 402);
for (int i = -30; i < 30; i++) {
assert(b.search(i) == true);
assert(b.remove(i) == true);
if (i != 0) {
assert(b.search(i) == false);
}
else {
assert(b.search(i) == true);
}
}
assert(b.size() == 342);
}
void testIterator() {
Bag b;
BagIterator it = b.iterator();
assert(it.valid() == false);
try {
it.next();
assert(false);
}
catch (exception&) {
assert(true);
}
try {
it.getCurrent();
assert(false);
}
catch (exception&) {
assert(true);
}
for (int i = 0; i < 100; i++) {
b.add(33);
}
BagIterator it2 = b.iterator();
assert(it2.valid() == true);
for (int i = 0; i < 100; i++) {
TElem elem = it2.getCurrent();
assert(elem == 33);
it2.next();
}
assert(it2.valid() == false);
it2.first();
assert(it2.valid() == true);
for (int i = 0; i < 100; i++) {
TElem elem = it2.getCurrent();
TElem elem2 = it2.getCurrent();
assert(elem == 33);
assert(elem2 == 33);
it2.next();
}
assert(it2.valid() == false);
try {
it2.next();
assert(false);
}
catch (exception&) {
assert(true);
}
try {
it2.getCurrent();
assert(false);
}
catch (exception&) {
assert(true);
}
Bag b2;
for (int i = -100; i < 100; i++) {
b2.add(i);
b2.add(i);
b2.add(i);
}
BagIterator it3 = b2.iterator();
assert(it3.valid() == true);
for (int i = 0; i < 600; i++) {
TElem e1 = it3.getCurrent();
it3.next();
}
assert(it3.valid() == false);
it3.first();
assert(it3.valid() == true);
Bag b3;
for (int i = 0; i < 200; i = i + 4) {
b3.add(i);
}
BagIterator it4 = b3.iterator();
assert(it4.valid() == true);
int count = 0;
while (it4.valid()) {
TElem e = it4.getCurrent();
assert(e % 4 == 0);
it4.next();
count++;
}
assert(count == 50);
Bag b4;
for (int i = 0; i < 100; i++) {
b4.add(i);
b4.add(i * (-2));
b4.add(i * 2);
b4.add(i / 2);
b4.add(i / (-2));
}
vector<TElem> elements;
BagIterator it5 = b4.iterator();
while (it5.valid()) {
TElem e = it5.getCurrent();
elements.push_back(e);
it5.next();
}
assert(elements.size() == b4.size());
for (unsigned int i = 0; i < elements.size(); i++) {
TElem lastElem = elements.at(elements.size() - i - 1);
assert(b4.search(lastElem) == true);
b4.remove(lastElem);
}
Bag b5;
for (int i = 0; i < 100; i++) {
b5.add(i);
b5.add(i * (-2));
b5.add(i * 2);
b5.add(i / 2);
b5.add(i / (-2));
}
vector<TElem> elements2;
BagIterator it6 = b5.iterator();
while (it6.valid()) {
TElem e = it6.getCurrent();
elements2.push_back(e);
it6.next();
}
assert(elements2.size() == b5.size());
for (unsigned int i = 0; i < elements2.size(); i++) {
TElem firstElem = elements2.at(i);
assert(b5.search(firstElem) == true);
b5.remove(firstElem);
}
}
void testQuantity() {
Bag b;
for (int i = 10; i >= 1; i--) {
for (int j = -30000; j < 30000; j = j + i) {
b.add(j);
}
}
assert(b.size() == 175739);
assert(b.nrOccurrences(-30000) == 10);
BagIterator it = b.iterator();
assert(it.valid() == true);
for (int i = 0; i < b.size(); i++) {
it.next();
}
it.first();
while (it.valid()) {
TElem e = it.getCurrent();
assert(b.search(e) == true);
assert(b.nrOccurrences(e) > 0);
it.next();
}
assert(it.valid() == false);
for (int i = 0; i < 10; i++) {
for (int j = 40000; j >= -40000; j--) {
b.remove(j);
}
}
assert(b.size() == 0);
}
void testAllExtended() {
testCreate();
cout << 1;
testAdd();
cout << 2;
testRemove();
cout << 3;
testIterator();
cout << 4;
testQuantity();
cout << 5;
}
| 19.684358 | 57 | 0.497942 | [
"vector"
] |
a473b714ca4dcae3aabf1d3b71e439bd09b2bcf1 | 1,372 | cpp | C++ | Algorithms/1438.Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/1438.Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/1438.Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | typedef vector<int> vi;
typedef vector<vi> vii;
class Solution {
public:
int longestSubarray(vector<int>& ar, int limit) {
int k = 0;
int n = ar.size();
vector<int> lg2(n+1,0);
for( int i = 1 ; (1<<i) <= n ; i++ )
k = lg2[1<<i] = i;
for( int i = 3 ; i <= n ; i++ )
if(lg2[i] == 0)
lg2[i] = lg2[i-1];
vii mn(k+1,vi(n));
vii mx(k+1,vi(n));
for( int i = 0 ; i < n ; i++ )
mn[0][i] = mx[0][i] = ar[i];
for( int j = 0 ; j < k ; j++ )
for( int i = 0 ; i + (1<<(j+1)) <= n ; i++ ) {
mn[j+1][i] = min( mn[j][i] , mn[j][i+(1<<j)] );
mx[j+1][i] = max( mx[j][i] , mx[j][i+(1<<j)] );
}
int best = 1;
for( int i = 0 ; i < n-best ; i++ ) {
int l = i+best , r = n-1;
while(l <= r) {
int mid = (l+r) >> 1;
int len = mid-i+1;
int lg = lg2[len];
int mnVal = min( mn[lg][i] , mn[lg][mid-(1<<lg)+1] );
int mxVal = max( mx[lg][i] , mx[lg][mid-(1<<lg)+1] );
if(mxVal - mnVal <= limit) {
l = mid+1;
best = len;
}
else
r = mid-1;
}
}
return best;
}
}; | 31.906977 | 69 | 0.325073 | [
"vector"
] |
a473c78c2640861e2b64f205e9397f20854d1a63 | 900 | hpp | C++ | src/main/cpp/pdf_tin/Page.hpp | tomault/pdf_tin | 5d33d87a622327fd5cb50e895435b454c02ecf06 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pdf_tin/Page.hpp | tomault/pdf_tin | 5d33d87a622327fd5cb50e895435b454c02ecf06 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pdf_tin/Page.hpp | tomault/pdf_tin | 5d33d87a622327fd5cb50e895435b454c02ecf06 | [
"Apache-2.0"
] | null | null | null | #ifndef __PDF_TIN__PAGE_HPP__
#define __PDF_TIN__PAGE_HPP__
#include <pdf_tin/Image.hpp>
#include <pdf_tin/Text.hpp>
#include <pdf_tin/detail/GObjectPtr.hpp>
#include <memory>
struct _PopplerPage;
namespace pdf_tin {
class Page {
public:
Page(_PopplerPage* page) : page_(page) { }
Page(const Page&) = default;
Page(Page&&) = default;
const char* label() const;
int index() const;
double width() const;
double height() const;
double duration() const;
std::vector<Text> text() const;
std::vector<Image> images() const;
Page& operator=(const Page&) = default;
Page& operator=(Page&&) = default;
protected:
Page(const detail::GObjectPtr<_PopplerPage>& page) : page_(page) { }
Page(detail::GObjectPtr<_PopplerPage>&& page) : page_(std::move(page)) { }
private:
detail::GObjectPtr<_PopplerPage> page_;
};
}
#endif
| 21.95122 | 78 | 0.66 | [
"vector"
] |
a475ae2c7ccf20df90bf018361ab4501571a3c56 | 624 | hpp | C++ | 05-Map/src/Map.hpp | eXpl0it3r/SFML-Workshop | 0a42acc8a4aa48d44f3191b7472ea1f666381dee | [
"Unlicense"
] | 9 | 2019-06-11T16:55:25.000Z | 2020-05-06T14:59:28.000Z | 05-Map/src/Map.hpp | eXpl0it3r/SFML-Workshop | 0a42acc8a4aa48d44f3191b7472ea1f666381dee | [
"Unlicense"
] | null | null | null | 05-Map/src/Map.hpp | eXpl0it3r/SFML-Workshop | 0a42acc8a4aa48d44f3191b7472ea1f666381dee | [
"Unlicense"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include <set>
class Map final : public sf::Drawable
{
public:
void load(const sf::Texture& tilesheet, sf::Vector2u tile_size,
const int* tile_map, sf::Vector2<std::size_t> map_size);
bool check_collision(sf::Vector2f next_position, std::set<int> collision_values);
private:
void generate_map(const sf::Texture& tilesheet);
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
std::vector<int> m_tile_map;
sf::Vector2u m_tile_size;
sf::Vector2<std::size_t> m_map_size;
std::vector<sf::Sprite> m_sprites;
};
| 27.130435 | 85 | 0.705128 | [
"vector"
] |
a4771c4d9b435163bae4093d61cd1edc782ce16a | 2,948 | cpp | C++ | window.cpp | Kepler-Br/SDLRayMarching | 5d6487ce0603eaa88e9b9d898bc86b76a814eeda | [
"MIT"
] | 1 | 2019-05-17T14:17:23.000Z | 2019-05-17T14:17:23.000Z | window.cpp | Kepler-Br/SDLRayMarching | 5d6487ce0603eaa88e9b9d898bc86b76a814eeda | [
"MIT"
] | null | null | null | window.cpp | Kepler-Br/SDLRayMarching | 5d6487ce0603eaa88e9b9d898bc86b76a814eeda | [
"MIT"
] | null | null | null | #include "window.h"
#include <iostream>
void Window::init(const glm::ivec2 &geometry)
{
this->geometry = geometry;
if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 )
{
std::cout << "Unable to init SDL, error: " << SDL_GetError() << std::endl;
exit(1);
}
SDL_CreateWindowAndRenderer(geometry.x, geometry.y, SDL_WINDOW_SHOWN, &window, &renderer);
if(window == nullptr || renderer == nullptr)
{
std::cout << "Unable to create window: " << SDL_GetError() << std::endl;
exit(1);
}
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
Window::Window(const glm::ivec2 &geometry, const std::string &windowTitle)
{
init(geometry);
setWindowTitle(windowTitle);
}
Window::Window(const int x, const int y, const std::string &windowTitle)
{
init(glm::ivec2(x, y));
setWindowTitle(windowTitle);
}
Window::~Window()
{
if(renderer != nullptr)
SDL_DestroyRenderer(renderer);
if(window != nullptr)
SDL_DestroyWindow(window);
SDL_Quit();
}
void Window::setWindowTitle(const std::string &title)
{
SDL_SetWindowTitle(window, title.c_str());
}
void Window::setWindowPosition(const glm::ivec2 &position)
{
SDL_SetWindowPosition(window, position.x, position.y);
}
const glm::ivec2 Window::getGeometry() const
{
return geometry;
}
void Window::setPixel(const glm::ivec2 &position, const glm::vec3 &color)
{
if(position.x >= geometry.x ||
position.y >= geometry.y)
return;
SDL_SetRenderDrawColor(renderer, static_cast<Uint8>(color.r*255),
static_cast<Uint8>(color.g*255),
static_cast<Uint8>(color.b*255),
255);
SDL_RenderDrawPoint(renderer, position.x, position.y);
}
void Window::setPixel(const glm::ivec2 &position, const glm::ivec3 &color)
{
if(position.x >= geometry.x ||
position.y >= geometry.y)
return;
SDL_SetRenderDrawColor(renderer, static_cast<Uint8>(color.r),
static_cast<Uint8>(color.g),
static_cast<Uint8>(color.b),
255);
SDL_RenderDrawPoint(renderer, position.x, position.y);
}
void Window::clear(const glm::vec3 &color)
{
SDL_SetRenderDrawColor(renderer, static_cast<Uint8>(color.r*255),
static_cast<Uint8>(color.g*255),
static_cast<Uint8>(color.b*255),
255);
SDL_RenderClear(renderer);
}
void Window::clear(const glm::ivec3 &color)
{
SDL_SetRenderDrawColor(renderer, static_cast<Uint8>(color.r),
static_cast<Uint8>(color.g),
static_cast<Uint8>(color.b),
255);
SDL_RenderClear(renderer);
}
void Window::clear()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
}
| 27.811321 | 94 | 0.60787 | [
"geometry"
] |
a477e20f7e3b7ad1b19bf7200a65b337499c4e22 | 4,957 | cpp | C++ | webkit/Source/WebKit/android/nav/SelectText.cpp | mogoweb/webkit_for_android5.1 | 63728b4ae4c494011e8e43a466637c826f0f6b5f | [
"Apache-2.0"
] | 2 | 2017-05-19T08:53:12.000Z | 2017-08-28T11:59:26.000Z | webkit/Source/WebKit/android/nav/SelectText.cpp | mogoweb/webkit_for_android5.1 | 63728b4ae4c494011e8e43a466637c826f0f6b5f | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | webkit/Source/WebKit/android/nav/SelectText.cpp | mogoweb/webkit_for_android5.1 | 63728b4ae4c494011e8e43a466637c826f0f6b5f | [
"Apache-2.0"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | /*
* Copyright 2008, The Android Open Source Project
*
* 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.
*
* 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.
*/
#define LOG_TAG "webviewglue"
#include "config.h"
#include "BidiResolver.h"
#include "BidiRunList.h"
#include "GLExtras.h"
#include "LayerAndroid.h"
#include "SelectText.h"
#include "SkBitmap.h"
#if ENABLE(OLD_SKIA)
#include "SkBounder.h"
#endif
#include "SkCanvas.h"
#include "SkPicture.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkRegion.h"
#include "TextRun.h"
#ifdef DEBUG_NAV_UI
#include <wtf/text/CString.h>
#endif
#define VERBOSE_LOGGING 0
// #define EXTRA_NOISY_LOGGING 1
#define DEBUG_TOUCH_HANDLES 0
#if DEBUG_TOUCH_HANDLES
#define DBG_HANDLE_LOG(format, ...) ALOGD("%s " format, __FUNCTION__, __VA_ARGS__)
#else
#define DBG_HANDLE_LOG(...)
#endif
// TextRunIterator has been copied verbatim from GraphicsContext.cpp
namespace WebCore {
class TextRunIterator {
public:
TextRunIterator()
: m_textRun(0)
, m_offset(0)
{
}
TextRunIterator(const TextRun* textRun, unsigned offset)
: m_textRun(textRun)
, m_offset(offset)
{
}
TextRunIterator(const TextRunIterator& other)
: m_textRun(other.m_textRun)
, m_offset(other.m_offset)
{
}
unsigned offset() const { return m_offset; }
void increment() { m_offset++; }
bool atEnd() const { return !m_textRun || m_offset >= m_textRun->length(); }
UChar current() const { return (*m_textRun)[m_offset]; }
WTF::Unicode::Direction direction() const { return atEnd() ? WTF::Unicode::OtherNeutral : WTF::Unicode::direction(current()); }
bool operator==(const TextRunIterator& other)
{
return m_offset == other.m_offset && m_textRun == other.m_textRun;
}
bool operator!=(const TextRunIterator& other) { return !operator==(other); }
private:
const TextRun* m_textRun;
int m_offset;
};
// ReverseBidi is a trimmed-down version of GraphicsContext::drawBidiText()
void ReverseBidi(UChar* chars, int len) {
using namespace WTF::Unicode;
WTF::Vector<UChar> result;
result.reserveCapacity(len);
TextRun run(chars, len);
BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
bidiResolver.setStatus(BidiStatus(LeftToRight, LeftToRight, LeftToRight,
BidiContext::create(0, LeftToRight, false)));
bidiResolver.setPosition(TextRunIterator(&run, 0));
bidiResolver.createBidiRunsForLine(TextRunIterator(&run, len));
if (!bidiRuns.runCount())
return;
BidiCharacterRun* bidiRun = bidiRuns.firstRun();
while (bidiRun) {
int bidiStart = bidiRun->start();
int bidiStop = bidiRun->stop();
int size = result.size();
int bidiCount = bidiStop - bidiStart;
result.append(chars + bidiStart, bidiCount);
if (bidiRun->level() % 2) {
UChar* start = &result[size];
UChar* end = start + bidiCount;
// reverse the order of any RTL substrings
while (start < end) {
UChar temp = *start;
*start++ = *--end;
*end = temp;
}
start = &result[size];
end = start + bidiCount - 1;
// if the RTL substring had a surrogate pair, restore its order
while (start < end) {
UChar trail = *start++;
if (!U16_IS_SURROGATE(trail))
continue;
start[-1] = *start; // lead
*start++ = trail;
}
}
bidiRun = bidiRun->next();
}
bidiRuns.deleteRuns();
memcpy(chars, &result[0], len * sizeof(UChar));
}
}
| 33.268456 | 131 | 0.66633 | [
"vector"
] |
a47b260284884eb97bf59b5a2e49dbaa89e2f109 | 2,946 | cpp | C++ | Section 4.2b/Exercise42b4/Exercise42b4/Main.cpp | scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate | 79c2fb297a85c914d5f0b8671bb17636801e3ce7 | [
"MIT"
] | 1 | 2021-11-05T08:14:37.000Z | 2021-11-05T08:14:37.000Z | Section 4.2b/Exercise42b4/Exercise42b4/Main.cpp | scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate | 79c2fb297a85c914d5f0b8671bb17636801e3ce7 | [
"MIT"
] | null | null | null | Section 4.2b/Exercise42b4/Exercise42b4/Main.cpp | scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate | 79c2fb297a85c914d5f0b8671bb17636801e3ce7 | [
"MIT"
] | null | null | null | // Exercise 4.2b.4 - Stack Class (composition)
//
// by Scott Sidoli
//
// 5-24-19
//
// Main.cpp
//
// In this exercise, we made a stack class. We use data storage from the array class, but we do not derive
// from the array class because there is functionality from the array class that we do not wish to include
// in the stack class. Instead we include an Array<T> as a data member in the stack class. This is called
// composition. The function of data storage is delegated to the array class. We add source file and header
// file. We include additional functionality of Push() and Pop(). The Push() function stores the element at
// the current position of the embedded array, then increments the current position forward. Pop()
// decrements the current position and then returns the element at that position. In either case, the index
// is unchanged if Array throws and exception. We test the stack class in main.cpp.
#include "Point.hpp"
#include "Array.hpp"
#include "Stack.hpp"
#include <iostream>
#include <iomanip>
using namespace ssidoli::CAD;
using namespace ssidoli::Containers;
int main()
{
// Create stack objects for tests
Stack<int> intstack1; // Default constructor
Stack<int> intstack2(6); // Stack of integers of size 5
Stack<int> intstack3(7); // Stack of integers of size 6
// Push elements into the stacks
for (int i = 0; i < 6; i++)
intstack2.Push(i);
for (int i = 0; i < 7; i++)
intstack3.Push(i);
Stack<int> intstack4(intstack3); // Copy constructor
// Pop elements from the stacks
cout << "intstack3 intstack4" << endl;
for (int i = 0; i < 6; i++)
{
cout << setw(5) << intstack3.Pop() << setw(13) << intstack4.Pop() << endl;
}
cout << endl;
// OutOfBound Exception with using Push()
try
{
cout << "i " << "m_current " << "m_array[i]" << endl;
for (int i = 0; i < 1000; i++)
{
intstack1.Push(i);
cout << i << setw(8) << intstack1.GetCurrentIndex()
<< setw(10) << intstack1.GetArrayElement(i) << endl;
}
}
catch (ArrayException& ex)
{
cout << ex.GetMessage() << endl;
}
catch (...)
{
cout << "An unhandled exception has occurred..." << endl;
}
cout << endl;
// OutOfBoundsException using Pop()
try
{
cout << "After Push(), m_current is "
<< intstack1.GetCurrentIndex() << endl;
cout << "i " << "m_array[i] " << "m_current" << endl;
for (int i = 0; i < 100; i++)
{
cout << i << setw(8) << intstack1.Pop()
<< setw(10) << intstack1.GetCurrentIndex() << endl;
}
}
catch (ArrayException& ex)
{
cout << ex.GetMessage() << endl;
}
catch (...)
{
cout << "An unhandled exception has occurred..." << endl;
}
cout << "m_current is set back to " << intstack1.GetCurrentIndex() << endl;
return 0;
} | 29.46 | 108 | 0.602172 | [
"cad"
] |
a47d7e5aeac3f75e556547575294d3451a9fa13b | 2,525 | cpp | C++ | Codes/Set_or_selfBalancingTree/sample-problems/leetCode-532-k-diff-pairs.cpp | fahimfarhan/FarCryCoding | ed9005194736c2b719823683c1295946bcb49910 | [
"MIT"
] | null | null | null | Codes/Set_or_selfBalancingTree/sample-problems/leetCode-532-k-diff-pairs.cpp | fahimfarhan/FarCryCoding | ed9005194736c2b719823683c1295946bcb49910 | [
"MIT"
] | null | null | null | Codes/Set_or_selfBalancingTree/sample-problems/leetCode-532-k-diff-pairs.cpp | fahimfarhan/FarCryCoding | ed9005194736c2b719823683c1295946bcb49910 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findPairsithNonZeroK(vector<int>& nums, int k) {
int pairCount = 0;
unordered_set<int> uset;
for(auto num: nums) {
uset.insert(num);
}
int m = 0;
bool exists = false;
/**
for(auto num: nums) {
m = num + k;
exists = uset.find(m) != uset.end();
if(exists) {
pairCount++;
// it could be counted twice, we should remove these 2 numbers from the set to avoid repeats.
// that could cause errors. let's iterate over the items of the set, not the vector
cout<<"( "<<num<<" , "<<m<<" )\n";
}
}
*/
for(auto num: uset) {
m = num + k;
exists = uset.find(m) != uset.end();
if(exists) {
pairCount++;
cerr<<"( "<<num<<" , "<<m<<" )\n";
}
}
return pairCount;
}
int findPairsithZeroK(vector<int>& nums) {
int pairCount = 0;
unordered_map<int, int> mp;
for(auto num: nums) {
mp[num]++;
}
for(auto num: nums) {
if(mp[num] > 1) {
pairCount++;
mp[num] = 0; // else the same pair will be counted multiple times!
}
}
return pairCount;
}
int findPairs(vector<int>& nums, int k) {
if(k == 0) {
return findPairsithZeroK(nums);
}
return findPairsithNonZeroK(nums, k);
}
int findPairsV1(vector<int>& nums, int k) {
int pairCount = 0;
unordered_map<int, int> mp;
for(auto num: nums) {
if(!mp[num]) {
mp[num]++;
}
}
int key1, key2, val1, val2;
for(auto num: nums) {
key1 = num + k;
// key2 = num - k;
val1 = mp[key1];
// val2 = mp[key2];
if(val1) {
pairCount += val1;
}
/*
if(val2) {
pairCount += val2;
}
*/
}
// let [3, ... ... 1, ...], for loop calcs 3-1=k, 3-1=-k, 1-3=k, 1-3=-k, ie,
// each element is added twice. hence divide by 2
/** pairCount /= 2; */
// alternatively, comment out key2, val2 part. then you don't need to divide by 2.
return pairCount;
}
};
int main() {
Solution s;
vector<int> input = {3,1,4,1,5};
cout<<s.findPairs(input, 2)<<"\n-------------------\n";
vector<int> in2 = {1,2,3,4,5};
cout<<s.findPairs(in2, 1)<<"\n-------------------\n";
vector<int> in3 = {1,3,1,5,4};
cout<<s.findPairs(in3, 0)<<"\n-------------------\n";
return 0;
} | 20.696721 | 103 | 0.481584 | [
"vector"
] |
a48a8a088ae4ae2a7ccbdd47de75bceb19f57dc4 | 114,475 | cpp | C++ | Nyancat.cpp | huydx/NyanNyan | 740c91af88946d15ce8bc5f68bba5197c1da2735 | [
"MIT"
] | 10 | 2015-07-31T02:28:30.000Z | 2021-06-12T15:49:49.000Z | Nyancat.cpp | huydx/NyanNyan | 740c91af88946d15ce8bc5f68bba5197c1da2735 | [
"MIT"
] | null | null | null | Nyancat.cpp | huydx/NyanNyan | 740c91af88946d15ce8bc5f68bba5197c1da2735 | [
"MIT"
] | null | null | null | /****
*
*
* nyancat part
*
****/
#define _DARWIN_C_SOURCE 1
#define __BSD_VISIBLE 1
#include <ctype.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <setjmp.h>
#include <getopt.h>
#include <sys/ioctl.h>
#ifndef TIOCGWINSZ
#include <termios.h>
#endif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'***''''****',,,,,,,,,,,,,,,,,,,,,",
"+++++++++++++++'**'''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,,,,",
"#######++++++++''**''@$$$$$$-'*************',,,,,,,,,,,,,,,,,,,,",
"################''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,,,,",
"#################''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,,,,",
"=======########====''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,,,,",
"===================='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,,,,",
";;;;;;;.=======;;;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,,,,",
",,,,.,,;;;.;;;;,,,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,",
"++++++++''**''@$$$$$$-'*************',,,,,,,,,,,,,,,,,,,,,,,,,,,",
"#########''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,,,,,,,,,,,",
"##########''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,,,,,,,,,,,",
"########====''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,,,,,,,,,,,",
"============='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,,,,,,,,,,,",
".=======;;;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;.;;;;,,,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,",
"####''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"#####''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"###====''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"========'@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"===;;;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;;;;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;;;;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;,,,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"#''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"===''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
"===='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
";;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,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,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,",
",,>>>>>>>>,,,,,,,,>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,",
">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,",
">>&&&&&&&&>>>>>>>>&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',,,,,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$'**'$$$@''**',,,,,,,,,,,,,,,,,,",
"&&++++++++&&&&&&&&'''++'@$$$$$-$$'***$$$@'***',,,,,,,,,,,,,,,,,,",
"++++++++++++++++++**''+'@$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,,",
"++++++++++++++++++'**'''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,",
"++########++++++++''**''@$$$$$$-'*************',,,,,,,,,,,,,,,,,",
"###################''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,",
"####################''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,",
"##========########====''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,",
"======================='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,",
"==;;;;;;;;.=======;;;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,",
";;,,,,,.,,;;;.;;;;,,,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,",
">>>>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,",
">>>>&&&&&&&&>>>>>>>>&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,",
"&&&&++++++++&&&&&&&&+++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,",
"+++++++++++++++++++++'+++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,",
"++++++++++++++++++++'*'++'@$$$$$$$$$'***********',,,,,,,,,,,,,,,",
"++++########++++++++'*''''@$$$$$$-$'*************',,,,,,,,,,,,,,",
"#####################****'@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,",
"#####################''**'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,",
"####========########==='''@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,",
"========================='@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,",
"====;;;;;;;;========;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;'**','*',,,,,,**','**',,,,,,,,,,,,,,,,,,",
";;;;,,,.,,,,;;;;;;;;,,,,''',,,'',,,,,,''',,''',,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,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>>>>>>>&&&&&&&&>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,",
"++&&++&&&&&&&++++++++&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,",
"+++++++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,",
"+++++++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,",
"##++##+++++++########++++++'@$$$$$$$$$'***********',,,,,,,,,,,,,",
"##########################''@$$$$$$-$'*************',,,,,,,,,,,,",
"#######################'''''@$-$$$$$$'***.'****.'**',,,,,,,,,,,,",
"==##==#######========#'****'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,",
"======================='''='@@$$$-$$$'*%%********%%',,,,,,,,,,,,",
";;==;;=======;;;;;;;;======'@@@$$$$$$$'***''''''**',,,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,",
";.;;;.;;;;;;;;;;;;;;;;;;;;;'*'''''''''''''''''''',,,,,,,,,,,,,,,",
".,.;.,.;;;;;;,,,,,,,,;;;;;;'**',**',,,,,,**','**',,,,,,,,,,,,,,,",
",.,,,.,,,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,",
"++&&&&++&&&&&&&++++++++&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,",
"+++++++++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,",
"+++++++++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,",
"##++++##+++++++########++++++'@$$$$$$$$$'***********',,,,,,,,,,,",
"###########################'''@$$$$$$-$'*************',,,,,,,,,,",
"#########################''**'@$-$$$$$$'***.'****.'**',,,,,,,,,,",
"==####==#######========##****'@$$$$$$$$'***''**'*''**',,,,,,,,,,",
"========================'*'=='@@$$$-$$$'*%%********%%',,,,,,,,,,",
";;====;;=======;;;;;;;;=='==='@@@$$$$$$$'***''''''**',,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,",
",,;;;;,,;;;;;;;,,,,,,,,;;;;;'**','*',,,,,,'*','**',,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,,'',,,,,,,'',,''',,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,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,,,,",
"++++++++++++++++++++++++++++++++'@$$$$$-$$'***$$$@'***',,,,,,,,,",
"+++++++++++++++++++++++++++'''++'@$$$$$$$$'***''''****',,,,,,,,,",
"++++++###########+#+++++++'**''''@$$$$$$$$'***********',,,,,,,,,",
"##########################'****''@$$$$$$-'*************',,,,,,,,",
"###########################''''*'@$-$$$$$'***.'****.'**',,,,,,,,",
"######===========#=########==='''@$$$$$$$'***''**'*''**',,,,,,,,",
"================================'@@$$$-$$'*%%********%%',,,,,,,,",
"======;;;;;;;;;;;=;========;;;;''@@@$$$$$$'***''''''**',,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;''''@@@@@@@@@'*********',,,,,,,,,,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;'***'''''''''''''''''''',,,,,,,,,,,",
";;;;;;,,,,,,,,,,,;,;;;;;;;;,,'**','**,,,,,,'**,'**',,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,,'',,,,,,,'',,''',,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,>>>>>>>>,,,,,>>>>>>>>,,,,,,,,>>>>>>>''''''''''''''',,,,,,,,,,",
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,",
">>>&&&&&&&&>>>>>&&&&&&&&>>>>>>>>&&&&&'@@@$$$$$$$$$$$@@@',,,,,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$''$$$@@','',,,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$'**'-$$@''**',,,,",
"&&&++++++++&&&&&++++++++&&&&&&&&+++++'@$$$$$$$$'***$$$@'***',,,,",
"+++++++++++++++++++++++++++++++++'+++'@$$$$$-$$'***''''****',,,,",
"++++++++++++++++++++++++++++++++'*'++'@$$$$$$$$'***********',,,,",
"+++########+++++########++++++++'*''''@$$$$$$$'*************,,,,",
"#################################****'@$$$$$$-'***.'****.'**,,,,",
"#################################''**'@$-$$$$$'***''**'*''**,,,,",
"###========#####========########==='''@$$$$$$$'*%%********%%,,,,",
"====================================='@@$$$-$$$'***''''''**',,,,",
"===;;;;;;;;=====;;;;;;;;========;;;;''@@@$$$$$$$'*********',,,,.",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'*''@@@@@@@@@@''''''''',,,,,.",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'***''''''''''''''''*',,,,,,,,",
";;;,,,,,,,,;;;;;,,,,,,,,;;;;;;;;,,'**','**,,,,,,'**,'**',,,,..,.",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,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",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,",
",,,,,,>>>>>>>>,,,,>>,,,,,,,>>>>>>>>,,,,,,,'@@@@@@@@@@@@@@@',,,,,",
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,",
">>>>>>&&&&&&&&>>>>&&>>>>>>>&&&&&&&&>>>>>>'@@$$$$$-$$-$$$$@@',,,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$'**'$$$@''**'",
"&&&&&&++++++++&&&&++&&&&&&&++++++++&'''&&'@$$$$$-$$'***$$$@'***'",
"++++++++++++++++++++++++++++++++++++'*''+'@$$$$$$$$'***''''****'",
"++++++++++++++++++++++++++++++++++++'**'''@$$$$$$$$'***********'",
"++++++########++++##+++++++########++'**''@$$$$$$-'*************",
"#####################################''**'@$-$$$$$'***.'****.'**",
"######################################''''@$$$$$$$'***''**'*''**",
"######========####==#######========#####''@@$$$-$$'*%%********%%",
"========================================='@@@$$$$$$'***''''''**'",
"======;;;;;;;;====;;=======;;;;;;;;====='''@@@@@@@@@'*********',",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'***''''''''''''''''''',,",
";;;;;;;;;;;;;;;;;;;;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,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
">>>>>>,,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''',,,,,,,,,,,,,,,,,,,,",
">>>>>>,,,,,,,>>>>>>>>,,,,,,,>>>>>>>>,,,,,,,'@@@@@@@@@@@@@@@',,,,",
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,",
"&&&&&&>>>>>>>&&&&&&&&>>>>>>>&&&&&&&&>>>>>>'@@$$$$$-$$-$$$$@@',,,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$$'**'$$@','*",
"++++++&&&&&&&++++++++&&&&&&&++++++++&&&&&&'@$$$$$-$$$'***$$@''**",
"++++++++++++++++++++++++++++++++++++++++++'@$$$$$$$$$'***''''***",
"++++++++++++++++++++++++++++++++++++++++++'@$$$$$$$$$'**********",
"######+++++++########+++++++########++++++'@$$$$$$-$'***********",
"##########################################'@$-$$$$$$'***.'****.'",
"##########################################'@$$$$$$$$'***''**'*''",
"======#######========#######========######'@@$$$-$$$'*%%********",
"=========================================='@@@$$$$$$$'***''''''*",
";;;;;;=======;;;;;;;;=======;;;;;;;;======''@@@@@@@@@@'*********",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;**''''''''''''''''''''",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;**','*',,,,,,**','**',",
",,,,,,;;;;;;;,,,,,,,,;;;;;;;,,,,,,,,;;;;;;'',,,'',,,,,,''',,''',",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,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''''''",
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@",
">>>>>>>>>>&&&&&&&&&&>>>>>>>>&&&&&&&&>>>>>>>>&&&&&'@@@$$$$$$$$$$$",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-",
"&&&&&&&&&&++++++++++&&&&&&&&++++++++&&&&&&&&+++++'@$$$$$$$$$'**'",
"+++++++++++++++++++++++++++++++++++++++++++++++++'@$$$$$-$$$'***",
"+++++++++++++++++++++++++++++++++++++++++++++++++'@$$$$$$$$$'***",
"++++++++++##########++++++++########++++++++#####'@$$$$$$$$$'***",
"################################################''@$$$$$$-$'****",
"#############################################'''''@$-$$$$$$'***.",
"##########==========########========########'****'@$$$$$$$$'***'",
"============================================='''='@@$$$-$$$'*%%*",
"==========;;;;;;;;;;========;;;;;;;;========;;;;;'@@@$$$$$$$'***",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'**",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'*'''''''''''''",
";;;;;;;;;;,,,,,,,,,,;;;;;;;;,,,,,,,,;;;;;;;;,,,,,'**',**',,,,,,*",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,''',,,,,,'",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,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&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@@$$",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'@$$-",
"&&&&&&++++++++&&&&&&&&++++++++&&&&&&&&++++++++&&&&&&&&+++++'@$$$",
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'@$$$",
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++'@$$$",
"++++++########++++++++########++++++++########++++++++#####'@$$$",
"#########################################################'''@$$$",
"#######################################################''**'@$-$",
"######========########========########========########=****'@$$$",
"======================================================'*'=='@@$$",
"======;;;;;;;;========;;;;;;;;========;;;;;;;;========;';;;'@@@$",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;''@@@",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'**'''",
";;;;;;,,,,,,,,;;;;;;;;,,,,,,,,;;;;;;;;,,,,,,,,;;;;;;;;,,,,'**','",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,.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++++++++++++++++++++++++++++++++++++++++++'''+",
"++++++++#######+++++++#######+++++++########+++++++########'**''",
"###########################################################'****",
"############################################################''''",
"########=======#######=======#######========#######========####'",
"================================================================",
"========;;;;;;;=======;;;;;;;=======;;;;;;;;=======;;;;;;;;=====",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;'*",
";;;;;;;;,,,,,,,;;;;;;;,,,,,,,;;;;;;;,,,,,,,,;;;;;;;,,,,,,,,;;;'*",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,''',,,''",
",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
".,.,.,,,,,,,,,,,,,,,,,,,,,,,,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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
">>>>>>>>>>,,,,,,,>>>>>>>,,,,,,,>>>>>>>,,,,,,,>>>>>>>>,,,,,,,>>>,",
">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>,",
"&&&&&&&&&&>>>>>>>&&&&&&&>>>>>>>&&&&&&&>>>>>>>&&&&&&&&>>>>>>>&&&,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&,",
"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&,",
"++++++++++&&&&&&&+++++++&&&&&&&+++++++&&&&&&&++++++++&&&&&&&+++,",
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,",
"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,",
"##########+++++++#######+++++++#######+++++++########+++++++###,",
"###############################################################,",
"###############################################################,",
"==========#######=======#######=======#######========#######===,",
"===============================================================,",
";;;;;;;;;;=======;;;;;;;=======;;;;;;;=======;;;;;;;;=======;;;,",
";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,",
";;;;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,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",
",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"};
const char ** frames[] = {
frame010,
frame09,
frame08,
frame07,
frame06,
frame05,
frame04,
frame03,
frame02,
frame01,
frame00,
frame0,
frame1,
frame2,
frame3,
frame4,
frame5,
frame6,
frame7,
frame8,
frame9,
frame10,
frame11,
NULL
};
#define FRAME_WIDTH 64
#define FRAME_HEIGHT 64
/*
* Color palette to use for final output
* Specifically, this should be either control sequences
* or raw characters (ie, for vt220 mode)
*/
const char * colors[256] = {NULL};
/*
* For most modes, we output spaces, but for some
* we will use block characters (or even nothing)
*/
const char * output = " ";
/*
* Are we currently in telnet mode?
*/
int telnet = 0;
/*
* Whether or not to show the counter
*/
int show_counter = 1;
/*
* Number of frames to show before quitting
* or 0 to repeat forever (default)
*/
unsigned int frame_count = 0;
/*
* Clear the screen between frames (as opposed to reseting
* the cursor position)
*/
int clear_screen = 1;
/*
* Force-set the terminal title.
*/
int set_title = 1;
/*
* Environment to use for setjmp/longjmp
* when breaking out of options handler
*/
jmp_buf environment;
/*
* I refuse to include libm to keep this low
* on external dependencies.
*
* Count the number of digits in a number for
* use with string output.
*/
int digits(int val) {
int d = 1, c;
if (val >= 0) for (c = 10; c <= val; c *= 10) d++;
else for (c = -10 ; c >= val; c *= 10) d++;
return (c < 0) ? ++d : d;
}
/*
* These values crop the animation, as we have a full 64x64 stored,
* but we only want to display 40x24 (double width).
*/
int min_row = -1;
int max_row = -1;
int min_col = -1;
int max_col = -1;
/*
* Actual width/height of terminal.
*/
int terminal_width = 80;
int terminal_height = 24;
/*
* Flags to keep track of whether width/height were automatically set.
*/
char using_automatic_width = 0;
char using_automatic_height = 0;
/*
* Print escape sequences to return cursor to visible mode
* and exit the application.
*/
void finish() {
if (clear_screen) {
printf("\033[?25h\033[0m\033[H\033[2J");
} else {
printf("\033[0m\n");
}
exit(0);
}
/*
* In the standalone mode, we want to handle an interrupt signal
* (^C) so that we can restore the cursor and clear the terminal.
*/
void SIGINT_handler(int sig){
(void)sig;
finish();
}
/*
* Handle the alarm which breaks us off of options
* handling if we didn't receive a terminal
*/
void SIGALRM_handler(int sig) {
(void)sig;
alarm(0);
longjmp(environment, 1);
/* Unreachable */
}
/*
* Handle the loss of stdout, as would be the case when
* in telnet mode and the client disconnects
*/
void SIGPIPE_handler(int sig) {
(void)sig;
finish();
}
void SIGWINCH_handler(int sig) {
(void)sig;
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
terminal_width = w.ws_col;
terminal_height = w.ws_row;
if (using_automatic_width) {
min_col = (FRAME_WIDTH - terminal_width/2) / 2;
max_col = (FRAME_WIDTH + terminal_width/2) / 2;
}
if (using_automatic_height) {
min_row = (FRAME_HEIGHT - (terminal_height-1)) / 2;
max_row = (FRAME_HEIGHT + (terminal_height-1)) / 2;
}
signal(SIGWINCH, SIGWINCH_handler);
}
int run_nyan(int frame) {
/* The default terminal is ANSI */
char term[1024] = {'a','n','s','i', 0};
unsigned int k;
int ttype;
if (0) {
//previous telnet
} else {
/* We are running standalone, retrieve the
* terminal type from the environment. */
char * nterm = getenv("TERM");
if (nterm) {
strcpy(term, nterm);
}
/* Also get the number of columns */
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
terminal_width = w.ws_col;
terminal_height = w.ws_row;
}
/* Convert the entire terminal string to lower case */
for (k = 0; k < strlen(term); ++k) {
term[k] = tolower(term[k]);
}
/* Do our terminal detection */
if (strstr(term, "xterm")) {
ttype = 1; /* 256-color, spaces */
} else if (strstr(term, "toaru")) {
ttype = 1; /* emulates xterm */
} else if (strstr(term, "linux")) {
ttype = 3; /* Spaces and blink attribute */
} else if (strstr(term, "vtnt")) {
ttype = 5; /* Extended ASCII fallback == Windows */
} else if (strstr(term, "cygwin")) {
ttype = 5; /* Extended ASCII fallback == Windows */
} else if (strstr(term, "vt220")) {
ttype = 6; /* No color support */
} else if (strstr(term, "fallback")) {
ttype = 4; /* Unicode fallback */
} else if (strstr(term, "rxvt")) {
ttype = 3; /* Accepts LINUX mode */
} else if (strstr(term, "vt100") && terminal_width == 40) {
ttype = 7; /* No color support, only 40 columns */
} else if (!strncmp(term, "st", 2)) {
ttype = 1; /* suckless simple terminal is xterm-256color-compatible */
} else {
ttype = 2; /* Everything else */
}
int always_escape = 0; /* Used for text mode */
/* Accept ^C -> restore cursor */
signal(SIGINT, SIGINT_handler);
/* Handle loss of stdout */
signal(SIGPIPE, SIGPIPE_handler);
/* Handle window changes */
if (!telnet) {
signal(SIGWINCH, SIGWINCH_handler);
}
switch (ttype) {
case 1:
colors[','] = "\033[48;5;17m"; /* Blue background */
colors['.'] = "\033[48;5;231m"; /* White stars */
colors['\''] = "\033[48;5;16m"; /* Black border */
colors['@'] = "\033[48;5;230m"; /* Tan poptart */
colors['$'] = "\033[48;5;175m"; /* Pink poptart */
colors['-'] = "\033[48;5;162m"; /* Red poptart */
colors['>'] = "\033[48;5;196m"; /* Red rainbow */
colors['&'] = "\033[48;5;214m"; /* Orange rainbow */
colors['+'] = "\033[48;5;226m"; /* Yellow Rainbow */
colors['#'] = "\033[48;5;118m"; /* Green rainbow */
colors['='] = "\033[48;5;33m"; /* Light blue rainbow */
colors[';'] = "\033[48;5;19m"; /* Dark blue rainbow */
colors['*'] = "\033[48;5;240m"; /* Gray cat face */
colors['%'] = "\033[48;5;175m"; /* Pink cheeks */
break;
case 2:
colors[','] = "\033[104m"; /* Blue background */
colors['.'] = "\033[107m"; /* White stars */
colors['\''] = "\033[40m"; /* Black border */
colors['@'] = "\033[47m"; /* Tan poptart */
colors['$'] = "\033[105m"; /* Pink poptart */
colors['-'] = "\033[101m"; /* Red poptart */
colors['>'] = "\033[101m"; /* Red rainbow */
colors['&'] = "\033[43m"; /* Orange rainbow */
colors['+'] = "\033[103m"; /* Yellow Rainbow */
colors['#'] = "\033[102m"; /* Green rainbow */
colors['='] = "\033[104m"; /* Light blue rainbow */
colors[';'] = "\033[44m"; /* Dark blue rainbow */
colors['*'] = "\033[100m"; /* Gray cat face */
colors['%'] = "\033[105m"; /* Pink cheeks */
break;
case 3:
colors[','] = "\033[25;44m"; /* Blue background */
colors['.'] = "\033[5;47m"; /* White stars */
colors['\''] = "\033[25;40m"; /* Black border */
colors['@'] = "\033[5;47m"; /* Tan poptart */
colors['$'] = "\033[5;45m"; /* Pink poptart */
colors['-'] = "\033[5;41m"; /* Red poptart */
colors['>'] = "\033[5;41m"; /* Red rainbow */
colors['&'] = "\033[25;43m"; /* Orange rainbow */
colors['+'] = "\033[5;43m"; /* Yellow Rainbow */
colors['#'] = "\033[5;42m"; /* Green rainbow */
colors['='] = "\033[25;44m"; /* Light blue rainbow */
colors[';'] = "\033[5;44m"; /* Dark blue rainbow */
colors['*'] = "\033[5;40m"; /* Gray cat face */
colors['%'] = "\033[5;45m"; /* Pink cheeks */
break;
case 4:
colors[','] = "\033[0;34;44m"; /* Blue background */
colors['.'] = "\033[1;37;47m"; /* White stars */
colors['\''] = "\033[0;30;40m"; /* Black border */
colors['@'] = "\033[1;37;47m"; /* Tan poptart */
colors['$'] = "\033[1;35;45m"; /* Pink poptart */
colors['-'] = "\033[1;31;41m"; /* Red poptart */
colors['>'] = "\033[1;31;41m"; /* Red rainbow */
colors['&'] = "\033[0;33;43m"; /* Orange rainbow */
colors['+'] = "\033[1;33;43m"; /* Yellow Rainbow */
colors['#'] = "\033[1;32;42m"; /* Green rainbow */
colors['='] = "\033[1;34;44m"; /* Light blue rainbow */
colors[';'] = "\033[0;34;44m"; /* Dark blue rainbow */
colors['*'] = "\033[1;30;40m"; /* Gray cat face */
colors['%'] = "\033[1;35;45m"; /* Pink cheeks */
output = "██";
break;
case 5:
colors[','] = "\033[0;34;44m"; /* Blue background */
colors['.'] = "\033[1;37;47m"; /* White stars */
colors['\''] = "\033[0;30;40m"; /* Black border */
colors['@'] = "\033[1;37;47m"; /* Tan poptart */
colors['$'] = "\033[1;35;45m"; /* Pink poptart */
colors['-'] = "\033[1;31;41m"; /* Red poptart */
colors['>'] = "\033[1;31;41m"; /* Red rainbow */
colors['&'] = "\033[0;33;43m"; /* Orange rainbow */
colors['+'] = "\033[1;33;43m"; /* Yellow Rainbow */
colors['#'] = "\033[1;32;42m"; /* Green rainbow */
colors['='] = "\033[1;34;44m"; /* Light blue rainbow */
colors[';'] = "\033[0;34;44m"; /* Dark blue rainbow */
colors['*'] = "\033[1;30;40m"; /* Gray cat face */
colors['%'] = "\033[1;35;45m"; /* Pink cheeks */
output = "\333\333";
break;
case 6:
colors[','] = "::"; /* Blue background */
colors['.'] = "@@"; /* White stars */
colors['\''] = " "; /* Black border */
colors['@'] = "##"; /* Tan poptart */
colors['$'] = "??"; /* Pink poptart */
colors['-'] = "<>"; /* Red poptart */
colors['>'] = "##"; /* Red rainbow */
colors['&'] = "=="; /* Orange rainbow */
colors['+'] = "--"; /* Yellow Rainbow */
colors['#'] = "++"; /* Green rainbow */
colors['='] = "~~"; /* Light blue rainbow */
colors[';'] = "$$"; /* Dark blue rainbow */
colors['*'] = ";;"; /* Gray cat face */
colors['%'] = "()"; /* Pink cheeks */
always_escape = 1;
break;
case 7:
colors[','] = "."; /* Blue background */
colors['.'] = "@"; /* White stars */
colors['\''] = " "; /* Black border */
colors['@'] = "#"; /* Tan poptart */
colors['$'] = "?"; /* Pink poptart */
colors['-'] = "O"; /* Red poptart */
colors['>'] = "#"; /* Red rainbow */
colors['&'] = "="; /* Orange rainbow */
colors['+'] = "-"; /* Yellow Rainbow */
colors['#'] = "+"; /* Green rainbow */
colors['='] = "~"; /* Light blue rainbow */
colors[';'] = "$"; /* Dark blue rainbow */
colors['*'] = ";"; /* Gray cat face */
colors['%'] = "o"; /* Pink cheeks */
always_escape = 1;
terminal_width = 40;
break;
default:
break;
}
if (min_col == max_col) {
min_col = (FRAME_WIDTH - terminal_width/2) / 2;
max_col = (FRAME_WIDTH + terminal_width/2) / 2;
using_automatic_width = 1;
}
if (min_row == max_row) {
min_row = (FRAME_HEIGHT - (terminal_height-1)) / 2;
max_row = (FRAME_HEIGHT + (terminal_height-1)) / 2;
using_automatic_height = 1;
}
if (clear_screen) {
/* Clear the screen */
printf("\033[H\033[2J\033[?25l");
} else {
printf("\033[s");
}
/* Store the start time */
time_t start;
time(&start);
int playing = 1; /* Animation should continue [left here for modifications] */
size_t i = frame; /* Current frame # */
unsigned int f = 0; /* Total frames passed */
char last = 0; /* Last color index rendered */
int y, x; /* x/y coordinates of what we're drawing */
//drawing
{
/* Reset cursor */
if (clear_screen) {
printf("\033[H");
} else {
printf("\033[u");
}
/* Render the frame */
for (y = min_row; y < max_row; ++y) {
for (x = min_col; x < max_col; ++x) {
char color;
if (y > 23 && y < 43 && x < 0) {
/*
* Generate the rainbow tail.
*
* This is done with a pretty simplistic square wave.
*/
int mod_x = ((-x+2) % 16) / 8;
if ((i / 2) % 2) {
mod_x = 1 - mod_x;
}
/*
* Our rainbow, with some padding.
*/
const char *rainbow = ",,>>&&&+++###==;;;,,";
color = rainbow[mod_x + y-23];
if (color == 0) color = ',';
} else if (x < 0 || y < 0 || y >= FRAME_HEIGHT || x >= FRAME_WIDTH) {
/* Fill all other areas with background */
color = ',';
} else {
/* Otherwise, get the color from the animation frame. */
color = frames[i][y][x];
}
if (always_escape) {
/* Text mode (or "Always Send Color Escapes") */
printf("%s", colors[(int)color]);
} else {
if (color != last && colors[(int)color]) {
/* Normal Mode, send escape (because the color changed) */
last = color;
printf("%s%s", colors[(int)color], output);
} else {
/* Same color, just send the output characters */
printf("%s", output);
}
}
}
}
/* Reset the last color so that the escape sequences rewrite */
last = 0;
/* Update frame count */
++f;
if (frame_count != 0 && f == frame_count) {
finish();
}
++i;
if (!frames[i]) {
/* Loop animation */
i = 0;
}
}
return 0;
}
/*******************************/
| 56.225442 | 82 | 0.067106 | [
"render"
] |
a48bda15d7f64762afb266c7ea3d49e57fdeba86 | 21,478 | cpp | C++ | practica2/ProyectosIG_x64_VS2019_FG/IG1App/Mesh.cpp | FRYoussef/openGL-scenes | e9a79d45956e9c41aa038fb4710a0590b3bc8f48 | [
"MIT"
] | null | null | null | practica2/ProyectosIG_x64_VS2019_FG/IG1App/Mesh.cpp | FRYoussef/openGL-scenes | e9a79d45956e9c41aa038fb4710a0590b3bc8f48 | [
"MIT"
] | null | null | null | practica2/ProyectosIG_x64_VS2019_FG/IG1App/Mesh.cpp | FRYoussef/openGL-scenes | e9a79d45956e9c41aa038fb4710a0590b3bc8f48 | [
"MIT"
] | null | null | null | #include "Mesh.h"
#include "CheckML.h"
#include <fstream>
#include <gtc/matrix_transform.hpp>
#include <iostream>
using namespace std;
using namespace glm;
//-------------------------------------------------------------------------
void Mesh::draw() const
{
glDrawArrays(mPrimitive, 0, size()); // primitive graphic, first index and number of elements to be rendered
/* EJERCICIO 8
if (vIndexes.empty()) {
glDrawArrays(mPrimitive, 0, size()); // primitive graphic, first index and number of elements to be rendered
}
else {
unsigned int stripIndices[10];
for (int i = 0; i < 10; i++) {
stripIndices[i] = vIndexes[i];
}
glDrawElements(mPrimitive, 10, GL_UNSIGNED_INT, stripIndices);
}*/
}
//-------------------------------------------------------------------------
void Mesh::render() const
{
if (vVertices.size() > 0) { // transfer data
// transfer the coordinates of the vertices
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_DOUBLE, 0, vVertices.data()); // number of coordinates per vertex, type of each coordinate, stride, pointer
if (vColors.size() > 0) { // transfer colors
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_DOUBLE, 0, vColors.data()); // components number (rgba=4), type of each component, stride, pointer
}
if (vTexCoords.size() > 0) { // transfer colors
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_DOUBLE, 0, vTexCoords.data()); // components number (rgba=4), type of each component, stride, pointer
}
if(vNormals.size() > 0){
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_DOUBLE, 0, vNormals.data());
}
draw();
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
}
//-------------------------------------------------------------------------
Mesh * Mesh::createRGBAxes(GLdouble l)
{
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_LINES;
mesh->mNumVertices = 6;
mesh->vVertices.reserve(mesh->mNumVertices);
// X axis vertices
mesh->vVertices.emplace_back(0.0, 0.0, 0.0);
mesh->vVertices.emplace_back(l, 0.0, 0.0);
// Y axis vertices
mesh->vVertices.emplace_back(0, 0.0, 0.0);
mesh->vVertices.emplace_back(0.0, l, 0.0);
// Z axis vertices
mesh->vVertices.emplace_back(0.0, 0.0, 0.0);
mesh->vVertices.emplace_back(0.0, 0.0, l);
mesh->vColors.reserve(mesh->mNumVertices);
// X axis color: red (Alpha = 1 : fully opaque)
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
// Y axis color: green
mesh->vColors.emplace_back(0.0, 1.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 1.0, 0.0, 1.0);
// Z axis color: blue
mesh->vColors.emplace_back(0.0, 0.0, 1.0, 1.0);
mesh->vColors.emplace_back(0.0, 0.0, 1.0, 1.0);
return mesh;
}
//-------------------------------------------------------------------------
Mesh* Mesh::generatePolygon(GLuint numL, GLdouble rd) {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_LINE_LOOP;
mesh->mNumVertices = numL;
mesh->vVertices.reserve(mesh->mNumVertices);
GLdouble vertex_X = 0;
GLdouble vertex_Y = 0;
GLdouble ang = 90.0;
GLdouble incr = 360.0 / numL;
for (int i = 0; i < numL; i++) {
vertex_X = rd * cos(radians(ang));
vertex_Y = rd * sin(radians(ang));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, 0.0);
ang += incr;
}
return mesh;
}
Mesh* Mesh::generateSierpinski(GLuint numP, GLdouble rd) {
Mesh* triangle = generatePolygon(3, rd);
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_POINTS;
mesh->mNumVertices = numP;
mesh->vVertices.reserve(mesh->mNumVertices);
mesh->vVertices = triangle->vVertices;
dvec3 p0 = mesh->vVertices[rand() % 2];
dvec3 p1 = mesh->vVertices[2];
mesh->vVertices.emplace_back((p0.x + p1.x) / 2,
(p0.y + p1.y) / 2,
(p0.z + p1.z) / 2);
for (int i = 4; i < numP; i++)
{
p0 = mesh->vVertices[rand() % 3];
p1 = mesh->vVertices[i-1];
mesh->vVertices.emplace_back((p0.x + p1.x) / 2,
(p0.y + p1.y) / 2,
(p0.z + p1.z) / 2);
}
delete triangle; triangle = nullptr;
return mesh;
}
Mesh* Mesh::generateTriangleRGB(GLdouble rd) {
Mesh* triangle = generatePolygon(3, rd);
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLES;
mesh->mNumVertices = 3;
mesh->vVertices = triangle->vVertices;
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 1.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 0.0, 1.0, 1.0);
return mesh;
}
Mesh* Mesh::generateRectangle(GLdouble w, GLdouble h) {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_STRIP;
mesh->mNumVertices = 4;
mesh->vVertices.reserve(mesh->mNumVertices);
/*GLdouble vertex_X = 0;
GLdouble vertex_Y = 0;
// circle diagonals
GLdouble ang[4] = {135, 225, 45, 315};
for (int i = 0; i < 4; i++) {
vertex_X = w * cos(radians(ang[i]));
vertex_Y = h * sin(radians(ang[i]));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, 0.0);
}*/
mesh->vVertices.emplace_back(-(w / 2), 0, (h / 2));
mesh->vVertices.emplace_back((w / 2), 0, (h / 2));
mesh->vVertices.emplace_back(-(w / 2), 0, -(h / 2));
mesh->vVertices.emplace_back((w / 2), 0, -(h / 2));
return mesh;
}
Mesh* Mesh::generateRGBRectangle(GLdouble w, GLdouble h) {
Mesh* rectangle = generateRectangle(w, h);
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_STRIP;
mesh->mNumVertices = rectangle->mNumVertices;
mesh->vVertices.reserve(mesh->mNumVertices);
mesh->vVertices = rectangle->vVertices;
mesh->vColors.emplace_back(0.11764, 0.5647, 1.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.3882, 0.2784, 1.0);
mesh->vColors.emplace_back(0.5960, 0.9843, 0.5961, 1.0);
mesh->vColors.emplace_back(0.11764, 0.5647, 1.0, 1.0);
return mesh;
}
Mesh* Mesh::generate3DStar(GLdouble re, GLdouble np, GLdouble h) {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_FAN;
mesh->mNumVertices = 2 * np + 2;
mesh->vVertices.reserve(mesh->mNumVertices);
GLdouble ri = re / 2;
GLdouble vertex_X = 0;
GLdouble vertex_Y = 0;
GLdouble ang = 90.0;
GLdouble incr = 360.0 / np;
//Center
mesh->vVertices.emplace_back(0.0, 0.0, 0.0);
for (int i = 0; i < np; i++) {
vertex_X = re * cos(radians(ang));
vertex_Y = re * sin(radians(ang));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, h);
vertex_X = ri * cos(radians((ang + ang + incr) / 2));
vertex_Y = ri * sin(radians((ang + ang + incr) / 2));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, h);
ang += incr;
}
// First vertex
mesh->vVertices.emplace_back(mesh->vVertices[1].x, mesh->vVertices[1].y, h);
return mesh;
}
Mesh* Mesh::generateStarTexCoord(GLdouble re, GLuint np, GLdouble h) {
Mesh* mesh = generate3DStar(re, np, h);
mesh->vTexCoords.reserve(mesh->mNumVertices);
GLdouble ri = 0.25;
GLdouble c = 0.5;
GLdouble vertex_X = 0;
GLdouble vertex_Y = 0;
GLdouble ang = 90.0;
GLdouble incr = 360.0 / np;
re = 0.5;
mesh->vTexCoords.emplace_back(c, c);
for (int i = 0; i < np; i++) {
vertex_X = c + re * cos(radians(ang));
vertex_Y = c + re * sin(radians(ang));
mesh->vTexCoords.emplace_back(vertex_X, vertex_Y);
vertex_X = c + ri * cos(radians((ang + ang + incr) / 2));
vertex_Y = c + ri * sin(radians((ang + ang + incr) / 2));
mesh->vTexCoords.emplace_back(vertex_X, vertex_Y);
ang += incr;
}
// First vertex
mesh->vTexCoords.emplace_back(mesh->vTexCoords[1].x, mesh->vTexCoords[1].y);
return mesh;
}
Mesh* Mesh::generateRectangleTexCoord(GLdouble w, GLdouble h, GLuint rw, GLuint rh) {
Mesh* mesh = generateRectangle(w, h);
mesh->vTexCoords.reserve(mesh->mNumVertices);
mesh->vTexCoords.emplace_back(0.0, rh);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(rw, rh);
mesh->vTexCoords.emplace_back(rw, 0.0);
return mesh;
}
Mesh* Mesh::generateContCube(GLdouble ld) {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_STRIP;
mesh->mNumVertices = 14;
mesh->vVertices.reserve(mesh->mNumVertices);
GLdouble size = ld / 2;
//V0
mesh->vVertices.emplace_back(-size, size, size);
//V1
mesh->vVertices.emplace_back(-size, -size, size);
//V2
mesh->vVertices.emplace_back(size, size, size);
//V3
mesh->vVertices.emplace_back(size, -size, size);
//V4
mesh->vVertices.emplace_back(size, size, -size);
//V5
mesh->vVertices.emplace_back(size, -size, -size);
//V6
mesh->vVertices.emplace_back(-size, size, -size);
//V7
mesh->vVertices.emplace_back(-size, -size, -size);
mesh->vVertices.emplace_back(mesh->vVertices[0]);
mesh->vVertices.emplace_back(mesh->vVertices[1]);
// suelo
mesh->vVertices.emplace_back(mesh->vVertices[1]);
mesh->vVertices.emplace_back(mesh->vVertices[7]);
mesh->vVertices.emplace_back(mesh->vVertices[3]);
mesh->vVertices.emplace_back(mesh->vVertices[5]);
return mesh;
}
Mesh* Mesh::generateBoxTextCoord(GLdouble nl) {
Mesh* mesh = generateContCube(nl);
mesh->vTexCoords.reserve(mesh->mNumVertices);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
return mesh;
}
vector<Mesh*> Mesh::generate3dObject(GLuint times, GLdouble w, GLdouble h) {
vector<Mesh*> gMesh;
GLdouble vertex_X = 0, vertex_Y = h, vertex_Z = 0, ang = 0, incr = 360.0 / (2 * (times-1));
for (int i = 0; i < times; i++) {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_STRIP;
mesh->mNumVertices = 4;
mesh->vVertices.reserve(mesh->mNumVertices);
//V0
vertex_X = (w / 2) * sin(radians(ang));
vertex_Z = (w / 2) * cos(radians(ang));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, vertex_Z);
//V1
vertex_X = (w / 2) * sin(radians(ang));
vertex_Z = (w / 2) * cos(radians(ang));
mesh->vVertices.emplace_back(vertex_X, 0, vertex_Z);
//V2
vertex_X = -(w / 2) * sin(radians(ang));
vertex_Z = -(w / 2) * cos(radians(ang));
mesh->vVertices.emplace_back(vertex_X, vertex_Y, vertex_Z);
//V3
vertex_X = -(w / 2) * sin(radians(ang));
vertex_Z = -(w / 2) * cos(radians(ang));
mesh->vVertices.emplace_back(vertex_X, 0, vertex_Z);
mesh->vTexCoords.reserve(mesh->mNumVertices);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
mesh->vTexCoords.emplace_back(0.0, 1);
mesh->vTexCoords.emplace_back(0.0, 0.0);
mesh->vTexCoords.emplace_back(1, 1);
mesh->vTexCoords.emplace_back(1, 0.0);
gMesh.push_back(mesh);
ang += incr;
}
return gMesh;
}
Mesh* Mesh::generateSquaredRing() {
Mesh* mesh = new Mesh();
mesh->mPrimitive = GL_TRIANGLE_STRIP;
mesh->mNumVertices = 10;
mesh->vVertices.reserve(mesh->mNumVertices);
mesh->vVertices.emplace_back(30.0, 30.0, 0.0);
mesh->vVertices.emplace_back(10.0, 10.0, 0.0);
mesh->vVertices.emplace_back(70.0, 30.0, 0.0);
mesh->vVertices.emplace_back(90.0, 10.0, 0.0);
mesh->vVertices.emplace_back(70.0, 70.0, 0.0);
mesh->vVertices.emplace_back(90.0, 90.0, 0.0);
mesh->vVertices.emplace_back(30.0, 70.0, 0.0);
mesh->vVertices.emplace_back(10.0, 90.0, 0.0);
mesh->vVertices.emplace_back(30.0, 30.0, 0.0);
mesh->vVertices.emplace_back(10.0, 10.0, 0.0);
mesh->vColors.emplace_back(0.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 1.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 0.0, 1.0, 1.0);
mesh->vColors.emplace_back(1.0, 1.0, 0.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.0, 1.0, 1.0);
mesh->vColors.emplace_back(0.0, 1.0, 1.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(0.0, 0.0, 0.0, 1.0);
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
for (int i = 0; i < 10; i++)
mesh->vIndices.emplace_back(i % 8);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &mesh->vVertices);
glColorPointer(4, GL_FLOAT, 0, &mesh->vColors);
mesh->draw();
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
mesh->vNormals.reserve(mesh->size());
for (int i = 0; i < mesh->size(); i++)
mesh->vNormals.emplace_back(glm::dvec3(0, 0, 1));
return mesh;
}
void IndexMesh::render() const{
if(vVertices.size() > 0){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_DOUBLE, 0, vVertices.data());
if(vIndexes != nullptr){
glEnableClientState(GL_INDEX_ARRAY);
glIndexPointer(GL_UNSIGNED_INT, 0, vIndexes);
}
if (vColors.size() > 0) {
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_DOUBLE, 0, vColors.data());
}
if (vTexCoords.size() > 0) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_DOUBLE, 0, vTexCoords.data());
}
if(vNormals.size() > 0){
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_DOUBLE, 0, vNormals.data());
}
draw();
glDisableClientState(GL_INDEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
}
void IndexMesh::draw() const{
glDrawElements(mPrimitive, nNumIndices, GL_UNSIGNED_INT, vIndexes);
}
void IndexMesh::buildNormalVectors() {
int i1, i2, i3;
glm::dvec3 a, b, c, normal;
vNormals.reserve(size());
// init vNormals
for(int i = 0; i < size(); i++)
vNormals.emplace_back(dvec3(0.0, 0.0, 0.0));
//calculate normals
for(int i = 0; i < nNumIndices; i += 3){
// take triangle ABC from indexes
i1 = vIndexes[i]; a = vVertices[i1];
i2 = vIndexes[i+1]; b = vVertices[i2];
i3 = vIndexes[i+2]; c = vVertices[i3];
normal = glm::cross(b - a, c - a);
vNormals[i1] += normal;
vNormals[i2] += normal;
vNormals[i3] += normal;
}
// normalize
for(int i = 0; i < size(); i++)
vNormals[i] = glm::normalize(vNormals[i]);
}
IndexMesh* IndexMesh::generateIndexCubeWithLids(GLdouble l){
IndexMesh* mesh = new IndexMesh();
mesh->mPrimitive = GL_TRIANGLES;
mesh->mNumVertices = 8;
mesh->vVertices.reserve(mesh->size());
mesh->vColors.reserve(mesh->size());
GLdouble half = l / 2;
// colors
for(int i = 0; i < mesh->size(); i++)
mesh->vColors.emplace_back(1.0, 0.0, 0.0, 1.0);
// vertexes
mesh->vVertices.emplace_back(half, half, half);
mesh->vVertices.emplace_back(half, -half, half);
mesh->vVertices.emplace_back(half, half, -half);
mesh->vVertices.emplace_back(half, -half, -half);
mesh->vVertices.emplace_back(-half, half, -half);
mesh->vVertices.emplace_back(-half, -half, -half);
mesh->vVertices.emplace_back(-half, half, half);
mesh->vVertices.emplace_back(-half, -half, half);
mesh->nNumIndices = 36;
mesh->vIndexes = new GLuint[mesh->nNumIndices]{
0, 1, 2,
2, 1, 3,
2, 3, 4,
4, 3, 5,
4, 5, 6,
6, 5, 7,
6, 7, 0,
0, 7, 1,
4, 6, 2,
2, 6, 0,
1, 7, 3,
3, 7, 5
};
// normals
//mesh->vNormals.emplace_back(1, 0, 0);
mesh->buildNormalVectors();
return mesh;
}
MbR* MbR::generateIndexMeshByRevolution(int mm, int nn, glm::dvec3* perfil){
MbR* mesh = new MbR(mm, nn, perfil);
mesh->mPrimitive = GL_TRIANGLES;
mesh->mNumVertices = mm*nn;
mesh->nNumIndices = nn * (mm - 1) * 6;
mesh->vVertices.reserve(mesh->size());
mesh->vColors.reserve(mesh->size());
mesh->vIndexes = new GLuint[mesh->nNumIndices];
dvec3* vertices = new dvec3[mesh->size()];
for(int i=0; i<nn; i++) {
GLdouble theta = i * 360 / nn;
GLdouble c = cos(radians(theta));
GLdouble s = sin(radians(theta));
for (int j = 0; j < mm; j++) {
int indice = i * mm + j;
GLdouble x = c * perfil[j].x + s * perfil[j].z;
GLdouble z = -s * perfil[j].x + c * perfil[j].z;
vertices[indice] = dvec3(x, perfil[j].y, z);
}
}
for (int i = 0; i < mesh->size(); i++){
mesh->vVertices.emplace_back(vertices[i]);
}
int indiceMayor = 0;
for (int i=0; i<nn; i++){
for(int j=0; j<mm-1; j++) {
int indice = i*mm+j;
mesh->vIndexes[indiceMayor] = indice;
indiceMayor++;
mesh->vIndexes[indiceMayor] = (indice + mm) % (nn * mm);
indiceMayor++;
mesh->vIndexes[indiceMayor] = (indice + mm + 1) % (nn * mm);
indiceMayor++;
mesh->vIndexes[indiceMayor] = (indice + mm + 1) % (nn * mm);
indiceMayor++;
mesh->vIndexes[indiceMayor] = indice + 1;
indiceMayor++;
mesh->vIndexes[indiceMayor] = indice;
indiceMayor++;
}
}
mesh->buildNormalVectors();
return mesh;
}
IndexMesh* IndexMesh::generateGrid(GLdouble side, GLuint chunks) {
IndexMesh* mesh = new IndexMesh();
mesh->mPrimitive = GL_TRIANGLES;
mesh->mNumVertices = (chunks + 1) * (chunks + 1);
mesh->vVertices.reserve(mesh->size());
// caras = chk * chk; triangulos = caras * 2; indice = triang * 3;
mesh->nNumIndices = chunks * chunks * 6;
mesh->vIndexes = new GLuint[mesh->nNumIndices];
// vertex
GLdouble chkSize = side / chunks;
GLdouble incX = 0.0, incY = 0.0;
for(int i = 0; i < chunks + 1; i++){
for(int j = 0; j < chunks + 1; j++){
mesh->vVertices.emplace_back(incX, incY, 0.0);
incY += chkSize;
}
incX += chkSize;
incY = 0.0;
}
// index
int index = 0;
for(int i = 0; i < chunks; i++){
for(int j = 0; j < chunks; j++){
// first triangle
mesh->vIndexes[index++] = j + i * (chunks + 1);
mesh->vIndexes[index++] = j + (i + 1) * (chunks + 1);
mesh->vIndexes[index++] = (j + 1) + (i + 1) * (chunks + 1);
// second triangle
mesh->vIndexes[index++] = (j + 1) + (i + 1) * (chunks + 1);
mesh->vIndexes[index++] = (j + 1) + i * (chunks + 1);
mesh->vIndexes[index++] = j + i * (chunks + 1);
}
}
mesh->buildNormalVectors();
return mesh;
}
IndexMesh* IndexMesh::generateGridTex(GLdouble side, GLuint chunks) {
IndexMesh* mesh = generateGrid(side, chunks);
mesh->vTexCoords.reserve(mesh->size());
GLdouble chkSize = side / chunks;
GLdouble incX = 0.0, incY = 0.0;
for(int i = 0; i < chunks + 1; i++){
for(int j = 0; j < chunks + 1; j++){
mesh->vTexCoords.emplace_back(incX/side, incY/side);
incY += chkSize;
}
incX += chkSize;
incY = 0.0;
}
return mesh;
}
| 30.682857 | 137 | 0.564112 | [
"mesh",
"render",
"vector"
] |
a49819499deddae7255de968b56adc3605ac6673 | 1,015 | hpp | C++ | source/LevelTheme.hpp | Amaranese/mario-bros-cplusplus | b5aefffbd3650cfa0ff5e846f43748efde8666c5 | [
"Unlicense"
] | 1 | 2021-08-15T00:37:29.000Z | 2021-08-15T00:37:29.000Z | source/LevelTheme.hpp | Amaranese/mario-bros-cplusplus | b5aefffbd3650cfa0ff5e846f43748efde8666c5 | [
"Unlicense"
] | null | null | null | source/LevelTheme.hpp | Amaranese/mario-bros-cplusplus | b5aefffbd3650cfa0ff5e846f43748efde8666c5 | [
"Unlicense"
] | null | null | null | #ifndef LEVELTHEME_HPP
#define LEVELTHEME_HPP
#include <string>
#include <vector>
#include "EntityTypes.hpp"
class Background;
class Music;
class ResourceManager;
/**
* Determines the theming (resources used) when generating a random Level.
*/
struct LevelTheme
{
std::vector<const Background*> backgrounds;
std::vector<const Music*> musics;
std::vector<const ResourceManager*> spriteTypes[NUM_SPRITE_TYPES];
std::vector<const ResourceManager*> tileTypes[NUM_TILE_TYPES];
/**
* Add an entity type to the theme to be randomly selected.
*
* @param name the name of the entity type.
* @param resourceGroup the ResourceManager for the entity to use.
*/
void addEntityType( const std::string& name, const ResourceManager* resourceGroup );
/**
* Inherit the theming resource groups from a parent level theme. Any
* type that the parent has a resource specified for that this
* instance lacks will be copied over.
*/
void inherit( const LevelTheme& parent );
};
#endif // LEVELTHEME_HPP
| 25.375 | 85 | 0.744828 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.