hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
933a3eba09ee7058ecbf4375bc4bbd7a39214df4
| 2,082
|
cpp
|
C++
|
foobar2000/SDK/console.cpp
|
ttsping/foo_fix
|
4a0b950ccb8c10c912a9abeeffdd85e777463309
|
[
"Info-ZIP"
] | 294
|
2017-11-20T17:42:08.000Z
|
2022-03-31T04:15:13.000Z
|
foobar2000/SDK/console.cpp
|
ttsping/foo_fix
|
4a0b950ccb8c10c912a9abeeffdd85e777463309
|
[
"Info-ZIP"
] | 108
|
2021-04-08T10:57:27.000Z
|
2022-03-27T08:02:15.000Z
|
foobar2000/SDK/console.cpp
|
ttsping/foo_fix
|
4a0b950ccb8c10c912a9abeeffdd85e777463309
|
[
"Info-ZIP"
] | 14
|
2018-03-10T12:47:03.000Z
|
2021-11-11T09:00:08.000Z
|
#include "foobar2000.h"
void console::info(const char * p_message) {print(p_message);}
void console::error(const char * p_message) {complain("Error", p_message);}
void console::warning(const char * p_message) {complain("Warning", p_message);}
void console::info_location(const playable_location & src) {print_location(src);}
void console::info_location(const metadb_handle_ptr & src) {print_location(src);}
void console::print_location(const metadb_handle_ptr & src)
{
print_location(src->get_location());
}
void console::print_location(const playable_location & src)
{
FB2K_console_formatter() << src;
}
void console::complain(const char * what, const char * msg) {
FB2K_console_formatter() << what << ": " << msg;
}
void console::complain(const char * what, std::exception const & e) {
complain(what, e.what());
}
void console::print(const char* p_message)
{
if (core_api::are_services_available()) {
service_ptr_t<console_receiver> ptr;
service_enum_t<console_receiver> e;
while(e.next(ptr)) ptr->print(p_message,~0);
}
}
void console::printf(const char* p_format,...)
{
va_list list;
va_start(list,p_format);
printfv(p_format,list);
va_end(list);
}
void console::printfv(const char* p_format,va_list p_arglist)
{
pfc::string8_fastalloc temp;
uPrintfV(temp,p_format,p_arglist);
print(temp);
}
namespace {
class event_logger_recorder_impl : public event_logger_recorder {
public:
void playback( event_logger::ptr playTo ) {
for(auto i = m_entries.first(); i.is_valid(); ++i ) {
playTo->log_entry( i->line.get_ptr(), i->severity );
}
}
void log_entry( const char * line, unsigned severity ) {
auto rec = m_entries.insert_last();
rec->line = line;
rec->severity = severity;
}
private:
struct entry_t {
pfc::string_simple line;
unsigned severity;
};
pfc::chain_list_v2_t< entry_t > m_entries;
};
}
event_logger_recorder::ptr event_logger_recorder::create() {
return new service_impl_t<event_logger_recorder_impl>();
}
| 25.084337
| 82
| 0.690202
|
ttsping
|
933ce72b5fe5ab5c82eb4813b347590d5c28c7da
| 4,816
|
cpp
|
C++
|
Source/V2World/V2Localisation.cpp
|
Zemurin/EU3ToVic2
|
7df6de2039986ed46683d792ec0c72bbdf6a2f18
|
[
"MIT"
] | 114
|
2015-06-07T20:27:45.000Z
|
2020-08-16T05:05:56.000Z
|
EU3ToV2/Source/V2World/V2Localisation.cpp
|
iamdafu/paradoxGameConverters
|
674364a22917155642ade923e5dfbe38a5fa9610
|
[
"MIT"
] | 553
|
2015-07-20T23:58:26.000Z
|
2019-06-13T21:45:56.000Z
|
EU3ToV2/Source/V2World/V2Localisation.cpp
|
iamdafu/paradoxGameConverters
|
674364a22917155642ade923e5dfbe38a5fa9610
|
[
"MIT"
] | 106
|
2015-07-27T00:21:16.000Z
|
2020-06-10T10:13:13.000Z
|
/*Copyright (c) 2014 The Paradox Game Converters Project
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 "V2Localisation.h"
#include <Windows.h>
#include "..\EU3World\EU3Country.h"
#include "..\Log.h"
#include "..\WinUtils.h"
const std::array<std::string, V2Localisation::numLanguages> V2Localisation::languages =
{ "code", "english", "french", "german", "spanish" };
void V2Localisation::SetTag(const std::string& newTag)
{
tag = newTag;
}
void V2Localisation::ReadFromCountry(const EU3Country& source)
{
for (size_t i = 1; i < numLanguages; ++i)
{
if (!languages[i].empty())
{
name[i - 1] = source.getName(i);
adjective[i - 1] = source.getAdjective(i);
}
}
}
void V2Localisation::SetPartyKey(size_t partyIndex, const std::string& partyKey)
{
if (parties.size() <= partyIndex)
{
parties.resize(partyIndex + 1);
}
parties[partyIndex].key = partyKey;
}
void V2Localisation::SetPartyName(size_t partyIndex, const std::string& language, const std::string& name)
{
if (parties.size() <= partyIndex)
{
parties.resize(partyIndex + 1);
}
auto languageIter = std::find(languages.begin(), languages.end(), language);
if (languageIter != languages.end())
{
size_t languageIndex = std::distance(languages.begin(), languageIter);
parties[partyIndex].name[languageIndex] = name;
}
}
void V2Localisation::WriteToStream(std::ostream& out) const
{
out << Convert(tag);
for (const auto& localisedName : name)
{
out << ';' << Convert(localisedName);
}
out << "x\n";
out << Convert(tag) << "_ADJ";
for (const auto& localisedAdjective : adjective)
{
out << ';' << Convert(localisedAdjective);
}
out << "x\n";
for (const auto& party : parties)
{
out << Convert(party.key);
for (const auto& localisedPartyName : party.name)
{
out << ';' << Convert(localisedPartyName);
}
out << "x\n";
}
}
std::string V2Localisation::convertCountryFileName(const std::string countryFileName) const
{
return Convert(countryFileName);
}
std::string V2Localisation::Convert(const std::string& text)
{
if (text.empty())
{
return "";
}
int utf16Size = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), text.size(), NULL, 0);
if (utf16Size == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to UTF-16: " << WinUtils::GetLastWindowsError();
return "";
}
std::vector<wchar_t> utf16Text(utf16Size, L'\0');
int result = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), text.size(), &utf16Text[0], utf16Size);
if (result == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to UTF-16: " << WinUtils::GetLastWindowsError();
return "";
}
int latin1Size = WideCharToMultiByte(1252, WC_NO_BEST_FIT_CHARS | WC_COMPOSITECHECK | WC_DEFAULTCHAR, &utf16Text[0], utf16Size, NULL, 0, "0", NULL);
if (latin1Size == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to Latin-1: " << WinUtils::GetLastWindowsError();
return "";
}
std::vector<char> latin1Text(latin1Size, '\0');
result = WideCharToMultiByte(1252, WC_NO_BEST_FIT_CHARS | WC_COMPOSITECHECK | WC_DEFAULTCHAR, &utf16Text[0], utf16Size, &latin1Text[0], latin1Size, "0", NULL);
if (result == 0)
{
LOG(LogLevel::Warning) << "Can't convert \"" << text << "\" to Latin-1: " << WinUtils::GetLastWindowsError();
return "";
}
return std::string(latin1Text.begin(), latin1Text.end());
}
std::string V2Localisation::GetLocalName()
{
for (std::string thisname : name)
{
if (!thisname.empty())
{
return thisname;
}
}
return "";
}
std::string V2Localisation::GetLocalAdjective()
{
for (std::string thisname : adjective)
{
if (!thisname.empty())
{
return thisname;
}
}
return "";
}
| 28.497041
| 161
| 0.670473
|
Zemurin
|
933db5aeb9fa89518a14f7f027f19c2f902cb16c
| 7,014
|
hpp
|
C++
|
cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp
|
msobkow/cfint_2_13
|
63ff9dfc85647066d0c8d61469ada572362e2b48
|
[
"Apache-2.0"
] | null | null | null |
cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp
|
msobkow/cfint_2_13
|
63ff9dfc85647066d0c8d61469ada572362e2b48
|
[
"Apache-2.0"
] | null | null | null |
cplus/libcfint/cfintobj/ICFIntMimeTypeTableObj.hpp
|
msobkow/cfint_2_13
|
63ff9dfc85647066d0c8d61469ada572362e2b48
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
// Description: C++18 Table Object interface for CFInt.
/*
* org.msscf.msscf.CFInt
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFInt 2.13 Internet Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MSS Code Factory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
#include <cfint/ICFIntPublic.hpp>
namespace cfint {
class ICFIntSchemaObj;
class ICFIntClusterObj;
class ICFIntClusterEditObj;
class ICFIntClusterTableObj;
class ICFIntHostNodeObj;
class ICFIntHostNodeEditObj;
class ICFIntHostNodeTableObj;
class ICFIntISOCcyObj;
class ICFIntISOCcyEditObj;
class ICFIntISOCcyTableObj;
class ICFIntISOCtryObj;
class ICFIntISOCtryEditObj;
class ICFIntISOCtryTableObj;
class ICFIntISOCtryCcyObj;
class ICFIntISOCtryCcyEditObj;
class ICFIntISOCtryCcyTableObj;
class ICFIntISOCtryLangObj;
class ICFIntISOCtryLangEditObj;
class ICFIntISOCtryLangTableObj;
class ICFIntISOLangObj;
class ICFIntISOLangEditObj;
class ICFIntISOLangTableObj;
class ICFIntISOTZoneObj;
class ICFIntISOTZoneEditObj;
class ICFIntISOTZoneTableObj;
class ICFIntLicenseObj;
class ICFIntLicenseEditObj;
class ICFIntLicenseTableObj;
class ICFIntMajorVersionObj;
class ICFIntMajorVersionEditObj;
class ICFIntMajorVersionTableObj;
class ICFIntMimeTypeObj;
class ICFIntMimeTypeEditObj;
class ICFIntMimeTypeTableObj;
class ICFIntMinorVersionObj;
class ICFIntMinorVersionEditObj;
class ICFIntMinorVersionTableObj;
class ICFIntSecAppObj;
class ICFIntSecAppEditObj;
class ICFIntSecAppTableObj;
class ICFIntSecDeviceObj;
class ICFIntSecDeviceEditObj;
class ICFIntSecDeviceTableObj;
class ICFIntSecFormObj;
class ICFIntSecFormEditObj;
class ICFIntSecFormTableObj;
class ICFIntSecGroupObj;
class ICFIntSecGroupEditObj;
class ICFIntSecGroupTableObj;
class ICFIntSecGroupFormObj;
class ICFIntSecGroupFormEditObj;
class ICFIntSecGroupFormTableObj;
class ICFIntSecGrpIncObj;
class ICFIntSecGrpIncEditObj;
class ICFIntSecGrpIncTableObj;
class ICFIntSecGrpMembObj;
class ICFIntSecGrpMembEditObj;
class ICFIntSecGrpMembTableObj;
class ICFIntSecSessionObj;
class ICFIntSecSessionEditObj;
class ICFIntSecSessionTableObj;
class ICFIntSecUserObj;
class ICFIntSecUserEditObj;
class ICFIntSecUserTableObj;
class ICFIntServiceObj;
class ICFIntServiceEditObj;
class ICFIntServiceTableObj;
class ICFIntServiceTypeObj;
class ICFIntServiceTypeEditObj;
class ICFIntServiceTypeTableObj;
class ICFIntSubProjectObj;
class ICFIntSubProjectEditObj;
class ICFIntSubProjectTableObj;
class ICFIntSysClusterObj;
class ICFIntSysClusterEditObj;
class ICFIntSysClusterTableObj;
class ICFIntTSecGroupObj;
class ICFIntTSecGroupEditObj;
class ICFIntTSecGroupTableObj;
class ICFIntTSecGrpIncObj;
class ICFIntTSecGrpIncEditObj;
class ICFIntTSecGrpIncTableObj;
class ICFIntTSecGrpMembObj;
class ICFIntTSecGrpMembEditObj;
class ICFIntTSecGrpMembTableObj;
class ICFIntTenantObj;
class ICFIntTenantEditObj;
class ICFIntTenantTableObj;
class ICFIntTldObj;
class ICFIntTldEditObj;
class ICFIntTldTableObj;
class ICFIntTopDomainObj;
class ICFIntTopDomainEditObj;
class ICFIntTopDomainTableObj;
class ICFIntTopProjectObj;
class ICFIntTopProjectEditObj;
class ICFIntTopProjectTableObj;
class ICFIntURLProtocolObj;
class ICFIntURLProtocolEditObj;
class ICFIntURLProtocolTableObj;
}
#include <cfintobj/ICFIntMimeTypeObj.hpp>
#include <cfintobj/ICFIntMimeTypeEditObj.hpp>
namespace cfint {
class ICFIntMimeTypeTableObj
{
public:
ICFIntMimeTypeTableObj();
virtual ~ICFIntMimeTypeTableObj();
virtual cfint::ICFIntSchemaObj* getSchema() = 0;
virtual void setSchema( cfint::ICFIntSchemaObj* value ) = 0;
virtual void minimizeMemory() = 0;
virtual const std::string getTableName() = 0;
virtual const std::string getTableDbName() = 0;
virtual const classcode_t* getObjQualifyingClassCode() = 0;
virtual cfint::ICFIntMimeTypeObj* newInstance() = 0;
virtual cfint::ICFIntMimeTypeEditObj* newEditInstance( cfint::ICFIntMimeTypeObj* orig ) = 0;
virtual cfint::ICFIntMimeTypeObj* realizeMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
virtual void deepDisposeByIdIdx( const int32_t MimeTypeId ) = 0;
virtual void deepDisposeByUNameIdx( const std::string& Name ) = 0;
virtual void reallyDeepDisposeMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
virtual cfint::ICFIntMimeTypeObj* createMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeType( cfint::CFIntMimeTypePKey* pkey,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* lockMimeType( cfint::CFIntMimeTypePKey* pkey ) = 0;
virtual std::vector<cfint::ICFIntMimeTypeObj*> readAllMimeType( bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByIdIdx( const int32_t MimeTypeId,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByUNameIdx(const std::string& Name,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeType( cfint::CFIntMimeTypePKey* pkey ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByIdIdx(const int32_t MimeTypeId ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByUNameIdx(const std::string& Name ) = 0;
virtual cfint::ICFIntMimeTypeObj* readMimeTypeByLookupUNameIdx(const std::string& Name,
bool forceRead = false ) = 0;
virtual cfint::ICFIntMimeTypeObj* readCachedMimeTypeByLookupUNameIdx(const std::string& Name ) = 0;
virtual cfint::ICFIntMimeTypeObj* updateMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual void deleteMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) = 0;
virtual void deleteMimeTypeByIdIdx( const int32_t MimeTypeId ) = 0;
virtual void deleteMimeTypeByUNameIdx(const std::string& Name ) = 0;
virtual void reallyDetachFromIndexesMimeType( cfint::ICFIntMimeTypeObj* Obj ) = 0;
};
}
| 32.929577
| 101
| 0.795979
|
msobkow
|
933ed79568df20fbe3b6c80e554625477769863e
| 5,289
|
cc
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/ScrollerItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/ScrollerItem.cc,v 1.4 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: ScrollerItem.cc,v $
* Revision 1.4 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.3 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
*
*
*
*/
#include "StreamUtils.hh"
#include "CheckBox.hh"
#include "Dialog.hh"
#include "Scroller.hh"
#include "CommandNumbers.hh"
#include "ScrollerItem.hh"
#include "ScrollerInfo.hh"
#include "ViewItemInfo.hh"
class SetScrollerInfoCommand : public Command {
public:
SetScrollerInfoCommand (ScrollerItem& item, ScrollerInfo& info);
override void DoIt ();
override void UnDoIt ();
private:
ScrollerItem& fItem;
Command* fItemInfoCommand;
Point fNewScrollSize;
Point fOldScrollSize;
Boolean fOldVSBar;
Boolean fNewVSBar;
Boolean fOldHSBar;
Boolean fNewHSBar;
};
/*
********************************************************************************
****************************** ScrollerItemType ********************************
********************************************************************************
*/
ScrollerItemType::ScrollerItemType () :
ItemType (eBuildGroup, "Scroller", (ItemBuilderProc)&ScrollerItemBuilder)
{
Require (sThis == Nil);
sThis = this;
}
ScrollerItemType& ScrollerItemType::Get ()
{
RequireNotNil (sThis);
return (*sThis);
}
ViewItem* ScrollerItemType::ScrollerItemBuilder ()
{
return (new ScrollerItem ());
}
ScrollerItemType* ScrollerItemType::sThis = Nil;
/*
********************************************************************************
****************************** ScrollerItem ************************************
********************************************************************************
*/
ScrollerItem::ScrollerItem () :
GroupItem (ScrollerItemType::Get (), True),
fHasVerticalSBar (True),
fHasHorizontalSBar (True)
{
SetMaxVersion (2);
}
ScrollerItem::ScrollerItem (ItemType& type) :
GroupItem (type, True),
fHasVerticalSBar (True),
fHasHorizontalSBar (True)
{
SetMaxVersion (2);
}
Boolean ScrollerItem::GetHasVerticalSBar () const
{
return (fHasVerticalSBar);
}
void ScrollerItem::SetHasVerticalSBar (Boolean hasSBar)
{
if (hasSBar != fHasVerticalSBar) {
fHasVerticalSBar = hasSBar;
GetGroupItemView ().SetVerticalScrollBar (hasSBar ? Scroller::kBuildDefaultSlider : Scroller::kBuildNoSlider);
}
Ensure (hasSBar == fHasVerticalSBar);
}
Boolean ScrollerItem::GetHasHorizontalSBar () const
{
return (fHasHorizontalSBar);
}
void ScrollerItem::SetHasHorizontalSBar (Boolean hasSBar)
{
if (hasSBar != fHasHorizontalSBar) {
fHasHorizontalSBar = hasSBar;
GetGroupItemView ().SetHorizontalScrollBar (hasSBar ? Scroller::kBuildDefaultSlider : Scroller::kBuildNoSlider);
}
Ensure (hasSBar == fHasHorizontalSBar);
}
String ScrollerItem::GetHeaderFileName ()
{
static const String kHeaderFileName = "Scroller.hh";
return (kHeaderFileName);
}
void ScrollerItem::DoRead_ (class istream& from)
{
GroupItem::DoRead_ (from);
if (GetVersion () > 1) {
Boolean h, v;
from >> v >> h;
SetHasVerticalSBar (v);
SetHasHorizontalSBar (h);
}
}
void ScrollerItem::DoWrite_ (class ostream& to, int tabCount) const
{
GroupItem::DoWrite_ (to, tabCount);
to << tab (tabCount) << GetHasVerticalSBar () << GetHasHorizontalSBar () << newline;
}
void ScrollerItem::WriteParameters (class ostream& to, int tabCount, CommandNumber language, CommandNumber gui)
{
GroupItem::WriteParameters (to, tabCount, language, gui);
}
void ScrollerItem::WriteBuilder (class ostream& to, int tabCount)
{
ViewItem::WriteBuilder (to, tabCount);
to << "(";
if (GetHasVerticalSBar ()) {
to << "Scroller::kBuildDefaultSlider, ";
}
else {
to << "Scroller::kBuildNoSlider, ";
}
if (GetHasHorizontalSBar ()) {
to << "Scroller::kBuildDefaultSlider";
}
else {
to << "Scroller::kBuildNoSlider";
}
to << ")," << newline;
}
SetScrollerInfoCommand::SetScrollerInfoCommand (ScrollerItem& item, ScrollerInfo& info) :
Command (eSetItemInfo, kUndoable),
fItem (item),
fItemInfoCommand (Nil),
fNewScrollSize (info.GetScrollBounds ()),
fOldScrollSize (item.GetScrollSize ()),
fOldVSBar (item.GetHasVerticalSBar ()),
fNewVSBar (info.GetVSBarField ().GetOn ()),
fOldHSBar (item.GetHasHorizontalSBar ()),
fNewHSBar (info.GetHSBarField ().GetOn ())
{
fItemInfoCommand = new SetItemInfoCommand (item, info.GetViewItemInfo ());
}
void SetScrollerInfoCommand::DoIt ()
{
fItemInfoCommand->DoIt ();
fItem.SetScrollSize (fNewScrollSize);
fItem.SetHasVerticalSBar (fNewVSBar);
fItem.SetHasHorizontalSBar (fNewHSBar);
Command::DoIt ();
}
void SetScrollerInfoCommand::UnDoIt ()
{
fItemInfoCommand->UnDoIt ();
fItem.SetScrollSize (fOldScrollSize);
fItem.SetHasVerticalSBar (fOldVSBar);
fItem.SetHasHorizontalSBar (fOldHSBar);
Command::UnDoIt ();
}
void ScrollerItem::SetItemInfo ()
{
ScrollerInfo info = ScrollerInfo (*this);
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetScrollerInfoCommand (*this, info));
DirtyDocument ();
}
}
| 22.896104
| 114
| 0.656646
|
SophistSolutions
|
9343eddb8090e93ce379fe6e757a74f1c43adb29
| 53,922
|
cpp
|
C++
|
Matrix4f.cpp
|
PankeyCR/aMonkeyEngine
|
83e631a6185a65e88d6eea95c73475b0da59ea54
|
[
"BSD-3-Clause"
] | 1
|
2021-07-02T11:47:10.000Z
|
2021-07-02T11:47:10.000Z
|
Matrix4f.cpp
|
PankeyCR/aMonkeyEngine
|
83e631a6185a65e88d6eea95c73475b0da59ea54
|
[
"BSD-3-Clause"
] | null | null | null |
Matrix4f.cpp
|
PankeyCR/aMonkeyEngine
|
83e631a6185a65e88d6eea95c73475b0da59ea54
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef Matrix4f_cpp
#define Matrix4f_cpp
#include "Matrix4f.h"
ame::Matrix4f *ame::Matrix4f::ZERO = new ame::Matrix4f(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
ame::Matrix4f *ame::Matrix4f::IDENTITY = new ame::Matrix4f();
ame::Matrix4f::Matrix4f() {
//this->loadIdentity();
}
ame::Matrix4f::Matrix4f(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
this->m00 = m00;
this->m01 = m01;
this->m02 = m02;
this->m03 = m03;
this->m10 = m10;
this->m11 = m11;
this->m12 = m12;
this->m13 = m13;
this->m20 = m20;
this->m21 = m21;
this->m22 = m22;
this->m23 = m23;
this->m30 = m30;
this->m31 = m31;
this->m32 = m32;
this->m33 = m33;
}
ame::Matrix4f::Matrix4f(ame::List<float> *array) {
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
ame::Matrix4f ame::Matrix4f::fromFrame(Vector3f location, Vector3f direction, Vector3f up, Vector3f left) {
// TempVars vars = TempVars.get();
// try {
// Vector3f fwdVector = vars.vect1.set(direction);
// Vector3f leftVector = vars.vect2.set(fwdVector).crossLocal(up);
// Vector3f upVector = vars.vect3.set(leftVector).crossLocal(fwdVector);
// m00 = leftVector.x;
// m01 = leftVector.y;
// m02 = leftVector.z;
// m03 = -leftVector.dot(location);
// m10 = upVector.x;
// m11 = upVector.y;
// m12 = upVector.z;
// m13 = -upVector.dot(location);
// m20 = -fwdVector.x;
// m21 = -fwdVector.y;
// m22 = -fwdVector.z;
// m23 = fwdVector.dot(location);
// m30 = 0f;
// m31 = 0f;
// m32 = 0f;
// m33 = 1f;
// } finally {
// vars.release();
// }
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::fromFrameLocal(Vector3f location, Vector3f direction, Vector3f up, Vector3f left) {
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
ame::List<float> *ame::Matrix4f::get(ame::List<float> *matrix) {
return this->get(matrix, true);
}
ame::List<float> *ame::Matrix4f::get(ame::List<float> *matrix, bool rowMajor) {
if (matrix == nullptr) {
return nullptr;
}
if (matrix->getPosition() == 0) {
if (rowMajor) {
matrix->addLValue(m00);
matrix->addLValue(m01);
matrix->addLValue(m02);
matrix->addLValue(m03);
matrix->addLValue(m10);
matrix->addLValue(m11);
matrix->addLValue(m12);
matrix->addLValue(m13);
matrix->addLValue(m20);
matrix->addLValue(m21);
matrix->addLValue(m22);
matrix->addLValue(m23);
matrix->addLValue(m30);
matrix->addLValue(m31);
matrix->addLValue(m32);
matrix->addLValue(m33);
} else {
matrix->addLValue(m00);
matrix->addLValue(m10);
matrix->addLValue(m20);
matrix->addLValue(m30);
matrix->addLValue(m01);
matrix->addLValue(m11);
matrix->addLValue(m21);
matrix->addLValue(m31);
matrix->addLValue(m02);
matrix->addLValue(m12);
matrix->addLValue(m22);
matrix->addLValue(m32);
matrix->addLValue(m03);
matrix->addLValue(m13);
matrix->addLValue(m23);
matrix->addLValue(m33);
}
}
return matrix;
}
// ame::List<float> ame::Matrix4f::get() {
// return get(true);
// }
// ame::List<float> ame::Matrix4f::get(bool rowMajor) {
// Arrayame::List<float> matrix();
// if (rowMajor) {
// matrix->addLValue(m00);
// matrix->addLValue(m01);
// matrix->addLValue(m02);
// matrix->addLValue(m03);
// matrix->addLValue(m10);
// matrix->addLValue(m11);
// matrix->addLValue(m12);
// matrix->addLValue(m13);
// matrix->addLValue(m20);
// matrix->addLValue(m21);
// matrix->addLValue(m22);
// matrix->addLValue(m23);
// matrix->addLValue(m30);
// matrix->addLValue(m31);
// matrix->addLValue(m32);
// matrix->addLValue(m33);
// } else {
// matrix->addLValue(m00);
// matrix->addLValue(m10);
// matrix->addLValue(m20);
// matrix->addLValue(m30);
// matrix->addLValue(m01);
// matrix->addLValue(m11);
// matrix->addLValue(m21);
// matrix->addLValue(m31);
// matrix->addLValue(m02);
// matrix->addLValue(m12);
// matrix->addLValue(m22);
// matrix->addLValue(m32);
// matrix->addLValue(m03);
// matrix->addLValue(m13);
// matrix->addLValue(m23);
// matrix->addLValue(m33);
// }
// return Arrayame::List<float>(&matrix);
// }
float ame::Matrix4f::get(int i, int j) {
switch (i) {
case 0:
switch (j) {
case 0:
return m00;
case 1:
return m01;
case 2:
return m02;
case 3:
return m03;
}
case 1:
switch (j) {
case 0:
return m10;
case 1:
return m11;
case 2:
return m12;
case 3:
return m13;
}
case 2:
switch (j) {
case 0:
return m20;
case 1:
return m21;
case 2:
return m22;
case 3:
return m23;
}
case 3:
switch (j) {
case 0:
return m30;
case 1:
return m31;
case 2:
return m32;
case 3:
return m33;
}
}
return 0.0f;
}
// ame::List<float> ame::Matrix4f::getColumn(int i) {
// return getColumn(i, NULL);
// }
ame::List<float> *ame::Matrix4f::getColumn(int i, ame::List<float> *store) {
if (store == nullptr) {
return nullptr;
}
if (store->getPosition() == 0) {
switch (i) {
case 0:
store->addLValue(this->m00);
store->addLValue(this->m10);
store->addLValue(this->m20);
store->addLValue(this->m30);
break;
case 1:
store->addLValue(this->m01);
store->addLValue(this->m11);
store->addLValue(this->m21);
store->addLValue(this->m31);
break;
case 2:
store->addLValue(this->m02);
store->addLValue(this->m12);
store->addLValue(this->m22);
store->addLValue(this->m32);
break;
case 3:
store->addLValue(this->m03);
store->addLValue(this->m13);
store->addLValue(this->m23);
store->addLValue(this->m33);
break;
default:
return nullptr;
}
}
return store;
}
ame::Matrix4f ame::Matrix4f::setColumn(int i, ame::List<float> *column) {
if (column == nullptr) {
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
if (column->getPosition() >= 4) {
}
switch (i) {
case 0:
this->m00 = *column->getByPosition(0);
this->m10 = *column->getByPosition(1);
this->m20 = *column->getByPosition(2);
this->m30 = *column->getByPosition(3);
break;
case 1:
this->m01 = *column->getByPosition(0);
this->m11 = *column->getByPosition(1);
this->m21 = *column->getByPosition(2);
this->m31 = *column->getByPosition(3);
break;
case 2:
this->m02 = *column->getByPosition(0);
this->m12 = *column->getByPosition(1);
this->m22 = *column->getByPosition(2);
this->m32 = *column->getByPosition(3);
break;
case 3:
this->m03 = *column->getByPosition(0);
this->m13 = *column->getByPosition(1);
this->m23 = *column->getByPosition(2);
this->m33 = *column->getByPosition(3);
break;
default:
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::set(int i, int j, float value) {
switch (i) {
case 0:
switch (j) {
case 0:
this->m00 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m01 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m02 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m03 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 1:
switch (j) {
case 0:
this->m10 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m11 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m12 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m13 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 2:
switch (j) {
case 0:
this->m20 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m21 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m22 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m23 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
case 3:
switch (j) {
case 0:
this->m30 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 1:
this->m31 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 2:
this->m32 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
case 3:
this->m33 = value;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
}
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
// ame::Matrix4f ame::Matrix4f::set(float[4][4] matrix) {
// if (matrix.length != 4 || matrix[0].length != 4) {
// return;
// }
// this->m00 = matrix[0][0];
// this->m01 = matrix[0][1];
// this->m02 = matrix[0][2];
// this->m03 = matrix[0][3];
// this->m10 = matrix[1][0];
// this->m11 = matrix[1][1];
// this->m12 = matrix[1][2];
// this->m13 = matrix[1][3];
// this->m20 = matrix[2][0];
// this->m21 = matrix[2][1];
// this->m22 = matrix[2][2];
// this->m23 = matrix[2][3];
// this->m30 = matrix[3][0];
// this->m31 = matrix[3][1];
// this->m32 = matrix[3][2];
// this->m33 = matrix[3][3];
// return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
// this->m10, this->m11, this->m12, this->m13,
// this->m20, this->m21, this->m22, this->m23,
// this->m30, this->m31, this->m32, this->m33);
// }
ame::Matrix4f ame::Matrix4f::set(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
this->m00 = m00;
this->m01 = m01;
this->m02 = m02;
this->m03 = m03;
this->m10 = m10;
this->m11 = m11;
this->m12 = m12;
this->m13 = m13;
this->m20 = m20;
this->m21 = m21;
this->m22 = m22;
this->m23 = m23;
this->m30 = m30;
this->m31 = m31;
this->m32 = m32;
this->m33 = m33;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
ame::Matrix4f ame::Matrix4f::set(ame::Matrix4f matrix) {
this->m00 = matrix.m00;
this->m01 = matrix.m01;
this->m02 = matrix.m02;
this->m03 = matrix.m03;
this->m10 = matrix.m10;
this->m11 = matrix.m11;
this->m12 = matrix.m12;
this->m13 = matrix.m13;
this->m20 = matrix.m20;
this->m21 = matrix.m21;
this->m22 = matrix.m22;
this->m23 = matrix.m23;
this->m30 = matrix.m30;
this->m31 = matrix.m31;
this->m32 = matrix.m32;
this->m33 = matrix.m33;
return ame::Matrix4f(this->m00, this->m01, this->m02, this->m03,
this->m10, this->m11, this->m12, this->m13,
this->m20, this->m21, this->m22, this->m23,
this->m30, this->m31, this->m32, this->m33);
}
/////////////////////////////////////////////////////////////////////////////////////////
/*
ame::List<float> *ame::Matrix4f::set(ame::List<float> *matrix) {
return this->set(matrix, true);
}
ame::List<float> *ame::Matrix4f::set(ame::List<float> *matrix, bool rowMajor) {
if (matrix == nullptr) {
return nullptr;
}
if (matrix->getPosition() < 16) {
return matrix;
}
if (rowMajor) {
this->m00 = *matrix->getByPosition(0);
this->m01 = *matrix->getByPosition(1);
this->m02 = *matrix->getByPosition(2);
this->m03 = *matrix->getByPosition(3);
this->m10 = *matrix->getByPosition(4);
this->m11 = *matrix->getByPosition(5);
this->m12 = *matrix->getByPosition(6);
this->m13 = *matrix->getByPosition(7);
this->m20 = *matrix->getByPosition(8);
this->m21 = *matrix->getByPosition(9);
this->m22 = *matrix->getByPosition(10);
this->m23 = *matrix->getByPosition(11);
this->m30 = *matrix->getByPosition(12);
this->m31 = *matrix->getByPosition(13);
this->m32 = *matrix->getByPosition(14);
this->m33 = *matrix->getByPosition(15);
} else {
this->m00 = *matrix->getByPosition(0);
this->m01 = *matrix->getByPosition(4);
this->m02 = *matrix->getByPosition(8);
this->m03 = *matrix->getByPosition(12);
this->m10 = *matrix->getByPosition(1);
this->m11 = *matrix->getByPosition(5);
this->m12 = *matrix->getByPosition(9);
this->m13 = *matrix->getByPosition(13);
this->m20 = *matrix->getByPosition(2);
this->m21 = *matrix->getByPosition(6);
this->m22 = *matrix->getByPosition(10);
this->m23 = *matrix->getByPosition(14);
this->m30 = *matrix->getByPosition(3);
this->m31 = *matrix->getByPosition(7);
this->m32 = *matrix->getByPosition(11);
this->m33 = *matrix->getByPosition(15);
}
return matrix;
}
ame::Matrix4f ame::Matrix4f::transpose() {
float tmp[16];
get(tmp, true);
return ame::Matrix4f(tmp);
}
ame::Matrix4f ame::Matrix4f::transposeLocal() {
float tmp = m01;
m01 = m10;
m10 = tmp;
tmp = m02;
m02 = m20;
m20 = tmp;
tmp = m03;
m03 = m30;
m30 = tmp;
tmp = m12;
m12 = m21;
m21 = tmp;
tmp = m13;
m13 = m31;
m31 = tmp;
tmp = m23;
m23 = m32;
m32 = tmp;
return ame::Matrix4f(this);
}
void ame::Matrix4f::loadIdentity() {
m01 = m02 = m03 = 0.0f;
m10 = m12 = m13 = 0.0f;
m20 = m21 = m23 = 0.0f;
m30 = m31 = m32 = 0.0f;
m00 = m11 = m22 = m33 = 1.0f;
}
void ame::Matrix4f::fromFrustum(float near, float far, float left, float right, float top, float bottom, bool parallel) {
loadIdentity();
if (parallel) {
// scale
m00 = 2.0f / (right - left);
//m11 = 2.0f / (bottom - top);
m11 = 2.0f / (top - bottom);
m22 = -2.0f / (far - near);
m33 = 1f;
// translation
m03 = -(right + left) / (right - left);
//m31 = -(bottom + top) / (bottom - top);
m13 = -(top + bottom) / (top - bottom);
m23 = -(far + near) / (far - near);
} else {
m00 = (2.0f * near) / (right - left);
m11 = (2.0f * near) / (top - bottom);
m32 = -1.0f;
m33 = -0.0f;
// A
m02 = (right + left) / (right - left);
// B
m12 = (top + bottom) / (top - bottom);
// C
m22 = -(far + near) / (far - near);
// D
m23 = -(2.0f * far * near) / (far - near);
}
}
void ame::Matrix4f::fromAngleAxis(float angle, Vector3f axis) {
Vector3f normAxis = axis.normalize();
fromAngleNormalAxis(angle, normAxis);
}
void ame::Matrix4f::fromAngleNormalAxis(float angle, Vector3f axis) {
zero();
m33 = 1;
float fCos = FastMath.cos(angle);
float fSin = FastMath.sin(angle);
float fOneMinusCos = ((float) 1.0) - fCos;
float fX2 = axis.x * axis.x;
float fY2 = axis.y * axis.y;
float fZ2 = axis.z * axis.z;
float fXYM = axis.x * axis.y * fOneMinusCos;
float fXZM = axis.x * axis.z * fOneMinusCos;
float fYZM = axis.y * axis.z * fOneMinusCos;
float fXSin = axis.x * fSin;
float fYSin = axis.y * fSin;
float fZSin = axis.z * fSin;
m00 = fX2 * fOneMinusCos + fCos;
m01 = fXYM - fZSin;
m02 = fXZM + fYSin;
m10 = fXYM + fZSin;
m11 = fY2 * fOneMinusCos + fCos;
m12 = fYZM - fXSin;
m20 = fXZM - fYSin;
m21 = fYZM + fXSin;
m22 = fZ2 * fOneMinusCos + fCos;
}
void ame::Matrix4f::multLocal(float scalar) {
m00 *= scalar;
m01 *= scalar;
m02 *= scalar;
m03 *= scalar;
m10 *= scalar;
m11 *= scalar;
m12 *= scalar;
m13 *= scalar;
m20 *= scalar;
m21 *= scalar;
m22 *= scalar;
m23 *= scalar;
m30 *= scalar;
m31 *= scalar;
m32 *= scalar;
m33 *= scalar;
}
ame::Matrix4f ame::Matrix4f::mult(float scalar) {
ame::Matrix4f out = new ame::Matrix4f();
out.set(this);
out.multLocal(scalar);
return out;
}
ame::Matrix4f ame::Matrix4f::mult(float scalar, ame::Matrix4f store) {
store.set(this);
store.multLocal(scalar);
return store;
}
ame::Matrix4f ame::Matrix4f::mult(ame::Matrix4f in2) {
return mult(in2, null);
}
ame::Matrix4f ame::Matrix4f::mult(ame::Matrix4f in2, ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float temp00, temp01, temp02, temp03;
float temp10, temp11, temp12, temp13;
float temp20, temp21, temp22, temp23;
float temp30, temp31, temp32, temp33;
temp00 = m00 * in2.m00
+ m01 * in2.m10
+ m02 * in2.m20
+ m03 * in2.m30;
temp01 = m00 * in2.m01
+ m01 * in2.m11
+ m02 * in2.m21
+ m03 * in2.m31;
temp02 = m00 * in2.m02
+ m01 * in2.m12
+ m02 * in2.m22
+ m03 * in2.m32;
temp03 = m00 * in2.m03
+ m01 * in2.m13
+ m02 * in2.m23
+ m03 * in2.m33;
temp10 = m10 * in2.m00
+ m11 * in2.m10
+ m12 * in2.m20
+ m13 * in2.m30;
temp11 = m10 * in2.m01
+ m11 * in2.m11
+ m12 * in2.m21
+ m13 * in2.m31;
temp12 = m10 * in2.m02
+ m11 * in2.m12
+ m12 * in2.m22
+ m13 * in2.m32;
temp13 = m10 * in2.m03
+ m11 * in2.m13
+ m12 * in2.m23
+ m13 * in2.m33;
temp20 = m20 * in2.m00
+ m21 * in2.m10
+ m22 * in2.m20
+ m23 * in2.m30;
temp21 = m20 * in2.m01
+ m21 * in2.m11
+ m22 * in2.m21
+ m23 * in2.m31;
temp22 = m20 * in2.m02
+ m21 * in2.m12
+ m22 * in2.m22
+ m23 * in2.m32;
temp23 = m20 * in2.m03
+ m21 * in2.m13
+ m22 * in2.m23
+ m23 * in2.m33;
temp30 = m30 * in2.m00
+ m31 * in2.m10
+ m32 * in2.m20
+ m33 * in2.m30;
temp31 = m30 * in2.m01
+ m31 * in2.m11
+ m32 * in2.m21
+ m33 * in2.m31;
temp32 = m30 * in2.m02
+ m31 * in2.m12
+ m32 * in2.m22
+ m33 * in2.m32;
temp33 = m30 * in2.m03
+ m31 * in2.m13
+ m32 * in2.m23
+ m33 * in2.m33;
store.m00 = temp00;
store.m01 = temp01;
store.m02 = temp02;
store.m03 = temp03;
store.m10 = temp10;
store.m11 = temp11;
store.m12 = temp12;
store.m13 = temp13;
store.m20 = temp20;
store.m21 = temp21;
store.m22 = temp22;
store.m23 = temp23;
store.m30 = temp30;
store.m31 = temp31;
store.m32 = temp32;
store.m33 = temp33;
return store;
}
ame::Matrix4f ame::Matrix4f::multLocal(ame::Matrix4f in2) {
return mult(in2, this);
}
Vector3f ame::Matrix4f::mult(Vector3f vec) {
return mult(vec, null);
}
Vector3f ame::Matrix4f::mult(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz + m03;
store.y = m10 * vx + m11 * vy + m12 * vz + m13;
store.z = m20 * vx + m21 * vy + m22 * vz + m23;
return store;
}
Vector4f ame::Matrix4f::mult(Vector4f vec) {
return mult(vec, null);
}
Vector4f ame::Matrix4f::mult(Vector4f vec, Vector4f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector4f();
}
float vx = vec.x, vy = vec.y, vz = vec.z, vw = vec.w;
store.x = m00 * vx + m01 * vy + m02 * vz + m03 * vw;
store.y = m10 * vx + m11 * vy + m12 * vz + m13 * vw;
store.z = m20 * vx + m21 * vy + m22 * vz + m23 * vw;
store.w = m30 * vx + m31 * vy + m32 * vz + m33 * vw;
return store;
}
Vector4f ame::Matrix4f::multAcross(Vector4f vec) {
return multAcross(vec, null);
}
Vector4f ame::Matrix4f::multAcross(Vector4f vec, Vector4f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector4f();
}
float vx = vec.x, vy = vec.y, vz = vec.z, vw = vec.w;
store.x = m00 * vx + m10 * vy + m20 * vz + m30 * vw;
store.y = m01 * vx + m11 * vy + m21 * vz + m31 * vw;
store.z = m02 * vx + m12 * vy + m22 * vz + m32 * vw;
store.w = m03 * vx + m13 * vy + m23 * vz + m33 * vw;
return store;
}
Vector3f ame::Matrix4f::multNormal(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz;
store.y = m10 * vx + m11 * vy + m12 * vz;
store.z = m20 * vx + m21 * vy + m22 * vz;
return store;
}
Vector3f ame::Matrix4f::multNormalAcross(Vector3f vec, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m10 * vy + m20 * vz;
store.y = m01 * vx + m11 * vy + m21 * vz;
store.z = m02 * vx + m12 * vy + m22 * vz;
return store;
}
float ame::Matrix4f::multProj(Vector3f vec, Vector3f store) {
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m01 * vy + m02 * vz + m03;
store.y = m10 * vx + m11 * vy + m12 * vz + m13;
store.z = m20 * vx + m21 * vy + m22 * vz + m23;
return m30 * vx + m31 * vy + m32 * vz + m33;
}
Vector3f ame::Matrix4f::multAcross(Vector3f vec, Vector3f store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Vector3f();
}
float vx = vec.x, vy = vec.y, vz = vec.z;
store.x = m00 * vx + m10 * vy + m20 * vz + m30 * 1;
store.y = m01 * vx + m11 * vy + m21 * vz + m31 * 1;
store.z = m02 * vx + m12 * vy + m22 * vz + m32 * 1;
return store;
}
Quaternion ame::Matrix4f::mult(Quaternion vec, Quaternion store) {
if (null == vec) {
logger.warning("Source vector is null, null result returned.");
return null;
}
if (store == null) {
store = new Quaternion();
}
float x = m00 * vec.x + m10 * vec.y + m20 * vec.z + m30 * vec.w;
float y = m01 * vec.x + m11 * vec.y + m21 * vec.z + m31 * vec.w;
float z = m02 * vec.x + m12 * vec.y + m22 * vec.z + m32 * vec.w;
float w = m03 * vec.x + m13 * vec.y + m23 * vec.z + m33 * vec.w;
store.x = x;
store.y = y;
store.z = z;
store.w = w;
return store;
}
float *ame::Matrix4f::mult(float[] vec4f) {
if (null == vec4f || vec4f.length != 4) {
logger.warning("invalid array given, must be nonnull and length 4");
return null;
}
float x = vec4f[0], y = vec4f[1], z = vec4f[2], w = vec4f[3];
vec4f[0] = m00 * x + m01 * y + m02 * z + m03 * w;
vec4f[1] = m10 * x + m11 * y + m12 * z + m13 * w;
vec4f[2] = m20 * x + m21 * y + m22 * z + m23 * w;
vec4f[3] = m30 * x + m31 * y + m32 * z + m33 * w;
return vec4f;
}
float *ame::Matrix4f::multAcross(float[] vec4f) {
if (null == vec4f || vec4f.length != 4) {
logger.warning("invalid array given, must be nonnull and length 4");
return null;
}
float x = vec4f[0], y = vec4f[1], z = vec4f[2], w = vec4f[3];
vec4f[0] = m00 * x + m10 * y + m20 * z + m30 * w;
vec4f[1] = m01 * x + m11 * y + m21 * z + m31 * w;
vec4f[2] = m02 * x + m12 * y + m22 * z + m32 * w;
vec4f[3] = m03 * x + m13 * y + m23 * z + m33 * w;
return vec4f;
}
ame::Matrix4f ame::Matrix4f::invert() {
return invert(null);
}
ame::Matrix4f ame::Matrix4f::invert(ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
if (FastMath.abs(fDet) <= 0f) {
throw new ArithmeticException("This matrix cannot be inverted");
}
store.m00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
store.m10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
store.m20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
store.m30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
store.m01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
store.m11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
store.m21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
store.m31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
store.m02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
store.m12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
store.m22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
store.m32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
store.m03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
store.m13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
store.m23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
store.m33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
float fInvDet = 1.0f / fDet;
store.multLocal(fInvDet);
return store;
}
ame::Matrix4f ame::Matrix4f::invertLocal() {
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
if (FastMath.abs(fDet) <= 0f) {
return zero();
}
float f00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
float f10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
float f20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
float f30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
float f01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
float f11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
float f21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
float f31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
float f02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
float f12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
float f22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
float f32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
float f03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
float f13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
float f23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
float f33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
m00 = f00;
m01 = f01;
m02 = f02;
m03 = f03;
m10 = f10;
m11 = f11;
m12 = f12;
m13 = f13;
m20 = f20;
m21 = f21;
m22 = f22;
m23 = f23;
m30 = f30;
m31 = f31;
m32 = f32;
m33 = f33;
float fInvDet = 1.0f / fDet;
multLocal(fInvDet);
return this;
}
ame::Matrix4f ame::Matrix4f::adjoint() {
return adjoint(null);
}
void ame::Matrix4f::setTransform(Vector3f position, Vector3f scale, Matrix3f rotMat) {
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
// Set up final matrix with scale, rotation and translation
m00 = scale.x * rotMat.m00;
m01 = scale.y * rotMat.m01;
m02 = scale.z * rotMat.m02;
m03 = position.x;
m10 = scale.x * rotMat.m10;
m11 = scale.y * rotMat.m11;
m12 = scale.z * rotMat.m12;
m13 = position.y;
m20 = scale.x * rotMat.m20;
m21 = scale.y * rotMat.m21;
m22 = scale.z * rotMat.m22;
m23 = position.z;
// No projection term
m30 = 0;
m31 = 0;
m32 = 0;
m33 = 1;
}
ame::Matrix4f ame::Matrix4f::adjoint(ame::Matrix4f store) {
if (store == null) {
store = new ame::Matrix4f();
}
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
store.m00 = +m11 * fB5 - m12 * fB4 + m13 * fB3;
store.m10 = -m10 * fB5 + m12 * fB2 - m13 * fB1;
store.m20 = +m10 * fB4 - m11 * fB2 + m13 * fB0;
store.m30 = -m10 * fB3 + m11 * fB1 - m12 * fB0;
store.m01 = -m01 * fB5 + m02 * fB4 - m03 * fB3;
store.m11 = +m00 * fB5 - m02 * fB2 + m03 * fB1;
store.m21 = -m00 * fB4 + m01 * fB2 - m03 * fB0;
store.m31 = +m00 * fB3 - m01 * fB1 + m02 * fB0;
store.m02 = +m31 * fA5 - m32 * fA4 + m33 * fA3;
store.m12 = -m30 * fA5 + m32 * fA2 - m33 * fA1;
store.m22 = +m30 * fA4 - m31 * fA2 + m33 * fA0;
store.m32 = -m30 * fA3 + m31 * fA1 - m32 * fA0;
store.m03 = -m21 * fA5 + m22 * fA4 - m23 * fA3;
store.m13 = +m20 * fA5 - m22 * fA2 + m23 * fA1;
store.m23 = -m20 * fA4 + m21 * fA2 - m23 * fA0;
store.m33 = +m20 * fA3 - m21 * fA1 + m22 * fA0;
return store;
}
float ame::Matrix4f::determinant() {
float fA0 = m00 * m11 - m01 * m10;
float fA1 = m00 * m12 - m02 * m10;
float fA2 = m00 * m13 - m03 * m10;
float fA3 = m01 * m12 - m02 * m11;
float fA4 = m01 * m13 - m03 * m11;
float fA5 = m02 * m13 - m03 * m12;
float fB0 = m20 * m31 - m21 * m30;
float fB1 = m20 * m32 - m22 * m30;
float fB2 = m20 * m33 - m23 * m30;
float fB3 = m21 * m32 - m22 * m31;
float fB4 = m21 * m33 - m23 * m31;
float fB5 = m22 * m33 - m23 * m32;
float fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0;
return fDet;
}
ame::Matrix4f ame::Matrix4f::zero() {
m00 = m01 = m02 = m03 = 0.0f;
m10 = m11 = m12 = m13 = 0.0f;
m20 = m21 = m22 = m23 = 0.0f;
m30 = m31 = m32 = m33 = 0.0f;
return this;
}
ame::Matrix4f ame::Matrix4f::addLValue(ame::Matrix4f mat) {
ame::Matrix4f result = new ame::Matrix4f();
result.m00 = this.m00 + mat.m00;
result.m01 = this.m01 + mat.m01;
result.m02 = this.m02 + mat.m02;
result.m03 = this.m03 + mat.m03;
result.m10 = this.m10 + mat.m10;
result.m11 = this.m11 + mat.m11;
result.m12 = this.m12 + mat.m12;
result.m13 = this.m13 + mat.m13;
result.m20 = this.m20 + mat.m20;
result.m21 = this.m21 + mat.m21;
result.m22 = this.m22 + mat.m22;
result.m23 = this.m23 + mat.m23;
result.m30 = this.m30 + mat.m30;
result.m31 = this.m31 + mat.m31;
result.m32 = this.m32 + mat.m32;
result.m33 = this.m33 + mat.m33;
return result;
}
void ame::Matrix4f::addLValueLocal(ame::Matrix4f mat) {
m00 += mat.m00;
m01 += mat.m01;
m02 += mat.m02;
m03 += mat.m03;
m10 += mat.m10;
m11 += mat.m11;
m12 += mat.m12;
m13 += mat.m13;
m20 += mat.m20;
m21 += mat.m21;
m22 += mat.m22;
m23 += mat.m23;
m30 += mat.m30;
m31 += mat.m31;
m32 += mat.m32;
m33 += mat.m33;
}
Vector3f ame::Matrix4f::toTranslationVector() {
return new Vector3f(m03, m13, m23);
}
void ame::Matrix4f::toTranslationVector(Vector3f vector) {
vector.set(m03, m13, m23);
}
Quaternion ame::Matrix4f::toRotationQuat() {
Quaternion quat = new Quaternion();
quat.fromRotationMatrix(toRotationMatrix());
return quat;
}
void ame::Matrix4f::toRotationQuat(Quaternion q) {
q.fromRotationMatrix(toRotationMatrix());
}
Matrix3f ame::Matrix4f::toRotationMatrix() {
return new Matrix3f(m00, m01, m02, m10, m11, m12, m20, m21, m22);
}
void ame::Matrix4f::toRotationMatrix(Matrix3f mat) {
mat.m00 = m00;
mat.m01 = m01;
mat.m02 = m02;
mat.m10 = m10;
mat.m11 = m11;
mat.m12 = m12;
mat.m20 = m20;
mat.m21 = m21;
mat.m22 = m22;
}
Vector3f ame::Matrix4f::toScaleVector() {
Vector3f result = new Vector3f();
this.toScaleVector(result);
return result;
}
void ame::Matrix4f::toScaleVector(Vector3f vector) {
float scaleX = (float) Math.sqrt(m00 * m00 + m10 * m10 + m20 * m20);
float scaleY = (float) Math.sqrt(m01 * m01 + m11 * m11 + m21 * m21);
float scaleZ = (float) Math.sqrt(m02 * m02 + m12 * m12 + m22 * m22);
vector.set(scaleX, scaleY, scaleZ);
}
void ame::Matrix4f::setScale(float x, float y, float z) {
TempVars vars = TempVars.get();
vars.vect1.set(m00, m10, m20);
vars.vect1.normalizeLocal().multLocal(x);
m00 = vars.vect1.x;
m10 = vars.vect1.y;
m20 = vars.vect1.z;
vars.vect1.set(m01, m11, m21);
vars.vect1.normalizeLocal().multLocal(y);
m01 = vars.vect1.x;
m11 = vars.vect1.y;
m21 = vars.vect1.z;
vars.vect1.set(m02, m12, m22);
vars.vect1.normalizeLocal().multLocal(z);
m02 = vars.vect1.x;
m12 = vars.vect1.y;
m22 = vars.vect1.z;
vars.release();
}
void ame::Matrix4f::setScale(Vector3f scale) {
this.setScale(scale.x, scale.y, scale.z);
}
void ame::Matrix4f::setTranslation(float[] translation) {
if (translation.length != 3) {
throw new IllegalArgumentException(
"Translation size must be 3.");
}
m03 = translation[0];
m13 = translation[1];
m23 = translation[2];
}
void ame::Matrix4f::setTranslation(float x, float y, float z) {
m03 = x;
m13 = y;
m23 = z;
}
void ame::Matrix4f::setTranslation(Vector3f translation) {
m03 = translation.x;
m13 = translation.y;
m23 = translation.z;
}
void ame::Matrix4f::setInverseTranslation(float[] translation) {
if (translation.length != 3) {
throw new IllegalArgumentException(
"Translation size must be 3.");
}
m03 = -translation[0];
m13 = -translation[1];
m23 = -translation[2];
}
void ame::Matrix4f::angleRotation(Vector3f angles) {
float angle;
float sr, sp, sy, cr, cp, cy;
angle = (angles.z * FastMath.DEG_TO_RAD);
sy = FastMath.sin(angle);
cy = FastMath.cos(angle);
angle = (angles.y * FastMath.DEG_TO_RAD);
sp = FastMath.sin(angle);
cp = FastMath.cos(angle);
angle = (angles.x * FastMath.DEG_TO_RAD);
sr = FastMath.sin(angle);
cr = FastMath.cos(angle);
// matrix = (Z * Y) * X
m00 = cp * cy;
m10 = cp * sy;
m20 = -sp;
m01 = sr * sp * cy + cr * -sy;
m11 = sr * sp * sy + cr * cy;
m21 = sr * cp;
m02 = (cr * sp * cy + -sr * -sy);
m12 = (cr * sp * sy + -sr * cy);
m22 = cr * cp;
m03 = 0.0f;
m13 = 0.0f;
m23 = 0.0f;
}
void ame::Matrix4f::setRotationQuaternion(Quaternion quat) {
quat.toRotationMatrix(this);
}
void ame::Matrix4f::setInverseRotationRadians(float[] angles) {
if (angles.length != 3) {
throw new IllegalArgumentException(
"Angles must be of size 3.");
}
double cr = FastMath.cos(angles[0]);
double sr = FastMath.sin(angles[0]);
double cp = FastMath.cos(angles[1]);
double sp = FastMath.sin(angles[1]);
double cy = FastMath.cos(angles[2]);
double sy = FastMath.sin(angles[2]);
m00 = (float) (cp * cy);
m10 = (float) (cp * sy);
m20 = (float) (-sp);
double srsp = sr * sp;
double crsp = cr * sp;
m01 = (float) (srsp * cy - cr * sy);
m11 = (float) (srsp * sy + cr * cy);
m21 = (float) (sr * cp);
m02 = (float) (crsp * cy + sr * sy);
m12 = (float) (crsp * sy - sr * cy);
m22 = (float) (cr * cp);
}
void ame::Matrix4f::setInverseRotationDegrees(float[] angles) {
if (angles.length != 3) {
throw new IllegalArgumentException(
"Angles must be of size 3.");
}
float vec[] = new float[3];
vec[0] = (angles[0] * FastMath.RAD_TO_DEG);
vec[1] = (angles[1] * FastMath.RAD_TO_DEG);
vec[2] = (angles[2] * FastMath.RAD_TO_DEG);
setInverseRotationRadians(vec);
}
void ame::Matrix4f::inverseTranslateVect(float[] vec) {
if (vec.length != 3) {
throw new IllegalArgumentException(
"vec must be of size 3.");
}
vec[0] = vec[0] - m03;
vec[1] = vec[1] - m13;
vec[2] = vec[2] - m23;
}
void ame::Matrix4f::inverseTranslateVect(Vector3f data) {
data.x -= m03;
data.y -= m13;
data.z -= m23;
}
void ame::Matrix4f::translateVect(Vector3f data) {
data.x += m03;
data.y += m13;
data.z += m23;
}
void ame::Matrix4f::inverseRotateVect(Vector3f vec) {
float vx = vec.x, vy = vec.y, vz = vec.z;
vec.x = vx * m00 + vy * m10 + vz * m20;
vec.y = vx * m01 + vy * m11 + vz * m21;
vec.z = vx * m02 + vy * m12 + vz * m22;
}
void ame::Matrix4f::rotateVect(Vector3f vec) {
float vx = vec.x, vy = vec.y, vz = vec.z;
vec.x = vx * m00 + vy * m01 + vz * m02;
vec.y = vx * m10 + vy * m11 + vz * m12;
vec.z = vx * m20 + vy * m21 + vz * m22;
}
String ame::Matrix4f::toString() {
StringBuilder result = new StringBuilder("ame::Matrix4f\n[\n");
result.append(" ");
result.append(m00);
result.append(" ");
result.append(m01);
result.append(" ");
result.append(m02);
result.append(" ");
result.append(m03);
result.append(" \n");
result.append(" ");
result.append(m10);
result.append(" ");
result.append(m11);
result.append(" ");
result.append(m12);
result.append(" ");
result.append(m13);
result.append(" \n");
result.append(" ");
result.append(m20);
result.append(" ");
result.append(m21);
result.append(" ");
result.append(m22);
result.append(" ");
result.append(m23);
result.append(" \n");
result.append(" ");
result.append(m30);
result.append(" ");
result.append(m31);
result.append(" ");
result.append(m32);
result.append(" ");
result.append(m33);
result.append(" \n]");
return result.toString();
}
bool ame::Matrix4f::equals(Object *o) {
if (!(o instanceof ame::Matrix4f) || o == null) {
return false;
}
if (this == o) {
return true;
}
ame::Matrix4f comp = (ame::Matrix4f) o;
if (Float.compare(m00, comp.m00) != 0) {
return false;
}
if (Float.compare(m01, comp.m01) != 0) {
return false;
}
if (Float.compare(m02, comp.m02) != 0) {
return false;
}
if (Float.compare(m03, comp.m03) != 0) {
return false;
}
if (Float.compare(m10, comp.m10) != 0) {
return false;
}
if (Float.compare(m11, comp.m11) != 0) {
return false;
}
if (Float.compare(m12, comp.m12) != 0) {
return false;
}
if (Float.compare(m13, comp.m13) != 0) {
return false;
}
if (Float.compare(m20, comp.m20) != 0) {
return false;
}
if (Float.compare(m21, comp.m21) != 0) {
return false;
}
if (Float.compare(m22, comp.m22) != 0) {
return false;
}
if (Float.compare(m23, comp.m23) != 0) {
return false;
}
if (Float.compare(m30, comp.m30) != 0) {
return false;
}
if (Float.compare(m31, comp.m31) != 0) {
return false;
}
if (Float.compare(m32, comp.m32) != 0) {
return false;
}
if (Float.compare(m33, comp.m33) != 0) {
return false;
}
return true;
}
// void write(JmeExporter e) throws IOException {
// OutputCapsule cap = e.getCapsule(this);
// cap.write(m00, "m00", 1);
// cap.write(m01, "m01", 0);
// cap.write(m02, "m02", 0);
// cap.write(m03, "m03", 0);
// cap.write(m10, "m10", 0);
// cap.write(m11, "m11", 1);
// cap.write(m12, "m12", 0);
// cap.write(m13, "m13", 0);
// cap.write(m20, "m20", 0);
// cap.write(m21, "m21", 0);
// cap.write(m22, "m22", 1);
// cap.write(m23, "m23", 0);
// cap.write(m30, "m30", 0);
// cap.write(m31, "m31", 0);
// cap.write(m32, "m32", 0);
// cap.write(m33, "m33", 1);
// }
// void read(JmeImporter e) throws IOException {
// InputCapsule cap = e.getCapsule(this);
// m00 = cap.readFloat("m00", 1);
// m01 = cap.readFloat("m01", 0);
// m02 = cap.readFloat("m02", 0);
// m03 = cap.readFloat("m03", 0);
// m10 = cap.readFloat("m10", 0);
// m11 = cap.readFloat("m11", 1);
// m12 = cap.readFloat("m12", 0);
// m13 = cap.readFloat("m13", 0);
// m20 = cap.readFloat("m20", 0);
// m21 = cap.readFloat("m21", 0);
// m22 = cap.readFloat("m22", 1);
// m23 = cap.readFloat("m23", 0);
// m30 = cap.readFloat("m30", 0);
// m31 = cap.readFloat("m31", 0);
// m32 = cap.readFloat("m32", 0);
// m33 = cap.readFloat("m33", 1);
// }
bool ame::Matrix4f::isIdentity() {
return (m00 == 1 && m01 == 0 && m02 == 0 && m03 == 0)
&& (m10 == 0 && m11 == 1 && m12 == 0 && m13 == 0)
&& (m20 == 0 && m21 == 0 && m22 == 1 && m23 == 0)
&& (m30 == 0 && m31 == 0 && m32 == 0 && m33 == 1);
}
void ame::Matrix4f::scale(Vector3f scale) {
m00 *= scale.getX();
m10 *= scale.getX();
m20 *= scale.getX();
m30 *= scale.getX();
m01 *= scale.getY();
m11 *= scale.getY();
m21 *= scale.getY();
m31 *= scale.getY();
m02 *= scale.getZ();
m12 *= scale.getZ();
m22 *= scale.getZ();
m32 *= scale.getZ();
}
bool ame::Matrix4f::equalIdentity(ame::Matrix4f mat) {
if (Math.abs(mat.m00 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m11 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m22 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m33 - 1) > 1e-4) {
return false;
}
if (Math.abs(mat.m01) > 1e-4) {
return false;
}
if (Math.abs(mat.m02) > 1e-4) {
return false;
}
if (Math.abs(mat.m03) > 1e-4) {
return false;
}
if (Math.abs(mat.m10) > 1e-4) {
return false;
}
if (Math.abs(mat.m12) > 1e-4) {
return false;
}
if (Math.abs(mat.m13) > 1e-4) {
return false;
}
if (Math.abs(mat.m20) > 1e-4) {
return false;
}
if (Math.abs(mat.m21) > 1e-4) {
return false;
}
if (Math.abs(mat.m23) > 1e-4) {
return false;
}
if (Math.abs(mat.m30) > 1e-4) {
return false;
}
if (Math.abs(mat.m31) > 1e-4) {
return false;
}
if (Math.abs(mat.m32) > 1e-4) {
return false;
}
return true;
}
void ame::Matrix4f::multLocal(Quaternion rotation) {
Vector3f axis = new Vector3f();
float angle = rotation.toAngleAxis(axis);
ame::Matrix4f ame::Matrix4f = new ame::Matrix4f();
ame::Matrix4f.fromAngleAxis(angle, axis);
multLocal(ame::Matrix4f);
}
ame::Matrix4f *ame::Matrix4f::clone() {
}
*/
#endif
| 31.944313
| 125
| 0.473109
|
PankeyCR
|
9344a6ad1befd9f84148b291e984f69434968892
| 8,354
|
cpp
|
C++
|
src/hpglopenglparser.cpp
|
jusirkka/qopencpn
|
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
|
[
"ISC",
"X11",
"MIT"
] | 2
|
2021-07-09T14:13:55.000Z
|
2022-02-11T06:41:03.000Z
|
src/hpglopenglparser.cpp
|
jusirkka/qopencpn
|
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
|
[
"ISC",
"X11",
"MIT"
] | null | null | null |
src/hpglopenglparser.cpp
|
jusirkka/qopencpn
|
5e514ae8f43199c4d52278df6e4df85c46bd1ddc
|
[
"ISC",
"X11",
"MIT"
] | 2
|
2022-02-11T06:41:05.000Z
|
2022-03-17T09:29:46.000Z
|
/* -*- coding: utf-8-unix -*-
*
* File: src/hpglparser.cpp
*
* Copyright (C) 2021 Jukka Sirkka
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hpglopenglparser.h"
#include <QDebug>
#include <glm/glm.hpp>
#include "triangulator.h"
#include "geomutils.h"
HPGL::OpenGLParser::OpenGLParser(const QString &src, const QString& colors,
const QPointF& pivot)
: Parser(colors)
, m_started(false)
, m_penDown(false)
, m_pivot(pivot)
{
parse(src);
if (!m_ok) {
return;
}
while (m_sketches.size() > 0) {
edgeSketch();
}
edgeSketch();
DataIterator it = m_storage.begin();
while (it != m_storage.end()) {
m_data.append(it.value());
it = m_storage.erase(it);
}
}
void HPGL::OpenGLParser::setColor(char c) {
if (!m_cmap.contains(c)) {
qWarning() << c << "not in colormap";
m_ok = false;
return;
}
const quint32 index = m_cmap[c];
if (!m_started) {
m_started = true;
m_currentSketch.color = S52::Color(index);
m_currentSketch.lineWidth = 0.;
LineString ls;
ls.closed = false;
m_currentSketch.parts.append(ls);
} else if (m_currentSketch.color.index != index) {
Sketch sketch = m_currentSketch.clone();
sketch.color.index = index;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::setAlpha(int a) {
auto alpha = as_enum<S52::Alpha>(a, S52::AllAlphas);
if (m_currentSketch.color.alpha == S52::Alpha::Unset) {
m_currentSketch.color.alpha = alpha;
} else if (m_currentSketch.color.alpha != alpha) {
Sketch sketch = m_currentSketch.clone();
sketch.color.alpha = alpha;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::setWidth(int w) {
const qreal lw = S52::LineWidthMM(w);
if (m_currentSketch.lineWidth == 0.) {
m_currentSketch.lineWidth = lw;
} else if (m_currentSketch.lineWidth != lw) {
Sketch sketch = m_currentSketch.clone();
sketch.lineWidth = lw;
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
}
void HPGL::OpenGLParser::movePen(const RawPoints &ps) {
if (ps.size() % 2 != 0) {
qWarning() << ps << "contains odd number of coordinates";
m_ok = false;
return;
}
m_pen = makePoint(ps[ps.size() - 2], ps[ps.size() - 1]);
LineString ls;
ls.closed = false;
m_currentSketch.parts.append(ls);
m_penDown = false;
}
void HPGL::OpenGLParser::drawLineString(const RawPoints &ps) {
if (ps.isEmpty()) {
// draw a single point
drawPoint();
m_penDown = true;
return;
}
if (ps.size() % 2 != 0) {
qWarning() << ps << "contains odd number of coordinates";
m_ok = false;
return;
}
if (!m_penDown) {
m_currentSketch.parts.last().points.append(m_pen);
}
for (int i = 0; i < ps.size() / 2; i++) {
m_currentSketch.parts.last().points.append(makePoint(ps[2 * i], ps[2 * i + 1]));
}
m_currentSketch.parts.last().closed =
m_currentSketch.parts.last().points.first() ==
m_currentSketch.parts.last().points.last();
m_pen = m_currentSketch.parts.last().points.last();
m_penDown = true;
}
void HPGL::OpenGLParser::drawPoint() {
pushSketch();
// opaque fill
m_currentSketch.color.alpha = S52::Alpha::P0;
const qreal lw = m_currentSketch.lineWidth == 0. ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const QPointF q = .5 * QPointF(lw, lw);
const QPointF p = .5 * QPointF(lw, -lw);
m_currentSketch.parts.last().closed = true;
m_currentSketch.parts.last().points.append(m_pen - q);
m_currentSketch.parts.last().points.append(m_pen + p);
m_currentSketch.parts.last().points.append(m_pen + q);
m_currentSketch.parts.last().points.append(m_pen - p);
m_currentSketch.parts.last().points.append(m_pen - q);
fillSketch();
}
void HPGL::OpenGLParser::drawCircle(int r0) {
LineString ls;
ls.closed = true;
const qreal lw = m_currentSketch.lineWidth == 0 ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const qreal r = mmUnit * r0;
auto n = qMin(90, 3 + 4 * static_cast<int>(r / lw));
for (int i = 0; i <= n; i++) {
const qreal a = 2 * i * M_PI / n;
const QPointF p = m_pen + QPointF(r * cos(a), r * sin(a));
ls.points.append(p);
}
m_currentSketch.parts.append(ls);
LineString ls2;
ls2.closed = false;
if (m_penDown) {
ls2.points.append(m_pen);
}
m_currentSketch.parts.append(ls2);
}
void HPGL::OpenGLParser::drawArc(int x0, int y0, int a0) {
LineString ls;
ls.closed = false;
const qreal lw = m_currentSketch.lineWidth == 0 ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
const QPointF c = makePoint(x0, y0);
const QPointF d = m_pen - c;
const qreal r = sqrt(QPointF::dotProduct(d, d));
const int n = qMin(90., std::ceil((3. + 4 * r / lw) * a0 / 360.));
for (int i = 0; i <= n; i++) {
const qreal a = a0 / 180. * i * M_PI / n;
const qreal ca = cos(a);
const qreal sa = sin(a);
const QPointF p = c + QPointF(ca * d.x() - sa * d.y(), sa * d.x() + ca * d.y());
ls.points.append(p);
}
m_currentSketch.parts.append(ls);
LineString ls2;
ls2.closed = false;
if (m_penDown) {
ls2.points.append(m_pen);
}
m_currentSketch.parts.append(ls2);
}
void HPGL::OpenGLParser::pushSketch() {
Sketch sketch = m_currentSketch.clone();
m_sketches.push(m_currentSketch);
m_currentSketch = sketch;
}
void HPGL::OpenGLParser::endSketch() {
// noop
}
void HPGL::OpenGLParser::fillSketch() {
// triangulate
Data d;
d.color = m_currentSketch.color;
if (d.color.alpha == S52::Alpha::Unset) {
d.color.alpha = S52::Alpha::P0;
}
for (const LineString& part: m_currentSketch.parts) {
if (!part.closed) continue;
if (part.points.size() < 3) continue;
triangulate(part.points, d);
}
// merge storage
if (!d.vertices.isEmpty()) {
if (m_storage.contains(d.color)) {
mergeData(m_storage[d.color], d);
} else {
m_storage.insert(d.color, d);
}
}
// pop sketch
if (!m_sketches.isEmpty()) {
m_currentSketch = m_sketches.pop();
}
}
void HPGL::OpenGLParser::edgeSketch() {
// thicker lines
Data d;
d.color.index = m_currentSketch.color.index;
d.color.alpha = S52::Alpha::P0;
const qreal lw = m_currentSketch.lineWidth == 0. ?
S52::LineWidthMM(1) : m_currentSketch.lineWidth;
for (const LineString& part: m_currentSketch.parts) {
if (part.points.size() < 2) continue;
thickerlines(part, lw, d);
}
// merge storage
if (!d.vertices.isEmpty()) {
if (m_storage.contains(d.color)) {
mergeData(m_storage[d.color], d);
} else {
m_storage.insert(d.color, d);
}
}
// pop sketch
if (!m_sketches.isEmpty()) {
m_currentSketch = m_sketches.pop();
}
}
void HPGL::OpenGLParser::mergeData(Data &tgt, const Data &d) {
const GLuint offset = tgt.vertices.size() / 2;
tgt.vertices.append(d.vertices);
for (auto index: d.indices) {
tgt.indices << offset + index;
}
}
QPointF HPGL::OpenGLParser::makePoint(int x, int y) const {
return QPointF(x * mmUnit - m_pivot.x(),
m_pivot.y() - y * mmUnit);
}
void HPGL::OpenGLParser::triangulate(const PointList& points, Data& out) {
GL::VertexVector vertices;
for (const QPointF p0: points) {
vertices << p0.x() << p0.y();
}
Triangulator tri(vertices);
tri.addPolygon(0, vertices.size() / 2 - 1);
auto indices = tri.triangulate();
const GLuint offset = out.vertices.size() / 2;
out.vertices.append(vertices);
for (auto index: indices) {
out.indices << offset + index;
}
}
void HPGL::OpenGLParser::thickerlines(const LineString &ls, qreal lw, Data &out) {
thickerLines(ls.points, ls.closed, lw, out.vertices, out.indices);
}
| 26.605096
| 84
| 0.645918
|
jusirkka
|
934930d25543e1a3a1034663733da437300199c0
| 1,161
|
cpp
|
C++
|
2021.09.08-Lesson-1/Project3/Source.cpp
|
021213/programming-c-eng--2021-autumn
|
84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348
|
[
"Apache-2.0"
] | null | null | null |
2021.09.08-Lesson-1/Project3/Source.cpp
|
021213/programming-c-eng--2021-autumn
|
84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348
|
[
"Apache-2.0"
] | null | null | null |
2021.09.08-Lesson-1/Project3/Source.cpp
|
021213/programming-c-eng--2021-autumn
|
84ff4e86e7b4ee68d5bfd83ef6388a1f3e762348
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
int main()
{
int a = 3;
int b = 5;
int c = 0;
c = a + b;
c = a - b;
c = a * b;
c = a / b;
c = a % b;
a += b;
a *= b;
a /= b; // a = a / b;
a %= b; // a = a / b;
a -= b; // a = a - b;
float f = 0;
a = 5;
b = 2;
f = a / b; // 2.0
f = (float)a / b;
f = 1.0f * a / b;
c = a | b;
c = a & b;
c = a ^ b;
cout << a << " " << b << endl;
a ^= b ^= a ^= b;
cout << a << " " << b << "\n";
a = 7; // 0000 0111
a = a << 2; // 0001 1100
cout << a << endl;
a = 7; // 0000 0111
a = a >> 1; // 0000 0011
cout << a << endl;
a++;
++a;
a--;
--a;
a = 7;
// 7 + 9 + 10 + 10
a = a++ + ++a + ++a + a++;
cout << a << endl; //38
a = 7;
a = ~a; // -8
a = 9;
a = ~a; // -10
// 1 1111 111
// 9 = 0000 1001
// -9 = 1111 0111
//9-9 = 1 0000 0000
// 9 = 0000 1001
// ~9 = 1111 0110 == -10
// ~9+1 = 1111 0111 == -9
bool bA = true;
bool bB = true;
bool bC = true;
bC = bA && bB;
bC = bA || bB;
bC = bA ^ bB;
bC = bA == bB;
bC = !bA;
a = 10;
b = 19;
c = (a > b ? a : b);
if (a > b)
{
c = a;
}
else
{
c = b;
}
return EXIT_SUCCESS;
}
| 12.619565
| 31
| 0.356589
|
021213
|
934e5aef93fda065b64434dfaa69269c0db2d171
| 16,781
|
cpp
|
C++
|
iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp
|
River707/iree
|
09b7742466ce7fb48742fd900e6c1f66cf51d3f3
|
[
"Apache-2.0"
] | 1
|
2020-08-16T17:38:25.000Z
|
2020-08-16T17:38:25.000Z
|
iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp
|
georgemitenkov/iree
|
77d2f8b4fd53f1dbe7ef03b4b4a7ba7be06f2416
|
[
"Apache-2.0"
] | null | null | null |
iree/compiler/Conversion/LinalgToSPIRV/LinalgTileAndFusePass.cpp
|
georgemitenkov/iree
|
77d2f8b4fd53f1dbe7ef03b4b4a7ba7be06f2416
|
[
"Apache-2.0"
] | 1
|
2021-01-29T09:30:09.000Z
|
2021-01-29T09:30:09.000Z
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//===- LinalgTilingOnBuffers.cpp - Tile and fuse Linalg on Buffers --------===//
//
// Implements a pass to tile and fuse linalg operations on buffers.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/Conversion/LinalgToSPIRV/Attributes.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/MarkerUtils.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/MemorySpace.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/Passes.h"
#include "iree/compiler/Conversion/LinalgToSPIRV/Utils.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/Linalg/Utils/Utils.h"
#include "mlir/Dialect/SPIRV/SPIRVOps.h"
#include "mlir/Dialect/SPIRV/TargetAndABI.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Identifier.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/FoldUtils.h"
#define DEBUG_TYPE "iree-linalg-tile-and-fuse-buffer"
static std::string PromotionMarker = "promotion";
namespace mlir {
namespace iree_compiler {
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
static ArrayRef<int64_t> dropTrailingOnes(ArrayRef<int64_t> vector) {
if (vector.empty()) return vector;
auto numTrailingOnes = 0;
for (unsigned i = vector.size() - 1; i > 0; --i) {
if (vector[i] != 1) {
break;
}
numTrailingOnes++;
}
return vector.drop_back(numTrailingOnes);
}
/// Returns true if the linalg op has padding attribute, and that it has
/// non-zero entries.
template <typename OpTy>
static bool hasPadding(OpTy op) {
Optional<DenseIntElementsAttr> padding = op.padding();
if (!padding) return false;
return llvm::any_of(padding.getValue(),
[](APInt v) -> bool { return !v.isNullValue(); });
}
namespace {
/// Computes tile sizes (and workgroup size) to use based on operations within
/// the function, and resource constraints on the module.
class TileSizeCalculator {
public:
TileSizeCalculator(FuncOp funcOp)
: resourceLimits(spirv::lookupTargetEnv(funcOp).getResourceLimits()) {
if (DenseIntElementsAttr attr = spirv::lookupLocalWorkGroupSize(funcOp)) {
for (auto val : attr.getValues<APInt>())
workgroupSize.push_back(val.getSExtValue());
}
workgroupSize.resize(3, 1);
}
/// Compute the tile sizes based on workgroup size specified.
LogicalResult setTileSizesBasedOnWorkgroupSize(
ArrayRef<int64_t> vWorkGroupSize) {
if (!vWorkGroupSize.empty()) {
vWorkGroupSize = dropTrailingOnes(vWorkGroupSize);
workgroupSize.assign(vWorkGroupSize.begin(), vWorkGroupSize.end());
auto rev = reverse(workgroupSize);
tileSizes.assign(rev.begin(), rev.end());
}
return success();
}
/// Compute the tile sizes based on the Linalg Ops within the dispatch region.
LogicalResult setTileSizesBasedOnOps(ArrayRef<linalg::LinalgOp> linalgOps);
/// Get the current tile size computed.
ArrayRef<int64_t> getTileSizes() const { return tileSizes; }
/// Returns the workgroup size to use based on the tile sizes.
ArrayRef<int64_t> getWorkGroupSize() const { return workgroupSize; }
private:
/// Current tile size configuration.
SmallVector<int64_t, 4> tileSizes;
/// Workgroup size to use.
SmallVector<int64_t, 3> workgroupSize;
/// Attribute for device constraints.
spirv::ResourceLimitsAttr resourceLimits;
};
} // namespace
LogicalResult TileSizeCalculator::setTileSizesBasedOnOps(
ArrayRef<linalg::LinalgOp> linalgOps) {
tileSizes.clear();
if (linalgOps.empty()) {
tileSizes = {1, 1, 1};
workgroupSize = {1, 1, 1};
return success();
}
// The tile size will be driven by operations like matmul, conv, etc. within
// the list. So see what operation exists in the list to decide the tile size.
// If there are two such operations in the list, return error.
enum OpInfo : uint32_t {
None = 0x0,
Convolution = 0x1,
Matmul = 0x2,
Pooling = 0x4,
};
uint32_t opInfo = OpInfo::None;
for (linalg::LinalgOp linalgOp : linalgOps) {
Operation *op = linalgOp.getOperation();
if (isa<linalg::ConvOp>(op)) opInfo |= OpInfo::Convolution;
if (isa<linalg::MatmulOp>(op)) opInfo |= OpInfo::Matmul;
if (isa<linalg::PoolingMaxOp>(op)) opInfo |= OpInfo::Pooling;
if (isa<linalg::PoolingMinOp>(op)) opInfo |= OpInfo::Pooling;
if (isa<linalg::PoolingSumOp>(op)) opInfo |= OpInfo::Pooling;
}
// If there are no tilable ops, there is nothing to do here.
if (!opInfo) return success();
Operation *linalgOp = *(linalgOps.begin());
if (llvm::countPopulation(opInfo) != 1)
return linalgOp->getParentOfType<FuncOp>().emitError(
"unhandled fusion of ops in dispatch function");
// TODO(ravishanarm, antiagainst): Only the maximum workgroup size is used
// here for computing tile sizes. In reality we also need the maximum
// workgroup memory size available (per workgroup) to compute the tile sizes
// effectively.
unsigned maxWorkgroupSize =
resourceLimits.max_compute_workgroup_invocations().getInt();
if (opInfo & OpInfo::Convolution) {
// TODO(ravishankarm): This tiling is meant to enable promotion to workgroup
// memory, but doesnt actually get us to a state where we can do this. The
// promotion is possible only when the subviews created are constant
// size. For now this doesnt really matter. Revisit this later.
int64_t tileSizeX = 32;
int64_t tileSizeY = maxWorkgroupSize / 32;
tileSizes = {1, tileSizeY, tileSizeX};
workgroupSize = {tileSizeX, tileSizeY, 1};
return success();
}
if (opInfo & OpInfo::Matmul) {
// TODO: For now just hard wire this, but we can do better.
tileSizes = {8, 8, 4};
workgroupSize = {8, 8, 1};
return success();
}
if (opInfo & OpInfo::Pooling) {
int64_t tileSizeX = 32;
int64_t tileSizeY = maxWorkgroupSize / 32;
tileSizes = {tileSizeY, tileSizeX};
workgroupSize = {tileSizeX, tileSizeY, 1};
return success();
}
return linalgOp->getParentOfType<FuncOp>().emitError(
"unable to find tile size for ops in this dispatch function");
}
//===----------------------------------------------------------------------===//
// Pass and patterns
//===----------------------------------------------------------------------===//
/// Allocation callback for allocation workgroup local memory.
static Value allocateWorkgroupMemory(OpBuilder &b, SubViewOp subview,
ArrayRef<Value> boundingSubViewSize,
OperationFolder *folder) {
// The bounding subview size is expected to be constant. This specified the
// shape of the allocation.
SmallVector<int64_t, 2> shape(boundingSubViewSize.size(),
ShapedType::kDynamicSize);
return b.create<AllocOp>(
subview.getLoc(),
MemRefType::get(shape, subview.getType().getElementType(), {},
getWorkgroupMemorySpace()),
boundingSubViewSize);
}
/// Deallocation callback for allocation workgroup local memory.
static LogicalResult deallocateWorkgroupMemory(OpBuilder &b, Value buffer) {
auto allocOp = buffer.getDefiningOp<AllocOp>();
b.create<DeallocOp>(allocOp.getLoc(), buffer);
return success();
}
/// Insert barrier after `op`.
static void insertBarrierAfter(OpBuilder &b, Location loc, Operation *op) {
OpBuilder::InsertionGuard guard(b);
b.setInsertionPointAfter(op);
b.create<spirv::ControlBarrierOp>(loc, spirv::Scope::Workgroup,
spirv::Scope::Workgroup,
spirv::MemorySemantics::AcquireRelease);
}
/// Function used as callback for copyin/copyout in promotion pattern used to
/// promote subviews to workgroup memory.
static LogicalResult copyToFromWorkgroupMemory(
OpBuilder &b, Value src, Value dst, StringRef marker = PromotionMarker) {
auto copyOp = b.create<linalg::CopyOp>(src.getLoc(), src, dst);
setMarker(copyOp, marker);
return success();
}
namespace {
/// Function pass that implements tiling and fusion in Linalg on buffers.
struct LinalgTileAndFusePass
: public PassWrapper<LinalgTileAndFusePass, FunctionPass> {
LinalgTileAndFusePass(ArrayRef<int64_t> workGroupSize = {},
bool useWorkgroupMem = false)
: workGroupSize(workGroupSize.begin(), workGroupSize.end()) {
this->useWorkgroupMemory = useWorkgroupMem;
}
LinalgTileAndFusePass(const LinalgTileAndFusePass &pass) {}
void runOnFunction() override;
Option<bool> useWorkgroupMemory{
*this, "use-workgroup-memory",
llvm::cl::desc("Promote subviews to use workgroup memory"),
llvm::cl::init(false)};
private:
SmallVector<int64_t, 3> workGroupSize;
};
/// Pattern for tiling operations. Updates the workgroup size in the surrounding
/// function operation if tiling succeeds.
template <typename OpTy>
struct TilingPattern : public linalg::LinalgTilingPattern<OpTy> {
using Base = linalg::LinalgTilingPattern<OpTy>;
TilingPattern(MLIRContext *context, linalg::LinalgTilingOptions options,
ArrayRef<int64_t> workgroupSize,
linalg::LinalgMarker marker = linalg::LinalgMarker(),
PatternBenefit benefit = 1)
: Base(context, options, marker, benefit),
workgroupSize(workgroupSize.begin(), workgroupSize.end()) {}
virtual LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const {
// Find the parent FuncOp before tiling. If tiling succeeds, the op will be
// erased.
FuncOp funcOp = op->getParentOfType<FuncOp>();
if (!funcOp || failed(Base::matchAndRewrite(op, rewriter)) ||
failed(updateWorkGroupSize(funcOp, workgroupSize)))
return failure();
funcOp.setAttr(getWorkgroupCountAttrName(),
rewriter.getI32IntegerAttr(static_cast<int32_t>(
WorkgroupCountMethodology::ResultShape)));
return success();
}
SmallVector<int64_t, 3> workgroupSize;
};
/// Pattern for tiling convolution and pooling operations. Currently is just a
/// way to not tile when the operation has padding.
template <typename OpTy>
struct TileConvPoolPattern : public TilingPattern<OpTy> {
using Base = TilingPattern<OpTy>;
using Base::TilingPattern;
LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
if (hasPadding(cast<OpTy>(op))) return failure();
FuncOp funcOp = op->getParentOfType<FuncOp>();
if (!funcOp || failed(Base::matchAndRewrite(op, rewriter)) ||
failed(updateWorkGroupSize(funcOp, this->workgroupSize)))
return failure();
funcOp.setAttr(getWorkgroupCountAttrName(),
rewriter.getI32IntegerAttr(static_cast<int32_t>(
WorkgroupCountMethodology::Default)));
return success();
}
};
/// Pattern to promote subviews to memory.
// TODO(ravishankarm): Generalize this for other operations.
struct PromoteSubviewsPattern
: public linalg::LinalgPromotionPattern<linalg::MatmulOp> {
PromoteSubviewsPattern(MLIRContext *context,
linalg::LinalgPromotionOptions options,
linalg::LinalgMarker marker = linalg::LinalgMarker(),
PatternBenefit benefit = 1)
: linalg::LinalgPromotionPattern<linalg::MatmulOp>(
context,
options.setOperandsToPromote({0, 1}).setUseFullTileBuffers(
{false, false}),
marker, benefit) {}
LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
if (!hasWorkGroupMarker(op)) return failure();
return linalg::LinalgPromotionPattern<linalg::MatmulOp>::matchAndRewrite(
op, rewriter);
}
};
} // namespace
void LinalgTileAndFusePass::runOnFunction() {
MLIRContext *context = &getContext();
FuncOp funcOp = getFunction();
Region &body = funcOp.getBody();
if (!llvm::hasSingleElement(body.getBlocks())) {
funcOp.emitError("unhandled dispatch function with multiple blocks");
return signalPassFailure();
}
Block &block = body.front();
auto linalgOps = block.getOps<linalg::LinalgOp>();
if (linalgOps.empty()) return;
TileSizeCalculator tileSizeCalculator(funcOp);
if (workGroupSize.empty()) {
// Get the tile sizes to use for the lowering.
SmallVector<int64_t, 3> tileSizes;
SmallVector<linalg::LinalgOp, 1> opsVec(linalgOps.begin(), linalgOps.end());
if (failed(tileSizeCalculator.setTileSizesBasedOnOps(opsVec)))
return signalPassFailure();
} else {
tileSizeCalculator.setTileSizesBasedOnWorkgroupSize(workGroupSize);
}
LLVM_DEBUG({
llvm::dbgs() << "--- IREE Linalg tile and fuse configuration ---\n";
llvm::dbgs() << "# workgroup sizes at start: [";
interleaveComma(workGroupSize, llvm::dbgs());
llvm::dbgs() << "]\ntile sizes: [";
interleaveComma(tileSizeCalculator.getTileSizes(), llvm::dbgs());
llvm::dbgs() << "]\n";
});
OwningRewritePatternList tilingPatterns;
tilingPatterns.insert<TileConvPoolPattern<linalg::ConvOp>,
TilingPattern<linalg::MatmulOp>,
TileConvPoolPattern<linalg::PoolingMaxOp>,
TileConvPoolPattern<linalg::PoolingMinOp>,
TileConvPoolPattern<linalg::PoolingSumOp>>(
context,
linalg::LinalgTilingOptions()
.setTileSizes(tileSizeCalculator.getTileSizes())
.setLoopType(linalg::LinalgTilingLoopType::ParallelLoops),
tileSizeCalculator.getWorkGroupSize(),
linalg::LinalgMarker(ArrayRef<Identifier>(),
Identifier::get(getWorkGroupMarker(), context)));
applyPatternsAndFoldGreedily(getOperation(), tilingPatterns);
if (useWorkgroupMemory) {
// The promotion patterns are put separate from the tiling patterns to make
// sure that the allocated scratchspace memory is constant sizes which
// requires some folding to trigger.
OwningRewritePatternList promotionPatterns;
promotionPatterns.insert<PromoteSubviewsPattern>(
context,
linalg::LinalgPromotionOptions()
.setAllocationDeallocationFns(allocateWorkgroupMemory,
deallocateWorkgroupMemory)
.setCopyInOutFns(
[&](OpBuilder &b, Value src, Value dst) -> LogicalResult {
return copyToFromWorkgroupMemory(b, src, dst);
},
[&](OpBuilder &b, Value src, Value dst) -> LogicalResult {
return copyToFromWorkgroupMemory(b, src, dst);
}),
linalg::LinalgMarker(Identifier::get(getWorkGroupMarker(), context),
Identifier::get(PromotionMarker, context)));
applyPatternsAndFoldGreedily(getOperation(), promotionPatterns);
}
// Add barrier after all linalg operations marked with workitem marker.
OpBuilder builder(context);
funcOp.walk([&builder](linalg::LinalgOp linalgOp) {
if (hasMarker(linalgOp, PromotionMarker)) {
setWorkGroupMarker(linalgOp);
insertBarrierAfter(builder, linalgOp.getLoc(), linalgOp);
}
});
}
//===----------------------------------------------------------------------===//
// Pass entry point and registration
//===----------------------------------------------------------------------===//
std::unique_ptr<OperationPass<FuncOp>> createLinalgTileAndFusePass(
ArrayRef<int64_t> workGroupSize, bool useWorkgroupMemory) {
return std::make_unique<LinalgTileAndFusePass>(workGroupSize,
useWorkgroupMemory);
}
static PassRegistration<LinalgTileAndFusePass> pass(
"iree-codegen-linalg-tile-and-fuse",
"Tile and fuse Linalg operations on buffers",
[] { return std::make_unique<LinalgTileAndFusePass>(); });
} // namespace iree_compiler
} // namespace mlir
| 39.954762
| 80
| 0.663012
|
River707
|
9350f8ba18aa434405f0b4cf415cf2e97241f204
| 152
|
hpp
|
C++
|
src/tokenizer.hpp
|
sischkg/nxnsattack
|
c20896e40187bbcacb5c0255ff8f3cc7d0592126
|
[
"MIT"
] | 5
|
2020-05-22T10:01:51.000Z
|
2022-01-01T04:45:14.000Z
|
src/tokenizer.hpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 1
|
2020-06-07T14:09:44.000Z
|
2020-06-07T14:09:44.000Z
|
src/tokenizer.hpp
|
sischkg/dns-fuzz-server
|
6f45079014e745537c2f564fdad069974e727da1
|
[
"MIT"
] | 2
|
2020-03-10T03:06:20.000Z
|
2021-07-25T15:07:45.000Z
|
#ifndef TOKENIZER_HPP
#define TOKENIZER_HPP
#include <string>
#include <vector>
std::vector<std::string> tokenize( const std::string &line );
#endif
| 15.2
| 61
| 0.743421
|
sischkg
|
93512b9e6cb0fef8ac747c2a714e04b563eddf0b
| 1,569
|
cpp
|
C++
|
src/graphics/texture.cpp
|
luihabl/tinysdl
|
5159577b4d7dd58d42df4f6790fabcd86e78491b
|
[
"MIT"
] | 2
|
2021-09-10T20:34:55.000Z
|
2021-11-27T11:25:23.000Z
|
src/graphics/texture.cpp
|
luihabl/tinysdl
|
5159577b4d7dd58d42df4f6790fabcd86e78491b
|
[
"MIT"
] | 1
|
2021-10-21T19:23:23.000Z
|
2021-10-21T21:25:29.000Z
|
src/graphics/texture.cpp
|
luihabl/tinysdl
|
5159577b4d7dd58d42df4f6790fabcd86e78491b
|
[
"MIT"
] | null | null | null |
#include <glad/glad.h>
#include "tinysdl/graphics/texture.h"
#include "tinysdl/platform/log.h"
#include "tinysdl/platform/file.h"
using namespace TinySDL;
Image::Image(const char * path) {
this->data = File::load_image(path, &this->w, &this->h, &this->n_comp);
if(!data) Log::error("File does not exist: %s", path);
}
Image::~Image() {
if(data) free_image_data();
}
void Image::free_image_data() {
File::free_image(data);
data = nullptr;
}
void Texture::bind() const {
glBindTexture(GL_TEXTURE_2D, this->id);
}
Texture::Texture(int w, int h, int n_comp, unsigned char * data) : w(w), h(h){
glGenTextures(1, &this->id);
glBindTexture(GL_TEXTURE_2D, this->id);
GLint format = n_comp == 3 ? GL_RGB : GL_RGBA;
glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, data);
full_rect = {0, 0, (float) w, (float) h};
// add a way to set these parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture Texture::from_sprite(Image * spr) {
return Texture(spr->w, spr->h, spr->n_comp, spr->data);
}
Texture Texture::from_file(const char * path) {
Image spr(path);
return Texture(spr.w, spr.h, spr.n_comp, spr.data);
}
Texture Texture::empty(int w, int h) {
return Texture(w, h, 4, NULL);
}
| 27.051724
| 84
| 0.684512
|
luihabl
|
9355019fd7bcf514e4ac35bbedb784badb1fad57
| 4,892
|
cpp
|
C++
|
examples/project3/src/rrt.cpp
|
harsha336/rrt_sig
|
1afa8ad45562f20850360d691c2cc29faf18565b
|
[
"Apache-2.0"
] | null | null | null |
examples/project3/src/rrt.cpp
|
harsha336/rrt_sig
|
1afa8ad45562f20850360d691c2cc29faf18565b
|
[
"Apache-2.0"
] | null | null | null |
examples/project3/src/rrt.cpp
|
harsha336/rrt_sig
|
1afa8ad45562f20850360d691c2cc29faf18565b
|
[
"Apache-2.0"
] | null | null | null |
#include "rrt.h"
RRTGraph::RRTGraph()
{
walls_ = new Walls;
alpha_ = 1;
maxi_ = 3000;
}
void RRTGraph::init(GsPnt2 start, float rt, float win_w, float win_h, GsMat *pos)
{
gsout << "RRTGraph::init: Got the matrix: " << gsnl;
position_ = pos;
root_ = new Node;
path_computed_ = false;
root_->parent = NULL;
root_->p = start;
last_node_ = root_;
nodes_.push_back(root_);
win_width_ = win_w;
win_height_ = win_h;
reach_thresh_ = rt;
new_goal_ = true;
robo_= new Robot;
robo_->pos = GsVec(start.x, start.y, 0);
robo_->m = 2.0f;
robo_->vel = GsVec2(0.0f,0.0f);
robo_->max_force = 2.0f;
robo_->max_speed = 0.1f;
robo_->steer_dir = GsVec(0.0f, 0.0f, 0.0f);
}
Node* RRTGraph::getRandomNode()
{
float x = rand() % 201 + (-100);
float y = rand() % 201 + (-100);
pnt p(x,y);
Node *ret;
//gsout << "Getting random node: " << p << gsnl;
if(x >= -100 && x <= 100 && y >= -100 && y <= 100)
{
ret = new Node;
ret->p = p;
return ret;
}
return NULL;
}
Node* RRTGraph::nearestPoint(pnt p)
{
float minDist = 1e9;
Node* nearest = NULL;
for(int i=0; i<nodes_.size(); i++)
{
float d = dist(p,nodes_[i]->p);
if(d < minDist)
{
minDist = d;
nearest = nodes_[i];
}
}
return nearest;
}
pnt RRTGraph::findConfig(Node *c, Node *c_near)
{
pnt to = c->p;
pnt from = c_near->p;
pnt inter = to - from;
inter = inter / inter.norm();
pnt ai(alpha_*inter.x, alpha_*inter.y);
pnt ret = from + ai;
return ret;
}
void RRTGraph::addConfig(Node *c_near, Node *c_new)
{
c_new->parent = c_near;
c_near->children.push_back(c_new);
nodes_.push_back(c_new);
last_node_ = c_new;
}
bool RRTGraph::reached()
{
if(dist(last_node_->p, goal_) < reach_thresh_)
{
gsout << "Goal reached" << gsnl;
return true;
}
return false;
}
void RRTGraph::performRRT(SnLines *pl, SnLines *gl)
{
while(!new_goal_);
for(int i=0; i<maxi_; i++)
{
Node *c = getRandomNode();
if(c)
{
Node *c_near = nearestPoint(c->p);
if(dist(c->p, c_near->p) > alpha_)
{
pnt new_config = findConfig(c, c_near);
if(walls_->queryIntersection(new_config, c_near->p))
{
Node *c_new = new Node;
c_new->p = new_config;
pl->push(c_new->p.x, c_new->p.y, 0.0f);
addConfig(c_near, c_new);
}
}
}
if(reached())
{
break;
}
}
Node *c;
if(reached())
c = last_node_;
else
c = nearestPoint(goal_);
while(c != NULL)
{
path_.push_back(c);
gl->push(c->p.x, c->p.y, 0.0f);
gsout << "Path of the goal: " << c->p << gsnl;
c = c->parent;
}
if(c != NULL)
{
new_goal_ = false;
path_computed_ = true;
}
gsout << "Start: " << root_->p << " goal: " << goal_ << gsnl;
}
std::vector<pnt> RRTGraph::getNodePoints()
{
std::vector<pnt> ret;
for(int i = 0;i < nodes_.size();i++)
ret.push_back(nodes_[i]->p);
return ret;
}
std::vector<pnt> RRTGraph::getPathPoints()
{
std::vector<pnt> ret;
for(int i = 0;i < path_.size();i++)
ret.push_back(path_[i]->p);
return ret;
}
void RRTGraph::eulerIntegration()
{
gsout << "RRTGraph::eulerIntegration: " << robo_->pos << " to " <<
goal_ << gsnl;
while(!path_computed_);
for(int i=0;i<path_.size();i++)
{
GsVec cur_g(path_[i]->p.x,path_[i]->p.y,0.0f);
gsout << "Traversing intermidiate path: " << cur_g << gsnl;
while(::dist(robo_->pos,cur_g) > 0.5)
{
gsout << "++++++++++++++++++++++++++++++++++++++++" << gsnl;
gsout << "RRTGraph::eulerIntegration: Distance to goal: " << cur_g <<
" is " << ::dist(robo_->pos,cur_g) << gsnl;
steering(cur_g);
GsVec steering_force = truncate(robo_->steer_dir, robo_->max_force);
gsout << "Steering force: " << steering_force << gsnl;
GsVec a = steering_force/robo_->m;
robo_->vel = truncate(robo_->vel + a, robo_->max_speed);
gsout << "Velocity: " << robo_->vel << gsnl;
robo_->pos = robo_->pos + robo_->vel;
gsout << "Robot position: " << robo_->pos << gsnl;
position_->setrans(robo_->pos);
gsout << "++++++++++++++++++++++++++++++++++++++++++" << gsnl;
}
}
path_.clear();
path_computed_ = false;
}
GsVec RRTGraph::truncate(GsVec v, float t)
{
gsout << "RRTGraph::truncate: v: " << v << "clip: " << t << gsnl;
GsVec ret;
ret.x = v.x>t?t:v.x;
ret.y = v.y>t?t:v.y;
ret.z = v.z>t?t:v.z;
}
void RRTGraph::steering( GsVec g)
{
gsout << "--------------------------" << gsnl;
GsVec target_offset = g - robo_->pos;
float distance = magnitude(target_offset);
gsout << "Magnitude: " << distance << gsnl;
float ramped_speed = robo_->max_speed * (distance/slowing_distance);
float clipped_speed = std::min(ramped_speed, robo_->max_speed);
gsout << "Clipped speed: " << clipped_speed << gsnl;
GsVec desired_vel = (clipped_speed/distance)*target_offset;
gsout << "Desired velocity: " << desired_vel << gsnl;
robo_->steer_dir = desired_vel - robo_->vel;
gsout << "RRTGraph::steering: " << robo_->steer_dir << gsnl;
gsout << "----------------------------" << gsnl;
}
| 23.295238
| 81
| 0.591578
|
harsha336
|
935927654a534a8a0ca4c10ca582ee2d59074ad8
| 3,520
|
cpp
|
C++
|
ScriptingProject/Item_Timer.cpp
|
CITMProject3/Project3
|
5076dbaf4eced4eb69bb43b811684206e62eded4
|
[
"MIT"
] | 3
|
2017-04-02T19:37:52.000Z
|
2018-11-06T13:37:33.000Z
|
ScriptingProject/Item_Timer.cpp
|
CITMProject3/Project3
|
5076dbaf4eced4eb69bb43b811684206e62eded4
|
[
"MIT"
] | 74
|
2017-04-03T14:32:09.000Z
|
2017-06-08T10:12:56.000Z
|
ScriptingProject/Item_Timer.cpp
|
CITMProject3/Project3
|
5076dbaf4eced4eb69bb43b811684206e62eded4
|
[
"MIT"
] | 3
|
2017-06-06T17:10:46.000Z
|
2019-10-28T16:25:27.000Z
|
#include "stdafx.h"
#include <string>
#include <map>
#include "../ModuleScripting.h"
#include "../GameObject.h"
#include "../ComponentScript.h"
#include "../ComponentCollider.h"
#include "../ComponentCar.h"
#include "../ComponentMesh.h"
#include "../ComponentAudioSource.h"
#include "../ComponentParticleSystem.h"
#include "../Time.h"
#include "../Globals.h"
#include "../PhysBody3D.h"
bool isHitodama = false;
float timer = 0.0f;
float max_time = 0.0f;
ComponentCollider* go_col = nullptr;
ComponentMesh* go_mesh = nullptr;
ComponentParticleSystem* go_part = nullptr;
ComponentAudioSource* audio_source = nullptr;
bool taken = false;
void Item_Timer_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
{
public_float->insert(pair<const char*, float>("max_time",max_time));
public_bools->insert(pair<const char*, bool>("isHitodama", isHitodama));
public_bools->insert(pair<const char*, bool>("taken", taken));
}
void Item_Timer_UpdatePublics(GameObject* game_object)
{
ComponentScript* script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
go_col = (ComponentCollider*)game_object->GetComponent(C_COLLIDER);
go_part = (ComponentParticleSystem*)game_object->GetComponent(C_PARTICLE_SYSTEM);
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
isHitodama = script->public_bools.at("isHitodama");
taken = script->public_bools.at("taken");
max_time = script->public_floats.at("max_time");
}
void Item_Timer_ActualizePublics(GameObject* game_object)
{
ComponentScript* script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);
script->public_bools.at("taken") = taken;
}
void Item_Timer_Start(GameObject* game_object)
{
go_col = (ComponentCollider*)game_object->GetComponent(C_COLLIDER);
if (isHitodama)
{
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
}
else
{
go_mesh = (ComponentMesh*)game_object->GetComponent(C_MESH);
}
taken = false;
audio_source = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
}
void Item_Timer_Update(GameObject* game_object)
{
Item_Timer_UpdatePublics(game_object);
if (taken)
{
if (isHitodama)
{
timer += time->DeltaTime();
if (timer >= max_time)
{
go_col->SetActive(true);
//Particle sytem here no mesh
go_mesh->SetActive(true);
taken = false;
timer = 0.0f;
}
}
else
{
timer += time->DeltaTime();
if (timer >= max_time)
{
go_col->SetActive(true);
go_mesh->SetActive(true);
taken = false;
timer = 0.0f;
}
}
}
}
void Item_Timer_OnCollision(GameObject* game_object, PhysBody3D* col)
{
ComponentCar* car = col->GetCar();
ComponentTransform* trs = (ComponentTransform*)game_object->GetComponent(C_TRANSFORM);
if (car && trs && taken == false)
{
Item_Timer_UpdatePublics(game_object);
if (go_col->IsActive())
{
if (isHitodama)
{
taken = car->AddHitodama();
if (taken)
{
go_col->SetActive(false);
//Particle sytem here no mesh
go_mesh->SetActive(false);
// Playing Hitodama sound
if (audio_source) audio_source->PlayAudio(0);
}
}
else
{
taken = true;
//Pep do your magic
if (taken)
{
go_col->SetActive(false);
go_mesh->SetActive(false);
// Playing ItemBox sound
if (audio_source) audio_source->PlayAudio(0);
}
}
}
}
}
| 26.074074
| 222
| 0.70483
|
CITMProject3
|
935a367f373c8b72d2d75dee4d2023c3bda40867
| 7,702
|
cpp
|
C++
|
test/map/HashMapProbingTest.cpp
|
zpooky/sputil
|
3eddf94655fe4ec5bc2a3b5e487a86d772b038ae
|
[
"Apache-2.0"
] | null | null | null |
test/map/HashMapProbingTest.cpp
|
zpooky/sputil
|
3eddf94655fe4ec5bc2a3b5e487a86d772b038ae
|
[
"Apache-2.0"
] | null | null | null |
test/map/HashMapProbingTest.cpp
|
zpooky/sputil
|
3eddf94655fe4ec5bc2a3b5e487a86d772b038ae
|
[
"Apache-2.0"
] | null | null | null |
#include <gtest/gtest.h>
#include <map/HashMapProbing.h>
#include <map/HashMapTree.h>
#include <test/gcstruct.h>
template <typename MAP>
static void
test_simple(MAP &map) {
using TK = typename MAP::key_type;
using TV = typename MAP::value_type;
const std::size_t c_key_one = 1;
std::size_t key_one = 1;
const TK c_tt_one(1);
TK tt_one(1);
{
ASSERT_FALSE(lookup(map, 1));
ASSERT_FALSE(lookup(map, c_key_one));
ASSERT_FALSE(lookup(map, key_one));
ASSERT_EQ(key_one, 1);
ASSERT_FALSE(lookup(map, c_tt_one));
ASSERT_FALSE(lookup(map, tt_one));
}
{ //
ASSERT_FALSE(lookup(map, 2));
}
{
{
TV *const i = insert(map, 1, 2);
ASSERT_TRUE(i);
ASSERT_FALSE(lookup(map, 2));
TV *const l = lookup(map, 1);
ASSERT_TRUE(l);
ASSERT_EQ(*i, 2);
ASSERT_EQ(*l, 2);
ASSERT_EQ(l, i);
}
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_FALSE(lookup(map, 2));
{
TV *i = insert(map, 2, 3);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
TV *l = lookup(map, 2);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 3);
ASSERT_EQ(l, i);
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 2);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_TRUE(lookup(map, 2));
{
TV *i = insert(map, 1, 10);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 10);
TV *l = lookup(map, 1);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
ASSERT_EQ(l, i);
{
TV *const l = lookup(map, c_key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
{
TV *const l = lookup(map, key_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
ASSERT_EQ(key_one, 1);
}
{
TV *const l = lookup(map, c_tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
{
TV *const l = lookup(map, tt_one);
ASSERT_TRUE(l);
ASSERT_EQ(*l, 10);
}
}
ASSERT_TRUE(lookup(map, 1));
ASSERT_TRUE(lookup(map, 2));
}
TEST(HashMapProbingTest, test_probing) {
sp::HashMapProbing<int, int> map;
test_simple(map);
}
TEST(HashMapProbingTest, test_probing_dtor) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<int, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_probing_dtor2) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<sp::GcStruct, int> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_probing_dtor3) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapProbing<sp::GcStruct, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree) {
sp::HashMapTree<int, int> map;
test_simple(map);
}
TEST(HashMapProbingTest, test_tree_dtor) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<int, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree_dtor2) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<sp::GcStruct, int> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
TEST(HashMapProbingTest, test_tree_dtor3) {
ASSERT_EQ(0, sp::GcStruct::active);
{
sp::HashMapTree<sp::GcStruct, sp::GcStruct> map;
test_simple(map);
}
ASSERT_EQ(0, sp::GcStruct::active);
}
template <typename MAP>
static void
test_gc_value(MAP &map) {
sp::GcStruct::ctor = 0;
ASSERT_EQ(0, sp::GcStruct::ctor);
{
sp::GcStruct *const i = insert(map, 0, 1);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 1);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
const int c_value = 3;
sp::GcStruct *const i = insert(map, 2, c_value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
int value = 4;
sp::GcStruct *const i = insert(map, 3, value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 4);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(4, value);
}
sp::GcStruct::ctor = 0;
#if 0
{
const sp::GcStruct c_value(6);
sp::GcStruct *const i = insert(map, 5, c_value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 6);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct value(8);
sp::GcStruct *const i = insert(map, 7, value);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 8);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(value, 8);
}
sp::GcStruct::ctor = 0;
#endif
#if 0
{
sp::GcStruct *const i = insert(map, 9, sp::GcStruct(10));
ASSERT_TRUE(i);
ASSERT_EQ(*i, 10);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct value(12);
sp::GcStruct *const i = insert(map, 11, std::move(value));
ASSERT_TRUE(i);
ASSERT_EQ(*i, 12);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
#endif
}
TEST(HashMapProbingTest, test_probing_gc_value) {
sp::HashMapProbing<int, sp::GcStruct> map;
test_gc_value(map);
}
TEST(HashMapProbingTest, test_tree_gc_value) {
sp::HashMapTree<int, sp::GcStruct> map;
test_gc_value(map);
}
template <typename MAP>
static void
test_gc_key(MAP &map) {
sp::GcStruct::ctor = 0;
ASSERT_EQ(0, sp::GcStruct::ctor);
{
int *const i = insert(map, 0, 1);
ASSERT_TRUE(i);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
const int c_key = 3;
int *const i = insert(map, c_key, 2);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 2);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
int key = 4;
int *const i = insert(map, key, 3);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 3);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(4, key);
}
sp::GcStruct::ctor = 0;
#if 0
{
const sp::GcStruct c_key(6);
int *const i = insert(map, c_key, 5);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 5);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(8);
int *const i = insert(map, key, 7);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 7);
ASSERT_EQ(1, sp::GcStruct::ctor);
ASSERT_EQ(key, 8);
}
sp::GcStruct::ctor = 0;
#endif
#if 0
{
int *const i = insert(map, sp::GcStruct(10), 9);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 9);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(12);
int *const i = insert(map, std::move(key), 11);
ASSERT_TRUE(i);
ASSERT_EQ(*i, 12);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
{
sp::GcStruct key(12);
int *const i = insert(map, 11, std::move(key));
ASSERT_TRUE(i);
ASSERT_EQ(1, sp::GcStruct::ctor);
}
sp::GcStruct::ctor = 0;
#endif
}
TEST(HashMapProbingTest, test_probing_gc_key) {
sp::HashMapProbing<sp::GcStruct, int> map;
test_gc_key(map);
}
TEST(HashMapProbingTest, test_tree_gc_key) {
sp::HashMapTree<sp::GcStruct, int> map;
test_gc_key(map);
}
| 20.3219
| 62
| 0.589977
|
zpooky
|
93612d7e4efc504ab2aa8a024bc874af40d6b4ba
| 2,202
|
hpp
|
C++
|
CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
CmnMath/module/numericalmethod/inc/numericalmethod/ode_euler.hpp
|
Khoronus/CmnUniverse
|
9cf9b4297f2fcb49330126aa1047b422144045e1
|
[
"MIT"
] | null | null | null |
// Geometric Tools LLC, Redmond WA 98052
// Copyright (c) 1998-2015
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 1.0.2 (2014/12/13)
// The TVector template parameter allows you to create solvers with
// Vector<N,Real> when the dimension N is known at compile time or
// GVector<Real> when the dimension N is known at run time. Both classes
// have 'int GetSize() const' that allow OdeSolver-derived classes to query
// for the dimension.
#ifndef CMNMATH_NUMERICALMETHOD_ODEEULER_HPP__
#define CMNMATH_NUMERICALMETHOD_ODEEULER_HPP__
#include "ode_solver.hpp"
namespace CmnMath
{
namespace numericalmethod
{
template <typename Real, typename TVector>
class OdeEuler : public OdeSolver<Real,TVector>
{
public:
// Construction and destruction.
virtual ~OdeEuler();
OdeEuler(Real tDelta,
std::function<TVector(Real, TVector const&)> const& F);
// Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may allow
// xIn and xOut to be the same object.
virtual void Update(Real tIn, TVector const& xIn, Real& tOut,
TVector& xOut);
};
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
OdeEuler<Real, TVector>::~OdeEuler()
{
}
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
OdeEuler<Real, TVector>::OdeEuler(Real tDelta,
std::function<TVector(Real, TVector const&)> const& F)
:
OdeSolver<Real, TVector>(tDelta, F)
{
}
//----------------------------------------------------------------------------
template <typename Real, typename TVector>
void OdeEuler<Real, TVector>::Update(Real tIn, TVector const& xIn,
Real& tOut, TVector& xOut)
{
TVector fVector = this->mFunction(tIn, xIn);
tOut = tIn + this->mTDelta;
xOut = xIn + this->mTDelta * fVector;
}
//----------------------------------------------------------------------------
} // namespace numericalmethod
} // namespace CmnMath
#endif /* CMNMATH_NUMERICALMETHOD_GAUSSIANELIMINATION_HPP__ */
| 33.363636
| 78
| 0.619437
|
Khoronus
|
9361b0b8990a7777692301a3bd08e43f4979bf0a
| 8,409
|
cpp
|
C++
|
third_party/vss/GoogleVssAgent/VssAgent.cpp
|
playplay/compute-image-windows
|
9f45829af870e7801ac9b9cdb2e3fe9820244e84
|
[
"Apache-2.0"
] | 97
|
2015-06-03T03:05:10.000Z
|
2021-11-13T13:52:20.000Z
|
third_party/vss/GoogleVssAgent/VssAgent.cpp
|
playplay/compute-image-windows
|
9f45829af870e7801ac9b9cdb2e3fe9820244e84
|
[
"Apache-2.0"
] | 112
|
2015-06-04T00:37:34.000Z
|
2022-03-25T10:39:02.000Z
|
third_party/vss/GoogleVssAgent/VssAgent.cpp
|
playplay/compute-image-windows
|
9f45829af870e7801ac9b9cdb2e3fe9820244e84
|
[
"Apache-2.0"
] | 70
|
2015-06-01T23:57:45.000Z
|
2022-02-22T06:15:20.000Z
|
// The VssAgent service logs the service start and stop information to
// the application event log, and runs the main function of the
// service in a thread pool worker thread.
#include "stdafx.h"
#include "VssAgent.h"
#include "../snapshot.h"
#include "GoogleVssClient.h"
#include "util.h"
VssService::VssService(PWSTR serviceName)
: GServiceBase(serviceName, TRUE, TRUE, FALSE),
srv_stopping_(false),
processing_thread_should_wakeup_(false),
adapter_(std::make_unique<Adapter>()) {
}
VssService::~VssService(void) {
}
// The function is executed when a Start command is sent to the service by
// the SCM or when the operating system starts when a service is configured
// to start automatically.
//
// Argumants:
// argc - number of command line arguments
// argv - array of command line arguments
void VssService::OnStart(DWORD argc, LPWSTR* argv) {
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(argv);
RegisterEvtLogHandle();
// Log a service start message to the Application log.
LogDebugMessage(L"VssService OnStart");
// Cancel any stray inquery requests in progress to unblock in case of
// previous server unclean exit like crash.
if (!adapter_->SendSnapshotIoctl(IOCTL_SNAPSHOT_DISCARD, NULL, NULL, 0)) {
// This will only happen in tests where there is no PD device.
// In that case, we don't need to start this service.
throw ERROR_NOT_SUPPORTED;
}
listening_thread_ = std::thread(&VssService::ListeningThreadWorker, this);
LogOperationalMessage(L"GoogleVssAgent service started successfully.");
}
void FinishBackupAfterThaw(GoogleVssClient* vssClient, BOOL ifSuccessful);
HRESULT PrepareVolumes(GoogleVssClient* vssClient,
const vector<wstring>& volume_names);
void VssService::ListeningThreadWorker() {
processing_thread_ = std::thread(&VssService::ProcessingThreadWorker, this);
while (!srv_stopping_.load()) {
LogDebugMessage(L"Sending IOCTL_SNAPSHOT_REQUESTED");
UCHAR target;
UCHAR lun;
// IOCTL_SNAPSHOT_REQUESTED will be in pending state until host sends a
// snapshot request or Agent cancel the operation in another thread.
BOOL ioctl_res =
adapter_->SendSnapshotIoctl(IOCTL_SNAPSHOT_REQUESTED, &target, &lun, 0);
LogDebugMessage(L"IOCTL_SNAPSHOT_REQUESTED returned.");
if (srv_stopping_.load()) {
LogDebugMessage(L"Listening Thread is exiting.");
break;
}
if (ioctl_res) {
SnapshotTarget snapshot_target;
snapshot_target.Target = target;
snapshot_target.Lun = lun;
{
std::lock_guard<std::mutex> lock(cv_wakeup_m_);
snapshot_targets_.push_back(snapshot_target);
processing_thread_should_wakeup_ = true;
}
cv_wakeup_.notify_one();
LogDebugMessage(L"Snapshot is requested for target %d, lun %d.", target,
lun);
}
}
// Wakeup and exit processing thread.
{
std::lock_guard<std::mutex> lock(cv_wakeup_m_);
processing_thread_should_wakeup_ = true;
}
cv_wakeup_.notify_one();
LogDebugMessage(L"Waiting for Processing Thread to be torn down.");
processing_thread_.join();
}
void VssService::ProcessingThreadWorker() {
while (!srv_stopping_.load()) {
std::vector<SnapshotTarget> st_local;
LogDebugMessage(L"ProcessingThreadWorker starts to wait.");
{
std::unique_lock<std::mutex> lk(cv_wakeup_m_);
cv_wakeup_.wait(lk, [this](){return processing_thread_should_wakeup_;});
processing_thread_should_wakeup_ = false;
st_local.swap(snapshot_targets_);
}
LogDebugMessage(L"ProcessingThreadWorker wakes up.");
for (const auto& st : st_local) {
UCHAR target = st.Target;
UCHAR lun = st.Lun;
vector<wstring> volumes;
DWORD ret;
ret = GetVolumesForScsiTarget(&volumes, adapter_->PortNumber(),
target, lun);
if (ERROR_SUCCESS != ret) {
LogDebugMessage(L"GetVolumesForScsiTarget failed with error %d", ret);
continue;
}
if (volumes.empty()) {
LogOperationalMessage(
L"Snapshot is requested for a disk which has no volumes");
// Stoport allows only one outstanding IOCTL for miniport drivers per
// given file handle. Since we are already having an IOCTL pending for
// adapter, we need to open a separate handle for that.
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(IOCTL_SNAPSHOT_CAN_PROCEED,
&target, &lun,
VIRTIO_SCSI_SNAPSHOT_PREPARE_COMPLETE)) {
LogDebugMessage(
L"IOCTL_SNAPSHOT_CAN_PROCEED failed for target %d, lun %d",
st.Target, st.Lun);
}
continue;
}
WCHAR event_name[64];
HANDLE event_handle = NULL;
if (SUCCEEDED(StringCchPrintf(event_name, ARRAYSIZE(event_name),
kSnapshotEventFormatString, (ULONG)target,
(ULONG)lun))) {
// Create a global event with default security descriptor which allow
// only owner (local system) and admin account access.
event_handle = CreateEvent(NULL, TRUE, FALSE, event_name);
if (event_handle == NULL) {
LogDebugMessage(L"CreateEvent failed with error %d", GetLastError());
}
}
if (event_handle != NULL) {
GoogleVssClient vssClient;
HRESULT hr = PrepareVolumes(&vssClient, volumes);
LogDebugMessage(L"PrepareVolumes return status %x", hr);
if (!SUCCEEDED(hr)) {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(IOCTL_SNAPSHOT_CAN_PROCEED,
&target, &lun, VIRTIO_SCSI_SNAPSHOT_PREPARE_ERROR)) {
LogDebugMessage(
L"IOCTL_SNAPSHOT_CAN_PROCEED failed for target %d, lun %d",
st.Target, st.Lun);
}
} else {
hr = vssClient.DoSnapshotSet();
if (!SUCCEEDED(hr)) {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(
IOCTL_SNAPSHOT_CAN_PROCEED, &target, &lun,
VIRTIO_SCSI_SNAPSHOT_ERROR)) {
LogDebugMessage(
L"Failed to report snapshot status for target %d, lun %d",
st.Target, st.Lun);
}
} else {
Adapter adapter_for_process;
if (!adapter_for_process.SendSnapshotIoctl(
IOCTL_SNAPSHOT_CAN_PROCEED, &target, &lun,
VIRTIO_SCSI_SNAPSHOT_COMPLETE)) {
LogDebugMessage(
L"Failed to report snapshot status for target %d, lun %d",
st.Target, st.Lun);
}
}
}
FinishBackupAfterThaw(&vssClient, SUCCEEDED(hr));
{
vector<EVENT_DATA_DESCRIPTOR> data_descr(volumes.size() + 3);
DWORD idx = 0;
DWORD num_volumes = (DWORD)volumes.size();
EventDataDescCreate(&data_descr[idx++], &st.Target, sizeof(UCHAR));
EventDataDescCreate(&data_descr[idx++], &st.Lun, sizeof(UCHAR));
EventDataDescCreate(&data_descr[idx++], &num_volumes,
sizeof(num_volumes));
for (auto& volume : volumes) {
EventDataDescCreate(
&data_descr[idx++], volume.c_str(),
(ULONG)((volume.length() + 1) * sizeof(WCHAR)));
}
LogSnapshotEvent(SUCCEEDED(hr) ? &SNAPSHOT_SUCCEED : &SNAPSHOT_FAILED,
(ULONG)data_descr.size(), data_descr.data());
}
CloseHandle(event_handle);
}
}
}
}
// The function is executed when a Stop command is sent to the service by SCM.
void VssService::OnStop() {
// Log a service stop message to the Application log.
LogDebugMessage(L"VssService OnStop");
srv_stopping_.store(true);
// Cancel the inquery request in progress. Note that Windows allow only one
// outstanding IOCTL_SCSI_MINIPORT per file handle. So, we need to use
// another adapter object (a new handle) to send a new ioctl down.
Adapter adapter_for_cancel;
adapter_for_cancel.SendSnapshotIoctl(IOCTL_SNAPSHOT_DISCARD, NULL, NULL, 0);
listening_thread_.join();
LogOperationalMessage(L"GoogleVssAgent service is stopped.");
UnregisterEvtLogHandle();
}
| 40.23445
| 92
| 0.649899
|
playplay
|
936418de8bc21450a377175496bf3bbe5f36d4f5
| 984
|
cpp
|
C++
|
arc.cpp
|
hepeidong/Graph
|
f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9
|
[
"Apache-2.0"
] | null | null | null |
arc.cpp
|
hepeidong/Graph
|
f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9
|
[
"Apache-2.0"
] | null | null | null |
arc.cpp
|
hepeidong/Graph
|
f2be17e9a656488b0e26db3bd76d2ca4a85ca1a9
|
[
"Apache-2.0"
] | null | null | null |
#include "arc.h"
#include <algorithm>
template<typename Tp>
Arc<Tp>::Arc():m_adjVertex(-1)
{
}
template<typename Tp>
Arc<Tp>::~Arc()
{
}
template<typename Tp>
Arc<Tp>* Arc<Tp>::CreateArc(value_t weight, site_t adjVertex)
{
Arc<Tp>* arc = new (std::nothrow) Arc();
if (arc->InitArc(weight, adjVertex))
{
arc->AutoReleasse();
}
else
{
SAFE_DELETE(arc);
}
return arc;
}
template<typename Tp>
bool Arc<Tp>::InitArc(value_t weight, site_t adjVertex)
{
m_weight = weight;
m_adjVertex = adjVertex;
return true;
}
template<typename Tp>
void Arc<Tp>::SetAdjVertex(site_t adjVertex)
{
m_adjVertex = adjVertex;
}
template<typename Tp>
inline typename Arc<Tp>::site_t Arc<Tp>::GetAdjVertex() const
{
return m_adjVertex;
}
template<typename Tp>
void Arc<Tp>::SetWeight(value_t weight)
{
m_weight = weight;
}
template<typename Tp>
inline typename Arc<Tp>::value_t Arc<Tp>::GetWeight() const
{
return m_weight;
}
| 15.870968
| 61
| 0.661585
|
hepeidong
|
9364706c8ae59aca17b5e39ea17a8bebb360734e
| 4,315
|
cpp
|
C++
|
src/count_kmers_per_bin.cpp
|
Felix-Droop/Chopper
|
5cc214103b2d088ae400bec0fde8973e03dd3095
|
[
"BSD-3-Clause"
] | null | null | null |
src/count_kmers_per_bin.cpp
|
Felix-Droop/Chopper
|
5cc214103b2d088ae400bec0fde8973e03dd3095
|
[
"BSD-3-Clause"
] | null | null | null |
src/count_kmers_per_bin.cpp
|
Felix-Droop/Chopper
|
5cc214103b2d088ae400bec0fde8973e03dd3095
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <chrono>
#include <numeric>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <seqan3/argument_parser/all.hpp>
#include <seqan3/io/sequence_file/input.hpp>
#include <seqan3/search/views/kmer_hash.hpp>
#include <chopper/build/read_chopper_split_file.hpp>
struct cmd_arguments
{
std::filesystem::path chopper_split_filename{};
uint8_t k{25};
size_t overlap{250};
bool verbose;
};
void initialize_argument_parser(seqan3::argument_parser & parser, cmd_arguments & args)
{
parser.info.author = "Avenja";
parser.info.short_description = "Count unique kmers in bins.";
parser.info.version = "1.0.0";
parser.add_option(args.chopper_split_filename, 'f', "files", "Give me a file produced by chopper split.",
seqan3::option_spec::required);
parser.add_option(args.k, 'k', "kmer-size", "The kmer to count with.");
parser.add_option(args.overlap, 'l', "overlap", "The overlap between splitted bins.");
parser.add_flag(args.verbose, 'v', "verbose", "Display more information.");
}
struct file_type_traits : public seqan3::sequence_file_input_default_traits_dna
{
using sequence_alphabet = seqan3::dna4;
};
using seq_file_type = seqan3::sequence_file_input<file_type_traits,
seqan3::fields<seqan3::field::seq, seqan3::field::id>,
seqan3::type_list<seqan3::format_fasta, seqan3::format_fastq>>;
auto read_sequences(std::vector<std::string> const & filenames)
{
std::unordered_map<std::string, seqan3::dna4_vector> info;
for (auto const & filename : filenames)
for (auto && [seq, id] : seq_file_type{filename})
info.emplace(filename + id, std::move(seq));
return info;
}
auto hash_infix(cmd_arguments const & args, auto const & seq, auto const begin, auto const end)
{
return seq | seqan3::views::drop(begin)
| seqan3::views::take(end + args.overlap - begin) // views::take never goes over the end
| seqan3::views::kmer_hash(seqan3::ungapped{args.k});
};
int main(int const argc, char const ** argv)
{
seqan3::argument_parser myparser{"count_kmers_per_bin", argc, argv};
cmd_arguments args{};
initialize_argument_parser(myparser, args);
try
{
myparser.parse();
}
catch (seqan3::argument_parser_error const & ext)
{
std::cout << "[ERROR] " << ext.what() << "\n";
return -1;
}
auto [data, batches] = read_chopper_split_file(args.chopper_split_filename);
std::vector<std::unordered_set<uint64_t>> kmer_counts;
for (auto const & batch_record : batches)
{
auto && info = read_sequences(batch_record.filenames);
if (batch_record.libf_num_bins > 0) // merged bin
{
kmer_counts.resize(batch_record.libf_num_bins);
for (auto const & [combined_id, seq] : info)
for (auto const & reg : data.region_map.at(combined_id))
for (auto hash : hash_infix(args, seq, reg.begin, reg.end))
kmer_counts[reg.lidx].insert(hash);
for (size_t i = 0; i < batch_record.libf_num_bins; ++i)
std::cout << batch_record.hibf_bins[0] << '_' << i << '\t' << kmer_counts[i].size() << '\n';
// also output size of merged bin
std::unordered_set<uint64_t> hibf_kmer_count{};
for (auto & set : kmer_counts)
{
hibf_kmer_count.merge(set);
set.clear();
}
std::cout << batch_record.hibf_bins[0] << '\t' << hibf_kmer_count.size();
}
else // split bin
{
kmer_counts.resize(batch_record.hibf_bins.size());
for (auto const & [combined_id, seq] : info)
for (auto const & reg : data.region_map.at(combined_id))
for (auto hash : hash_infix(args, seq, reg.begin, reg.end))
kmer_counts[reg.hidx].insert(hash);
for (size_t i = 0; i < batch_record.hibf_bins.size(); ++i)
std::cout << batch_record.hibf_bins[i] << '\t' << kmer_counts[i].size() << '\n';
}
kmer_counts.clear();
}
}
| 35.081301
| 113
| 0.609502
|
Felix-Droop
|
936719eb694d275d2b3d1a7acad921e888c92889
| 10,453
|
cp
|
C++
|
Win32/Sources/Application/Speech/CSpeechSynthesis.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
Win32/Sources/Application/Speech/CSpeechSynthesis.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
Win32/Sources/Application/Speech/CSpeechSynthesis.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007-2009 Cyrus Daboo. 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.
*/
// CSpeechSynthesis.cp
// Class to handle speech sythesis
#include "CSpeechSynthesis.h"
#include "CAddressList.h"
#include "CEnvelope.h"
#include "CErrorHandler.h"
#include "CMbox.h"
#include "CMessage.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
// === Static Members ===
CComPtr<ISpVoice> CSpeechSynthesis::sSpVoice;
bool CSpeechSynthesis::sAvailable = false;
#ifdef __MULBERRY
cdmutex CSpeechSynthesis::_mutex;
#endif
cdstrqueue CSpeechSynthesis::sSpeakQueue;
bool CSpeechSynthesis::sTopDone = false;
cdstrvect CSpeechSynthesis::sItemList;
// === constants ===
const char* cSpeakPause = ", ";
const char* cSpeakEndSentence = ". ";
#pragma ARM_conform on
// __________________________________________________________________________________________________
// C L A S S __ C A B O U T D I A L O G
// __________________________________________________________________________________________________
CSpeechSynthesis::CSpeechSynthesis()
{
}
CSpeechSynthesis::~CSpeechSynthesis()
{
}
// Check for speech and install menus etc
bool CSpeechSynthesis::InstallSpeechSynthesis()
{
CMenu* speak_menu = NULL;
// Load COM
CoInitialize(NULL);
try
{
// First check to see if the Speech Manager extension is present
HRESULT result = sSpVoice.CoCreateInstance(CLSID_SpVoice);
// Check state
if (SUCCEEDED(result))
{
// Get descriptor strings
for(short i = IDS_SPEAK_FROM1; i <= IDS_SPEAK_NONE; i++)
{
cdstring str;
str.FromResource(i);
sItemList.push_back(str);
}
sAvailable = true;
}
}
catch (...)
{
CLOG_LOGCATCH(...);
// Not loaded - do nothing
sAvailable = false;
}
return sAvailable;
}
// Remove speech
void CSpeechSynthesis::RemoveSpeechSynthesis()
{
// Explicitly release COM object here rather than rely on static destructor to do it
// Release COM object
sSpVoice.Release();
// Unload COM
CoUninitialize();
}
// Create menu
void CSpeechSynthesis::InstallMenu(CMenu* menu)
{
}
bool CSpeechSynthesis::OnUpdateEditSpeak(UINT nID, CCmdUI* pCmdUI)
{
bool handled = false;
if (!Available())
{
pCmdUI->Enable(false);
return false;
}
#ifdef __MULBERRY
switch(nID)
{
case IDM_EDIT_SPEAK:
if (Speaking())
{
CString txt;
txt.LoadString(IDS_SPEAK_STOPSPEAKING);
OnUpdateMenuTitle(pCmdUI, txt);
pCmdUI->Enable(true); // Always
handled = true;
}
break;
default:;
}
#endif
return handled;
}
bool CSpeechSynthesis::OnEditSpeak(UINT nID)
{
bool handled = false;
#ifdef __MULBERRY
switch(nID)
{
case IDM_EDIT_SPEAK:
if (Speaking())
{
StopSpeaking();
handled = true;
}
break;
default:;
}
#endif
return handled;
}
bool CSpeechSynthesis::Speaking(void)
{
if (!Available())
return false;
SPVOICESTATUS status;
HRESULT result = sSpVoice->GetStatus(&status, NULL);
if (SUCCEEDED(result))
return status.dwRunningState == SPRS_IS_SPEAKING;
else
return false;
}
void CSpeechSynthesis::SpeakText(char* txt, long length)
{
if (!Available())
return;
std::auto_ptr<wchar_t> wtxt(new wchar_t[::strlen(txt) + 1]);
const char* p = txt;
wchar_t* q = wtxt.get();
while(*p)
*q++ = *p++;
*q++ = *p++;
sSpVoice->Speak(wtxt.get(), SPF_ASYNC | SPF_IS_NOT_XML, 0);
}
void CSpeechSynthesis::StopSpeaking(void)
{
if (!Available())
return;
// Stop actual speech
sSpVoice->Speak(NULL, SPF_PURGEBEFORESPEAK, 0);
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Clear all from queue
while(!sSpeakQueue.empty())
sSpeakQueue.pop();
sTopDone = false;
}
// Speak items from queue (remember that Speech Manager 'captures' text buffer while speaking)
void CSpeechSynthesis::SpendTime(void)
{
if (!Available())
return;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Ignore if speaking or empty queue
if (sSpeakQueue.empty() || Speaking())
return;
// Pop off top item if done
if (sTopDone)
{
sSpeakQueue.pop();
sTopDone = false;
}
// Check for next item
if (!sSpeakQueue.empty())
{
cdstring& spk = sSpeakQueue.front();
SpeakText(spk, spk.length());
sTopDone = true;
}
}
// Speak specific text item
void CSpeechSynthesis::SpeakString(const cdstring& txt)
{
if (!Available())
return;
cdstring spk = txt;
// Add end of sentence
spk += cSpeakEndSentence;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Add item to speech queue
sSpeakQueue.push(spk);
}
void CSpeechSynthesis::SpeakNewMessages(CMbox* mbox)
{
if (!Available())
return;
}
void CSpeechSynthesis::SpeakMessage(CMessage* msg, CAttachment* attach, bool letter)
{
if (!Available())
return;
if (!msg)
return;
CEnvelope* env = msg->GetEnvelope();
if (!env)
return;
cdstring spk;
const CMessageSpeakVector* items;
// Adjust for first text part
if (!attach)
attach = msg->FirstDisplayPart();
// Got appropriate item array
if (letter)
items = &CPreferences::sPrefs->mSpeakLetterItems.GetValue();
else
items = &CPreferences::sPrefs->mSpeakMessageItems.GetValue();
// Assume text read in
for(CMessageSpeakVector::const_iterator iter = items->begin(); iter != items->end(); iter++)
{
// Add user item to text and add pause after
spk = (*iter).mItemText;
spk += cSpeakPause;
switch((*iter).mItem)
{
case eMessageSpeakFrom1: // Speak single from address
if (!env->GetFrom()->empty())
spk += env->GetFrom()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakFromAll: // Speak all from addresses
if (!env->GetFrom()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetFrom()->begin(); iter2 < env->GetFrom()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakTo1:
if (!env->GetTo()->empty()) // Speak single to address
spk += env->GetTo()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakToAll: // Speak all to addresses
if (!env->GetTo()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetTo()->begin(); iter2 < env->GetTo()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakCC1: // Speak single CC address
if (!env->GetCC()->empty())
spk += env->GetCC()->front()->GetNamedAddress();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakCCAll: // Speak all CC addresses
if (!env->GetCC()->empty())
{
for(CAddressList::const_iterator iter2 = env->GetCC()->begin(); iter2 < env->GetCC()->end(); iter2++)
{
spk += (*iter2)->GetNamedAddress();
spk += cSpeakPause;
}
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakDate: // Speak date
if (env->GetTextDate(true, true).length())
spk += env->GetTextDate(true, true);
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakSubject: // Speak subject
if (env->GetSubject().length())
spk += env->GetSubject();
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
case eMessageSpeakNumParts: // Speak number of parts
spk += cdstring(msg->GetBody()->CountParts());
break;
case eMessageSpeakBodyNoHdr: // Speak message text without header
{
const char* body = nil;
try
{
if (attach)
body = attach->ReadPart(msg);
}
catch (...)
{
CLOG_LOGCATCH(...);
}
if (body && ::strlen(body))
{
// Limit size to user specified maximum
size_t len = ::strlen(body);
if (len > CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue())
len = CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue();
spk += cdstring(body, len);
}
else
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
break;
}
case eMessageSpeakBodyHdr: // Speak message text with header
{
const char* body = nil;
char* hdr = msg->GetHeader();
try
{
if (attach)
body = attach->ReadPart(msg);
}
catch (...)
{
CLOG_LOGCATCH(...);
}
if ((!hdr || !::strlen(hdr)) && (!body || !::strlen(body)))
spk += CPreferences::sPrefs->mSpeakMessageEmptyItem.GetValue();
else
{
if (hdr)
spk += cdstring(hdr, ::strlen(hdr));
spk += cSpeakPause;
if (body)
{
// Limit size to user specified maximum
size_t len = ::strlen(body);
if (len > CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue())
len = CPreferences::sPrefs->mSpeakMessageMaxLength.GetValue();
spk += cdstring(body, len);
}
}
break;
}
case eMessageSpeakNone: // Do not speak any extra text
default:
break;
}
// Add end of sentence
spk += cSpeakEndSentence;
// Protect queue against multi-thread access
#ifdef __MULBERRY
cdmutex::lock_cdmutex _lock(_mutex);
#endif
// Add item to speech queue
sSpeakQueue.push(spk);
}
}
| 22.923246
| 110
| 0.647565
|
mulberry-mail
|
9368165cf6fefe25843710913b94afec7f6edb5d
| 1,539
|
cpp
|
C++
|
test_mbed/src/main.cpp
|
chris3069/BLDC_Project
|
69f6b7ed810d091dd430d93554056e34af130d2d
|
[
"BSL-1.0"
] | null | null | null |
test_mbed/src/main.cpp
|
chris3069/BLDC_Project
|
69f6b7ed810d091dd430d93554056e34af130d2d
|
[
"BSL-1.0"
] | null | null | null |
test_mbed/src/main.cpp
|
chris3069/BLDC_Project
|
69f6b7ed810d091dd430d93554056e34af130d2d
|
[
"BSL-1.0"
] | null | null | null |
#include <mbed.h>
#define MAXIMUM_BUFFER_SIZE 32
// Open Loop Betrieb
// Timer lauft, y Values verändern sich alle 100ms
// y-Value in pulsewidth laden
// IN2 startet von Value 20,
// IN3 starte von Value 40
// mit Poti einstellbar
InterruptIn button_stop(D7); // Stop Taster, Falling Edge glaub ich
InterruptIn button_start(D8); // Start Taster, Falling Edge
InterruptIn rotary_encoder1(D12); // Rotary Encoder, Falling Edge glaub ich
InterruptIn rotary_encoder2(D13); // Rotary Encoder, Falling Edge
DigitalOut
uint8_t sine_wave[] = {49, 54, 59, 64, 69, 73, 78, 82, 85, 89, 91, 94, 95, 97, 97, 97, 97, 96, 95, 93, 90, 87, 84, 80, 76, 71, 66, 61, 56, 51, 46, 41, 36, 31, 26, 21, 17, 13, 10, 7, 4, 2, 1, 0, 0, 0, 0, 2, 3, 6, 8, 12, 15, 19, 24, 28, 33, 38, 43, 48}
// Create a BufferedSerial object with a default baud rate.
static BufferedSerial serial_port(USBTX, USBRX);
int main() {
// Set desired properties (9600-8-N-1).
serial_port.set_baud(9600);
serial_port.set_format(
/* bits */ 8,
/* parity */ BufferedSerial::None,
/* stop bit */ 1
);
char buf[MAXIMUM_BUFFER_SIZE] = {0};
// put your setup code here, to run once:
PwmOut IN1(D9);
PwmOut IN2(D10);
PwmOut IN3(D11);
// DigitalOut
// Timer t
// t.
IN1.period_us(100);
IN1.pulsewidth_us(10);
// uint32_t periodlength = TIM3->CCR2;
// serial_port.write(buf, periodlength);
while(1) {
serial_port.write(buf, periodlength);
// D9.
// put your main code here, to run repeatedly:
}
}
| 24.046875
| 250
| 0.647823
|
chris3069
|
9370df570a0ad5b979edcff5c6b44d9018735660
| 4,660
|
cpp
|
C++
|
src/svLibrary/src/resource/ResourceFolderPC.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | null | null | null |
src/svLibrary/src/resource/ResourceFolderPC.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | 1
|
2017-06-11T06:34:50.000Z
|
2017-06-11T06:34:50.000Z
|
src/svLibrary/src/resource/ResourceFolderPC.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | null | null | null |
#include <sv/System.h>
#if SV_PLATFORM_POSIX
#include <cstdio>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <fstream>
#include <sstream>
#include <sv/resource/ResourceFolderPC.h>
namespace sv {
bool ResourceFolderPC::open() {
isFolderOpen = true;
// No need to 'open' a folder
return true;
}
bool ResourceFolderPC::isOpen() { return isFolderOpen; }
int32_t ResourceFolderPC::getRawResourceSize(const Resource &r) {
std::stringstream fullPath;
fullPath << folderPath << "/" << r.name;
std::ifstream in(fullPath.str(),
std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
int32_t ResourceFolderPC::getRawResource(const Resource &r,
void *const buffer) {
// http://stackoverflow.com/questions/18816126/c-read-the-whole-file-in-buffer
std::stringstream fullPath;
fullPath << folderPath << "/" << r.name;
std::ifstream in(fullPath.str(),
std::ifstream::ate | std::ifstream::binary);
std::streamsize size = in.tellg();
in.seekg(0, std::ios::beg);
if (in.read((char *const)buffer, size)) {
// Successful
return size;
} else {
return -1;
}
}
size_t ResourceFolderPC::getNumResources() const {
return getNumFilesInDir(folderPath);
}
Resource ResourceFolderPC::getResourceIdentifier(size_t index) const {
size_t i = 0;
std::string resourceIdentifier =
getFileNameInDirByIndex(folderPath, index, i);
return Resource(resourceIdentifier);
}
DateTime ResourceFolderPC::getResourceModifiedDate(const Resource &r) const {
DateTime dateTime;
#if SV_PLATFORM_POSIX
struct tm *clock;
struct stat attr;
std::stringstream filePath;
filePath << folderPath << "/" << r.name;
stat(filePath.str().c_str(), &attr);
clock = localtime(&(attr.st_mtime));
dateTime = DateTime(clock->tm_sec, clock->tm_min, clock->tm_hour,
clock->tm_mday, clock->tm_mon, clock->tm_year + 1900);
#else
// TODO Windows
#endif
return dateTime;
}
size_t ResourceFolderPC::getNumFilesInDir(const std::string &dirPath) const {
size_t numFiles = 0;
#if SV_PLATFORM_POSIX
DIR *dp;
struct dirent *ep = nullptr;
dp = opendir(dirPath.c_str());
if (dp != nullptr) {
while ((ep = readdir(dp))) {
// Ignore ., .. and all other hidden files
if (strncmp(ep->d_name, ".", 1) != 0) {
if (ep->d_type == DT_REG) {
++numFiles;
} else if (ep->d_type == DT_DIR) {
std::stringstream newDir;
newDir << dirPath << "/" << std::string(ep->d_name);
numFiles += getNumFilesInDir(newDir.str());
}
}
}
closedir(dp);
}
#else
// TODO Windows
#endif
return numFiles;
}
std::string
ResourceFolderPC::getFileNameInDirByIndex(const std::string &dirPath,
size_t indexToFind) const {
size_t currentIndex = 0;
return getFileNameInDirByIndex(dirPath, indexToFind, currentIndex);
}
std::string
ResourceFolderPC::getFileNameInDirByIndex(const std::string &dirPath,
size_t indexToFind,
size_t ¤tIndex) const {
std::string resourceName = "";
#if SV_PLATFORM_POSIX
DIR *dp;
struct dirent *ep = nullptr;
dp = opendir(dirPath.c_str());
if (dp != nullptr) {
while ((ep = readdir(dp))) {
// Ignore ., .. and all other hidden files
if (strncmp(ep->d_name, ".", 1) != 0) {
if (ep->d_type == DT_REG) {
// For each regular file, check if index we are looking
// for, else increase current index
if (currentIndex == indexToFind) {
resourceName = ep->d_name;
break;
}
++currentIndex;
} else if (ep->d_type == DT_DIR) {
std::stringstream newDir;
newDir << dirPath << "/" << std::string(ep->d_name);
resourceName = getFileNameInDirByIndex(
newDir.str(), indexToFind, currentIndex);
if (resourceName != "") {
break;
}
}
}
}
closedir(dp);
}
#else
// TODO Windows
#endif
return resourceName;
}
}
| 27.251462
| 82
| 0.550429
|
sevanspowell
|
93710bca8319031063d93ccf1a196ae4359500c4
| 1,381
|
hpp
|
C++
|
lib/why3cpp/private/whyml-lextract-listener.hpp
|
sellamiy/GPiD-Framework
|
f6ed1abb2da6d51639f5ee410b1f9b143a200465
|
[
"BSD-3-Clause"
] | 8
|
2018-07-13T07:07:08.000Z
|
2021-05-18T17:56:59.000Z
|
lib/why3cpp/private/whyml-lextract-listener.hpp
|
sellamiy/GPiD-Framework
|
f6ed1abb2da6d51639f5ee410b1f9b143a200465
|
[
"BSD-3-Clause"
] | null | null | null |
lib/why3cpp/private/whyml-lextract-listener.hpp
|
sellamiy/GPiD-Framework
|
f6ed1abb2da6d51639f5ee410b1f9b143a200465
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef LIB_WHY3CPP__LOCAL_INCLUDE__L_EXTRACT_LISTENER_HPP
#define LIB_WHY3CPP__LOCAL_INCLUDE__L_EXTRACT_LISTENER_HPP
#include <WhyMLBaseListener.h>
#include "whyml-type-visitor.hpp"
class LextractWhyMLListener : public WhyMLBaseListener {
map<string, string> literals;
stack<pair<string, string>> lstack;
public:
LextractWhyMLListener() {}
inline const map<string, string>& getLiterals() {
unstack();
return literals;
}
inline void unstack() {
while (!lstack.empty()) {
literals.insert(lstack.top());
lstack.pop();
}
}
virtual void exitInteger(WhyMLParser::IntegerContext* ctx) override {
lstack.push(pair<string, string>(ctx->INTEGER()->getText(), INT_TYPESTR));
}
virtual void exitReal(WhyMLParser::RealContext* ctx) override {
lstack.push(pair<string, string>(ctx->REAL()->getText(), REAL_TYPESTR));
}
virtual void exitPriority_expr_tight(WhyMLParser::Priority_expr_tightContext* ctx) override {
if (!lstack.empty() && ctx->tightop() != nullptr) {
// Tight operator extraction
lstack.top().first = ctx->tightop()->getText() + lstack.top().first;
lstack.top().second = prefixTypeConversion(ctx->tightop()->getText(), lstack.top().second);
} else {
unstack();
}
}
};
#endif
| 30.021739
| 103
| 0.645185
|
sellamiy
|
9373fe179f73403d0d7e13d85b99cb7a94c7332b
| 3,797
|
hpp
|
C++
|
libs/renderer/include/Skybox.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | null | null | null |
libs/renderer/include/Skybox.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | null | null | null |
libs/renderer/include/Skybox.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | 1
|
2021-03-21T16:52:22.000Z
|
2021-03-21T16:52:22.000Z
|
#ifndef SKYBOX_H
#define SKYBOX_H
#include <glad/glad.h> // holds all OpenGL type declarations
#include <glm/glm.hpp>
#include <vector>
class Skybox
{
public:
Skybox()
{
}
Skybox(vector<std::string> faces)
{
LoadCubemap(faces);
SetupSkybox();
}
void DrawSkybox(unsigned int shaderID)
{
glDepthFunc(GL_LEQUAL);
// skybox cube
glBindVertexArray(skyboxVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS);
glActiveTexture(GL_TEXTURE0);
}
void ActivateTexture()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
}
private:
unsigned int cubemapTexture;
unsigned int skyboxVAO, skyboxVBO;
void LoadCubemap(vector<std::string> faces)
{
glGenTextures(1, &cubemapTexture);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
void SetupSkybox()
{
float skyboxVertices[] =
{
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
glGenVertexArrays(1, &skyboxVAO);
glGenBuffers(1, &skyboxVBO);
glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
}
};
#endif SKYBOX_H
| 28.765152
| 126
| 0.51725
|
Sharpyfile
|
93740f1fd09685bf8a244b2c138b953501436c45
| 4,389
|
cpp
|
C++
|
src/mfx/cmd/lat/TreeList.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | 69
|
2017-01-17T13:17:31.000Z
|
2022-03-01T14:56:32.000Z
|
src/mfx/cmd/lat/TreeList.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | 1
|
2020-11-03T14:52:45.000Z
|
2020-12-01T20:31:15.000Z
|
src/mfx/cmd/lat/TreeList.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | 8
|
2017-02-08T13:30:42.000Z
|
2021-12-09T08:43:09.000Z
|
/*****************************************************************************
TreeList.cpp
Author: Laurent de Soras, 2019
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "mfx/cmd/lat/GraphInterface.h"
#include "mfx/cmd/lat/Node.h"
#include "mfx/cmd/lat/Tools.h"
#include "mfx/cmd/lat/TreeList.h"
#include <cassert>
namespace mfx
{
namespace cmd
{
namespace lat
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
void TreeList::init (GraphInterface &graph)
{
const int nbr_nodes = graph.get_nbr_nodes ();
_info_list.clear (); // Max nbr trees = nbr nodes
_node_list.resize (nbr_nodes);
_nbr_trees = 0;
int node_start = 0;
int node_list_start_index = 0;
while (node_start < nbr_nodes)
{
const Node & node = graph.use_node (node_start);
if (! node.is_tree_set ())
{
assert (_nbr_trees == int (_info_list.size ()));
_info_list.emplace_back (node_list_start_index);
TreeInfo & tree_info = _info_list.back ();
build_rec (graph, node_start, _nbr_trees);
node_list_start_index += tree_info._nbr_nodes;
assert (node_list_start_index <= nbr_nodes);
++ _nbr_trees;
}
++ node_start;
}
_info_list.resize (_nbr_trees);
}
void TreeList::restore ()
{
_info_list.clear ();
_node_list.clear ();
_nbr_trees = -1;
}
int TreeList::get_nbr_trees () const
{
assert (_nbr_trees >= 0);
return _nbr_trees;
}
int TreeList::get_nbr_nodes (int tree) const
{
assert (tree >= 0);
assert (tree < get_nbr_trees ());
const TreeInfo & tree_info = _info_list [tree];
const int nbr_nodes = tree_info._nbr_nodes;
assert (nbr_nodes > 0);
return nbr_nodes;
}
int TreeList::get_node (int tree, int index) const
{
assert (tree >= 0);
assert (tree < get_nbr_trees ());
assert (index >= 0);
assert (index < get_nbr_nodes (tree));
const TreeInfo & tree_info = _info_list [tree];
const int pos = tree_info._start_index + index;
const int node_index = _node_list [pos];
return node_index;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
TreeList::TreeInfo::TreeInfo (int start_index)
: _nbr_nodes (0)
, _start_index (start_index)
{
assert (start_index >= 0);
}
void TreeList::build_rec (GraphInterface &graph, int node_index, int cur_tree)
{
assert (node_index >= 0);
assert (node_index < graph.get_nbr_nodes ());
assert (cur_tree >= 0);
assert (cur_tree < int (_info_list.size ()));
assert (cur_tree <= _nbr_trees);
// Associates node to current tree
Node & node = graph.use_node (node_index);
node.set_tree (cur_tree);
TreeInfo & tree_info = _info_list [cur_tree];
// Puts current node index into the node list of this tree
const int node_list_index =
tree_info._start_index + tree_info._nbr_nodes;
_node_list [node_list_index] = node_index;
++ tree_info._nbr_nodes;
// Explores adjacent nodes
for (int dir_cnt = 0; dir_cnt < piapi::Dir_NBR_ELT; ++dir_cnt)
{
const piapi::Dir dir = static_cast <piapi::Dir> (dir_cnt);
const int nbr_cnx = node.get_nbr_cnx (dir);
for (int cnx_pos = 0; cnx_pos < nbr_cnx; ++cnx_pos)
{
const int next_node_index = Tools::get_next_node (
graph,
node_index,
dir,
cnx_pos
);
const Node & next_node = graph.use_node (next_node_index);
if (! next_node.is_tree_set ())
{
build_rec (graph, next_node_index, cur_tree);
}
}
}
}
} // namespace lat
} // namespace cmd
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 21.945
| 78
| 0.57553
|
mikelange49
|
9374a2124793d3532000d617cc30248de7baefb5
| 13,428
|
hxx
|
C++
|
c++/laolrt/laol/rt/primitives.hxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
c++/laolrt/laol/rt/primitives.hxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
c++/laolrt/laol/rt/primitives.hxx
|
gburdell/laol
|
4ba457b2d4fa25525173cd045aa57ff4485ef7ae
|
[
"MIT"
] | null | null | null |
/*
* The MIT License
*
* Copyright 2017 kpfalzer.
*
* 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.
*/
/*
* File: primitives.hxx
* Author: kpfalzer
*
* Created on May 15, 2017, 9:50 AM
*/
#ifndef _laol_rt_primitives_hxx_
#define _laol_rt_primitives_hxx_
#include "laol/rt/laol.hxx"
namespace laol {
namespace rt {
//NOTE: while we have these discrete primitive types; we do not (yet?!)
//have proper operator overloads to allow "Int op UnsignedInt"...
class Int;
class UnsignedInt;
class LongInt;
class UnsignedLongInt;
class Char;
class Float;
class Double;
class Bool : public virtual Laol {
public:
explicit Bool(bool val) : m_val(val) {
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
return !m_val;
}
virtual LaolObj complement(const LaolObj&, const LaolObj&) const override {
return ~m_val;
}
virtual std::ostream& print(std::ostream& os) const override {
os << (m_val ? "true" : "false");
return os;
}
//allow copy constructors
const bool m_val;
};
struct INumber : public virtual Laol {
enum EType {
eInt, eUnsignedInt, eLongInt, eUnsignedLongInt,
eChar,
eFloat, eDouble
};
virtual EType getType() const = 0;
template<typename GETFN>
static LaolObj getIntVal(const LaolObj& op, const EType type, GETFN rcvr);
template<typename GETFN>
static LaolObj getIntVal(const LaolObj& op, GETFN rcvr) {
return getIntVal(op, op.toType<INumber>().getType(), rcvr);
}
template<typename GETFN>
static LaolObj getVal(const LaolObj& op, const EType type, GETFN rcvr);
template<typename GETFN>
static LaolObj getVal(const LaolObj& op, GETFN rcvr) {
return getVal(op, op.toType<INumber>().getType(), rcvr);
}
static int toInt(const LaolObj& v);
static unsigned int toUnsignedInt(const LaolObj& v);
static long int toLongInt(const LaolObj& v);
static unsigned long int toUnsignedLongInt(const LaolObj& v);
static double toDouble(const LaolObj& v);
static float toFloat(const LaolObj& v);
};
template<typename T>
class IntBase : public INumber {
public:
explicit IntBase(T val) : m_val(val) {
}
/* Integer only operations
*/
virtual LaolObj left_shift(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val << bb;
});
}
virtual LaolObj right_shift(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val >> bb;
});
}
virtual LaolObj modulus(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val % bb;
});
}
virtual LaolObj logical_and(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val && bb;
});
}
virtual LaolObj logical_or(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val || bb;
});
}
virtual LaolObj bitwise_and(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val & bb;
});
}
virtual LaolObj bitwise_or(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val | bb;
});
}
virtual LaolObj bitwise_xor(const LaolObj&, const LaolObj& opB) const override {
return getIntVal(opB, [this](auto bb) {
return m_val ^ bb;
});
}
virtual LaolObj complement(const LaolObj&, const LaolObj&) const override {
return ~m_val;
}
// Generate specializations for Int here for performance
virtual LaolObj post_increment(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val++;
}
virtual LaolObj post_decrement(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val--;
}
virtual LaolObj pre_increment(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val + 1;
return self;
}
virtual LaolObj pre_decrement(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val - 1;
return self;
}
virtual LaolObj add(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val + bb;
});
}
virtual LaolObj subtract(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val - bb;
});
}
virtual LaolObj multiply(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val * bb;
});
}
virtual LaolObj divide(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val / bb;
});
}
virtual LaolObj equal(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val == bb;
});
}
virtual LaolObj less(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val < bb;
});
}
virtual LaolObj greater(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val > bb;
});
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
//For an expression e,
//the unary expression !e is equivalent to the expression (e == 0)
return (m_val != 0);
}
virtual std::ostream& print(std::ostream& os) const override {
os << m_val;
return os;
}
private:
friend class INumber;
T m_val;
};
template<typename T>
class FloatBase : public INumber {
public:
explicit FloatBase(T val) : m_val(val) {
}
// Generate specializations for Float here for performance
virtual LaolObj post_increment(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val++;
}
virtual LaolObj post_decrement(const LaolObj& self, const LaolObj&) const override {
return unconst(this)->m_val--;
}
virtual LaolObj pre_increment(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val + 1;
return self;
}
virtual LaolObj pre_decrement(const LaolObj& self, const LaolObj&) const override {
unconst(this)->m_val = m_val - 1;
return self;
}
virtual LaolObj add(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val + bb;
});
}
virtual LaolObj subtract(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val - bb;
});
}
virtual LaolObj multiply(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val * bb;
});
}
virtual LaolObj divide(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val / bb;
});
}
virtual LaolObj equal(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val == bb;
});
}
virtual LaolObj less(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val < bb;
});
}
virtual LaolObj greater(const LaolObj&, const LaolObj& opB) const override {
return getVal(opB, [this](auto bb) {
return m_val > bb;
});
}
virtual LaolObj negate(const LaolObj&, const LaolObj&) const override {
//For an expression e,
//the unary expression !e is equivalent to the expression (e == 0)
return (m_val != 0);
}
virtual std::ostream& print(std::ostream& os) const override {
os << m_val;
return os;
}
private:
friend class INumber;
T m_val;
};
#define DEFINE_INTS(_cls, _prim) \
class _cls : public IntBase<_prim> { \
public: explicit _cls(_prim val) : IntBase(val) {} \
EType getType() const override {return e##_cls ;} \
}
DEFINE_INTS(Int, int);
DEFINE_INTS(UnsignedInt, unsigned int);
DEFINE_INTS(LongInt, long int);
DEFINE_INTS(UnsignedLongInt, unsigned long int);
DEFINE_INTS(Char, char);
#undef DEFINE_INTS
#define DEFINE_FLOATS(_cls, _prim) \
class _cls : public FloatBase<_prim> { \
public: explicit _cls(_prim val) : FloatBase(val) {} \
EType getType() const override {return e##_cls ;} \
}
DEFINE_FLOATS(Float, float);
DEFINE_FLOATS(Double, double);
#undef DEFINE_FLOATS
template<typename GETFN>
LaolObj
INumber::getIntVal(const LaolObj& op, const EType type, GETFN rcvr) {
switch (type) {
case eInt:
return rcvr(op.toType<Int>().m_val);
case eUnsignedInt:
return rcvr(op.toType<UnsignedInt>().m_val);
case eLongInt:
return rcvr(op.toType<LongInt>().m_val);
case eUnsignedLongInt:
return rcvr(op.toType<UnsignedLongInt>().m_val);
case eChar:
return rcvr(op.toType<Char>().m_val);
default:
ASSERT_NEVER;
}
return NULLOBJ;
}
template<typename GETFN>
LaolObj
INumber::getVal(const LaolObj& op, const EType type, GETFN rcvr) {
switch (type) {
case eFloat:
return rcvr(op.toType<Float>().m_val);
case eDouble:
return rcvr(op.toType<Double>().m_val);
default:
return getIntVal(op, type, rcvr);
}
return NULLOBJ;
}
}
}
#endif /* _laol_rt_primitives_hxx_ */
| 33.994937
| 96
| 0.524873
|
gburdell
|
9374f01b5eaee6710c7a94d56f031e5a5859ed9f
| 48,416
|
cpp
|
C++
|
src/CX_Synth.cpp
|
hardmanko/ofxCX
|
0d1276e4ba8c25a0803da7b03088da24d8871f38
|
[
"MIT"
] | 7
|
2015-02-19T21:21:34.000Z
|
2022-03-18T13:38:20.000Z
|
src/CX_Synth.cpp
|
hardmanko/ofxCX
|
0d1276e4ba8c25a0803da7b03088da24d8871f38
|
[
"MIT"
] | null | null | null |
src/CX_Synth.cpp
|
hardmanko/ofxCX
|
0d1276e4ba8c25a0803da7b03088da24d8871f38
|
[
"MIT"
] | 4
|
2018-02-16T12:56:13.000Z
|
2022-03-23T01:27:33.000Z
|
#include "CX_Synth.h"
namespace CX {
namespace Synth {
// Initial id is 0.
uint64_t ModuleControlData::_nextId = 1;
/*! The sinc function, defined as `sin(x)/x`. */
double sinc(double x) {
return sin(x) / x;
}
/*! This function returns the frequency that is `semitoneDifference` semitones from `f`.
\param f The starting frequency.
\param semitoneDifference The difference (positive or negative) from `f` to the desired output frequency.
\return The final frequency. */
double relativeFrequency(double f, double semitoneDifference) {
return f * pow(2.0, semitoneDifference / 12);
}
/*! This operator is used to connect modules together. `l` is set as the input for `r`.
\code{.cpp}
Oscillator osc;
StreamOutput out;
osc >> out; //Connect osc as the input for out.
\endcode
*/
ModuleBase& operator>> (ModuleBase& l, ModuleBase& r) {
r._assignInput(&l);
l._assignOutput(&r);
return r;
}
/*! This operator connects a module to the module parameter. It is not possible to connect a module
parameter as an input for anything: They are dead ends.
\code{.cpp}
using namespace CX::Synth;
Oscillator osc;
Envelope fenv;
Adder add;
add.amount = 500;
fenv >> add >> osc.frequency; //Connect the envelope as the input for the frequency of the oscillator with an offset of 500 Hz.
\endcode
*/
void operator>>(ModuleBase& l, ModuleParameter& r) {
r._input = &l;
r._owner->_setDataIfNotSet(&l);
}
////////////////
// ModuleBase //
////////////////
/*! This function should be overloaded for any derived class that can be used as the input for another module.
\return The value of the next sample from the module. */
double ModuleBase::getNextSample(void) {
return 0;
}
/*! This function sets the data needed by this module in order to function properly. Many modules need this data,
specifically the sample rate that the synth using. If several modules are connected together, you will only need
to set the data for one module and the change will propagate to the other connected modules automatically.
This function does not usually need to be called driectly by the user. If an appropriate input or output is
connected, the data will be set from that module. However, there are some cases where a pattern of reconnecting
previously used modules may result in inappropriate sample rates being set. For that reason, if you are having
a problem with seeing the correct sample rate after reconnecting some modules, try manually calling setData().
\param d The data to set.
*/
void ModuleBase::setData(std::shared_ptr<ModuleControlData> mcd) {
_mcd = mcd;
_dataSet(nullptr);
}
/*! Gets the data used by the module. */
std::shared_ptr<ModuleControlData> ModuleBase::getData(void) {
return _mcd;
}
/*! Disconnect a module that is an input to this module. This is a reciprocal operation:
This module's input is disconnected and `in`'s output to this module is disconnected. */
void ModuleBase::disconnectInput(ModuleBase* in) {
auto input = std::find(_inputs.begin(), _inputs.end(), in);
if (input != _inputs.end()) {
ModuleBase* inputModule = *input;
_inputs.erase(input);
inputModule->disconnectOutput(this);
}
}
/*! Disconnect a module that this module outputs to. This is a reciprocal operation:
This module's output is disconnected and `out`'s input from this module is disconnected. */
void ModuleBase::disconnectOutput(ModuleBase* out) {
auto output = std::find(_outputs.begin(), _outputs.end(), out);
if (output != _outputs.end()) {
ModuleBase* outputModule = *output;
_outputs.erase(output);
outputModule->disconnectInput(this);
}
}
/*! \brief Fully disconnect a module from all inputs and outputs. */
void ModuleBase::disconnect(void) {
while (_inputs.size() > 0) {
this->disconnectInput(_inputs[0]);
}
while (_outputs.size() > 0) {
this->disconnectOutput(_outputs[0]);
}
}
/*! Assigns a module as an input to this module. This is not a reciprocal operation.
\param in The module to assign as an input. */
void ModuleBase::_assignInput(ModuleBase* in) {
if (_maxInputs() == 0) {
return;
}
if (std::find(_inputs.begin(), _inputs.end(), in) == _inputs.end()) { //If it is not in the vector, try to add it.
if (_inputs.size() == _maxInputs()) { //If the vector is full, pop off an element before adding the new one.
disconnectInput(_inputs.back());
}
_inputs.push_back(in);
_setDataIfNotSet(in);
_inputAssignedEvent(in);
}
}
/*! Assigns a module as an output from this module. This is not a reciprocal operation.
\param out The module to asssign as an output. */
void ModuleBase::_assignOutput(ModuleBase* out) {
if (_maxOutputs() == 0) {
return;
}
if (std::find(_outputs.begin(), _outputs.end(), out) == _outputs.end()) {
if (_outputs.size() == _maxOutputs()) {
disconnectOutput(_outputs.back());
}
_outputs.push_back(out);
_setDataIfNotSet(out);
_outputAssignedEvent(out);
}
}
/*! This function is called on a module after the data for that module has been set.
\param caller The module that set the data for this module. */
void ModuleBase::_dataSet(ModuleBase* caller) {
this->_dataSetEvent();
for (unsigned int i = 0; i < _inputs.size(); i++) {
if (_inputs[i] != nullptr && _inputs[i] != caller) {
_setDataIfNotSet(_inputs[i]);
}
}
for (unsigned int i = 0; i < _outputs.size(); i++) {
if (_outputs[i] != nullptr && _outputs[i] != caller) {
_setDataIfNotSet(_outputs[i]);
}
}
for (unsigned int i = 0; i < _parameters.size(); i++) {
if (_parameters[i]->_input != nullptr) {
_setDataIfNotSet(_parameters[i]->_input);
}
}
}
/*! This function sets the data for a target module if the data for that module has not been set.
\param target The target module to set the data for. */
void ModuleBase::_setDataIfNotSet(ModuleBase* target) {
// this is uninitialized: Do nothing
if (this->_mcd == nullptr) {
return;
}
// target is uninitialized: Set it to this
if (target->_mcd == nullptr) {
target->_mcd = this->_mcd; // copy pointer
target->_dataSet(this);
return;
}
if (this->_mcd->isNewerThan(*target->_mcd)) {
// target is older; update it
target->_mcd = this->_mcd; // copy pointer
target->_dataSet(this);
return;
}
}
/*! This function is a sort of callback that is called whenever _dataSet is called. Within this
function, you should do things for your module that depend on the new data values. You should
not attempt to propagate the data values to inputs, outputs, or parameters: that is all done
for you. */
void ModuleBase::_dataSetEvent(void) {
return;
}
/*! If you are using a CX::Synth::ModuleParameter in your module, you must register that ModuleParameter
during construction (or setup) of the module using this function.
\code{.cpp}
class MyModule : public ModuleBase {
public:
MyModule(void) {
this->_registerParameter(&myParam);
//...
}
ModuleParameter myParam;
//...
};
\endcode
*/
void ModuleBase::_registerParameter(ModuleParameter* p) {
if (std::find(_parameters.begin(), _parameters.end(), p) == _parameters.end()) {
_parameters.push_back(p);
p->_owner = this;
}
}
/*! Returns the maximum number of inputs to this module. */
unsigned int ModuleBase::_maxInputs(void) {
return 1;
}
/*! Returns the maximum numer of outputs from this module. */
unsigned int ModuleBase::_maxOutputs(void) {
return 1;
}
/*! Does nothing by default, but can be overridden by inheriting classes. */
void ModuleBase::_inputAssignedEvent(ModuleBase* in) {
return;
}
/*! Does nothing by default, but can be overridden by inheriting classes. */
void ModuleBase::_outputAssignedEvent(ModuleBase* out) {
return;
}
/////////////////////
// ModuleParameter //
/////////////////////
/*! \brief Construct a ModuleParameter with no value. */
ModuleParameter::ModuleParameter(void) :
_owner(nullptr),
_input(nullptr),
_updated(true),
_value(0)
{}
/*! \brief Construct a ModuleParameter with the given start value. */
ModuleParameter::ModuleParameter(double d) :
_owner(nullptr),
_input(nullptr),
_updated(true),
_value(d)
{}
/*! Update the value of the module parameter. This gets the next sample from the module
that is the input for the ModuleParameter, if any. */
void ModuleParameter::updateValue(void) {
if (_input != nullptr) { //If there is no input connected, just keep the same value.
double temp = _input->getNextSample();
if (temp != _value) {
_value = temp;
_updated = true;
}
}
}
/*! Returns `true` if the value of the ModuleParameter has been updated since the last time
this function was called. This should be called right after updateValue() or with `checkForUpdates = true`.
Updates to the value resulting from assignment of a new value with `operator=()` count as updates
to the value.
If you don't care whether the value has been updated before using it, don't call this function.
Instead, just use updateValue() and getValue().
\param checkForUpdates Check for updates before determining whether the value has been updated.
\return `true` if the value has been updated since the last check.
*/
bool ModuleParameter::valueUpdated(bool checkForUpdates) {
if (checkForUpdates) {
updateValue();
}
if (_updated) {
_updated = false;
return true;
}
return false;
}
/*! Gets the current value of the parameter. */
double& ModuleParameter::getValue(void) {
return _value;
}
/*! \brief Implicitly converts the parameter to `double`. */
ModuleParameter::operator double(void) {
return _value;
}
/*! \brief Assign a value to the parameter. */
ModuleParameter& ModuleParameter::operator=(double d) {
_value = d;
_updated = true;
_input = nullptr; //Disconnect the input
return *this;
}
///////////
// Adder //
///////////
Adder::Adder(void) :
amount(0)
{
this->_registerParameter(&amount);
}
Adder::Adder(double amount_) :
Adder()
{
amount = amount_;
}
double Adder::getNextSample(void) {
amount.updateValue();
if (_inputs.size() > 0) {
return amount.getValue() + _inputs.front()->getNextSample();
}
return amount.getValue();
}
///////////////////
// AdditiveSynth //
///////////////////
AdditiveSynth::AdditiveSynth(void) :
fundamental(1)
{
this->_registerParameter(&fundamental);
}
double AdditiveSynth::getNextSample(void) {
double rval = 0;
if (fundamental.valueUpdated(true)) {
_recalculateWaveformPositions();
}
for (unsigned int i = 0; i < _harmonics.size(); i++) {
double waveformPos = _harmonics[i].waveformPosition + _harmonics[i].positionChangePerSample;
waveformPos = fmod(waveformPos, 1);
rval += Oscillator::sine(waveformPos) * _harmonics[i].amplitude;
_harmonics[i].waveformPosition = waveformPos;
}
return rval;
}
/*! This function sets the amplitudes of the harmonics based on the chosen type. The resulting waveform
will only be correct if the harmonic series is the standard harmonic series (see setStandardHarmonicSeries()).
\param a The type of wave calculate amplitudes for.
*/
void AdditiveSynth::setAmplitudes(AmplitudePresets a) {
vector<double> amps = calculateAmplitudes(a, _harmonics.size());
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = amps[i];
}
}
/*! This function sets the amplitudes of the harmonics based on a mixture of the chosen types. The resulting waveform
will only be correct if the harmonic series is the standard harmonic series (see setStandardHarmonicSeries()).
This is a convenient way to morph between waveforms.
\param a1 The first preset.
\param a2 The second present.
\param mixture Should be in the interval [0,1]. The proportion of `a1` that will be used, with the remainder (`1 - mixture`) used from `a2`.
*/
void AdditiveSynth::setAmplitudes(AmplitudePresets a1, AmplitudePresets a2, double mixture) {
vector<double> amps1 = calculateAmplitudes(a1, _harmonics.size());
vector<double> amps2 = calculateAmplitudes(a2, _harmonics.size());
mixture = CX::Util::clamp<double>(mixture, 0, 1);
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = (amps1[i] * mixture) + (amps2[i] * (1 - mixture));
}
}
/*! This function sets the amplitudes of the harmonics to arbitrary values as specified in `amps`.
\param amps The amplitudes of the harmonics. If this vector does not contain as many values as
there are harmonics, the unspecified amplitudes will be set to 0.
*/
void AdditiveSynth::setAmplitudes(std::vector<double> amps) {
while (amps.size() < _harmonics.size()) {
amps.push_back(0.0);
}
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].amplitude = amps[i];
}
}
/*! This is a specialty function that only works when the standard harmonic series is being used. If so,
it calculates the amplitudes needed for the hamonics so as to produce the specified waveform type.
\param a The type of waveform that should be output from the additive synth.
\param count The number of harmonics.
\return A vector of amplitudes.
*/
std::vector<double> AdditiveSynth::calculateAmplitudes(AmplitudePresets a, unsigned int count) {
std::vector<double> rval(count, 0.0);
if (a == AmplitudePresets::SAW) {
for (unsigned int i = 0; i < count; i++) {
rval[i] = 2 / (PI * (i + 1));
if ((i % 2) == 1) { //Is even-numbered harmonic
rval[i] *= -1;
}
}
} else if (a == AmplitudePresets::SQUARE) {
for (unsigned int i = 0; i < count; i++) {
if ((i % 2) == 0) { //Is odd-numbered harmonic
//rval[i] = 2 / (PI * (i + 1));
rval[i] = 4 / (PI * (i + 1));
}
//Do nothing for even harmonics: they remain at 0.
}
} else if (a == AmplitudePresets::TRIANGLE) {
for (unsigned int i = 0; i < count; i++) {
if ((i % 2) == 0) { //Is odd-numbered harmonic
rval[i] = 8 / ((PI * PI) * pow(i + 1, 2));
if (((i / 2) % 2) == 1) {
rval[i] *= -1;
}
}
//Do nothing for even harmonics: they remain at 0.
}
} else if (a == AmplitudePresets::SINE) {
rval[0] = 1;
}
return rval;
}
/*! This function removes all harmonics that have an amplitude that is less than or equal to a tolerance
times the amplitude of the harmonic with the greatest absolute amplitude. The result of this pruning is that
the synthesizer will be more computationally efficient but provide a less precise approximation of the desired
waveform.
\param tol `tol` is interpreted differently depending on its value. If `tol` is greater than or equal to 0, it is treated
as a proportion of the amplitude of the frequency with the greatest amplitude. If `tol` is less than 0, it is treated as
the difference in decibels between the frequency with the greatest amplitude and the tolerance cutoff point.
\note Because only harmonics with an amplitude less than or equal to the tolerance times an amplitude are pruned,
setting `tol` to 0 will remove harmonics with 0 amplitude, but no others.
*/
void AdditiveSynth::pruneLowAmplitudeHarmonics(double tol) {
double maxAmplitude = 0;
for (unsigned int i = 0; i < _harmonics.size(); i++) {
if (abs(_harmonics[i].amplitude) > maxAmplitude) {
maxAmplitude = abs(_harmonics[i].amplitude);
}
}
if (tol < 0) {
tol = sqrt(pow(10.0f, tol / 10.0f));
}
double cutoffAmplitude = maxAmplitude * tol;
for (unsigned int i = 0; i < _harmonics.size(); i++) {
if (abs(_harmonics[i].amplitude) < cutoffAmplitude) {
_harmonics.erase(_harmonics.begin() + i);
i--;
}
}
}
/*! The standard harmonic series begins with the fundamental frequency f1 and each seccuessive
harmonic has a frequency equal to f1 * n, where n is the harmonic number for the harmonic.
This is the natural harmonic series, one that occurs, e.g., in a vibrating string.
*/
void AdditiveSynth::setStandardHarmonicSeries(unsigned int harmonicCount) {
this->setHarmonicSeries(harmonicCount, HarmonicSeriesType::MULTIPLE, 1.0);
}
/*! Set the harmonic series for the AdditiveSynth.
\param harmonicCount The number of harmonics to use.
\param type The type of harmonic series to generate. Can be either HS_MULTIPLE or HS_SEMITONE. For HS_MULTIPLE, each
harmonic's frequency will be some multiple of the fundamental frequency, depending on the harmonic number and
controlParameter. For HS_SEMITONE, each harmonic's frequency will be some number of semitones above the previous frequency,
based on controlParameter (specifying the number of semitones).
\param controlParameter If `type == HS_MULTIPLE`, the frequency for harmonic `i` will be `i * controlParameter`, where the
fundamental gives the value 1 for `i`. If `type == HS_SEMITONE`, the frequency for harmonic `i` will be
`pow(2, (i - 1) * controlParameter/12)`, where the fundamental gives the value 1 for `i`.
\note If `type == HS_MULTIPLE` and `controlParameter == 1`, then the standard harmonic series will be generated.
\note If `type == HS_SEMITONE`, `controlParameter` does not need to be an integer.
*/
void AdditiveSynth::setHarmonicSeries(unsigned int harmonicCount, HarmonicSeriesType type, double controlParameter) {
_harmonics.resize(harmonicCount);
if (type == HarmonicSeriesType::MULTIPLE) {
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = (i + 1) * controlParameter;
}
} else if (type == HarmonicSeriesType::SEMITONE) {
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = pow(2.0, i * controlParameter / 12);
}
}
_recalculateWaveformPositions();
}
/*! This function applies the harmonic series from a vector of harmonics supplied by the user.
\param harmonicSeries A vector frequencies that create a harmonic series. These values
will be multiplied by the fundamental frequency in order to obtain the final frequency
of each harmonic. The multiplier for the first harmonic is at index 0, so by convention
you might want to set harmonicSeries[0] equal to 1, so that when the fundamental frequency
is set with setFundamentalFrequency(), the first harmonic is actually the fundamental
frequency, but this is not enforced.
\note If `harmonicSeries.size()` is greater than the current number of harmonics, the
new harmonics will have an amplitude of 0. If `harmonicSeries.size()` is less than the
current number of harmonics, the number of harmonics will be reduced to the size of
`harmonicSeries`.
*/
void AdditiveSynth::setHarmonicSeries(std::vector<double> harmonicSeries) {
_harmonics.resize(harmonicSeries.size());
for (unsigned int i = 0; i < _harmonics.size(); i++) {
_harmonics[i].relativeFrequency = harmonicSeries[i];
}
_recalculateWaveformPositions();
}
void AdditiveSynth::_recalculateWaveformPositions(void) {
double firstHarmonicPos = _harmonics[0].waveformPosition;
double normalizedFrequency = fundamental.getValue() / _mcd->getOversamplingSampleRate();
for (unsigned int i = 0; i < _harmonics.size(); ++i) {
double relativeFrequency = _harmonics[i].relativeFrequency;
_harmonics[i].positionChangePerSample = normalizedFrequency * relativeFrequency;
_harmonics[i].waveformPosition = firstHarmonicPos * relativeFrequency; //This keeps the harmonics in phase
}
}
void AdditiveSynth::_dataSetEvent(void) {
_recalculateWaveformPositions();
}
/////////////
// Clamper //
/////////////
Clamper::Clamper(void) :
low(-1),
high(1)
{
this->_registerParameter(&low);
this->_registerParameter(&high);
}
Clamper::Clamper(double low_, double high_) :
Clamper()
{
low = low_;
high = high_;
}
double Clamper::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
double temp = this->_inputs.front()->getNextSample();
low.updateValue();
high.updateValue();
return Util::clamp<double>(temp, low.getValue(), high.getValue());
}
//////////////
// Envelope //
//////////////
Envelope::Envelope(void) :
gateInput(0.5),
_stage(4)
{
this->_registerParameter(&gateInput);
this->_registerParameter(&a);
this->_registerParameter(&d);
this->_registerParameter(&s);
this->_registerParameter(&r);
}
Envelope::Envelope(double a_, double d_, double s_, double r_) :
Envelope()
{
a = a_;
d = d_;
s = s_;
r = r_;
}
double Envelope::getNextSample(void) {
if (gateInput.valueUpdated(true)) {
if (gateInput.getValue() == 1.0) {
this->attack();
} else if (gateInput.getValue() == 0.0) {
this->release();
}
}
if (_stage > 3) {
return 0;
}
if (a.valueUpdated(true)) {
_a = a.getValue();
}
if (d.valueUpdated(true)) {
_d = d.getValue();
}
if (s.valueUpdated(true)) {
_s = s.getValue();
}
if (r.valueUpdated(true)) {
_r = r.getValue();
}
//p is the proportion of the envelope, that controls e.g. how loud the output is.
double p = _lastP; //In case somehow none of the cases is hit, the level is just the last level
switch (_stage) {
//Attack:
case 0:
//If within the attack time
if ((_timeSinceLastStage < _a) && (_a != 0)) {
//The proportion is the amount of time spent in attack so far divided by the length of the attack
p = _timeSinceLastStage / _a;
break;
} else {
_timeSinceLastStage = 0;
_stage++;
//Intentional fall through
}
//Decay:
case 1:
//If within the decay time
if ((_timeSinceLastStage < _d) && (_d != 0)) {
//The proportion the linear interpolation between the max (1) and the sustain
//level (_s) as a function of time in the decay stage
p = 1 - (_timeSinceLastStage / _d) * (1 - _s);
break;
} else {
_timeSinceLastStage = 0;
_stage++;
//Intentional fall through
}
//Sustain:
case 2:
p = _s; //The proportion is just the sustain level. Sustain lasts indefinitely until another event ends the sustain.
break;
//Release:
case 3:
//If within the release time
if ((_timeSinceLastStage < _r) && (_r != 0)) {
//The p is the linear interpolation between the level that the envelope was at when the release
//happened (not neccessarily the sustain level!) as a function of time in the release stage
p = (1 - _timeSinceLastStage / _r) * _levelAtRelease;
break;
} else {
//_timeSinceLastStage = 0;
_stage++;
p = 0;
}
}
_lastP = p;
_timeSinceLastStage += _timePerSample;
double val;
if (_inputs.size() > 0) {
val = _inputs.front()->getNextSample();
} else {
val = 1;
}
return val * p;
}
/*! \brief Trigger the attack of the Envelope. */
void Envelope::attack(void) {
_stage = 0;
_timeSinceLastStage = 0;
}
/*! \brief Trigger the release of the Envelope. */
void Envelope::release(void) {
_stage = 3;
_timeSinceLastStage = 0;
_levelAtRelease = _lastP;
}
void Envelope::_dataSetEvent(void) {
_timePerSample = 1.0 / _mcd->getOversamplingSampleRate();
}
////////////
// Filter //
////////////
Filter::Filter(void) :
cutoff(1000),
bandwidth(50),
_filterType(FilterType::LOW_PASS),
x1(0),
x2(0),
y1(0),
y2(0)
{
this->_registerParameter(&cutoff);
this->_registerParameter(&bandwidth);
}
Filter::Filter(Filter::FilterType type, double cutoff_, double bandwidth_) :
Filter()
{
cutoff = cutoff_;
if (bandwidth_ < 0) {
bandwidth = cutoff_ / 10;
} else {
bandwidth = bandwidth_;
}
setType(type);
}
/*! \brief Set the type of filter to use, from the Filter::FilterType enum. */
void Filter::setType(FilterType type) {
_filterType = type;
_recalculateCoefficients();
}
double Filter::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
if (cutoff.valueUpdated(true) || bandwidth.valueUpdated(true)) {
_recalculateCoefficients();
}
double x0 = _inputs.front()->getNextSample();
double y0;
if (_filterType == FilterType::LOW_PASS || _filterType == FilterType::HIGH_PASS) {
//a2 and b2 are always 0 for LOW_PASS and HIGH_PASS, so they are omitted from the calculation.
y0 = a0*x0 + a1*x1 + b1*y1;
y1 = y0;
x1 = x0;
} else {
y0 = a0*x0 + a1*x1 + a2*x2 + b1*y1 + b2*y2;
y2 = y1;
y1 = y0;
x2 = x1;
x1 = x0;
}
return y0;
}
void Filter::_recalculateCoefficients(void) {
if (_mcd == nullptr) {
return;
}
double frequencyDivisor = _mcd->getOversamplingSampleRate();
double f_angular = 2 * PI * cutoff.getValue() / frequencyDivisor; //Normalized angular frequency
if (_filterType == FilterType::LOW_PASS || _filterType == FilterType::HIGH_PASS) {
double x = exp(-f_angular);
a2 = 0;
b2 = 0;
if (_filterType == FilterType::LOW_PASS) {
a0 = 1 - x;
a1 = 0;
b1 = x;
} else if (_filterType == FilterType::HIGH_PASS) {
a0 = (1 + x) / 2;
a1 = -(1 + x) / 2;
b1 = x;
}
} else if (_filterType == FilterType::BAND_PASS || _filterType == FilterType::NOTCH) {
double R = 1 - (3 * bandwidth.getValue() / frequencyDivisor); //Bandwidth is normalized
double K = (1 - 2 * R*cos(f_angular) + (R*R)) / (2 - 2 * cos(f_angular));
b1 = 2 * R * cos(f_angular);
b2 = -(R*R);
if (_filterType == FilterType::BAND_PASS) {
a0 = 1 - K;
a1 = 2 * (K - R) * cos(f_angular);
a2 = (R*R) - K;
} else if (_filterType == FilterType::NOTCH) {
a0 = K;
a1 = -2 * K * cos(f_angular);
a2 = K;
}
}
}
///////////
// Mixer //
///////////
double Mixer::getNextSample(void) {
double d = 0;
for (unsigned int i = 0; i < _inputs.size(); i++) {
d += _inputs[i]->getNextSample();
}
return d;
}
unsigned int Mixer::_maxInputs(void) {
return 32;
}
////////////////
// Multiplier //
////////////////
Multiplier::Multiplier(void) :
amount(1)
{
this->_registerParameter(&amount);
}
/*! Convenience constructor.
\param amount_ The amount to multiply the input by.
*/
Multiplier::Multiplier(double amount_) :
amount(amount_)
{
this->_registerParameter(&amount);
}
double Multiplier::getNextSample(void) {
if (_inputs.size() == 0) {
return 0;
}
amount.updateValue();
return _inputs.front()->getNextSample() * amount.getValue();
}
/*! Sets the `amount` of the multiplier based on gain in decibels.
\param decibels The gain to apply. If greater than 0, `amount` will be greater than 1. If less than 0, `amount` will be less than 1.
After calling this function, `amount` will never be negative.
*/
void Multiplier::setGain(double decibels) {
amount = sqrt(pow(10.0, decibels / 10.0));
}
////////////////
// Oscillator //
////////////////
Oscillator::Oscillator(void) :
frequency(0),
_waveformPos(0)
{
this->_registerParameter(&frequency);
setGeneratorFunction(Oscillator::sine);
}
Oscillator::Oscillator(std::function<double(double)> generatorFunction, double frequency_) :
Oscillator()
{
setGeneratorFunction(generatorFunction);
frequency = frequency_;
}
double Oscillator::getNextSample(void) {
frequency.updateValue();
double addAmount = frequency.getValue() / _mcd->getOversamplingSampleRate();
_waveformPos = fmod(_waveformPos + addAmount, 1);
return _generatorFunction(_waveformPos);
}
/*! It is very easy to make your own waveform generating functions to be used with an Oscillator.
A waveform generating function takes a value that represents the location in the waveform at
the current point in time. These values are in the interval [0,1).
The waveform generating function should return a double representing the amplitude of the
wave at the given waveform position.
To put this all together, a sine wave generator looks like this:
\code{.cpp}
double sineWaveGeneratorFunction(double waveformPosition) {
return sin(2 * PI * waveformPosition); //The argument for sin() is in radians. 1 cycle is 2*PI radians.
}
\endcode
*/
void Oscillator::setGeneratorFunction(std::function<double(double)> f) {
_generatorFunction = f;
}
/*! Produces a sawtooth wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::saw(double wp) {
return (2 * wp) - 1;
}
/*! Produces a sine wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::sine(double wp) {
return sin(wp * 2 * PI);
}
/*! Produces a square wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::square(double wp) {
if (wp < .5) {
return 1;
} else {
return -1;
}
}
/*! Produces a triangle wave.
\param wp The waveform position to sample, in the interval [0, 1), where 0 is the
start of the waveform and 1 is the end of the waveform.
\return A value normalized to the interval [-1, 1] containing the value of the waveform
function at the given waveform position.
*/
double Oscillator::triangle(double wp) {
if (wp < .5) {
return ((4 * wp) - 1);
} else {
return (3 - (4 * wp));
}
}
/*! Produces white noise.
\param wp This argument is ignored.
\return A random value in the interval [-1, 1].
*/
double Oscillator::whiteNoise(double wp) {
return CX::Instances::RNG.randomDouble(-1, 1);
}
///////////////////
// RingModulator //
///////////////////
double RingModulator::getNextSample(void) {
if (_inputs.size() == 2) {
double i1 = _inputs[0]->getNextSample();
double i2 = _inputs[1]->getNextSample();
return i1 * i2;
} else if (_inputs.size() == 1) {
return _inputs.front()->getNextSample();
}
return 0;
}
unsigned int RingModulator::_maxInputs(void) {
return 2;
}
//////////////
// Splitter //
//////////////
Splitter::Splitter(void) :
_currentSample(0.0),
_fedOutputs(0)
{}
//The way this works is that each output gets the same value from a single
//input, so only once all of the outputs have been fed do we update the
//sample value. If the splitter is feeding, e.g., two different stream outputs,
//there is the potential for substantial desynchronization. Basically, samples
//from all outputs of the splitter must happen at adjacent times.
double Splitter::getNextSample(void) {
if (_fedOutputs >= _outputs.size()) {
_currentSample = _inputs.front()->getNextSample();
_fedOutputs = 0;
}
_fedOutputs++;
return _currentSample;
}
void Splitter::_outputAssignedEvent(ModuleBase* out) {
_fedOutputs = _outputs.size();
}
//////////////////////
// SoundBufferInput //
//////////////////////
SoundBufferInput::SoundBufferInput(void) :
_sb(nullptr),
_currentSample(0)
{}
SoundBufferInput::SoundBufferInput(CX::CX_SoundBuffer *sb, unsigned int channel) :
SoundBufferInput()
{
setup(sb, channel);
}
/*! This function sets the CX_SoundBuffer from which data will be drawn. Because the SoundBufferInput is monophonic,
you must pick one channel of the CX_SoundBuffer to use.
\param sb The CX_SoundBuffer to use. Because this CX_SoundBuffer is taken as a pointer and is not copied,
you should make sure that `sb` remains in existence and unmodified while the SoundBufferInput is in use.
\param channel The channel of the CX_SoundBuffer to use.
*/
void SoundBufferInput::setup(CX::CX_SoundBuffer *sb, unsigned int channel) {
_sb = sb;
_channel = channel;
this->setData(ModuleControlData::construct(_sb->getSampleRate(), 1));
}
/*! Set the playback time of the current CX_SoundBuffer. When playback starts, it will start from this time.
If playback is in progress, playback will skip to the selected time. */
void SoundBufferInput::setTime(CX::CX_Millis t) {
if (_sb != nullptr) {
unsigned int startSample = _sb->getChannelCount() * (unsigned int)(_sb->getSampleRate() * t.seconds());
_currentSample = startSample + _channel;
} else {
_currentSample = _channel;
}
}
double SoundBufferInput::getNextSample(void) {
if (!this->canPlay()) {
return 0;
}
double value = _sb->getRawDataReference().at(_currentSample);
_currentSample += _sb->getChannelCount();
return value;
}
/*! Checks to see if the CX_SoundBuffer that is associated with this SoundBufferInput is able to play.
It is unable to play if CX_SoundBuffer::isReadyToPlay() is false or if the whole sound has been played.*/
bool SoundBufferInput::canPlay(void) {
return (_sb != nullptr) && (_sb->isReadyToPlay()) && (_currentSample < _sb->getTotalSampleCount());
}
void SoundBufferInput::_dataSetEvent(void) {
if (_mcd->getSampleRate() != _sb->getSampleRate()) {
_sb->resample(_mcd->getSampleRate());
}
if (_mcd->getOversampling() > 1) {
this->setData(ModuleControlData::construct(_mcd->getSampleRate(), 1));
}
}
///////////////////////
// SoundBufferOutput //
///////////////////////
SoundBufferOutput::SoundBufferOutput(float sampleRate, unsigned int oversampling) {
setup(sampleRate, oversampling);
}
/*! Configure the output to use a particular sample rate. If this function is not called, the sample rate
of the modular synth may be undefined.
\param sampleRate The sample rate in Hz. */
void SoundBufferOutput::setup(float sampleRate, unsigned int oversampling) {
this->setData(ModuleControlData::construct(sampleRate, oversampling));
sb.clear();
sb.setFromVector(std::vector<float>(), 1, sampleRate);
}
/*! This function samples `t` milliseconds of data at the sample rate given in setup().
The result is stored in the `sb` member of this class. If `sb` is not empty when this function
is called, the data is appended to `sb`. */
void SoundBufferOutput::sampleData(CX::CX_Millis t, bool clear) {
if (_inputs.size() == 0) {
CX::Instances::Log.warning("SoundBufferOutput") << "sampleData(): Attempted to sample data when no inputs were connected.";
return;
}
if (clear) {
sb.clear();
}
unsigned int samplesToTake = ceil(_mcd->getSampleRate() * t.seconds());
std::vector<float> tempData(samplesToTake);
ModuleBase* input = _inputs.front();
unsigned int oversampling = _mcd->getOversampling();
for (unsigned int i = 0; i < samplesToTake; i++) {
double sum = 0;
for (unsigned int ovs = 0; ovs < oversampling; ovs++) {
sum += input->getNextSample();
}
tempData[i] = CX::Util::clamp<float>(sum / oversampling, -1, 1);
}
//for (unsigned int i = 0; i < samplesToTake; i++) {
// tempData[i] = CX::Util::clamp<float>((float)input->getNextSample(), -1, 1);
//}
if (sb.getTotalSampleCount() == 0) {
sb.setFromVector(tempData, 1, _mcd->getSampleRate());
} else {
std::vector<float>& bufData = sb.getRawDataReference();
bufData.insert(bufData.end(), tempData.begin(), tempData.end());
}
}
/////////////////////////////
// StereoSoundBufferOutput //
/////////////////////////////
StereoSoundBufferOutput::StereoSoundBufferOutput(float sampleRate, unsigned int oversampling) {
setup(sampleRate, oversampling);
}
/*! Configure the output to use a particular sample rate. If this function is not called, the sample rate
of the modular synth may be undefined.
\param sampleRate The sample rate in Hz. */
void StereoSoundBufferOutput::setup(float sampleRate, unsigned int oversampling) {
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(sampleRate, oversampling);
left.setData(mcd);
right.setData(mcd);
sb.clear();
sb.setFromVector(std::vector<float>(), 2, sampleRate);
}
/*! This function samples `t` milliseconds of data at the sample rate given in setup().
The result is stored in the `sb` member of this class. If `sb` is not empty when this function
is called, the data is appended to `sb`. */
void StereoSoundBufferOutput::sampleData(CX::CX_Millis t, bool clear) {
if (clear) {
sb.clear();
}
unsigned int samplesToTake = ceil(left.getData()->getSampleRate() * t.seconds());
unsigned int channels = 2; //Stereo
std::vector<float> tempData(samplesToTake * channels);
// GenericOutput deals with oversampling
for (unsigned int i = 0; i < samplesToTake; i++) {
unsigned int index = i * channels;
tempData[index + 0] = CX::Util::clamp<float>((float)left.getNextSample(), -1, 1);
tempData[index + 1] = CX::Util::clamp<float>((float)right.getNextSample(), -1, 1);
}
if (sb.getTotalSampleCount() == 0) {
sb.setFromVector(tempData, channels, left.getData()->getSampleRate());
} else {
std::vector<float>& bufData = sb.getRawDataReference();
bufData.insert(bufData.end(), tempData.begin(), tempData.end());
}
}
/////////////////
// StreamInput //
/////////////////
StreamInput::StreamInput(void) :
_maxBufferSize(4096),
_soundStream(nullptr),
_listeningForEvents(false)
{}
StreamInput::StreamInput(CX::CX_SoundStream* ss) :
StreamInput()
{
setup(ss);
}
StreamInput::~StreamInput(void) {
_listenForEvents(false);
}
/*! Set up the StreamInput with a CX_SoundStream configured for input.
\param stream A pointer to the sound stream. */
void StreamInput::setup(CX::CX_SoundStream* stream) {
if (stream->getConfiguration().inputChannels != 1) {
CX::Instances::Log.error("StreamInput") << "setInputStream(): The provided stream must be"
"configured with a single input channel, but it is not.";
}
_soundStream = stream;
_listenForEvents(true);
}
double StreamInput::getNextSample(void) {
double rval = 0;
if (_maxBufferSize != 0) {
while (_buffer.size() > _maxBufferSize) {
_buffer.pop_front();
}
}
if (_buffer.size() > 0) {
rval = _buffer.front();
_buffer.pop_front();
}
return rval;
}
/*! \brief Clear the contents of the input buffer. */
void StreamInput::clear(void) {
_buffer.clear();
}
/*! Set the maximum number of samples that the input buffer can contain.
\param size The size of the input buffer, in samples. */
void StreamInput::setMaximumBufferSize(unsigned int size) {
_maxBufferSize = size;
}
void StreamInput::_callback(const CX::CX_SoundStream::InputEventArgs& in) {
for (unsigned int sampleFrame = 0; sampleFrame < in.bufferSize; sampleFrame++) {
_buffer.push_back(in.inputBuffer[sampleFrame]);
}
}
void StreamInput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->inputEvent, this, &StreamInput::_callback);
} else {
ofRemoveListener(_soundStream->inputEvent, this, &StreamInput::_callback);
}
_listeningForEvents = listen;
}
unsigned int StreamInput::_maxInputs(void) {
return 0;
}
//////////////////
// StreamOutput //
//////////////////
StreamOutput::StreamOutput(CX::CX_SoundStream* stream, unsigned int oversampling) {
setup(stream, oversampling);
}
StreamOutput::~StreamOutput(void) {
_listenForEvents(false);
}
/*! Set up the StereoStreamOutput with the given CX_SoundStream.
\param stream A CX_SoundStream that is configured for output to any number of channels. */
void StreamOutput::setup(CX::CX_SoundStream* stream, unsigned int oversampling) {
_soundStream = stream;
_listenForEvents(true);
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(_soundStream->getConfiguration().sampleRate, oversampling);
this->setData(mcd);
}
void StreamOutput::_callback(const CX::CX_SoundStream::OutputEventArgs& d) {
if (_inputs.size() == 0) {
return;
}
ModuleBase* input = _inputs.front();
unsigned int oversampling = _mcd->getOversampling();
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
double sum = 0;
for (unsigned int ovs = 0; ovs < oversampling; ovs++) {
sum += input->getNextSample();
}
double mean = CX::Util::clamp<float>(sum / oversampling, -1, 1);
for (int ch = 0; ch < d.outputChannels; ch++) {
d.outputBuffer[(sample * d.outputChannels) + ch] += mean;
}
}
/*
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
float value;
if (_data->oversampling > 1) {
double sum = 0;
for (unsigned int oversamp = 0; oversamp < _data->oversampling; oversamp++) {
sum += input->getNextSample();
}
double mean = sum / _data->oversampling;
value = CX::Util::clamp<float>(mean, -1, 1);
} else {
value = CX::Util::clamp<float>(input->getNextSample(), -1, 1);
}
for (int ch = 0; ch < d.outputChannels; ch++) {
d.outputBuffer[(sample * d.outputChannels) + ch] += value;
}
}
*/
}
void StreamOutput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->outputEvent, this, &StreamOutput::_callback);
} else {
ofRemoveListener(_soundStream->outputEvent, this, &StreamOutput::_callback);
}
_listeningForEvents = listen;
}
////////////////////////
// StereoStreamOutput //
////////////////////////
StereoStreamOutput::StereoStreamOutput(CX::CX_SoundStream* stream, unsigned int oversampling) {
setup(stream, oversampling);
}
StereoStreamOutput::~StereoStreamOutput(void) {
_listenForEvents(false);
}
/*! Set up the StereoStreamOutput with the given CX_SoundStream.
\param stream A CX_SoundStream that is configured for stereo output. */
void StereoStreamOutput::setup(CX::CX_SoundStream* stream, unsigned int oversampling) {
_soundStream = stream;
_listenForEvents(true);
std::shared_ptr<ModuleControlData> mcd = ModuleControlData::construct(_soundStream->getConfiguration().sampleRate, oversampling);
left.setData(mcd);
right.setData(mcd);
}
void StereoStreamOutput::_callback(const CX::CX_SoundStream::OutputEventArgs& d) {
unsigned int oversampling = left.getData()->getOversampling();
// GenericOutput deals with oversampling
for (unsigned int sample = 0; sample < d.bufferSize; sample++) {
unsigned int index = sample * d.outputChannels;
d.outputBuffer[index + 0] += CX::Util::clamp<float>(right.getNextSample(), -1, 1); //The buffers only use float, so clamp with float.
d.outputBuffer[index + 1] += CX::Util::clamp<float>(left.getNextSample(), -1, 1);
}
}
void StereoStreamOutput::_listenForEvents(bool listen) {
if ((listen == _listeningForEvents) || (_soundStream == nullptr)) {
return;
}
if (listen) {
ofAddListener(_soundStream->outputEvent, this, &StereoStreamOutput::_callback);
} else {
ofRemoveListener(_soundStream->outputEvent, this, &StereoStreamOutput::_callback);
}
_listeningForEvents = listen;
}
//////////////////////
// TrivialGenerator //
//////////////////////
TrivialGenerator::TrivialGenerator(void) :
value(0),
step(0)
{
this->_registerParameter(&value);
this->_registerParameter(&step);
}
TrivialGenerator::TrivialGenerator(double value_, double step_) :
TrivialGenerator()
{
value = value_;
step = step_;
}
double TrivialGenerator::getNextSample(void) {
value.updateValue();
value.getValue() += step;
return value.getValue() - step;
}
///////////////
// FIRFilter //
///////////////
FIRFilter::FIRFilter(void) :
_filterType(FilterType::LOW_PASS),
_coefCount(-1)
{}
FIRFilter::FIRFilter(FilterType filterType, unsigned int coefficientCount) :
FIRFilter()
{
setup(filterType, coefficientCount);
}
FIRFilter::FIRFilter(const std::vector<double>& coefficients) :
FIRFilter()
{
setup(coefficients);
}
/*! Set up the FIRFilter with the given filter type and number of coefficients to use.
\param filterType Should be a type of filter other than FIRFilter::FilterType::FIR_USER_DEFINED. If you want
to define your own filter type, use FIRFilter::setup(std::vector<double>) instead.
\param coefficientCount The number of coefficients sets the length of time, in samples, that the filter will
produce a non-zero output following an impulse. In other words, the filter operates on `coefficientCount`
samples at a time to produce each output sample.
*/
void FIRFilter::setup(FilterType filterType, unsigned int coefficientCount) {
if (filterType == FIRFilter::FilterType::USER_DEFINED) {
CX::Instances::Log.error("FIRFilter") << "setup(): FilterType::FIR_USER_DEFINED should not be used explicity."
"Use FIRFilter::setup(std::vector<double>) if you want to define your own filter type.";
}
_filterType = filterType;
if ((coefficientCount % 2) == 0) {
coefficientCount++; //Must be odd in this implementation
}
_coefCount = coefficientCount;
_coefficients.assign(_coefCount, 0);
_inputSamples.assign(_coefCount, 0); //Fill with zeroes so that we never have to worry about not having enough input data.
}
/*! You can use this function to supply your own filter coefficients, which allows a great
deal of flexibility in the use of the FIRFilter. See the fir1 and fir2 functions from the
//"signal" package for R for a way to design your own filter.
\param coefficients The filter coefficients to use.
*/
void FIRFilter::setup(const std::vector<double>& coefficients) {
_filterType = FilterType::USER_DEFINED;
_coefficients = coefficients;
_coefCount = coefficients.size();
_inputSamples.assign(_coefCount, 0); //Fill with zeroes so that we never have to worry about not having enough input data.
}
/*! If using either FilterType::LOW_PASS or FilterType::HIGH_PASS, this function allows you to
change the cutoff frequency for the filter. This causes the filter coefficients to be recalculated.
\param cutoff The cutoff frequency, in Hz. */
void FIRFilter::setCutoff(double cutoff) {
if (_filterType != FilterType::LOW_PASS && _filterType != FilterType::HIGH_PASS) {
CX::Instances::Log.warning("FIRFilter") << "setCutoff() should only be used when the filter type is LOW_PASS or HIGH_PASS.";
return;
}
//See https://www.mikroe.com/ebooks/digital-filter-design/finite-impulse-response-fir-filter-design-methods (fairly far down the page, table 2-2-1.)
// TODO: Test the difference (also in setBandCutoffs)
double omega = 2 * PI * cutoff / _mcd->getSampleRate();
//double omega = 2 * PI * cutoff / _mcd->getOversampledSampleRate();
int N = _coefCount - 1; //N is the order of the filter
float M = (float)N / 2;
for (int n = 0; n < _coefCount; n++) {
double hn = 0;
if (n == M) {
if (_filterType == FilterType::LOW_PASS) {
hn = omega / PI;
} else if (_filterType == FilterType::HIGH_PASS) {
hn = 1 - omega / PI;
}
} else {
float dif = n - M;
if (_filterType == FilterType::LOW_PASS) {
hn = sin(omega * dif) / (PI * dif);
} else if (_filterType == FilterType::HIGH_PASS) {
hn = -sin(omega * dif) / (PI * dif);
}
}
_coefficients[n] = hn;
}
_applyWindowToCoefs();
}
/*! Sets the upper and lower cutoffs for a band filter mode (i.e. `BAND_PASS` or `BAND_STOP`).
\param lower The lower end of the band (Hz).
\param upper The upper end of the band (Hz).
*/
void FIRFilter::setBandCutoffs(double lower, double upper) {
if (_filterType != FilterType::BAND_PASS && _filterType != FilterType::BAND_STOP) {
CX::Instances::Log.warning("FIRFilter") << "setBandCutoffs() should only be used when the filter type is BAND_PASS or BAND_STOP.";
return;
}
auto commonF = [](double omega, int dif) -> double {
return sin(omega * dif) / (PI * dif);
};
//Super useful page:
//See https://www.mikroe.com/ebooks/digital-filter-design/finite-impulse-response-fir-filter-design-methods (fairly far down the page, table 2-2-1.)
double oc2 = 2 * PI * lower / _mcd->getSampleRate(); // oversampling?
double oc1 = 2 * PI * upper / _mcd->getSampleRate();
int N = _coefCount - 1; //N is the order of the filter
float M = (float)N / 2;
for (int n = 0; n < _coefCount; n++) {
double hn = 0;
if (n == M) {
if (_filterType == FilterType::BAND_PASS) {
hn = (oc2 - oc1) / PI;
} else if (_filterType == FilterType::BAND_STOP) {
hn = 1 - (oc2 - oc1) / PI;
}
} else {
float dif = n - M;
double val1 = commonF(oc1, dif);
double val2 = commonF(oc2, dif);
if (_filterType == FilterType::BAND_PASS) {
hn = val2 - val1;
} else if (_filterType == FilterType::BAND_STOP) {
hn = val1 - val2;
}
}
_coefficients[n] = hn;
}
_applyWindowToCoefs();
}
double FIRFilter::getNextSample(void) {
//Because _inputSamples is set up to have _coefCount elements, you just always pop off an element to start.
_inputSamples.pop_front();
_inputSamples.push_back(_inputs.front()->getNextSample());
double y_n = 0;
for (unsigned int i = 0; i < _coefCount; i++) {
y_n += _inputSamples[i] * _coefficients[i];
}
return y_n;
}
double FIRFilter::_calcH(int n, double omega) {
if (n == 0) {
return omega / PI;
}
return omega / PI * sinc(n*omega);
}
void FIRFilter::_applyWindowToCoefs(void) {
//Do nothing for rectangular window
if (_windowType == WindowType::HANNING) {
for (int i = 0; i < _coefCount; i++) {
_coefficients[i] *= 0.5*(1 - cos(2 * PI*i / (_coefCount - 1)));
}
} else if (_windowType == WindowType::BLACKMAN) {
for (int i = 0; i < _coefCount; i++) {
double a0 = 7938 / 18608;
double a1 = 9240 / 18608;
double a2 = 1430 / 18608;
_coefficients[i] *= a0 - a1 * cos(2 * PI*i / (_coefCount - 1)) + a2*cos(4 * PI*i / (_coefCount - 1));
}
}
}
} //namespace Synth
} //namespace CX
| 29.026379
| 149
| 0.696278
|
hardmanko
|
937826ce082e414a4045cbb7aa1e028ee32805d2
| 955
|
hpp
|
C++
|
src/tools/tools.hpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
src/tools/tools.hpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
src/tools/tools.hpp
|
InspectorSolaris/nd-engine
|
a8d63fe4bc0e57a96317adf015534d2e779ffcbb
|
[
"WTFPL"
] | null | null | null |
#pragma once
#include "pch.hpp"
#include "types.hpp"
#include "scope.hpp"
#if defined(NDEBUG)
#define ND_ASSERT_NOTHROW (true)
#else
#define ND_ASSERT_NOTHROW (false)
#endif
#define ND_DECLARE_BUILDER_FIELD(field) decltype(Type::field) field
#define ND_DEFINE_BUILDER_SET(field) \
Builder& set(const decltype(Type::field)& cfg) noexcept \
{ \
field = cfg; \
return *this; \
}
#define ND_DEFINE_BUILDER_OPERATOR(field) \
Builder& operator<<(const decltype(Type::field)& cfg) noexcept \
{ \
return set(cfg); \
}
namespace nd::src::tools
{
f64
getDt(const f64 min) noexcept;
} // namespace nd::src::tools
| 28.088235
| 68
| 0.464921
|
InspectorSolaris
|
937a04039a3c3b06f33d76e0bc6442a8980d670c
| 1,747
|
hpp
|
C++
|
include/Factory/Module/Decoder/RA/Decoder_RA.hpp
|
FredrikBlomgren/aff3ct
|
fa616bd923b2dcf03a4cf119cceca51cf810d483
|
[
"MIT"
] | 315
|
2016-06-21T13:32:14.000Z
|
2022-03-28T09:33:59.000Z
|
include/Factory/Module/Decoder/RA/Decoder_RA.hpp
|
a-panella/aff3ct
|
61509eb756ae3725b8a67c2d26a5af5ba95186fb
|
[
"MIT"
] | 153
|
2017-01-17T03:51:06.000Z
|
2022-03-24T15:39:26.000Z
|
include/Factory/Module/Decoder/RA/Decoder_RA.hpp
|
a-panella/aff3ct
|
61509eb756ae3725b8a67c2d26a5af5ba95186fb
|
[
"MIT"
] | 119
|
2017-01-04T14:31:58.000Z
|
2022-03-21T08:34:16.000Z
|
/*!
* \file
* \brief Class factory::Decoder_RA.
*/
#ifndef FACTORY_DECODER_RA_HPP
#define FACTORY_DECODER_RA_HPP
#include <vector>
#include <string>
#include <map>
#include <cli.hpp>
#include "Tools/Factory/Header.hpp"
#include "Tools/auto_cloned_unique_ptr.hpp"
#include "Module/Encoder/Encoder.hpp"
#include "Module/Decoder/Decoder_SIHO.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
namespace aff3ct
{
namespace factory
{
extern const std::string Decoder_RA_name;
extern const std::string Decoder_RA_prefix;
class Decoder_RA : public Decoder
{
public:
// ----------------------------------------------------------------------------------------------------- PARAMETERS
// optional parameters
int n_ite = 10;
// depending parameters
tools::auto_cloned_unique_ptr<Interleaver> itl;
// -------------------------------------------------------------------------------------------------------- METHODS
explicit Decoder_RA(const std::string &p = Decoder_RA_prefix);
virtual ~Decoder_RA() = default;
Decoder_RA* clone() const;
virtual std::vector<std::string> get_names () const;
virtual std::vector<std::string> get_short_names() const;
virtual std::vector<std::string> get_prefixes () const;
// parameters construction
void get_description(cli::Argument_map_info &args) const;
void store (const cli::Argument_map_value &vals);
void get_headers (std::map<std::string,tools::header_list>& headers, const bool full = true) const;
// builder
template <typename B = int, typename Q = float>
module::Decoder_SIHO<B,Q>* build(const module::Interleaver<Q> &itl, module::Encoder<B> *encoder = nullptr) const;
};
}
}
#endif /* FACTORY_DECODER_RA_HPP */
| 30.12069
| 116
| 0.655982
|
FredrikBlomgren
|
937b13734bffb857defc4114a0f1bbee1512662c
| 3,197
|
cpp
|
C++
|
Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp
|
calidrelle/Gamecodeur
|
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
|
[
"CC0-1.0"
] | 29
|
2016-05-04T08:22:46.000Z
|
2022-01-27T10:20:55.000Z
|
Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp
|
calidrelle/Gamecodeur
|
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
|
[
"CC0-1.0"
] | 1
|
2018-11-25T14:12:39.000Z
|
2018-11-25T14:12:39.000Z
|
Sources Age of Enigma/Scene_Egypt_Mazeentry.cpp
|
calidrelle/Gamecodeur
|
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
|
[
"CC0-1.0"
] | 49
|
2016-04-29T19:43:42.000Z
|
2022-02-19T16:13:35.000Z
|
/*
* Scene_Egypt_Mazeentry.cpp
* enigma
*
* Created by MEKERSA David on 24/11/10.
* Copyright 2010 Casual Games France. All rights reserved.
*
*/
#include "EScene.h"
#include "Scene_Egypt_Mazeentry.h"
#include "ESceneDirector.h"
#include "GlobalBank.h"
/* Constructeur */
Scene_Egypt_Mazeentry::Scene_Egypt_Mazeentry(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector)
{
_lpBgGraphic = KPTK::createKGraphic ();
}
/* Destructeur */
Scene_Egypt_Mazeentry::~Scene_Egypt_Mazeentry()
{
delete _lpBgGraphic;
}
void Scene_Egypt_Mazeentry::Init()
{
SetupItem("egypt_symbol_god04h");
if (!TaskResolved("task_egypt_meetmummy")) {
AddHint("egypt","laby","how");
ResolveTask("task_egypt_meetmummy");
_lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_CINEMATIC, true);
_lpSceneDirector->getSequencer()->PlaySound(NULL,"ghostappear");
_lpSceneDirector->getSequencer()->ShowImage(NULL, "egypt_mummy", true);
int x,y;
GetObjectPosition("egypt_mummy", x, y, true, false);
_lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("EGYPT_MUMMY_RITUAL1"), "", false);
_lpSceneDirector->getSequencer()->Talk(NULL, x, y, KStr("EGYPT_MUMMY_RITUAL2"), "", false);
_lpSceneDirector->getSequencer()->ShowImage(NULL, "egypt_mummy", false);
_lpSceneDirector->getSequencer()->NarrationMode(NULL, SEQUENCE_NARRATION_CINEMATIC, false);
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("EGYPT_NEFERES_WHATHAP"), "", true, true);
AddObjective("egypt","laby");
}
// Porte du laby
if (!TaskResolved("task_egypt_openmaze")) {
SetVisible("egypt_mazedoor", true, true);
SetVisible("egypt_maze_zone",false);
}
else {
SetVisible("egypt_mazedoor", false, true);
SetVisible("egypt_maze_zone",true);
}
// Retour après s'être perdu dans le laby
if (getAdditionalName() == "lost") {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("EGYPT_NEFERES_LOST"), "", true, false);
}
}
void Scene_Egypt_Mazeentry::Check()
{
EScene::Check();
#ifdef SCENE_SHORTCUT
if (KInput::isPressed(K_VK_F5))
{
_lpSceneDirector->GoToScene("menu");
}
if (KInput::isPressed(K_VK_F6))
{
}
#endif
}
void Scene_Egypt_Mazeentry::Logic()
{
EScene::Logic();
}
void Scene_Egypt_Mazeentry::Draw()
{
EScene::Draw();
}
void Scene_Egypt_Mazeentry::Close()
{
}
bool Scene_Egypt_Mazeentry::ObjectClicked(const char *szObjectName, float x, float y)
{
if (strcmp(szObjectName, "egypt_symbol_god04h") == 0) {
PickupSimple(szObjectName, "inv_egypt_god04");
}
return false;
}
bool Scene_Egypt_Mazeentry::ObjectOver(char *szObjectName, float x, float y)
{
return false;
}
bool Scene_Egypt_Mazeentry::ItemUsed(const char *szItemName, const char *szObjectName)
{
return false;
}
void Scene_Egypt_Mazeentry::MiniGameDone(const char *szGameName, bool bIsRevolved)
{
if (!bIsRevolved) {
_lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("MIDDLEAGE_MONK_GATHERFAILED"), "", true, false);
return;
}
}
| 27.324786
| 137
| 0.699093
|
calidrelle
|
938936970416a05ff2ebb471131e86bcf9a0b165
| 14
|
cpp
|
C++
|
src/test.cpp
|
xpack/xpm-develop-test-xpack
|
c8f60e64324f751d3848dad12f4add838fa9da8c
|
[
"MIT"
] | null | null | null |
src/test.cpp
|
xpack/xpm-develop-test-xpack
|
c8f60e64324f751d3848dad12f4add838fa9da8c
|
[
"MIT"
] | null | null | null |
src/test.cpp
|
xpack/xpm-develop-test-xpack
|
c8f60e64324f751d3848dad12f4add838fa9da8c
|
[
"MIT"
] | null | null | null |
// Test file.
| 7
| 13
| 0.571429
|
xpack
|
93896c5f265e702f4c7628ca39b30322980dde21
| 452
|
cxx
|
C++
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx
|
TeoZosa/ITK
|
bc989624d640b30ee047634eda6acfc4cdd3f39b
|
[
"Apache-2.0"
] | 1
|
2019-12-10T21:26:08.000Z
|
2019-12-10T21:26:08.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx
|
TeoZosa/ITK
|
bc989624d640b30ee047634eda6acfc4cdd3f39b
|
[
"Apache-2.0"
] | null | null | null |
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+uint.allsizes-.cxx
|
TeoZosa/ITK
|
bc989624d640b30ee047634eda6acfc4cdd3f39b
|
[
"Apache-2.0"
] | null | null | null |
#include "vnl/vnl_vector_fixed.hxx"
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,2);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,3);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,4);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,5);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,6);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,7);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,8);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,9);
VNL_VECTOR_FIXED_INSTANTIATE(unsigned int,10);
| 37.666667
| 46
| 0.862832
|
TeoZosa
|
938cf719dbd42d5ca3727e460f1042314873a7bb
| 3,075
|
cpp
|
C++
|
codes/tool/Project.cpp
|
liangpengcheng/tng
|
01c6517f734d5db01f7d59bf95b225f6d1642b6e
|
[
"BSD-3-Clause"
] | 3
|
2016-04-16T06:24:20.000Z
|
2018-09-29T13:36:51.000Z
|
codes/tool/Project.cpp
|
liangpengcheng/tng
|
01c6517f734d5db01f7d59bf95b225f6d1642b6e
|
[
"BSD-3-Clause"
] | null | null | null |
codes/tool/Project.cpp
|
liangpengcheng/tng
|
01c6517f734d5db01f7d59bf95b225f6d1642b6e
|
[
"BSD-3-Clause"
] | 3
|
2016-04-29T11:46:08.000Z
|
2019-09-16T03:27:30.000Z
|
#include "Project.h"
#include <QAction>
#include <QFileDialog>
#include "modelimport/port.h"
#include "core/binary_reader_writer.h"
namespace tng
{
void ProjectMain::Init()
{
tng::Log* log = new tng::ConsoleLog;
tng::Log::SetLog(log);
string exename, exepath, exeext;
Path::GetExePath().Split(exepath, exename, exeext);
Path::SetWorkPath(exepath);
//ResourceManger::GetInstance()->AddLoader(LocalFilesLoader);
graphics::InitGraphics();
GFXService* gfx = GFXService::CreateGraphics();
InitModelImpPlugin();
QUiLoader loader;
QFile file("../EditorAsset/MainWindow.ui");
file.open(QFile::ReadOnly);
main_frame_ = loader.load(&file);
file.close();
if (main_frame_)
{
main_frame_->setWindowFlags(Qt::SubWindow);
}
setCentralWidget(main_frame_);
QAction* loadbtn = main_frame_->findChild<QAction*>("actionLoad");
connect(loadbtn, SIGNAL(triggered()), this, SLOT(OnLoad()));
QAction* expbtn = main_frame_->findChild<QAction*>("actionExport");
connect(expbtn, SIGNAL(triggered()), this, SLOT(OnExport()));
resize(1024, 768);
}
void ProjectMain::OnLoad()
{
QFileDialog dialog;
dialog.setFileMode(QFileDialog::DirectoryOnly);
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
dialog.setOption(QFileDialog::DontResolveSymlinks);
dialog.setViewMode(QFileDialog::Detail);
int res = dialog.exec();
if (res)
{
QDir directory = dialog.selectedFiles()[0];
LoadProject(directory.absolutePath().toUtf8().data());
}
}
void ProjectMain::OnExport()
{
QFileDialog dialog;
dialog.setFileMode(QFileDialog::DirectoryOnly);
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
dialog.setOption(QFileDialog::DontResolveSymlinks);
dialog.setViewMode(QFileDialog::Detail);
int res = dialog.exec();
if (res)
{
QDir directory = dialog.selectedFiles()[0];
Export(directory.absolutePath().toUtf8().data());
}
}
void ProjectMain::LoadProject(const string& path)
{
runing_path_ = path;
}
void ProjectMain::Export(const string& path)
{
vector<Path> retPath;
FileSystem::FindFiles(runing_path_, retPath, FileSystem::FFile, true);
StreamLoader* loader = ResourceManger::GetInstance()->GetLoader(LocalFilesLoader);
if (loader)
{
for each (Path var in retPath)
{
string fn, ext, dir;
var.Split(dir, fn, ext);
ToLower(ext);
if (ext == "res")
{
continue;
}
Path relativePath = Path(dir).RelativePath(runing_path_);
//use resource processor process every file,if no processor exist just copy to export dir
std::istream* content = loader->Load(var);
ResDecoder* decoder = ResourceManger::GetInstance()->GetDecoder(ext);
if (content)
{
string ext_e = decoder != NULL ? decoder->ResType() : ext;
if (ext_e == "res")
{
continue;
}
string pathexp = path + "/" + string(relativePath);
FileSystem::CreateDirs(pathexp);
FileOutputStream fs(pathexp + fn + "." + ext_e);
content->seekg(0, std::ios::beg);
fs << content->rdbuf();
fs.flush();
}
}
}
}
}
| 25.204918
| 93
| 0.682602
|
liangpengcheng
|
938d563efe409da780ef3115ba532f41ac67a326
| 1,136
|
cpp
|
C++
|
liberty/support/specpriv-profile/escape.cpp
|
righier/cpf
|
0a9d7c2cde6676be519c490d98197eb5283520b4
|
[
"MIT"
] | 18
|
2020-08-14T21:19:59.000Z
|
2022-02-22T12:43:52.000Z
|
liberty/support/specpriv-profile/escape.cpp
|
righier/cpf
|
0a9d7c2cde6676be519c490d98197eb5283520b4
|
[
"MIT"
] | 23
|
2020-08-17T21:04:36.000Z
|
2022-03-02T19:29:27.000Z
|
liberty/support/specpriv-profile/escape.cpp
|
righier/cpf
|
0a9d7c2cde6676be519c490d98197eb5283520b4
|
[
"MIT"
] | 2
|
2020-09-17T17:25:19.000Z
|
2021-05-21T11:21:43.000Z
|
#include "escape.h"
void EscapeTable::report_escape(const AUHolder &au, const CtxHolder &ctx)
{
Escape key(au,ctx);
++escapeFrequencies[key];
}
void EscapeTable::report_local(const AUHolder &au, const CtxHolder &ctx)
{
for(CtxHolder cc=ctx; !cc.is_null(); cc=cc->parent)
{
Escape key(au,cc);
++localFrequencies[key];
}
}
void EscapeTable::print(std::ostream &fout) const
{
for(EscapeMap::const_iterator i=escapeFrequencies.begin(), e=escapeFrequencies.end(); i!=e; ++i)
{
AUHolder au = i->first.first;
CtxHolder ctx = i->first.second;
unsigned count = i->second;
fout << "ESCAPE OBJECT " << au << " ESCAPES " << ctx << " COUNT " << count << " ;\n";
}
for(EscapeMap::const_iterator i=localFrequencies.begin(), e=localFrequencies.end(); i!=e; ++i)
{
Escape key = i->first;
if( escapeFrequencies.count(key) )
continue;
unsigned count = i->second;
fout << "LOCAL OBJECT " << key.first << " IS LOCAL TO " << key.second << " COUNT " << count << " ;\n";
}
}
std::ostream &operator<<(std::ostream &fout, const EscapeTable &et)
{
et.print(fout);
return fout;
}
| 22.72
| 106
| 0.629401
|
righier
|
938ed5ee46e822eb997eee1f0ece1885b921cc16
| 9,515
|
cpp
|
C++
|
src/filesiconv/IconvWorker.cpp
|
hufuman/filesiconv
|
1443469db1a37571c984b64027f8936c87dc3e3d
|
[
"MIT"
] | 2
|
2015-07-01T01:24:15.000Z
|
2017-07-13T14:54:29.000Z
|
src/filesiconv/IconvWorker.cpp
|
hufuman/filesiconv
|
1443469db1a37571c984b64027f8936c87dc3e3d
|
[
"MIT"
] | null | null | null |
src/filesiconv/IconvWorker.cpp
|
hufuman/filesiconv
|
1443469db1a37571c984b64027f8936c87dc3e3d
|
[
"MIT"
] | 3
|
2015-02-08T15:24:43.000Z
|
2018-03-08T05:18:05.000Z
|
#include "StdAfx.h"
#include "IconvWorker.h"
#include "FileMap.h"
#include <cassert>
#include <Shlwapi.h>
BYTE g_byUtf8BOM[] = {0xEF, 0xBB, 0xBF};
BYTE g_byUnicodeBOM[] = {0xFF, 0xFE};
BOOL WriteFileHelper(HANDLE hFile, LPCVOID pBuffer, int nSize)
{
DWORD dwWritten = 0;
BOOL bResult = ::WriteFile(hFile, pBuffer, nSize, &dwWritten, NULL);
if(!bResult)
bResult = bResult;
bResult = bResult && (dwWritten == nSize);
if(!bResult)
bResult = bResult;
return bResult;
}
CIconvWorker::CIconvWorker(void)
{
m_arrFiles = NULL;
m_bStop = FALSE;
m_strTargetPath = _T("");
m_bOverwrite = FALSE;
m_bWriteBom = TRUE;
m_nSrcCodepage = CodeAuto;
m_nDstCodepage = CodeAuto;
m_pBuffer = NULL;
m_nBufferSize = 0;
}
CIconvWorker::~CIconvWorker(void)
{
ReleaseBuffer();
}
void CIconvWorker::SetCodepage(CodePageValue nSrcCodepage, CodePageValue nDstCodepage)
{
m_nSrcCodepage = nSrcCodepage;
m_nDstCodepage = nDstCodepage;
}
void CIconvWorker::SetFiles(ATL::CSimpleArray<CString>* arrFiles)
{
m_arrFiles = arrFiles;
}
void CIconvWorker::SetOverwrite(BOOL bOverwrite)
{
m_bOverwrite = bOverwrite;
}
void CIconvWorker::SetWriteBom(BOOL bWriteBom)
{
m_bWriteBom = bWriteBom;
}
void CIconvWorker::SetTargetPath(LPCTSTR szTargetPath)
{
m_strTargetPath = szTargetPath;
m_strTargetPath.Replace(_T('/'), _T('\\'));
if(m_strTargetPath.GetLength() > 0
&& m_strTargetPath[m_strTargetPath.GetLength() - 1] != _T('\\'))
{
m_strTargetPath += _T('\\');
}
}
BOOL CIconvWorker::Convert(ATL::CSimpleArray<CString>* failedFiles, ATL::CSimpleArray<CString>* outFiles)
{
m_bStop = FALSE;
if(failedFiles)
failedFiles->RemoveAll();
if(outFiles)
outFiles->RemoveAll();
CString strSrcTemp = GetTempFilePath();
int nCount = m_arrFiles->GetSize();
for(int i=0; !m_bStop && i<nCount; ++ i)
{
CString strSrc = (*m_arrFiles)[i];
// Get File Data
CFileMap m;
if(!m.MapFile(strSrc))
{
if(failedFiles)
failedFiles->Add(strSrc);
continue;
}
const BYTE * pData = static_cast<const BYTE *>(m.GetData());
int nSize = m.GetSize();
CodePageValue nSrcCodepage = m_nSrcCodepage;
if(nSrcCodepage == CodeAuto)
nSrcCodepage = GetFileCodepage(pData, nSize);
else
GetFileCodepage(pData, nSize);
CString strDstPath;
CodePageValue nDstCodepage = m_nDstCodepage;
if(nSrcCodepage == nDstCodepage)
{
m.Close();
if(!m_bOverwrite)
{
// Copy to dst
strDstPath = GetDstPath(strSrc);
if(CopyFile(strSrc, strDstPath, FALSE))
{
if(outFiles)
outFiles->Add(strSrc);
}
else
{
if(failedFiles)
failedFiles->Add(strSrc);
}
}
continue;
}
for(;;)
{
BOOL bResult = FALSE;
if((nSrcCodepage == CodeUnicode && nDstCodepage != CodeUnicode)
|| (nSrcCodepage != CodeUnicode && nDstCodepage == CodeUnicode))
{
if(!ConvFile(pData, nSize, strSrcTemp, nSrcCodepage, nDstCodepage))
break;
// Copy to dst
strDstPath = GetDstPath(strSrc);
m.Close();
if(!CopyFile(strSrcTemp, strDstPath, FALSE))
break;
if(outFiles)
outFiles->Add(strDstPath);
bResult = TRUE;
}
else
{
// nSrcCodepage != CodeUnicode && nDstCodepage != CodeUnicode
// Convert to unicode first
if(!ConvFile(pData, nSize, strSrcTemp, nSrcCodepage, CodeUnicode))
break;
m.Close();
// Convert to dst codepage
CString strDstTemp = GetTempFilePath();
CFileMap mTemp;
if(!mTemp.MapFile(strSrcTemp))
break;
pData = static_cast<const BYTE *>(mTemp.GetData());
nSize = mTemp.GetSize();
GetFileCodepage(pData, nSize);
if(!ConvFile(pData, nSize, strDstTemp, CodeUnicode, nDstCodepage))
break;
strDstPath = GetDstPath(strSrc);
mTemp.Close();
if(!CopyFile(strDstTemp, strDstPath, FALSE))
break;
if(outFiles)
outFiles->Add(strDstPath);
bResult = TRUE;
}
if(!bResult)
failedFiles->Add(strSrc);
break;
}
}
return (failedFiles->GetSize() == 0);
}
void CIconvWorker::Stop()
{
m_bStop = TRUE;
}
CString CIconvWorker::GetDstPath(LPCTSTR szSrcPath)
{
if(m_bOverwrite)
return szSrcPath;
LPCTSTR szFileName = ::PathFindFileName(szSrcPath);
CString strResult = m_strTargetPath + szFileName;
return strResult;
}
CodePageValue CIconvWorker::GetFileCodepage(const BYTE *& pData, int& nSize)
{
if(nSize >= 3 && memcmp(g_byUtf8BOM, pData, 3) == 0)
{
pData += 3;
nSize -= 3;
return CodeUtf8;
}
else if(nSize >= 2 && memcmp(g_byUnicodeBOM, pData, 2) == 0)
{
pData += 2;
nSize -= 2;
return CodeUnicode;
}
else
{
return CodeAnsi;
}
}
CString CIconvWorker::GetTempFilePath()
{
TCHAR szTmpPath[MAX_PATH];
TCHAR szTmpFile[MAX_PATH];
::GetTempPath(MAX_PATH, szTmpPath);
::GetTempFileName(szTmpPath, _T("iconv"), rand(), szTmpFile);
return szTmpFile;
}
BOOL CIconvWorker::ConvFile(const BYTE * pData, int nSize, LPCTSTR szDstPath, CodePageValue nSrcCodepage, CodePageValue nDstCodepage)
{
BOOL bMultiByteToWideChar = FALSE;
DWORD dwCodepage = GetRealCodepage(nSrcCodepage, nDstCodepage, bMultiByteToWideChar);
if(dwCodepage == -1)
return FALSE;
LPBYTE pBuffer = NULL;
int nBufferSize = 0;
if(bMultiByteToWideChar)
{
nBufferSize = ::MultiByteToWideChar(dwCodepage,
0,
(LPCSTR)pData,
nSize,
NULL,
0);
if(nBufferSize <= 0)
return (nSize == 0);
pBuffer = GetBuffer(nBufferSize * 2 + 2);
if(pBuffer == NULL)
return FALSE;
nBufferSize = ::MultiByteToWideChar(dwCodepage,
0,
(LPCSTR)pData,
nSize,
(LPWSTR)pBuffer,
nBufferSize);
if(nBufferSize == 0)
{
return FALSE;
}
nBufferSize = nBufferSize * 2;
}
else
{
nBufferSize = ::WideCharToMultiByte(dwCodepage,
0,
(LPCTSTR)pData,
nSize / 2,
0,
0,
0,
0);
if(nBufferSize == 0)
return (nSize == 0);
pBuffer = GetBuffer(nBufferSize + 1);
if(::WideCharToMultiByte(dwCodepage,
0,
(LPCTSTR)pData,
nSize / 2,
(LPSTR)pBuffer,
nBufferSize,
0,
0) == 0)
{
return FALSE;
}
}
HANDLE hFile = ::CreateFile(szDstPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if(hFile == INVALID_HANDLE_VALUE)
return FALSE;
BOOL bResult = TRUE;
// Write BOM
if(m_bWriteBom)
{
if(nDstCodepage == CodeUnicode)
{
bResult = WriteFileHelper(hFile, g_byUnicodeBOM, sizeof(g_byUnicodeBOM));
}
else if(nDstCodepage == CodeUtf8)
{
bResult = WriteFileHelper(hFile, g_byUtf8BOM, sizeof(g_byUtf8BOM));
}
}
if(bResult)
{
// Write Content
SetLastError(0);
bResult = WriteFileHelper(hFile, pBuffer, nBufferSize);
if(!bResult)
{
bResult = bResult;
}
}
else
{
bResult = bResult;
}
::CloseHandle(hFile);
return bResult;
}
DWORD CIconvWorker::GetRealCodepage(CodePageValue nSrcCodepage, CodePageValue nDstCodepage, BOOL& bMultiByteToWideChar)
{
DWORD dwCodepage = -1;
assert(nSrcCodepage == CodeUnicode || nDstCodepage == CodeUnicode);
bMultiByteToWideChar = (nDstCodepage == CodeUnicode);
struct
{
CodePageValue codepage;
DWORD dwCodepage;
} data[] =
{
{CodeAnsi, CP_ACP},
{CodeUnicode, CP_ACP},
{CodeUtf8, CP_UTF8},
{CodeChinese, 936},
};
CodePageValue codepage = (nSrcCodepage == CodeUnicode) ? nDstCodepage : nSrcCodepage;
for(int i=0; i<_countof(data); ++ i)
{
if(codepage == data[i].codepage)
dwCodepage = data[i].dwCodepage;
}
return dwCodepage;
}
LPBYTE CIconvWorker::GetBuffer(int nSize)
{
if(nSize <= m_nBufferSize)
return m_pBuffer;
ReleaseBuffer();
m_pBuffer = static_cast<LPBYTE>(malloc(nSize));
if(m_pBuffer)
m_nBufferSize = nSize;
return m_pBuffer;
}
void CIconvWorker::ReleaseBuffer()
{
if(m_pBuffer)
{
free(m_pBuffer);
m_pBuffer = NULL;
m_nBufferSize = 0;
}
}
| 24.714286
| 133
| 0.548292
|
hufuman
|
9390d396b3f0a13d8508cb8226a5b36d5ac6bff4
| 3,493
|
hpp
|
C++
|
Source/boost/scoped_ptr.hpp
|
Negrutiu/nsis
|
14eed5608d44e998309892fe8226aeb5252b9ab9
|
[
"BSD-3-Clause"
] | 19
|
2018-09-21T09:44:42.000Z
|
2022-03-26T03:37:02.000Z
|
Source/boost/scoped_ptr.hpp
|
Negrutiu/nsis
|
14eed5608d44e998309892fe8226aeb5252b9ab9
|
[
"BSD-3-Clause"
] | 3
|
2019-07-19T08:58:50.000Z
|
2021-02-03T19:42:00.000Z
|
Source/boost/scoped_ptr.hpp
|
Negrutiu/nsis
|
14eed5608d44e998309892fe8226aeb5252b9ab9
|
[
"BSD-3-Clause"
] | 1
|
2021-08-23T02:44:27.000Z
|
2021-08-23T02:44:27.000Z
|
#ifndef BOOST_SCOPED_PTR_HPP_INCLUDED
#define BOOST_SCOPED_PTR_HPP_INCLUDED
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001, 2002 Peter Dimov
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// http://www.boost.org/libs/smart_ptr/scoped_ptr.htm
//
// From Boost 1.31.0, http://www.boost.org
// Modified by Ori Peleg for use in NSIS, to reduce the required Boost includes
#include <cassert>
#include "checked_delete.hpp"
#include "detail/workaround.hpp"
#include <memory> // for std::auto_ptr or std::unique_ptr
// std::auto_ptr was deprecated in C++11 and removed in C++17
namespace NSIS { namespace CXX {
#if __cplusplus >= 201103L
template<class T> struct stdsmartptr { typedef std::unique_ptr<T> type; };
#else
template<class T> struct stdsmartptr { typedef std::auto_ptr<T> type; };
#endif
}} //~ NSIS::CXX
namespace boost
{
// scoped_ptr mimics a built-in pointer except that it guarantees deletion
// of the object pointed to, either on destruction of the scoped_ptr or via
// an explicit reset(). scoped_ptr is a simple solution for simple needs;
// use shared_ptr or std::auto_ptr if your needs are more complex.
template<class T> class scoped_ptr // noncopyable
{
private:
T * ptr;
scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &);
typedef scoped_ptr<T> this_type;
public:
typedef T element_type;
explicit scoped_ptr(T * p = 0): ptr(p) // never throws
{
}
explicit scoped_ptr(typename NSIS::CXX::stdsmartptr<T>::type p): ptr(p.release()) // never throws
{
}
~scoped_ptr() // never throws
{
boost::checked_delete(ptr);
}
void reset(T * p = 0) // never throws
{
assert(p == 0 || p != ptr); // catch self-reset errors
this_type(p).swap(*this);
}
T & operator*() const // never throws
{
assert(ptr != 0);
return *ptr;
}
T * operator->() const // never throws
{
assert(ptr != 0);
return ptr;
}
T * get() const // never throws
{
return ptr;
}
// implicit conversion to "bool"
#if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const
{
return ptr != 0;
}
#elif defined(__MWERKS__) && BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws
{
return ptr == 0? 0: &this_type::get;
}
#else
typedef T * this_type::*unspecified_bool_type;
operator unspecified_bool_type() const // never throws
{
return ptr == 0? 0: &this_type::ptr;
}
#endif
bool operator! () const // never throws
{
return ptr == 0;
}
void swap(scoped_ptr & b) // never throws
{
T * tmp = b.ptr;
b.ptr = ptr;
ptr = tmp;
}
};
template<class T> inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) // never throws
{
a.swap(b);
}
// get_pointer(p) is a generic way to say p.get()
template<class T> inline T * get_pointer(scoped_ptr<T> const & p)
{
return p.get();
}
} // namespace boost
#endif // #ifndef BOOST_SCOPED_PTR_HPP_INCLUDED
| 23.761905
| 101
| 0.643287
|
Negrutiu
|
9394c96f6fac255fc668b2770bcecf5f8b8a67a6
| 1,016
|
cpp
|
C++
|
src/QtFTP/FTP/nBonjourRecord.cpp
|
Vladimir-Lin/QtFTP
|
a297ac9cd3dd44407a39adcd87953fb4d2d90f1f
|
[
"MIT"
] | null | null | null |
src/QtFTP/FTP/nBonjourRecord.cpp
|
Vladimir-Lin/QtFTP
|
a297ac9cd3dd44407a39adcd87953fb4d2d90f1f
|
[
"MIT"
] | null | null | null |
src/QtFTP/FTP/nBonjourRecord.cpp
|
Vladimir-Lin/QtFTP
|
a297ac9cd3dd44407a39adcd87953fb4d2d90f1f
|
[
"MIT"
] | null | null | null |
#include <qtftp.h>
N::BonjourRecord:: BonjourRecord(void)
{
}
N::BonjourRecord:: BonjourRecord (
const QString & name ,
const QString & regType ,
const QString & domain )
: serviceName ( name )
, registeredType ( regType )
, replyDomain ( domain )
{
}
N::BonjourRecord:: BonjourRecord (
const char * name ,
const char * regType ,
const char * domain )
{
serviceName = QString :: fromUtf8 ( name ) ;
registeredType = QString :: fromUtf8 ( regType ) ;
replyDomain = QString :: fromUtf8 ( domain ) ;
}
N::BonjourRecord::~BonjourRecord(void)
{
}
bool N::BonjourRecord::operator == (const BonjourRecord & other) const
{
return ( serviceName == other.serviceName &&
registeredType == other.registeredType &&
replyDomain == other.replyDomain ) ;
}
| 27.459459
| 70
| 0.515748
|
Vladimir-Lin
|
93966166dcfeeb1355a91268734307e26950ffea
| 11,525
|
cpp
|
C++
|
src/clp/FileCompressor.cpp
|
NITROGENousFish/clp-core
|
2dcc58aae66a97fca43a139a4ff637005c0f9065
|
[
"Apache-2.0"
] | null | null | null |
src/clp/FileCompressor.cpp
|
NITROGENousFish/clp-core
|
2dcc58aae66a97fca43a139a4ff637005c0f9065
|
[
"Apache-2.0"
] | null | null | null |
src/clp/FileCompressor.cpp
|
NITROGENousFish/clp-core
|
2dcc58aae66a97fca43a139a4ff637005c0f9065
|
[
"Apache-2.0"
] | null | null | null |
#include "FileCompressor.hpp"
// C++ standard libraries
#include <algorithm>
#include <iostream>
#include <set>
// Boost libraries
#include <boost/filesystem/path.hpp>
// libarchive
#include <archive_entry.h>
// Project headers
#include "utils.hpp"
using std::cout;
using std::endl;
using std::set;
using std::string;
using std::vector;
// Local prototypes
/**
* Computes empty directories as directories - parent_directories and adds them to the given archive
* @param directories
* @param parent_directories
* @param parent_path Path that should be the parent of all added directories
* @param archive
*/
static void compute_and_add_empty_directories (const set<string>& directories, const set<string>& parent_directories,
const boost::filesystem::path& parent_path, streaming_archive::writer::Archive& archive);
/**
* Writes the given message to the given encoded file
* @param msg
* @param archive
* @param file
*/
static void write_message_to_encoded_file (const ParsedMessage& msg, streaming_archive::writer::Archive& archive, streaming_archive::writer::File* file);
static void compute_and_add_empty_directories (const set<string>& directories, const set<string>& parent_directories,
const boost::filesystem::path& parent_path, streaming_archive::writer::Archive& archive)
{
// Determine empty directories by subtracting parent directories
vector<string> empty_directories;
auto directories_ix = directories.cbegin();
for (auto parent_directories_ix = parent_directories.cbegin();
directories.cend() != directories_ix && parent_directories.cend() != parent_directories_ix;)
{
const auto& directory = *directories_ix;
const auto& parent_directory = *parent_directories_ix;
if (directory < parent_directory) {
auto boost_path_for_compression = parent_path / directory;
empty_directories.emplace_back(boost_path_for_compression.string());
++directories_ix;
} else if (directory == parent_directory) {
++directories_ix;
++parent_directories_ix;
} else {
++parent_directories_ix;
}
}
for (; directories.cend() != directories_ix; ++directories_ix) {
auto boost_path_for_compression = parent_path / *directories_ix;
empty_directories.emplace_back(boost_path_for_compression.string());
}
archive.add_empty_directories(empty_directories);
}
static void write_message_to_encoded_file (const ParsedMessage& msg, streaming_archive::writer::Archive& archive, streaming_archive::writer::File* file) {
if (msg.has_ts_patt_changed()) {
archive.change_ts_pattern(*file, msg.get_ts_patt());
}
archive.write_msg(*file, msg.get_ts(), msg.get_content(), msg.get_orig_num_bytes());
}
namespace clp {
bool FileCompressor::compress_file (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const FileToCompress& file_to_compress,
streaming_archive::writer::Archive& archive_writer)
{
m_file_reader.open(file_to_compress.get_path());
// Check that file is UTF-8 encoded
auto error_code = m_file_reader.try_read(m_utf8_validation_buf, cUtf8ValidationBufCapacity, m_utf8_validation_buf_length);
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile != error_code) {
SPDLOG_ERROR("Failed to read {}, errno={}", file_to_compress.get_path().c_str(), errno);
return false;
}
}
bool succeeded = true;
if (is_utf8_sequence(m_utf8_validation_buf_length, m_utf8_validation_buf)) {
parse_and_encode(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
file_to_compress.get_path_for_compression(), file_to_compress.get_group_id(), archive_writer, m_file_reader);
} else {
if (false == try_compressing_as_archive(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
file_to_compress, archive_writer))
{
succeeded = false;
}
}
m_file_reader.close();
return succeeded;
}
void FileCompressor::parse_and_encode (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const string& path_for_compression, group_id_t group_id,
streaming_archive::writer::Archive& archive_writer, ReaderInterface& reader)
{
m_parsed_message.clear();
// Open compressed file
auto* file = create_and_open_in_memory_file(archive_writer, path_for_compression, group_id, m_uuid_generator(), 0);
// Parse content from UTF-8 validation buffer
size_t buf_pos = 0;
while (m_message_parser.parse_next_message(false, m_utf8_validation_buf_length, m_utf8_validation_buf, buf_pos, m_parsed_message)) {
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_file_and_archive(archive_user_config, print_archive_ids, path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer,
file);
} else if (file->get_encoded_size_in_bytes() >= target_encoded_file_size) {
split_file(path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer, file);
}
write_message_to_encoded_file(m_parsed_message, archive_writer, file);
}
// Parse remaining content from file
while (m_message_parser.parse_next_message(true, reader, m_parsed_message)) {
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_file_and_archive(archive_user_config, print_archive_ids, path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer,
file);
} else if (file->get_encoded_size_in_bytes() >= target_encoded_file_size) {
split_file(path_for_compression, group_id, m_parsed_message.get_ts_patt(), archive_writer, file);
}
write_message_to_encoded_file(m_parsed_message, archive_writer, file);
}
close_file_and_mark_ready_for_segment(archive_writer, file);
}
bool FileCompressor::try_compressing_as_archive (size_t target_data_size_of_dicts, streaming_archive::writer::Archive::UserConfig& archive_user_config,
bool print_archive_ids, size_t target_encoded_file_size, const FileToCompress& file_to_compress,
streaming_archive::writer::Archive& archive_writer)
{
auto file_boost_path = boost::filesystem::path(file_to_compress.get_path_for_compression());
auto parent_boost_path = file_boost_path.parent_path();
// Determine path without extension (used if file is a single compressed file, e.g., syslog.gz -> syslog)
std::string filename_if_compressed;
if (file_boost_path.has_stem()) {
filename_if_compressed = file_boost_path.stem().string();
} else {
filename_if_compressed = file_boost_path.filename().string();
}
// Check if it's an archive
auto error_code = m_libarchive_reader.try_open(m_utf8_validation_buf_length, m_utf8_validation_buf, m_file_reader, filename_if_compressed);
if (ErrorCode_Success != error_code) {
SPDLOG_ERROR("Cannot compress {} - not UTF-8 encoded.", file_to_compress.get_path().c_str());
return false;
}
// Compress each file and directory in the archive
bool succeeded = true;
set<string> directories;
set<string> parent_directories;
while (true) {
error_code = m_libarchive_reader.try_read_next_header();
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile == error_code) {
break;
}
SPDLOG_ERROR("Failed to read entry in {}.", file_to_compress.get_path().c_str());
succeeded = false;
break;
}
// Determine what type of file it is
auto file_type = m_libarchive_reader.get_entry_file_type();
if (AE_IFREG != file_type) {
if (AE_IFDIR == file_type) {
// Trim trailing slash
string directory_path(m_libarchive_reader.get_path());
directory_path.resize(directory_path.length() - 1);
directories.emplace(directory_path);
auto directory_parent_path = boost::filesystem::path(directory_path).parent_path().string();
if (false == directory_parent_path.empty()) {
parent_directories.emplace(directory_parent_path);
}
} // else ignore irregular files
continue;
}
auto file_parent_path = boost::filesystem::path(m_libarchive_reader.get_path()).parent_path().string();
if (false == file_parent_path.empty()) {
parent_directories.emplace(file_parent_path);
}
if (archive_writer.get_data_size_of_dictionaries() >= target_data_size_of_dicts) {
split_archive(archive_user_config, print_archive_ids, archive_writer);
}
m_libarchive_reader.open_file_reader(m_libarchive_file_reader);
// Check that file is UTF-8 encoded
error_code = m_libarchive_file_reader.try_read(m_utf8_validation_buf, cUtf8ValidationBufCapacity, m_utf8_validation_buf_length);
if (ErrorCode_Success != error_code) {
if (ErrorCode_EndOfFile != error_code) {
SPDLOG_ERROR("Failed to read {} from {}.", m_libarchive_reader.get_path(), file_to_compress.get_path().c_str());
m_libarchive_file_reader.close();
succeeded = false;
continue;
}
}
if (is_utf8_sequence(m_utf8_validation_buf_length, m_utf8_validation_buf)) {
auto boost_path_for_compression = parent_boost_path / m_libarchive_reader.get_path();
parse_and_encode(target_data_size_of_dicts, archive_user_config, print_archive_ids, target_encoded_file_size,
boost_path_for_compression.string(), file_to_compress.get_group_id(), archive_writer, m_libarchive_file_reader);
} else {
SPDLOG_ERROR("Cannot compress {} - not UTF-8 encoded.", m_libarchive_reader.get_path());
succeeded = false;
}
m_libarchive_file_reader.close();
}
compute_and_add_empty_directories(directories, parent_directories, parent_boost_path, archive_writer);
m_libarchive_reader.close();
return succeeded;
}
}
| 47.427984
| 158
| 0.653189
|
NITROGENousFish
|
939766ed756a9cf44e433c592abc0ba7a57e6518
| 4,308
|
cpp
|
C++
|
mock-eye-module/main.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 52
|
2021-03-02T14:28:37.000Z
|
2022-02-07T20:27:52.000Z
|
mock-eye-module/main.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 29
|
2021-03-03T09:36:33.000Z
|
2022-03-12T00:59:10.000Z
|
mock-eye-module/main.cpp
|
hogaku/azure-percept-advanced-development
|
90177b9f1ec96dee1e7c436af5471007c4092655
|
[
"MIT"
] | 30
|
2021-03-02T14:09:14.000Z
|
2022-03-11T05:58:54.000Z
|
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*
* Use this application as a test bed for adding new AI models to the Azure Percept DK azureeyemodule.
* This application is small and easy to extend, so can be used for debugging and proving that a model
* works before porting it to the Azure Percept DK.
*/
// Standard Library includes
#include <fstream>
#include <iostream>
#include <signal.h>
#include <string>
#include <vector>
// Local includes
#include "kernels/utils.hpp"
#include "modules/device.hpp"
#include "modules/objectdetection/object_detectors.hpp"
#include "modules/parser.hpp"
/** Arguments for this program (short-arg long-arg | default-value | help message) */
static const std::string keys =
"{ h help | | Print this message }"
"{ d device | CPU | Device to run inference on. Options: CPU, GPU, NCS2 }"
"{ p parser | ssd | Parser kind required for input model. Possible values: ssd }"
"{ w weights | | Weights file }"
"{ x xml | | Network XML file }"
"{ labels | | Path to the labels file }"
"{ show | false | Show output BGR image. Requires graphical environment }"
"{ video_in | | If given, we use this file as input instead of the camera }";
/**
* This is just a helper function for loading a label file.
*
* @param labelfile The path to the label file. Should be a file that contains one label per line.
* @returns The class list from the file.
*/
static std::vector<std::string> load_label(const std::string &labelfile)
{
std::vector<std::string> classes;
std::ifstream file(labelfile);
if (file.is_open())
{
std::string line;
while (std::getline(file, line))
{
// remove \r in the end of line
if (!line.empty() && line[line.size() - 1] == '\r')
{
line.erase(line.size() - 1);
}
classes.push_back(line);
}
file.close();
}
else
{
std::cerr << "Cannot open labelfile " << labelfile << std::endl;
std::cerr << "Labels will not be available." << std::endl;
}
return classes;
}
/** If we receive a SIGINT, we print a message and try to exit cleanly. */
static void interrupt(int)
{
std::cout << "Received interrupt signal." << std::endl;
exit(0);
}
/**
* Here's the main function.
* To add a new AI model, all you need to do is add a corresponding "parser",
* which is the code that is used to load the neural network and post-process its outputs.
*
* 1. Start by adding an enum variant to the parser enum in modules/parser.[c/h]pp.
* 2. Then add a new module into modules/. If you are adding an object detector, you can make use
* of some of the code in modules/object_detectors.[c/h]pp.
*/
int main(int argc, char* argv[])
{
// Parse the command line args
cv::CommandLineParser cmd(argc, argv, keys);
if (cmd.has("help"))
{
cmd.printMessage();
return 0;
}
// Assign application parameters
const auto dev = device::look_up_device(cmd.get<std::string>("device"));
const auto parser = parser::look_up_parser(cmd.get<std::string>("parser"));
const auto weights = cmd.get<std::string>("weights");
const auto xml = cmd.get<std::string>("xml");
const auto labelfile = cmd.get<std::string>("labels");
const auto show = cmd.get<bool>("show");
const auto video_in = cmd.get<std::string>("video_in");
// Set up SIGINT handler - we peform cleanup and exit the application
signal(SIGINT, interrupt);
// Choose the appropriate path based on the parser we've chosen (which indicates which model we are running)
// If you are extending this application, add a new case with your parser here. Take a look at one of the other
// compile_and_run() functions to use as an example.
std::vector<std::string> classes;
switch (parser)
{
case parser::Parser::SSD:
classes = load_label(labelfile);
detection::compile_and_run(video_in, parser, xml, weights, dev, show, classes);
break;
default:
std::cerr << "Programmer error: Please implement the appropriate logic for this Parser." << std::endl;
exit(__LINE__);
}
return 0;
}
| 35.02439
| 115
| 0.639044
|
hogaku
|
9397a1566ba2f8b4d802fe9b27344fc1e0dac58f
| 1,323
|
cpp
|
C++
|
shared_mutex.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | null | null | null |
shared_mutex.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | null | null | null |
shared_mutex.cpp
|
opensvn/boost_learning
|
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
|
[
"BSL-1.0"
] | 1
|
2021-10-01T04:27:44.000Z
|
2021-10-01T04:27:44.000Z
|
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
boost::mutex io_mu;
class rw_data
{
private:
int m_x;
boost::shared_mutex rw_mu;
public:
rw_data() : m_x(0)
{ }
void write()
{
boost::unique_lock<boost::shared_mutex> ul(rw_mu);
++m_x;
}
void read(int *x)
{
boost::shared_lock<boost::shared_mutex> sl(rw_mu);
*x = m_x;
}
int get_value()
{ return m_x; }
};
void writer(rw_data &d)
{
for (int i = 0; i < 20; ++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(10));
d.write();
boost::mutex::scoped_lock lock(io_mu);
cout << boost::this_thread::get_id() << " write " << d.get_value() << endl;
}
}
void reader(rw_data &d)
{
int x;
for (int i = 0; i < 10; ++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(5));
d.read(&x);
boost::mutex::scoped_lock lock(io_mu);
cout << boost::this_thread::get_id() << " reader: " << x << endl;
}
}
int main()
{
rw_data d;
boost::thread_group pool;
for (int i = 0; i < 4; ++i)
pool.create_thread(bind(reader, boost::ref(d)));
for (int i = 0; i < 2; ++i)
pool.create_thread(bind(writer, boost::ref(d)));
pool.join_all();
return 0;
}
| 18.633803
| 83
| 0.543462
|
opensvn
|
939ac781007d93639b949611cab142451205015c
| 5,313
|
cpp
|
C++
|
libraries/PION/src/PION_Network.cpp
|
joaopedrovbs/arduino-support-test
|
1bea23f00040e386b44285f926b6871ba1bcd5fb
|
[
"MIT"
] | 17
|
2021-07-28T21:57:26.000Z
|
2022-02-28T20:32:04.000Z
|
libraries/PION/src/PION_Network.cpp
|
joaopedrovbs/arduino-support-test
|
1bea23f00040e386b44285f926b6871ba1bcd5fb
|
[
"MIT"
] | 7
|
2021-08-07T23:20:14.000Z
|
2022-03-20T15:05:21.000Z
|
libraries/PION/src/PION_Network.cpp
|
joaopedrovbs/arduino-support-test
|
1bea23f00040e386b44285f926b6871ba1bcd5fb
|
[
"MIT"
] | 10
|
2021-08-11T13:47:36.000Z
|
2022-03-26T02:41:45.000Z
|
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include "_config.h"
#include "_types.h"
#include "webpage.h"
#include "PION_System.h"
#include "PION_Network.h"
#include "PION_Sensors.h"
#include "PION_Storage.h"
#include "PION_Interface.h"
// External Objects
AsyncWebServer server(80);
char ssidId[32]; // Final ssid buffer
uint32_t chipId; // chipId Holder
String baseName = "PION Satélite "; // WiFi Base SSID to have the id string added
const char* password = "meusatpion"; // Default WiFi Password
TaskHandle_t Network::netTask;
void sendDataWs();
void NetworkTask(void *pvParameters);
void onEvent(AsyncWebSocket *, AsyncWebSocketClient *, AwsEventType , void *, uint8_t *, size_t );
AsyncWebSocket ws("/ws");
const char* sdStatusMessage[] = {"NO_SD","SD_CONNECTED","SD_RECORDING","SD_ERROR"};
const char* sirenMessage[] = {"ALARM_OFF","ALARM_SIREN","ALARM_ERROR","ALARM_LOW_BATTERY"};
__attribute__((weak)) void networkConnect(){
// Transforma o serial number do sistema em uma String
String id = String(System::getSerialNumber());
// Cria uma nova String com o nome PION Satélite + o serial
String ssid = baseName + id;
// Adapta a string para um array de caracteres
ssid.toCharArray(ssidId, sizeof(ssidId));
// Para qualquer aplicação bluetooth que possa existir
btStop();
// Inicializa um WiFi Access Point com um nome + serial e a senha padrão
WiFi.mode(WIFI_AP);
WiFi.softAP(ssidId, password);
WiFi.setHostname("PION Satelite");
}
__attribute__((weak)) void serverResponse(){
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
// Send File
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", DASH_HTML, DASH_HTML_SIZE);
response->addHeader("Content-Encoding","gzip");
request->send(response);
});
}
void Network::init(){
networkConnect();
serverResponse();
ws.onEvent(onEvent);
server.addHandler(&ws);
// Start Web Server
server.begin();
xTaskCreatePinnedToCore(NetworkTask, "NetworkTask", 8192, NULL, 1, &Network::netTask, ARDUINO_RUNNING_CORE);
}
void Network::deInit(){
vTaskSuspend(Network::netTask);
// server.reset();
server.end();
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void NetworkTask(void *pvParameters){
(void) pvParameters;
for (;;){
sendDataWs();
vTaskDelay(1000);
}
}
__attribute__((weak)) void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, "toggleRGB") == 0) {
Interface::shouldChangeRGB = true;
} else if (strcmp((char*)data, "toggleLED") == 0) {
Interface::shouldChangeLed = true;
} else if (strcmp((char*)data, "toggleSiren") == 0) {
Interface::toggleSiren();
} else if (strcmp((char*)data, "toggleSD1") == 0) {
Storage::toggleSD(0);
} else if (strcmp((char*)data, "toggleSD2") == 0) {
Storage::toggleSD(1);
} else if (strcmp((char*)data, "reboot") == 0) {
ESP.restart();
}
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket cliente #%u conectado do %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket cliente #%u desconectado\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
default:
break;
}
}
__attribute__((weak)) void sendDataWs() {
// Faz a alocação de 512 Bytes para o JSON
DynamicJsonDocument jsonBuffer(512);
// Adiciona todas as leituras necessárias com o formato chave:valor do JSON
jsonBuffer["bateria"] = System::battery;
jsonBuffer["pressao"] = Sensors::pressure;
jsonBuffer["temperatura"] = Sensors::temperature;
jsonBuffer["humidade"] = Sensors::humidity;
jsonBuffer["co2"] = Sensors::CO2Level;
jsonBuffer["luminosidade"] = Sensors::luminosity;
jsonBuffer["sdCard"] = sdStatusMessage[Storage::sdStatus];
jsonBuffer["siren"] = sirenMessage[Interface::sirenAction];
// Adiciona as leituras a um array dentro do JSON
JsonArray accel = jsonBuffer.createNestedArray("acelerometro");
accel.add(Sensors::accel[0]);
accel.add(Sensors::accel[1]);
accel.add(Sensors::accel[2]);
JsonArray gyro = jsonBuffer.createNestedArray("giroscopio");
gyro.add(Sensors::gyro[0]);
gyro.add(Sensors::gyro[1]);
gyro.add(Sensors::gyro[2]);
JsonArray mag = jsonBuffer.createNestedArray("magnetometro");
mag.add(Sensors::mag[0]);
mag.add(Sensors::mag[1]);
mag.add(Sensors::mag[2]);
// Mede o tamanho do buffer do JSON
size_t len = measureJson(jsonBuffer);
// Cria um espaço na RAM de (len + 1)
AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len);
if (buffer) {
// Transforma o JSON em um grande texto e o coloca no espaço criado anteriormente
serializeJson(jsonBuffer,(char *)buffer->get(), len + 1);
// Envia pelo WebSocket para todos os usuários
ws.textAll(buffer);
}
}
| 30.534483
| 125
| 0.678336
|
joaopedrovbs
|
4d34bfb49b84429f084a6ffb47759ba06fecac7f
| 5,457
|
hpp
|
C++
|
heart/src/problem/AbstractOutputModifier.hpp
|
AvciRecep/chaste_2019
|
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 1
|
2020-04-05T12:11:54.000Z
|
2020-04-05T12:11:54.000Z
|
heart/src/problem/AbstractOutputModifier.hpp
|
AvciRecep/chaste_2019
|
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
heart/src/problem/AbstractOutputModifier.hpp
|
AvciRecep/chaste_2019
|
1d46cdac647820d5c5030f8a9ea3a1019f6651c1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 2
|
2020-04-05T14:26:13.000Z
|
2021-03-09T08:18:17.000Z
|
/*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#ifndef ABSTRACTOUTPUTMODIFIER_HPP_
#define ABSTRACTOUTPUTMODIFIER_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/string.hpp>
#include "ClassIsAbstract.hpp"
#include <string>
#include "AbstractTetrahedralMesh.hpp"
/**
* A plug-in class for on-the-fly output. This is designed so that a user can insert something in
* order to monitor the progress of a simulation or to produce "post processed" output during the simulation.
*/
class AbstractOutputModifier
{
private:
/** For testing */
friend class TestMonodomainProblem;
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive this modifier. Just calls the base class version.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & mFilename;
archive & mFlushTime;
}
protected:
/** Constructor that does nothing, for archiving */
AbstractOutputModifier()
: mFilename(), mFlushTime(0.0)
{}
std::string mFilename; /**<The file which is eventually produced by this modifier*/
/** Simulation time period between flushes to disk */
double mFlushTime;
public:
/**
* Standard construction method contains only the name of the file which this simulation modifier should produce.
*
* Note that construction occurs before the Solve() loop and probably before initialisation. This means that it
* will not be possible to view certain data (e.g the mesh) at the time of construction
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible.
* @param rFilename The file which is eventually produced by this modifier
* @param flushTime The (simulation) time between flushing the file to disk. Default (0) means don't flush.
*
*/
AbstractOutputModifier(const std::string& rFilename, double flushTime=0.0)
: mFilename(rFilename),
mFlushTime(flushTime)
{}
/**
* Destructor should be overridden when necessary
*/
virtual ~AbstractOutputModifier()
{
}
/**
* Initialise the modifier (open a file or make some memory) when the solve loop is starting
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible. That is, it might have been slicker to pass in the mesh but that would require multiple templates.
* @param pVectorFactory The vector factory which is associated with the calling problem's mesh
* @param rNodePermutation The permutation associated with the calling problem's mesh (when running with parallel partitioning)
*/
virtual void InitialiseAtStart(DistributedVectorFactory* pVectorFactory, const std::vector<unsigned>& rNodePermutation)=0;
/**
* Finalise the modifier (close a file or dump the calculation to disk)
*/
virtual void FinaliseAtEnd()=0;
/**
* Process a solution time-step (dump a small line to file or compute the latest activation times)
* @param time The current simulation time
* @param solution A working copy of the solution at the current time-step. This is the PETSc vector which is distributed across the processes.
* @param problemDim The calling problem dimension. Used here to avoid probing the size of the solution vector
*/
virtual void ProcessSolutionAtTimeStep(double time, Vec solution, unsigned problemDim)=0;
};
CLASS_IS_ABSTRACT(AbstractOutputModifier)
#endif /* ABSTRACTOUTPUTMODIFIER_HPP_ */
| 40.422222
| 149
| 0.741067
|
AvciRecep
|
4d3fdf9a85f8d94b2ebe372c8eeb2e5d06d11fb3
| 1,834
|
cpp
|
C++
|
examples/ftp_server/ftp_server.cpp
|
kayfour/MAVSDK
|
48faf36a15ad9371b9e0a3c16ecac248e27e03ad
|
[
"BSD-3-Clause"
] | null | null | null |
examples/ftp_server/ftp_server.cpp
|
kayfour/MAVSDK
|
48faf36a15ad9371b9e0a3c16ecac248e27e03ad
|
[
"BSD-3-Clause"
] | null | null | null |
examples/ftp_server/ftp_server.cpp
|
kayfour/MAVSDK
|
48faf36a15ad9371b9e0a3c16ecac248e27e03ad
|
[
"BSD-3-Clause"
] | 1
|
2021-01-08T00:43:04.000Z
|
2021-01-08T00:43:04.000Z
|
/**
* @file ftp_server.cpp
*
* @brief Demonstrates how to use a FTP server with MAVSDK.
*
* @author Matej Frančeškin <matej@auterion.com>,
* @date 2019-09-06
*/
#include <mavsdk/mavsdk.h>
#include <mavsdk/plugins/ftp/ftp.h>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <string>
#include <thread>
#define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red
#define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour
using namespace mavsdk;
void usage(const std::string& bin_name)
{
std::cout
<< NORMAL_CONSOLE_TEXT << "Usage : " << bin_name << " <remote_ip> <remote_port> <root_dir>"
<< std::endl
<< "Start mavlink FTP server on <root_dir> sending heartbeats to <remote_ip>:<remote_port>"
<< std::endl;
}
int main(int argc, char** argv)
{
if (argc != 4) {
usage(argv[0]);
return 1;
}
Mavsdk mavsdk;
Mavsdk::Configuration configuration(Mavsdk::Configuration::UsageType::CompanionComputer);
mavsdk.set_configuration(configuration);
ConnectionResult connection_result = mavsdk.setup_udp_remote(argv[1], std::stoi(argv[2]));
if (connection_result != ConnectionResult::Success) {
std::cout << ERROR_CONSOLE_TEXT << "Error setting up Mavlink FTP server." << std::endl;
return 1;
}
auto system_cc = mavsdk.systems().at(0);
auto ftp_server = std::make_shared<Ftp>(system_cc);
ftp_server->set_root_directory(argv[3]);
std::cout << NORMAL_CONSOLE_TEXT << "Mavlink FTP server running." << std::endl
<< "Remote: " << argv[1] << ":" << argv[2] << std::endl
<< "Component ID: " << static_cast<int>(ftp_server->get_our_compid()) << std::endl;
for (;;) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
| 28.65625
| 99
| 0.640676
|
kayfour
|
4d41c982c02c6b1679db108db4806e2ebbb3178e
| 6,347
|
inl
|
C++
|
gemcutter/Entity/Entity.inl
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | 30
|
2017-02-02T01:57:13.000Z
|
2020-07-04T04:38:20.000Z
|
gemcutter/Entity/Entity.inl
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | null | null | null |
gemcutter/Entity/Entity.inl
|
EmilianC/Jewel3D
|
ce11aa686ab35d4989f018c948b26abed6637d77
|
[
"MIT"
] | 10
|
2017-07-10T01:31:54.000Z
|
2020-01-13T20:38:57.000Z
|
// Copyright (c) 2017 Emilian Cioca
namespace gem
{
namespace detail
{
// Allows for compile-time decision of whether or not a dynamic cast is required.
// A dynamic cast is required when a class inherits from Component indirectly, and
// as such, doesn't compile its own unique component type ID.
template<class T>
T* safe_cast(ComponentBase* comp)
{
if constexpr (std::is_same_v<T, typename T::StaticComponentType>)
{
return static_cast<T*>(comp);
}
else
{
return dynamic_cast<T*>(comp);
}
}
}
template<class derived>
Component<derived>::Component(Entity& owner)
: ComponentBase(owner, componentId)
{}
template<class derived>
unsigned Component<derived>::GetComponentId()
{
return componentId;
}
template<class T, typename... Args>
T& Entity::Add(Args&&... constructorParams)
{
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Template argument cannot be a Tag.");
ASSERT(!Has<T>(), "Component already exists on this entity.");
auto* newComponent = new T(*this, std::forward<Args>(constructorParams)...);
components.push_back(newComponent);
if (IsEnabled())
{
Index(*newComponent);
}
return *newComponent;
}
template<class T1, class T2, typename... Tx>
std::tuple<T1&, T2&, Tx&...> Entity::Add()
{
return std::tie(Add<T1>(), Add<T2>(), Add<Tx>()...);
}
template<class T>
T& Entity::Require()
{
auto* comp = Try<T>();
return comp ? *comp : Add<T>();
}
template<class T1, class T2, typename... Tx>
std::tuple<T1&, T2&, Tx&...> Entity::Require()
{
return std::tie(Require<T1>(), Require<T2>(), Require<Tx>()...);
}
template<class T> const T& Entity::Get() const { return GetComponent<T>(); }
template<class T> T& Entity::Get() { return GetComponent<T>(); }
template<class T> const T* Entity::Try() const { return TryComponent<T>(); }
template<class T> T* Entity::Try() { return TryComponent<T>(); }
template<class T>
void Entity::Remove()
{
using namespace detail;
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Template argument cannot be a Tag.");
for (unsigned i = 0; i < components.size(); ++i)
{
if (components[i]->componentId == T::GetComponentId())
{
if (safe_cast<T>(components[i]))
{
auto* comp = components[i];
components.erase(components.begin() + i);
if (comp->IsEnabled())
{
Unindex(*comp);
}
delete comp;
}
return;
}
}
}
template<class T>
bool Entity::Has() const
{
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Template argument cannot be a Tag.");
return Try<T>() != nullptr;
}
template<class T, typename... Args>
void Entity::Tag()
{
if constexpr (sizeof...(Args))
{
Tag<T>();
Tag<Args...>();
}
else
{
static_assert(std::is_base_of_v<TagBase, T>, "Template argument must inherit from Tag.");
if (!HasTag<T>())
{
Tag(T::GetComponentId());
}
}
}
template<class T>
void Entity::RemoveTag()
{
static_assert(std::is_base_of_v<TagBase, T>, "Template argument must inherit from Tag.");
RemoveTag(T::GetComponentId());
}
template<class T>
bool Entity::HasTag() const
{
static_assert(std::is_base_of_v<TagBase, T>, "Template argument must inherit from Tag.");
for (auto tag : tags)
{
if (tag == T::GetComponentId())
{
return true;
}
}
return false;
}
template<class T>
void Entity::GlobalRemoveTag()
{
static_assert(std::is_base_of_v<TagBase, T>, "Template argument must inherit from Tag.");
std::vector<Entity*>& taggedEntities = detail::entityIndex[T::GetComponentId()];
for (Entity* ent : taggedEntities)
{
auto& tags = ent->tags;
auto itr = std::find(tags.begin(), tags.end(), T::GetComponentId());
*itr = tags.back();
tags.pop_back();
}
taggedEntities.clear();
}
template<class T>
void Entity::Enable()
{
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Tags cannot be enabled or disabled. Add or remove them instead.");
auto& comp = Get<T>();
// The component state changes either way, but it only gets indexed if the Entity is also enabled.
bool wasEnabled = comp.isEnabled;
comp.isEnabled = true;
if (!this->IsEnabled())
{
return;
}
if (!wasEnabled)
{
Index(comp);
static_cast<ComponentBase&>(comp).OnEnable();
}
}
template<class T>
void Entity::Disable()
{
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Tags cannot be enabled or disabled. Add or remove them instead.");
auto& comp = Get<T>();
// The component state changes either way, but it only gets removed if the Entity is enabled.
bool wasEnabled = comp.isEnabled;
comp.isEnabled = false;
if (!this->IsEnabled())
{
return;
}
if (wasEnabled)
{
Unindex(comp);
static_cast<ComponentBase&>(comp).OnDisable();
}
}
template<class T>
T& Entity::GetComponent() const
{
using namespace detail;
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Template argument cannot be a Tag.");
auto itr = components.begin();
while (true)
{
ASSERT(itr != components.end(), "Entity did not have the expected component.");
if ((*itr)->componentId == T::GetComponentId())
{
ASSERT(safe_cast<T>(*itr), "Entity did not have the expected component.");
return *static_cast<T*>(*itr);
}
++itr;
}
}
template<class T>
T* Entity::TryComponent() const
{
using namespace detail;
static_assert(std::is_base_of_v<ComponentBase, T>, "Template argument must inherit from Component.");
static_assert(!std::is_base_of_v<TagBase, T>, "Template argument cannot be a Tag.");
for (auto* comp : components)
{
if (comp->componentId == T::GetComponentId())
{
return safe_cast<T>(comp);
}
}
return nullptr;
}
}
| 24.13308
| 115
| 0.659367
|
EmilianC
|
4d4371cc7edda0cc1c18a53bb8f33acfeedaa2a2
| 1,045
|
cpp
|
C++
|
13.cpp
|
jonathanxqs/lintcode
|
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
|
[
"MIT"
] | 1
|
2016-06-21T16:29:37.000Z
|
2016-06-21T16:29:37.000Z
|
13.cpp
|
jonathanxqs/lintcode
|
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
|
[
"MIT"
] | null | null | null |
13.cpp
|
jonathanxqs/lintcode
|
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
|
[
"MIT"
] | null | null | null |
class Solution {
public:
/**
* Returns a index to the first occurrence of target in source,
* or -1 if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
int strStr(const char *source, const char *target) {
// write your code here
int result = -1;
int i = 0;
int j = -1;
if (source == nullptr || target == nullptr) {
return result;
}
if ( *target == '\0')
return i;
while (*source !='\0') {
++j;
if(*source == *target) {
i = j;
const char *p = source;
const char *q = target;
while (*p == *q) {
if (*(q+1) =='\0') {
return i;
}
p++;
q++;
}
}
++source;
++i;
}
return result;
}
};
| 26.794872
| 75
| 0.396172
|
jonathanxqs
|
4d45f4dcb3f8f12614bda83bfaa9de1c212b7f9d
| 1,112
|
cpp
|
C++
|
tests/juliet/testcases/CWE775_Missing_Release_of_File_Descriptor_or_Handle/CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82_goodB2G.cpp
|
RanerL/analyzer
|
a401da4680f163201326881802ee535d6cf97f5a
|
[
"MIT"
] | 28
|
2017-01-20T15:25:54.000Z
|
2020-03-17T00:28:31.000Z
|
testcases/CWE775_Missing_Release_of_File_Descriptor_or_Handle/CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82_goodB2G.cpp
|
mellowCS/cwe_checker_juliet_suite
|
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
|
[
"MIT"
] | 1
|
2017-01-20T15:26:27.000Z
|
2018-08-20T00:55:37.000Z
|
testcases/CWE775_Missing_Release_of_File_Descriptor_or_Handle/CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82_goodB2G.cpp
|
mellowCS/cwe_checker_juliet_suite
|
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
|
[
"MIT"
] | 2
|
2019-07-15T19:07:04.000Z
|
2019-09-07T14:21:04.000Z
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82_goodB2G.cpp
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close.label.xml
Template File: source-sinks-82_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
* BadSource: Open a file using fopen()
* Sinks:
* GoodSink: Close the file using fclose()
* BadSink : Do not close file
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82.h"
namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82
{
void CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_82_goodB2G::action(FILE * data)
{
/* FIX: If the file is still opened, close it */
if (data != NULL)
{
fclose(data);
}
}
}
#endif /* OMITGOOD */
| 31.771429
| 105
| 0.758094
|
RanerL
|
4d476c70e24e2cc79d4838d0bcb7f49818ef157f
| 1,795
|
cc
|
C++
|
Linked_List/7B_Merge_K_Sorted_Lists/method2/solution.cc
|
sheriby/DandAInLeetCode
|
dd7f5029aa0c297ea82bb20f882b524789f35c96
|
[
"MIT"
] | 1
|
2020-02-07T12:25:56.000Z
|
2020-02-07T12:25:56.000Z
|
Linked_List/7B_Merge_K_Sorted_Lists/method2/solution.cc
|
sheriby/DandAInLeetCode
|
dd7f5029aa0c297ea82bb20f882b524789f35c96
|
[
"MIT"
] | null | null | null |
Linked_List/7B_Merge_K_Sorted_Lists/method2/solution.cc
|
sheriby/DandAInLeetCode
|
dd7f5029aa0c297ea82bb20f882b524789f35c96
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
/**
* The definition from single-linked list
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int val)
: val(val), next(nullptr) {} // here use nullptr instead of NULL
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// divide and conquer algorithm
// merge sort is a good example of divide and conquer algorithm
if (lists.size() == 0) {
return nullptr;
}
return mergeKListsHelper(lists, 0, lists.size() - 1);
}
ListNode *mergeKListsHelper(vector<ListNode *> &lists, int left,
int right) {
if (left < right) {
int mid = left + (right - left) / 2;
ListNode *leftList = mergeKListsHelper(lists, left, mid);
ListNode *rightList = mergeKListsHelper(lists, mid + 1, right);
return mergeTwoLists(leftList, rightList);
} else {
// std::cout << left << std::endl;
return lists.at(left);
}
}
private:
// we have already writeen merge two sorted lists before.
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// the second methods is two pointer.
ListNode *p = l1, *q = l2;
ListNode *head = new ListNode(0);
ListNode *pos = head;
while (p && q) {
if (p->val < q->val) {
pos->next = p;
p = p->next;
} else {
pos->next = q;
q = q->next;
}
pos = pos->next;
}
if (p) {
pos->next = p;
} else {
pos->next = q;
}
return head->next;
}
};
| 26.791045
| 75
| 0.504178
|
sheriby
|
4d4998fa064380187f433abefda6740bd4e4f9d8
| 2,476
|
cpp
|
C++
|
development/Tests/YagetCore-Test/TestFiles/Json_Test.cpp
|
eglowacki/zloty
|
9c864ae0beb1ac64137a096795261768b7fc6710
|
[
"MIT"
] | null | null | null |
development/Tests/YagetCore-Test/TestFiles/Json_Test.cpp
|
eglowacki/zloty
|
9c864ae0beb1ac64137a096795261768b7fc6710
|
[
"MIT"
] | 44
|
2018-06-28T03:01:44.000Z
|
2022-03-20T19:53:00.000Z
|
development/Tests/YagetCore-Test/TestFiles/Json_Test.cpp
|
eglowacki/zloty
|
9c864ae0beb1ac64137a096795261768b7fc6710
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Debugging/DevConfiguration.h"
#include "Debugging/DevConfigurationParsers.h"
#include "TestHelpers/TestHelpers.h"
#include "Json/JsonHelpers.h"
//CHECK_EQUAL(expected, actual);
class JsonUtilities : public ::testing::Test
{
};
TEST_F(JsonUtilities, ConfigString)
{
using namespace yaget;
dev::Configuration expectedTestconfiguration1;
expectedTestconfiguration1.mDebug.mMetrics.TraceOn = false;
dev::Configuration expectedTestconfiguration2;
expectedTestconfiguration2.mDebug.mMetrics.TraceFileName = "Foo.trc";
dev::Configuration expectedTestconfiguration4;
expectedTestconfiguration4.mDebug.mMetrics.TraceFileName = "";
const char* testString1 = "Debug.Metrics.TraceOn=false";
const char* testString2 = "Debug.Metrics.TraceFileName = 'Foo.trc'";
const char* testString3 = "Debug.Metrics.TraceFileName='Foo.trc'";
const char* testString4 = "Debug.Metrics.TraceFileName=''";
const char* testString5 = "Debug.Metrics.TraceFileName";
const auto jsonBlock1 = json::ParseConfig(testString1);
const auto jsonBlock2 = json::ParseConfig(testString2);
const auto jsonBlock3 = json::ParseConfig(testString3);
const auto jsonBlock4 = json::ParseConfig(testString4);
const auto jsonBlock5 = json::ParseConfig(testString5);
dev::Configuration configuration;
EXPECT_TRUE(configuration.mDebug.mMetrics.TraceOn);
from_json(jsonBlock1, configuration);
EXPECT_EQ(expectedTestconfiguration1, configuration);
configuration = {};
EXPECT_STREQ(configuration.mDebug.mMetrics.TraceFileName.c_str(), "$(Temp)/$(AppName)_trace.json");
from_json(jsonBlock2, configuration);
EXPECT_EQ(expectedTestconfiguration2, configuration);
configuration = {};
EXPECT_STREQ(configuration.mDebug.mMetrics.TraceFileName.c_str(), "$(Temp)/$(AppName)_trace.json");
from_json(jsonBlock3, configuration);
EXPECT_EQ(expectedTestconfiguration2, configuration);
configuration = {};
EXPECT_STREQ(configuration.mDebug.mMetrics.TraceFileName.c_str(), "$(Temp)/$(AppName)_trace.json");
from_json(jsonBlock4, configuration);
EXPECT_EQ(expectedTestconfiguration4, configuration);
configuration = {};
EXPECT_STREQ(configuration.mDebug.mMetrics.TraceFileName.c_str(), "$(Temp)/$(AppName)_trace.json");
from_json(jsonBlock5, configuration);
EXPECT_STREQ(configuration.mDebug.mMetrics.TraceFileName.c_str(), "$(Temp)/$(AppName)_trace.json");
}
| 38.6875
| 103
| 0.753635
|
eglowacki
|
4d4ad7e828eb02cd709ca8268e8ee2d507abc1b8
| 1,231
|
cpp
|
C++
|
src/pages/incomes_pages.cpp
|
FORGIS98/budgetwarrior
|
ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971
|
[
"MIT"
] | null | null | null |
src/pages/incomes_pages.cpp
|
FORGIS98/budgetwarrior
|
ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971
|
[
"MIT"
] | null | null | null |
src/pages/incomes_pages.cpp
|
FORGIS98/budgetwarrior
|
ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971
|
[
"MIT"
] | null | null | null |
//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "incomes.hpp"
#include "writer.hpp"
#include "pages/incomes_pages.hpp"
#include "http.hpp"
using namespace budget;
void budget::incomes_page(const httplib::Request& req, httplib::Response& res) {
std::stringstream content_stream;
if (!page_start(req, res, content_stream, "All Incomes")) {
return;
}
budget::html_writer w(content_stream);
budget::show_incomes(w);
make_tables_sortable(w);
page_end(w, req, res);
}
void budget::set_incomes_page(const httplib::Request& req, httplib::Response& res) {
std::stringstream content_stream;
if (!page_start(req, res, content_stream, "Set income")) {
return;
}
budget::html_writer w(content_stream);
w << title_begin << "Set income" << title_end;
form_begin(w, "/api/incomes/add/", "/incomes/set/");
add_amount_picker(w);
form_end(w);
page_end(w, req, res);
}
| 25.645833
| 84
| 0.595451
|
FORGIS98
|
4d4d390aa51a2f123a85615508ca73322ec5c7fc
| 3,327
|
cpp
|
C++
|
Source/Macad.Occt/Generated/BRepIntCurveSurface.cpp
|
zhyifei/Macad3D
|
55d92a7de53a1fc8f4453c09b162c261a40586f0
|
[
"MIT"
] | 107
|
2020-11-29T18:01:50.000Z
|
2022-03-31T13:54:40.000Z
|
Source/Macad.Occt/Generated/BRepIntCurveSurface.cpp
|
zhyifei/Macad3D
|
55d92a7de53a1fc8f4453c09b162c261a40586f0
|
[
"MIT"
] | 10
|
2021-03-12T18:34:24.000Z
|
2022-01-08T21:03:58.000Z
|
Source/Macad.Occt/Generated/BRepIntCurveSurface.cpp
|
zhyifei/Macad3D
|
55d92a7de53a1fc8f4453c09b162c261a40586f0
|
[
"MIT"
] | 42
|
2021-01-07T06:23:24.000Z
|
2022-03-29T10:03:51.000Z
|
// Generated wrapper code for package BRepIntCurveSurface
#include "OcctPCH.h"
#include "BRepIntCurveSurface.h"
using namespace System::Runtime::InteropServices; // for class Marshal
#include "BRepIntCurveSurface.h"
#include "TopoDS.h"
#include "GeomAdaptor.h"
#include "Standard.h"
#include "gp.h"
#include "TopAbs.h"
//---------------------------------------------------------------------
// Class BRepIntCurveSurface_Inter
//---------------------------------------------------------------------
Macad::Occt::BRepIntCurveSurface_Inter::BRepIntCurveSurface_Inter()
: BaseClass<::BRepIntCurveSurface_Inter>(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::BRepIntCurveSurface_Inter();
}
Macad::Occt::BRepIntCurveSurface_Inter::BRepIntCurveSurface_Inter(Macad::Occt::BRepIntCurveSurface_Inter^ parameter1)
: BaseClass<::BRepIntCurveSurface_Inter>(BaseClass::InitMode::Uninitialized)
{
_NativeInstance = new ::BRepIntCurveSurface_Inter(*(::BRepIntCurveSurface_Inter*)parameter1->NativeInstance);
}
void Macad::Occt::BRepIntCurveSurface_Inter::Init(Macad::Occt::TopoDS_Shape^ theShape, Macad::Occt::GeomAdaptor_Curve^ theCurve, double theTol)
{
((::BRepIntCurveSurface_Inter*)_NativeInstance)->Init(*(::TopoDS_Shape*)theShape->NativeInstance, *(::GeomAdaptor_Curve*)theCurve->NativeInstance, theTol);
}
void Macad::Occt::BRepIntCurveSurface_Inter::Init(Macad::Occt::TopoDS_Shape^ theShape, Macad::Occt::gp_Lin^ theLine, double theTol)
{
((::BRepIntCurveSurface_Inter*)_NativeInstance)->Init(*(::TopoDS_Shape*)theShape->NativeInstance, *(::gp_Lin*)theLine->NativeInstance, theTol);
}
void Macad::Occt::BRepIntCurveSurface_Inter::Load(Macad::Occt::TopoDS_Shape^ theShape, double theTol)
{
((::BRepIntCurveSurface_Inter*)_NativeInstance)->Load(*(::TopoDS_Shape*)theShape->NativeInstance, theTol);
}
void Macad::Occt::BRepIntCurveSurface_Inter::Init(Macad::Occt::GeomAdaptor_Curve^ theCurve)
{
((::BRepIntCurveSurface_Inter*)_NativeInstance)->Init(*(::GeomAdaptor_Curve*)theCurve->NativeInstance);
}
bool Macad::Occt::BRepIntCurveSurface_Inter::More()
{
return ((::BRepIntCurveSurface_Inter*)_NativeInstance)->More();
}
void Macad::Occt::BRepIntCurveSurface_Inter::Next()
{
((::BRepIntCurveSurface_Inter*)_NativeInstance)->Next();
}
Macad::Occt::Pnt Macad::Occt::BRepIntCurveSurface_Inter::Pnt()
{
return Macad::Occt::Pnt(((::BRepIntCurveSurface_Inter*)_NativeInstance)->Pnt());
}
double Macad::Occt::BRepIntCurveSurface_Inter::U()
{
return ((::BRepIntCurveSurface_Inter*)_NativeInstance)->U();
}
double Macad::Occt::BRepIntCurveSurface_Inter::V()
{
return ((::BRepIntCurveSurface_Inter*)_NativeInstance)->V();
}
double Macad::Occt::BRepIntCurveSurface_Inter::W()
{
return ((::BRepIntCurveSurface_Inter*)_NativeInstance)->W();
}
Macad::Occt::TopAbs_State Macad::Occt::BRepIntCurveSurface_Inter::State()
{
return (Macad::Occt::TopAbs_State)((::BRepIntCurveSurface_Inter*)_NativeInstance)->State();
}
Macad::Occt::TopoDS_Face^ Macad::Occt::BRepIntCurveSurface_Inter::Face()
{
::TopoDS_Face* _result = new ::TopoDS_Face();
*_result = (::TopoDS_Face)((::BRepIntCurveSurface_Inter*)_NativeInstance)->Face();
return _result==nullptr ? nullptr : gcnew Macad::Occt::TopoDS_Face(_result);
}
| 34.65625
| 157
| 0.715359
|
zhyifei
|
4d50a0e6b36072965cdb4ebd4e6b830f58f7bf35
| 2,522
|
cpp
|
C++
|
src/CLR/CorLib/corlib_native_System_Object.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | null | null | null |
src/CLR/CorLib/corlib_native_System_Object.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | 1
|
2021-02-22T07:54:30.000Z
|
2021-02-22T07:54:30.000Z
|
src/CLR/CorLib/corlib_native_System_Object.cpp
|
TIPConsulting/nf-interpreter
|
d5407872f4705d6177e1ee5a2e966bd02fd476e4
|
[
"MIT"
] | null | null | null |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"
//--//
HRESULT Library_corlib_native_System_Object::Equals___BOOLEAN__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
stack.SetResult_Boolean( CLR_RT_HeapBlock::ObjectsEqual( stack.Arg0(), stack.Arg1(), true ) );
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Object::GetHashCode___I4( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
stack.SetResult_I4( CLR_RT_HeapBlock::GetHashCode( stack.This(), true, 0 ) );
NANOCLR_NOCLEANUP_NOLABEL();
}
#if (NANOCLR_REFLECTION == TRUE)
HRESULT Library_corlib_native_System_Object::GetType___SystemType( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_TypeDescriptor desc;
CLR_RT_ReflectionDef_Index idx;
CLR_RT_HeapBlock& arg0 = stack.Arg0();
CLR_RT_HeapBlock* pObj;
NANOCLR_CHECK_HRESULT(desc.InitializeFromObject( arg0 ));
pObj = arg0.Dereference();
if(pObj && arg0.DataType() == DATATYPE_REFLECTION)
{
idx.m_kind = REFLECTION_TYPE;
idx.m_levels = 0;
idx.m_data.m_type.m_data = desc.m_handlerCls.m_data;
}
else
{
idx = desc.m_reflex;
}
{
CLR_RT_HeapBlock& top = stack.PushValue();
CLR_RT_HeapBlock* hbObj;
NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_TypeStatic));
hbObj = top.Dereference();
hbObj->SetReflection( idx );
}
NANOCLR_NOCLEANUP();
}
#endif // NANOCLR_REFLECTION
HRESULT Library_corlib_native_System_Object::MemberwiseClone___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
NANOCLR_SET_AND_LEAVE(g_CLR_RT_ExecutionEngine.CloneObject( stack.PushValueAndClear(), stack.Arg0() ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Object::ReferenceEquals___STATIC__BOOLEAN__OBJECT__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
stack.SetResult_Boolean( CLR_RT_HeapBlock::ObjectsEqual( stack.Arg0(), stack.Arg1(), true ) );
NANOCLR_NOCLEANUP_NOLABEL();
}
| 27.413043
| 123
| 0.692308
|
TIPConsulting
|
4d51020f7f574bf33eb2bc46fcf386c3e10c485f
| 2,107
|
cpp
|
C++
|
neutrino/graphics/src/render/opengl/opengl_logger.cpp
|
alexiynew/nih_framework
|
a65335586331daa0ece892f98265bd1d2f8f579f
|
[
"MIT"
] | 1
|
2017-07-14T04:51:54.000Z
|
2017-07-14T04:51:54.000Z
|
neutrino/graphics/src/render/opengl/opengl_logger.cpp
|
alexiynew/nih_framework
|
a65335586331daa0ece892f98265bd1d2f8f579f
|
[
"MIT"
] | 32
|
2017-02-02T14:49:41.000Z
|
2019-06-25T19:38:27.000Z
|
neutrino/graphics/src/render/opengl/opengl_logger.cpp
|
alexiynew/nih_framework
|
a65335586331daa0ece892f98265bd1d2f8f579f
|
[
"MIT"
] | null | null | null |
#include <map>
#include <string>
#include <log/log.hpp>
#include <graphics/src/opengl/opengl.hpp>
#include <graphics/src/render/opengl/opengl_logger.hpp>
using namespace framework::graphics::details::opengl;
namespace framework::graphics
{
const std::string tag = "OpenGL";
void log_opengl_errors(const std::string& file, int line)
{
struct ErrorDescription
{
std::string name;
std::string description;
};
static const std::map<GLenum, ErrorDescription> error_descriptions = {
{GL_INVALID_ENUM,
{"GL_INVALID_ENUM",
"An unacceptable value is specified for an enumerated argument. The offending command is ignored and has no "
"other side effect than to set the error flag."}},
{GL_INVALID_VALUE,
{"GL_INVALID_VALUE",
"A numeric argument is out of range. The offending command is ignored and has no other side effect than to set "
"the error flag."}},
{GL_INVALID_OPERATION,
{"GL_INVALID_OPERATION",
"The specified operation is not allowed in the current state. The offending command is ignored and has no other "
"side effect than to set the error flag."}},
{GL_INVALID_FRAMEBUFFER_OPERATION,
{"GL_INVALID_FRAMEBUFFER_OPERATION",
"The framebuffer object is not complete. The offending command is ignored and has no other side effect than to "
"set the error flag."}},
{GL_OUT_OF_MEMORY,
{"GL_OUT_OF_MEMORY",
"There is not enough memory left to execute the command. The state of the GL is undefined, except for the state "
"of the error flags, after this error is recorded."}},
};
for (GLenum error = glGetError(); error != GL_NO_ERROR; error = glGetError()) {
if (error_descriptions.count(error)) {
const auto& desc = error_descriptions.at(error);
log::error(tag) << file << ":" << line << "\n" << desc.name << " " << desc.description;
} else {
log::error(tag) << file << ":" << line << "\n"
<< "Unknown error: " << error;
}
}
}
} // namespace framework::graphics
| 36.964912
| 119
| 0.654485
|
alexiynew
|
4d5369d2135904d9036d4497808d6d343d0553d3
| 128
|
hpp
|
C++
|
libraries/fc/include/fc/compress/zlib.hpp
|
techsharesteam/techshares
|
47c58630a578204147057b7504e571e19546444f
|
[
"MIT"
] | 6
|
2018-08-08T06:10:45.000Z
|
2019-06-23T13:45:08.000Z
|
libraries/fc/include/fc/compress/zlib.hpp
|
techsharesteam/techshares
|
47c58630a578204147057b7504e571e19546444f
|
[
"MIT"
] | null | null | null |
libraries/fc/include/fc/compress/zlib.hpp
|
techsharesteam/techshares
|
47c58630a578204147057b7504e571e19546444f
|
[
"MIT"
] | 2
|
2018-08-06T06:50:46.000Z
|
2019-01-03T09:48:54.000Z
|
#pragma once
#include <fc/string.hpp>
namespace fc
{
string zlib_compress(const string& in);
} // namespace fc
| 11.636364
| 42
| 0.640625
|
techsharesteam
|
4d55a5a46029f396546008aaed68a9e37b73376b
| 1,651
|
cpp
|
C++
|
sliding-window-min-swaps-group-1s/min_swaps.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
sliding-window-min-swaps-group-1s/min_swaps.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
sliding-window-min-swaps-group-1s/min_swaps.cpp
|
JBlakd/self-study
|
71cb86d43fe7f6514657958db0c0e81113bd4c43
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int minSwaps(vector<int>& data) {
// count number of 1's
int count = 0;
for (int& element : data) {
if (element == 1) {
++count;
}
}
if (count < 1) {
return 0;
}
// Create the window, track number of 0's in the window
int lo = 0;
int hi = count - 1;
// Repurpose the count variable
count = 0;
for (int i = lo; i <= hi; ++i) {
if (data[i] == 0) {
++count;
}
}
int ret = count;
++lo;
++hi;
// Slide the window
while (hi < data.size()) {
if (data[hi] == 0) {
++count;
}
if (data[lo - 1] == 0) {
--count;
}
ret = min(ret, count);
++lo;
++hi;
}
return ret;
}
};
template <typename T>
void print_vector(vector<T> vec) {
cout << "{";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i];
if (i != vec.size() - 1) {
cout << ", ";
}
}
cout << "}";
}
int main() {
Solution solution;
vector<int> data;
// 1
data = {1, 0, 1, 0, 1};
cout << solution.minSwaps(data) << '\n';
// 0
data = {0, 0, 0, 1, 0};
cout << solution.minSwaps(data) << '\n';
// 3
data = {1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1};
cout << solution.minSwaps(data) << '\n';
}
| 19.423529
| 63
| 0.396124
|
JBlakd
|
4d5a9f0b7a81565ca0eb186d5b068b8f40997fff
| 1,064
|
cpp
|
C++
|
benchmarks/binary_tree/taskflow.cpp
|
drobison00/taskflow
|
9415c3b68fd050889f57412394933e94b74755e0
|
[
"MIT"
] | 3,337
|
2020-06-02T02:04:17.000Z
|
2022-03-31T19:12:03.000Z
|
benchmarks/binary_tree/taskflow.cpp
|
drobison00/taskflow
|
9415c3b68fd050889f57412394933e94b74755e0
|
[
"MIT"
] | 235
|
2020-06-02T01:26:49.000Z
|
2022-03-31T01:35:31.000Z
|
benchmarks/binary_tree/taskflow.cpp
|
drobison00/taskflow
|
9415c3b68fd050889f57412394933e94b74755e0
|
[
"MIT"
] | 414
|
2020-06-02T16:25:23.000Z
|
2022-03-30T09:17:19.000Z
|
#include "binary_tree.hpp"
#include <taskflow/taskflow.hpp>
// binary_tree_taskflow
void binary_tree_taskflow(size_t num_layers, unsigned num_threads) {
std::atomic<size_t> counter {0};
std::vector<tf::Task> tasks(1 << num_layers);
tf::Executor executor(num_threads);
tf::Taskflow taskflow;
for(unsigned i=1; i<tasks.size(); i++) {
tasks[i] = taskflow.emplace([&](){
counter.fetch_add(1, std::memory_order_relaxed);
});
}
for(unsigned i=1; i<tasks.size(); i++) {
unsigned l = i << 1;
unsigned r = l + 1;
if(l < tasks.size() && r < tasks.size()) {
tasks[i].precede(tasks[l], tasks[r]);
}
}
executor.run(taskflow).get();
assert(counter + 1 == tasks.size());
}
std::chrono::microseconds measure_time_taskflow(
size_t num_layers,
unsigned num_threads
) {
auto beg = std::chrono::high_resolution_clock::now();
binary_tree_taskflow(num_layers, num_threads);
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(end - beg);
}
| 24.744186
| 74
| 0.660714
|
drobison00
|
4d5d98e5f9a65f11b2760888910775c9e064eb45
| 9,782
|
cpp
|
C++
|
src/common.cpp
|
bwpow/libshaga
|
d457ee8dc267af9e20564961c9f6928290cb29cb
|
[
"CC0-1.0"
] | 1
|
2018-05-09T18:15:21.000Z
|
2018-05-09T18:15:21.000Z
|
src/common.cpp
|
bwpow/libshaga
|
d457ee8dc267af9e20564961c9f6928290cb29cb
|
[
"CC0-1.0"
] | null | null | null |
src/common.cpp
|
bwpow/libshaga
|
d457ee8dc267af9e20564961c9f6928290cb29cb
|
[
"CC0-1.0"
] | null | null | null |
/******************************************************************************
Shaga library is released under the New BSD license (see LICENSE.md):
Copyright (c) 2012-2021, SAGE team s.r.o., Samuel Kupka
All rights reserved.
*******************************************************************************/
#include "shaga/common.h"
namespace shaga {
#if BYTE_ORDER == LITTLE_ENDIAN
const bool _shaga_compiled_little_endian {true};
#ifndef __clang__
#pragma message "Endian: LITTLE"
#endif // __clang__
#elif BYTE_ORDER == BIG_ENDIAN
const bool _shaga_compiled_little_endian {false};
#ifndef __clang__
#pragma message "Endian: BIG"
#endif // __clang__
#else
#error Unable to detect version of the library
#endif
#if defined SHAGA_MULTI_THREAD
const bool _shaga_compiled_with_threading {true};
#ifndef __clang__
#pragma message "Threading support: YES"
#endif // __clang__
#elif defined SHAGA_SINGLE_THREAD
const bool _shaga_compiled_with_threading {false};
#ifndef __clang__
#pragma message "Threading support: NO"
#endif // __clang__
#else
#error Unable to detect version of the library
#endif
#if defined SHAGA_LITE
const bool _shaga_compiled_full {false};
#ifndef __clang__
#pragma message "Version: LITE"
#endif // __clang__
#elif defined SHAGA_FULL
const bool _shaga_compiled_full {true};
#ifndef __clang__
#pragma message "Version: FULL"
#endif // __clang__
#else
#error Unable to detect version of the library
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Most used templates ////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template class SPSC<std::string>;
template class Simple8EncodeSPSC<SPSCDataPreAlloc>;
template class Simple8DecodeSPSC<SPSCDataPreAlloc>;
template class Simple16EncodeSPSC<SPSCDataPreAlloc>;
template class Simple16DecodeSPSC<SPSCDataPreAlloc>;
template class PacketEncodeSPSC<SPSCDataDynAlloc>;
template class PacketDecodeSPSC<SPSCDataDynAlloc>;
template class SeqPacketEncodeSPSC<SPSCDataDynAlloc>;
template class SeqPacketDecodeSPSC<SPSCDataDynAlloc>;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Static definitions /////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef SHAGA_THREADING
static std::mutex _callback_mutex;
static std::recursive_mutex _exit_mutex;
#endif // SHAGA_THREADING
typedef std::list<std::function<void (void)>> CALLBACK_LIST;
static CALLBACK_LIST _at_shutdown_callback_list;
static CALLBACK_LIST _at_exit_callback_list;
static FINAL_CALL _final_call {nullptr};
#ifdef SHAGA_THREADING
static std::atomic<bool> _is_shutdown {false};
static std::atomic<bool> _is_in_exit {false};
#else
volatile bool _is_shutdown {false};
bool _is_in_exit {false};
#endif // SHAGA_THREADING
void add_at_exit_callback (std::function<void (void)> func)
{
#ifdef SHAGA_THREADING
std::lock_guard<std::mutex> lock (_callback_mutex);
#endif // SHAGA_THREADING
_at_exit_callback_list.push_back (func);
}
HEDLEY_NO_RETURN void _exit (const std::string_view text, const int rcode, const std::string_view prefix) noexcept
{
try {
#ifdef SHAGA_THREADING
std::unique_lock<std::recursive_mutex> exitlck (_exit_mutex);
#endif // SHAGA_THREADING
#ifdef SHAGA_THREADING
if (_is_in_exit.exchange (true) == true)
#else
if (std::exchange (_is_in_exit, true) == true)
#endif // SHAGA_THREADING
{
/* This function is already being executed, clearly from one of the callback functions. */
P::_print ("Exit executed recursively from callback function."sv, "FATAL ERROR: "sv, true);
P::set_enabled (false);
::exit (EXIT_FAILURE);
}
#ifdef SHAGA_THREADING
std::unique_lock<std::mutex> lck (_callback_mutex);
#endif // SHAGA_THREADING
CALLBACK_LIST lst;
lst.swap (_at_exit_callback_list);
#ifdef SHAGA_THREADING
lck.unlock ();
#endif // SHAGA_THREADING
for (auto &func : lst) {
if (func != nullptr) {
func ();
func = nullptr;
}
}
lst.clear ();
if (text.empty () == false || prefix.empty () == false) {
P::_print (text, prefix, true);
}
P::print ("Application exit with errorcode {}"sv, rcode);
if (nullptr != _final_call) {
_final_call (text, rcode);
_final_call = nullptr;
}
P::set_enabled (false);
::exit (rcode);
}
catch (...) {
P::_print ("Exception caught in exit."sv, "FATAL ERROR: "sv, true);
P::set_enabled (false);
::exit (EXIT_FAILURE);
}
}
HEDLEY_NO_RETURN void exit (const int rcode) noexcept
{
_exit (""sv, rcode);
}
HEDLEY_NO_RETURN void exit_failure (void) noexcept
{
_exit (""sv, EXIT_FAILURE);
}
HEDLEY_NO_RETURN void exit (void) noexcept
{
_exit (""sv, EXIT_SUCCESS);
}
void set_final_call (FINAL_CALL func)
{
_final_call = func;
}
void add_at_shutdown_callback (std::function<void (void)> func)
{
#ifdef SHAGA_THREADING
std::lock_guard<std::mutex> lock(_callback_mutex);
#endif // SHAGA_THREADING
_at_shutdown_callback_list.push_back (func);
}
void _try_to_shutdown (const char *file, const char *funct, const int line)
{
#ifdef SHAGA_THREADING
if (_is_shutdown.exchange (true, std::memory_order_seq_cst) == false)
#else
if (std::exchange (_is_shutdown, true) == false)
#endif // SHAGA_THREADING
{
P::print ("Shutdown requested from {}: {} line {}"sv, file, funct, line);
#ifdef SHAGA_THREADING
std::unique_lock<std::mutex> lck (_callback_mutex);
#endif // SHAGA_THREADING
CALLBACK_LIST lst;
lst.swap (_at_shutdown_callback_list);
#ifdef SHAGA_THREADING
lck.unlock ();
#endif // SHAGA_THREADING
for (auto &func : lst) {
if (func != nullptr) {
func ();
func = nullptr;
}
}
}
}
HEDLEY_WARN_UNUSED_RESULT bool is_shutting_down (void)
{
#ifdef SHAGA_THREADING
return _is_shutdown.load (std::memory_order_relaxed);
#else
return _is_shutdown;
#endif // SHAGA_THREADING
}
HEDLEY_WARN_UNUSED_RESULT int64_t timeval_diff_msec (const struct timeval &starttime, const struct timeval &finishtime)
{
return ((static_cast<int64_t> (finishtime.tv_sec) - static_cast<int64_t> (starttime.tv_sec)) * 1'000) +
(static_cast<int64_t> (finishtime.tv_usec) - static_cast<int64_t> (starttime.tv_usec)) / 1'000;
}
HEDLEY_WARN_UNUSED_RESULT int64_t timespec_diff_msec (const struct timespec &starttime, const struct timespec &finishtime)
{
return ((static_cast<int64_t> (finishtime.tv_sec) - static_cast<int64_t> (starttime.tv_sec)) * 1'000) +
(static_cast<int64_t> (finishtime.tv_nsec / 1'000'000) - static_cast<int64_t> (starttime.tv_nsec / 1'000'000));
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_monotime_sec (void)
{
struct timespec monotime;
#ifdef CLOCK_MONOTONIC_RAW
::clock_gettime(CLOCK_MONOTONIC_RAW, &monotime);
#else
::clock_gettime(CLOCK_MONOTONIC, &monotime);
#endif // CLOCK_MONOTONIC_RAW
return static_cast<uint64_t> (monotime.tv_sec);
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_monotime_msec (void)
{
struct timespec monotime;
#ifdef CLOCK_MONOTONIC_RAW
::clock_gettime(CLOCK_MONOTONIC_RAW, &monotime);
#else
::clock_gettime(CLOCK_MONOTONIC, &monotime);
#endif // CLOCK_MONOTONIC_RAW
return (static_cast<uint64_t> (monotime.tv_sec) * 1'000) + (static_cast<uint64_t> (monotime.tv_nsec) / 1'000'000);
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_monotime_usec (void)
{
struct timespec monotime;
#ifdef CLOCK_MONOTONIC_RAW
::clock_gettime(CLOCK_MONOTONIC_RAW, &monotime);
#else
::clock_gettime(CLOCK_MONOTONIC, &monotime);
#endif // CLOCK_MONOTONIC_RAW
return (static_cast<uint64_t> (monotime.tv_sec) * 1'000'000) + (static_cast<uint64_t> (monotime.tv_nsec) / 1'000);
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_realtime_sec (void)
{
struct timespec monotime;
::clock_gettime (CLOCK_REALTIME, &monotime);
return static_cast<uint64_t> (monotime.tv_sec);
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_realtime_msec (void)
{
struct timespec monotime;
::clock_gettime (CLOCK_REALTIME, &monotime);
return (static_cast<uint64_t> (monotime.tv_sec) * 1'000) + (static_cast<uint64_t> (monotime.tv_nsec) / 1'000'000);
}
HEDLEY_WARN_UNUSED_RESULT uint64_t get_realtime_usec (void)
{
struct timespec monotime;
::clock_gettime (CLOCK_REALTIME, &monotime);
return (static_cast<uint64_t> (monotime.tv_sec) * 1'000'000) + (static_cast<uint64_t> (monotime.tv_nsec) / 1'000);
}
HEDLEY_WARN_UNUSED_RESULT SHAGA_PARSED_REALTIME get_realtime_parsed (const time_t theTime, const bool local)
{
SHAGA_PARSED_REALTIME out;
struct tm t;
::memset (&t, 0, sizeof (t));
if (local == true) {
::localtime_r (&theTime, &t);
}
else {
::gmtime_r (&theTime, &t);
}
out.year = t.tm_year + 1900;
out.month = t.tm_mon + 1;
out.day = t.tm_mday;
out.hour = t.tm_hour;
out.minute = t.tm_min;
out.second = t.tm_sec;
return out;
}
HEDLEY_WARN_UNUSED_RESULT SHAGA_PARSED_REALTIME get_realtime_parsed (const bool local)
{
time_t theTime;
::time (&theTime);
return get_realtime_parsed (theTime, local);
}
HEDLEY_WARN_UNUSED_RESULT time_t get_realtime_sec_shifted (const time_t shift_start)
{
struct timespec monotime;
::clock_gettime (CLOCK_REALTIME, &monotime);
if (shift_start > monotime.tv_sec) {
return 0;
}
else {
return (monotime.tv_sec - shift_start);
}
}
}
| 29.026706
| 123
| 0.665099
|
bwpow
|
4d62d974734cff2e28346adfc6941e2f4c8d5a4f
| 1,320
|
hpp
|
C++
|
boost/network/message/directives/detail/string_value.hpp
|
antoinelefloch/cpp-netlib
|
5eb9b5550a10d06f064ee9883c7d942d3426f31b
|
[
"BSL-1.0"
] | 3
|
2015-02-10T22:08:08.000Z
|
2021-11-13T20:59:25.000Z
|
include/boost/network/message/directives/detail/string_value.hpp
|
waTeim/boost
|
eb3850fae8c037d632244cf15cf6905197d64d39
|
[
"BSL-1.0"
] | 1
|
2018-08-10T04:47:12.000Z
|
2018-08-10T13:54:57.000Z
|
include/boost/network/message/directives/detail/string_value.hpp
|
waTeim/boost
|
eb3850fae8c037d632244cf15cf6905197d64d39
|
[
"BSL-1.0"
] | 5
|
2017-12-28T12:42:25.000Z
|
2021-07-01T07:41:53.000Z
|
#ifndef BOOST_NETWORK_MESSAGE_DIRECTIVES_DETAIL_STRING_VALUE_HPP_20100915
#define BOOST_NETWORK_MESSAGE_DIRECTIVES_DETAIL_STRING_VALUE_HPP_20100915
// Copyright Dean Michael Berris 2010.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/network/traits/string.hpp>
#include <boost/network/support/is_async.hpp>
#include <boost/network/support/is_sync.hpp>
#include <boost/thread/future.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/or.hpp>
namespace boost { namespace network { namespace detail {
template <class Tag>
struct string_value :
mpl::if_<
is_async<Tag>,
boost::shared_future<typename string<Tag>::type>,
typename mpl::if_<
mpl::or_<
is_sync<Tag>,
is_same<Tag, tags::default_string>,
is_same<Tag, tags::default_wstring>
>,
typename string<Tag>::type,
unsupported_tag<Tag>
>::type
>
{};
} /* detail */
} /* network */
} /* boost */
#endif /* BOOST_NETWORK_MESSAGE_DIRECTIVES_DETAIL_STRING_VALUE_HPP_20100915 */
| 32.195122
| 78
| 0.643939
|
antoinelefloch
|
4d6595d2982fe160d200bd0cf3f2e92703cb6a68
| 1,003
|
cpp
|
C++
|
oy/test1.cpp
|
mhilmyh/algo-data-struct
|
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
|
[
"MIT"
] | null | null | null |
oy/test1.cpp
|
mhilmyh/algo-data-struct
|
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
|
[
"MIT"
] | null | null | null |
oy/test1.cpp
|
mhilmyh/algo-data-struct
|
6a9b1e5220e3c4e4a41200a09cb27f3f55560693
|
[
"MIT"
] | null | null | null |
// **Level 1** operator (+, -)
// “-3+2” = -1
// “4+7” = 11
// “9-5” = 4
// “4-7+5-3” = -1
#include <bits/stdc++.h>
#define lli long long int
using namespace std;
bool isNum(char x)
{
return x >= '0' && x <= '9';
}
int main()
{
string str;
int sum = 0;
int num = 0;
bool neg = false;
cin >> str;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '-')
{
sum += neg ? num * -1 : num;
num = 0;
// cout << "sum: " << sum << "--\n";
neg = true;
}
else if (str[i] == '+')
{
sum += neg ? num * -1 : num;
num = 0;
// cout << "sum: " << sum << "--\n";
neg = false;
}
else if (isNum(str[i]))
{
num *= 10;
num += (int)(str[i] - '0');
// cout << "num: " << num << "\tneg:" << neg << "\n";
}
}
sum += neg ? num * -1 : num;
cout << sum << "\n";
return 0;
}
| 20.06
| 65
| 0.335992
|
mhilmyh
|
4d6e617024c9b39158f791aa408cfdb29b0b247b
| 10,909
|
cpp
|
C++
|
src/ace/ACE_wrappers/apps/JAWS/clients/Blobby/Blob_Handler.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | 8
|
2017-06-05T08:56:27.000Z
|
2020-04-08T16:50:11.000Z
|
src/ace/ACE_wrappers/apps/JAWS/clients/Blobby/Blob_Handler.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | null | null | null |
src/ace/ACE_wrappers/apps/JAWS/clients/Blobby/Blob_Handler.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | 17
|
2017-06-05T08:54:27.000Z
|
2021-08-29T14:19:12.000Z
|
#include "Blob_Handler.h"
#include "ace/OS_NS_stdio.h"
#include "ace/OS_NS_string.h"
#include "ace/OS_NS_strings.h"
// Empty constructor for compliance with new Connector behavior.
ACE_Blob_Handler::ACE_Blob_Handler (void)
{
}
// Always use this constructor
ACE_Blob_Handler::ACE_Blob_Handler (ACE_Message_Block * mb,
size_t length,
size_t offset,
ACE_TCHAR *filename) :
mb_ (mb),
length_ (length),
offset_ (offset),
filename_ (ACE_OS::strdup (filename)),
bytecount_ (0)
{
}
ACE_Blob_Handler::~ACE_Blob_Handler (void)
{
if (filename_)
{
ACE_OS::free ((void *) filename_);
filename_ = 0;
}
}
// Called by Connector after connection is established
int
ACE_Blob_Handler::open (void *)
{
if (this->send_request () != 0)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "ACE_Blob_Handler::open():send_request failed"), -1);
if (this->receive_reply () != 0)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "ACE_Blob_Handler::open():receive_reply failed"), -1);
return 0;
}
// No-op
int
ACE_Blob_Handler::close (u_long flags)
{
ACE_UNUSED_ARG (flags);
return 0;
}
// Always overridden by the derived classes
int
ACE_Blob_Handler::send_request (void)
{
return -1;
}
// Always overridden by the derived classes
int
ACE_Blob_Handler::receive_reply (void)
{
return -1;
}
// used to retrieve the number of bytes read/written by the
// last operation on the Blob
int
ACE_Blob_Handler::byte_count (void)
{
return bytecount_;
}
// Reader **************************************************
ACE_Blob_Reader::ACE_Blob_Reader (ACE_Message_Block * mb,
size_t length,
size_t offset,
ACE_TCHAR *filename,
const char *request_prefix,
const char *request_suffix) :
ACE_Blob_Handler (mb, length, offset, filename),
request_prefix_ (request_prefix),
request_suffix_ (request_suffix)
{
}
// Send the HTTP request
int
ACE_Blob_Reader::send_request (void)
{
char mesg [MAX_HEADER_SIZE];
// Check to see if the request is too big
if (MAX_HEADER_SIZE < (ACE_OS::strlen (request_prefix_)
+ ACE_OS::strlen (filename_)
+ ACE_OS::strlen (request_suffix_) + 4))
ACE_ERROR_RETURN((LM_ERROR,"Request too large!"), -1);
// Create a message to send to the server requesting retrieval of the file
int len = ACE_OS::sprintf (mesg, "%s %s %s",
request_prefix_,
ACE_TEXT_ALWAYS_CHAR (filename_),
request_suffix_);
// Send the message to server
if (peer ().send_n (mesg, len) != len)
ACE_ERROR_RETURN((LM_ERROR,"Error sending request"), -1);
return 0;
}
// Recieve the HTTP Reply
int
ACE_Blob_Reader::receive_reply (void)
{
ssize_t len;
char buf [MAX_HEADER_SIZE + 1];
char *buf_ptr;
size_t bytes_read = 0;
size_t bytes_left = this->length_;
size_t offset_left = this->offset_;
// Receive the first MAX_HEADER_SIZE bytes to be able to strip off the
// header. Note that we assume that the header will fit into the
// first MAX_HEADER_SIZE bytes of the transmitted data.
if ((len = peer ().recv_n (buf, MAX_HEADER_SIZE)) >= 0)
{
buf[len] = '\0';
// Search for the header termination string "\r\n\r\n", or "\n\n". If
// found, move past it to get to the data portion.
if ((buf_ptr = ACE_OS::strstr (buf,"\r\n\r\n")) != 0)
buf_ptr += 4;
else if ((buf_ptr = ACE_OS::strstr (buf, "\n\n")) != 0)
buf_ptr += 2;
else
buf_ptr = buf;
// Determine number of data bytes read. This is equal to the
// total bytes read minus number of header bytes.
bytes_read = (buf + len) - buf_ptr;
}
else
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "ACE_Blob_Reader::receiveReply():Error while reading header"), -1);
// ***************************************************************
// At this point, we have stripped off the header and are ready to
// process data. buf_ptr points to the data
// First adjust for offset. There are two cases:
// (1) The first block of data encountered the offset. In this case
// we simply increment the buf_ptr by offset.
// (2) The first block of data did not encounter the offset. That
// is, the offset needs to go past the number of data bytes already read.
if (bytes_read > offset_left)
{
// The first case is true -- that is offset is less than the
// data bytes we just read.
buf_ptr += offset_left;
// Determine how many data bytes are actually there. This is
// basically the total number of data bytes we read minus any
// offset we have.
size_t data_bytes = bytes_read - offset_left;
// Check for the case where the bytes read are enough to fulfill
// our request (for length bytes). If this is the case, then we
// don't need to do any extra recvs and can simply return with
// the data.
if (data_bytes >= bytes_left)
{
// The first block contains enough data to satisfy the
// length. So copy the data into the message buffer.
if (mb_->copy (buf_ptr, bytes_left) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n",
"ACE Blob_Reader::receiveReply():Error copying data into Message_Block"), -1);
bytecount_ = length_;
return 0;
}
// Copy over all the data bytes into our message buffer.
if (mb_->copy (buf_ptr, data_bytes) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n",
"ACE_Blob_Reader::receiveReply():Error copying data into Message_Block" ), -1);
// Adjust bytes left
bytes_left -= data_bytes;
// No more offset left. So set it to zero.
offset_left = 0;
}
else
{
// The second case is true -- that is offset is greater than
// the data bytes we just read.
offset_left -= bytes_read;
}
// If we ad any offset left, take care of that.
while (offset_left > 0)
{
// MAX_HEADER_SIZE in which case we should do a receive of
// offset bytes into a temporary buffer. Otherwise, we should
// receive MAX_HEADER_SIZE bytes into temporary buffer and
// decrement offset_left.
if (offset_left < (sizeof buf))
len = offset_left;
else
len = sizeof buf;
if (peer().recv_n (buf, len) != len)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n",
"ACE_Blob_Reader::receiveReply():Read error" ),
-1);
offset_left -= len;
}
// *****************************************************************
// At this point we are all set to receive the actual data which the
// user wants. We have made adjustments for offset and are ready to
// receive the actual data. Receive the data directly into the
// message buffer.
len = peer().recv_n (mb_->wr_ptr (), bytes_left);
if (len < 0 || static_cast<size_t> (len) != bytes_left)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n",
"ACE_Blob_Reader::receiveReply():Read error" ),
-1);
// Adjust the message buffer write pointer by number of bytes we
// received.
mb_->wr_ptr (len);
// Set the byte count to number of bytes received
this->bytecount_ = length_;
return 0;
}
// Writer **************************************************
ACE_Blob_Writer::ACE_Blob_Writer (ACE_Message_Block * mb,
size_t length,
size_t offset,
ACE_TCHAR *filename,
const char *request_prefix,
const char *request_suffix) :
ACE_Blob_Handler (mb, length, offset, filename),
request_prefix_ (request_prefix),
request_suffix_ (request_suffix)
{
}
int
ACE_Blob_Writer::send_request (void)
{
// Check for sanity -- check if we have any data to send.
if (offset_+ length_ > mb_->length ())
ACE_ERROR_RETURN((LM_ERROR, "%p\n",
"ACE_Blob_Writer::sendRequest():Invalid offset/length"), -1);
// Determine the length of the header message we will be sending to
// the server. Note that we add 32 for safety -- this corresponds to
// the number of bytes needed for the length field.
size_t mesglen =
ACE_OS::strlen (request_prefix_)
+ ACE_OS::strlen (filename_)
+ ACE_OS::strlen (request_suffix_)
+ 32; // safety
// Allocate a buffer to hold the header
char *mesg = 0;
ACE_NEW_RETURN (mesg, char [mesglen], -1);
// Create the header, store the actual length in mesglen.
mesglen = ACE_OS::sprintf (mesg, "%s /%s %s " ACE_SIZE_T_FORMAT_SPECIFIER_ASCII "\n\n",
request_prefix_, ACE_TEXT_ALWAYS_CHAR (filename_),
request_suffix_, length_);
// Send the header followed by the data
// First send the header
if (peer ().send_n (mesg, mesglen) == -1)
ACE_ERROR_RETURN((LM_ERROR, "%p\n", "Error sending request"), -1);
// "Consume" the offset by moving the read pointer of the message
// buffer
mb_->rd_ptr (offset_);
// Now send the data
if (peer ().send_n (mb_->rd_ptr (), length_) != (int)length_)
ACE_ERROR_RETURN((LM_ERROR, "%p\n", "Error sending file"), -1);
// Adjust the read pointer of the mesage buffer
mb_->rd_ptr (length_);
return 0;
}
int
ACE_Blob_Writer::receive_reply (void)
{
// Allocate a buffer big enough to hold the header
char buf[MAX_HEADER_SIZE];
// Receive the reply from the server
size_t num_recvd = 0;
ssize_t len = peer ().recv_n (buf, sizeof buf - 1, 0, &num_recvd); // reserve one byte to store the \0
if (len ==-1)
ACE_ERROR_RETURN((LM_ERROR, "%p\n", "Error reading header"), -1);
buf [num_recvd] = 0;
// Parse the header
char *lasts = 0;
// First check if this was a valid header -- HTTP/1.0
char *token = ACE_OS::strtok_r (buf, " \t", &lasts);
if ( (token == 0) || (ACE_OS::strcasecmp (token, "HTTP/1.0") != 0))
ACE_ERROR_RETURN((LM_ERROR, "%p\n", "Did not receive a HTTP/1.0 response"), -1);
// Get the return code.
int return_code = ACE_OS::atoi (ACE_OS::strtok_r (0, " \t", &lasts));
// Check if the transaction succeeded. The only success codes are in
// the range of 200-299 (HTTP specification).
if (return_code >= 200 && return_code < 300)
return 0;
else
{
// Something went wrong!
// Get the description from the header message of what went wrong.
char *description = ACE_OS::strtok_r (0, "\n\r", &lasts);
ACE_ERROR_RETURN((LM_ERROR, "%p\n", description), -1);
}
ACE_NOTREACHED(return 0);
}
| 31.62029
| 109
| 0.602713
|
wfnex
|
4d6eac15ee37d246dc7c92db6ee8cf1035e95de5
| 682
|
cpp
|
C++
|
demos/game_of_life/get_life_1_06.cpp
|
a-n-t-h-o-n-y/MCurses
|
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
|
[
"MIT"
] | 284
|
2017-11-07T10:06:48.000Z
|
2021-01-12T15:32:51.000Z
|
demos/game_of_life/get_life_1_06.cpp
|
a-n-t-h-o-n-y/MCurses
|
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
|
[
"MIT"
] | 38
|
2018-01-14T12:34:54.000Z
|
2020-09-26T15:32:43.000Z
|
demos/game_of_life/get_life_1_06.cpp
|
a-n-t-h-o-n-y/MCurses
|
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
|
[
"MIT"
] | 31
|
2017-11-30T11:22:21.000Z
|
2020-11-03T05:27:47.000Z
|
#include "get_life_1_06.hpp"
#include <fstream>
#include <string>
#include "coordinate.hpp"
#include "pattern.hpp"
namespace gol {
auto get_life_1_06(std::string const& filename) -> Pattern
{
auto file = std::ifstream{filename};
if (file.fail())
return {};
auto cells = Pattern::Cells{};
auto first_line = std::string{};
std::getline(file, first_line);
while (file) {
auto x = 0;
file >> x;
if (!file)
break;
auto y = 0;
file >> y;
if (!file.good())
break;
cells.push_back({x, y});
}
return {cells, parse_rule_string("B3/S23")};
}
} // namespace gol
| 19.485714
| 58
| 0.548387
|
a-n-t-h-o-n-y
|
4d6ef2f4ab020aa44724318655dc86a81342b6e5
| 150
|
cpp
|
C++
|
ace/OS_NS_dlfcn.cpp
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | 16
|
2015-05-11T04:33:44.000Z
|
2022-02-15T04:28:39.000Z
|
ace/OS_NS_dlfcn.cpp
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | null | null | null |
ace/OS_NS_dlfcn.cpp
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | 7
|
2015-01-08T16:11:34.000Z
|
2021-07-04T16:04:40.000Z
|
// $Id$
#include "ace/OS_NS_dlfcn.h"
#if !defined (ACE_HAS_INLINED_OSCALLS)
# include "ace/OS_NS_dlfcn.inl"
#endif /* ACE_HAS_INLINED_OSCALLS */
| 13.636364
| 38
| 0.72
|
BeiJiaan
|
4d6f5ab508b9e91fd3279b2ab2256a5bbd018544
| 5,424
|
cpp
|
C++
|
src/Magnum/MeshTools/Test/SubdivideRemoveDuplicatesBenchmark.cpp
|
Graphics-Physics-Libraries/magnum-games-and-data-visualization
|
a817f55d6ff0ef0510d93b310c2ba897e4de49ee
|
[
"MIT"
] | null | null | null |
src/Magnum/MeshTools/Test/SubdivideRemoveDuplicatesBenchmark.cpp
|
Graphics-Physics-Libraries/magnum-games-and-data-visualization
|
a817f55d6ff0ef0510d93b310c2ba897e4de49ee
|
[
"MIT"
] | null | null | null |
src/Magnum/MeshTools/Test/SubdivideRemoveDuplicatesBenchmark.cpp
|
Graphics-Physics-Libraries/magnum-games-and-data-visualization
|
a817f55d6ff0ef0510d93b310c2ba897e4de49ee
|
[
"MIT"
] | null | null | null |
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/Containers/GrowableArray.h>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/Utility/Algorithms.h>
#include "Magnum/Math/Vector4.h"
#include "Magnum/MeshTools/Duplicate.h"
#include "Magnum/MeshTools/RemoveDuplicates.h"
#include "Magnum/MeshTools/Subdivide.h"
#include "Magnum/Primitives/Icosphere.h"
#include "Magnum/Trade/MeshData.h"
namespace Magnum { namespace MeshTools { namespace Test { namespace {
struct SubdivideRemoveDuplicatesBenchmark: TestSuite::Tester {
explicit SubdivideRemoveDuplicatesBenchmark();
void subdivide();
void subdivideAndRemoveDuplicatesAfter();
void subdivideAndRemoveDuplicatesAfterInPlace();
void subdivideAndRemoveDuplicatesInBetween();
};
SubdivideRemoveDuplicatesBenchmark::SubdivideRemoveDuplicatesBenchmark() {
addBenchmarks({&SubdivideRemoveDuplicatesBenchmark::subdivide,
&SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesAfter,
&SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesAfterInPlace,
&SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesInBetween}, 4);
}
namespace {
static Vector3 interpolator(const Vector3& a, const Vector3& b) {
return (a+b).normalized();
}
}
void SubdivideRemoveDuplicatesBenchmark::subdivide() {
Trade::MeshData icosphere = Primitives::icosphereSolid(0);
CORRADE_BENCHMARK(3) {
Containers::Array<UnsignedInt> indices;
arrayResize(indices, Containers::NoInit, icosphere.indexCount());
Utility::copy(icosphere.indices<UnsignedInt>(), indices);
Containers::Array<Vector3> positions;
arrayResize(positions, Containers::NoInit, icosphere.vertexCount());
Utility::copy(icosphere.attribute<Vector3>(Trade::MeshAttribute::Position), positions);
/* Subdivide 5 times */
for(std::size_t i = 0; i != 5; ++i)
MeshTools::subdivide(indices, positions, interpolator);
}
}
void SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesAfter() {
Trade::MeshData icosphere = Primitives::icosphereSolid(0);
CORRADE_BENCHMARK(3) {
Containers::Array<UnsignedInt> indices;
arrayResize(indices, Containers::NoInit, icosphere.indexCount());
Utility::copy(icosphere.indices<UnsignedInt>(), indices);
Containers::Array<Vector3> positions;
arrayResize(positions, Containers::NoInit, icosphere.vertexCount());
Utility::copy(icosphere.attribute<Vector3>(Trade::MeshAttribute::Position), positions);
/* Subdivide 5 times */
for(std::size_t i = 0; i != 5; ++i)
MeshTools::subdivide(indices, positions, interpolator);
/* Remove duplicates after */
arrayResize(positions, MeshTools::removeDuplicatesIndexedInPlace(
stridedArrayView(indices), stridedArrayView(positions)));
}
}
void SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesAfterInPlace() {
CORRADE_BENCHMARK(3) {
/* Because that's what this thing does */
Trade::MeshData icosphere = Primitives::icosphereSolid(5);
}
}
void SubdivideRemoveDuplicatesBenchmark::subdivideAndRemoveDuplicatesInBetween() {
Trade::MeshData icosphere = Primitives::icosphereSolid(0);
CORRADE_BENCHMARK(3) {
Containers::Array<UnsignedInt> indices;
arrayResize(indices, Containers::NoInit, icosphere.indexCount());
Utility::copy(icosphere.indices<UnsignedInt>(), indices);
Containers::Array<Vector3> positions;
arrayResize(positions, Containers::NoInit, icosphere.vertexCount());
Utility::copy(icosphere.attribute<Vector3>(Trade::MeshAttribute::Position), positions);
/* Subdivide 5 times and remove duplicates during the operation */
for(std::size_t i = 0; i != 5; ++i) {
MeshTools::subdivide(indices, positions, interpolator);
arrayResize(positions, MeshTools::removeDuplicatesIndexedInPlace(
stridedArrayView(indices), stridedArrayView(positions)));
}
}
}
}}}}
CORRADE_TEST_MAIN(Magnum::MeshTools::Test::SubdivideRemoveDuplicatesBenchmark)
| 40.781955
| 99
| 0.722529
|
Graphics-Physics-Libraries
|
4d7486d172f08aa5b6a4322a5aed68011e24833e
| 766
|
cpp
|
C++
|
C++/lengthOfLongestSubstring.cpp
|
colorfulberry/LeetCode
|
a4103a63d2969e8819447685f42423cd22fed2ff
|
[
"MIT"
] | 2
|
2020-04-08T17:57:43.000Z
|
2021-11-07T09:11:51.000Z
|
C++/lengthOfLongestSubstring.cpp
|
colorfulberry/LeetCode
|
a4103a63d2969e8819447685f42423cd22fed2ff
|
[
"MIT"
] | null | null | null |
C++/lengthOfLongestSubstring.cpp
|
colorfulberry/LeetCode
|
a4103a63d2969e8819447685f42423cd22fed2ff
|
[
"MIT"
] | 8
|
2018-03-13T18:20:26.000Z
|
2022-03-09T19:48:11.000Z
|
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> last(26, -1);
int start = 0;
int ans = 0;
for(int i = 0; i < s.size(); ++i) {
if(last[s[i] - 'a'] >= start) { // meet a repeated character
ans = max(i - start, ans); // recount max length of substring
start = last[s[i] - 'a'] + 1; // update start index next to the repeated one
}
last[s[i] - 'a'] = i; // update last index
}
return max(static_cast<int>(s.size()) - start, ans); // recount max length of substring due to end
}
};
| 34.818182
| 110
| 0.462141
|
colorfulberry
|
4d7a143cd5adac6653ab63b68221b4be6add2a3f
| 1,954
|
cpp
|
C++
|
LuoguCodes/P2568.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/P2568.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/P2568.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
// luogu-judger-enable-o2
// luogu-judger-enable-o2
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define fn "2818"
#define ll long long
#define int long long
#define pc(x) putchar(x)
#define fileIn freopen("testdata.in", "r", stdin)
#define fileOut freopen("testdata.out", "w", stdout)
#define rep(i, a, b) for (register int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#ifdef yyfLocal
#define dbg(x) std::clog << #x" = " << (x) << std::endl
#define logs(x) std::clog << (x) << std::endl
#else
#define dbg(x) 42
#define logs(x) 42
#endif
int read() {
int res = 0, flag = 1; char ch = getchar();
while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); }
while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar();
return res * flag;
}
void print(int x) {
if (x < 0) putchar(';-';), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + 48);
}
const int N = 10000000 + 5;
int n, p = 0, ans = 0, prime[N >> 2], phi[N];
bool v[N];
void solution() {
n = read();
rep(i, 2, n) {
if (!v[i]) prime[++p] = i, phi[i] = i - 1;
for (int j = 1; j <= p && prime[j] * i <= n; ++j) {
v[i * prime[j]] = true;
if (!(i % prime[j])) {
phi[i * prime[j]] = phi[i] * prime[j];
break;
}
phi[i * prime[j]] = phi[i] * (prime[j] - 1);
}
}
rep(i, 3, n) phi[i] += phi[i - 1];
rep(i, 1, p) ans += phi[n / prime[i]];
print((ans << 1) + p), puts("");
}
signed main() {
#ifdef yyfLocal
fileIn;
// fileOut;
#else
#ifndef ONLINE_JUDGE
freopen(fn".in", "r", stdin);
freopen(fn".out", "w", stdout);
#endif
#endif
logs("2818.exe");
solution();
return 0;
}
| 24.123457
| 72
| 0.520983
|
Anguei
|
4d7a53e6253cd1f694f58516275d426e8cb95458
| 42,863
|
cxx
|
C++
|
GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx
|
chengtt0406/AliRoot
|
c1d89b133b433f608b2373112d3608d8cec26095
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx
|
chengtt0406/AliRoot
|
c1d89b133b433f608b2373112d3608d8cec26095
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx
|
chengtt0406/AliRoot
|
c1d89b133b433f608b2373112d3608d8cec26095
|
[
"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 Project *\
//* ALICE Experiment at CERN, All rights reserved. *\
//* *\
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\
//* for The ALICE HLT Project. *\
//* *\
//* 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. *\
//**************************************************************************
/// \file GPUChainTrackingClusterizer.cxx
/// \author David Rohr
#include "GPUChainTracking.h"
#include "GPUChainTrackingDefs.h"
#include "GPULogging.h"
#include "GPUO2DataTypes.h"
#include "GPUMemorySizeScalers.h"
#include "GPUTrackingInputProvider.h"
#include <fstream>
#ifdef GPUCA_O2_LIB
#include "CommonDataFormat/InteractionRecord.h"
#endif
#ifdef HAVE_O2HEADERS
#include "GPUHostDataTypes.h"
#include "GPUTPCCFChainContext.h"
#include "GPURawData.h"
#include "DataFormatsTPC/ZeroSuppression.h"
#include "DetectorsRaw/RDHUtils.h"
#include "DataFormatsTPC/Digit.h"
#include "DataFormatsTPC/Constants.h"
#else
#include "GPUO2FakeClasses.h"
#endif
#include "utils/strtag.h"
#ifndef GPUCA_NO_VC
#include <Vc/Vc>
#endif
using namespace GPUCA_NAMESPACE::gpu;
using namespace o2::tpc;
using namespace o2::tpc::constants;
using namespace o2::dataformats;
#ifdef GPUCA_TPC_GEOMETRY_O2
std::pair<unsigned int, unsigned int> GPUChainTracking::TPCClusterizerDecodeZSCountUpdate(unsigned int iSlice, const CfFragment& fragment)
{
bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder::ZSOffset* o = processors()->tpcClusterer[iSlice].mPzsOffsets;
unsigned int digits = 0;
unsigned int pages = 0;
for (unsigned short j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
clusterer.mMinMaxCN[j] = mCFContext->fragmentData[fragment.index].minMaxCN[iSlice][j];
if (doGPU) {
unsigned short posInEndpoint = 0;
unsigned short pagesEndpoint = 0;
for (unsigned int k = clusterer.mMinMaxCN[j].minC; k < clusterer.mMinMaxCN[j].maxC; k++) {
const unsigned int minL = (k == clusterer.mMinMaxCN[j].minC) ? clusterer.mMinMaxCN[j].minN : 0;
const unsigned int maxL = (k + 1 == clusterer.mMinMaxCN[j].maxC) ? clusterer.mMinMaxCN[j].maxN : mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k];
for (unsigned int l = minL; l < maxL; l++) {
unsigned short pageDigits = mCFContext->fragmentData[fragment.index].pageDigits[iSlice][j][posInEndpoint++];
if (pageDigits) {
*(o++) = GPUTPCClusterFinder::ZSOffset{digits, j, pagesEndpoint};
digits += pageDigits;
}
pagesEndpoint++;
}
}
if (pagesEndpoint != mCFContext->fragmentData[fragment.index].pageDigits[iSlice][j].size()) {
GPUFatal("TPC raw page count mismatch in TPCClusterizerDecodeZSCountUpdate: expected %d / buffered %lu", pagesEndpoint, mCFContext->fragmentData[fragment.index].pageDigits[iSlice][j].size());
}
} else {
clusterer.mPzsOffsets[j] = GPUTPCClusterFinder::ZSOffset{digits, j, 0};
digits += mCFContext->fragmentData[fragment.index].nDigits[iSlice][j];
pages += mCFContext->fragmentData[fragment.index].nPages[iSlice][j];
}
}
if (doGPU) {
pages = o - processors()->tpcClusterer[iSlice].mPzsOffsets;
}
return {digits, pages};
}
std::pair<unsigned int, unsigned int> GPUChainTracking::TPCClusterizerDecodeZSCount(unsigned int iSlice, const CfFragment& fragment)
{
mRec->getGeneralStepTimer(GeneralStep::Prepare).Start();
unsigned int nDigits = 0;
unsigned int nPages = 0;
bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding;
int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0;
for (unsigned short j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 3 && j < GPUTrackingInOutZS::NENDPOINTS - 1) {
for (unsigned int k = 0; k < mIOPtrs.tpcZS->slice[iSlice].count[j + 1]; k++) {
for (unsigned int l = 0; l < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j + 1][k]; l++) {
Vc::Common::prefetchMid(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchMid(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU));
}
}
}
#endif
std::vector<std::pair<CfFragment, std::array<int, 5>>> fragments;
fragments.reserve(mCFContext->nFragments);
fragments.emplace_back(std::pair<CfFragment, std::array<int, 5>>{fragment, {0, 0, 0, 0, 0}});
for (unsigned int i = 1; i < mCFContext->nFragments; i++) {
fragments.emplace_back(std::pair<CfFragment, std::array<int, 5>>{fragments.back().first.next(), {0, 0, 0, 0, 0}});
}
unsigned int emptyPages = 0;
unsigned int firstPossibleFragment = 0;
for (unsigned int k = 0; k < mIOPtrs.tpcZS->slice[iSlice].count[j]; k++) {
nPages += mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k];
for (unsigned int l = 0; l < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]; l++) {
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 2 && l + 1 < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]) {
Vc::Common::prefetchForOneRead(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchForOneRead(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU));
}
#endif
const unsigned char* const page = ((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE;
const RAWDataHeaderGPU* rdh = (const RAWDataHeaderGPU*)page;
if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(RAWDataHeaderGPU)) {
emptyPages++;
continue;
}
const TPCZSHDR* const hdr = (const TPCZSHDR*)(page + sizeof(RAWDataHeaderGPU));
nDigits += hdr->nADCsamples;
unsigned int timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN;
if (timeBin + hdr->nTimeBins > mCFContext->tpcMaxTimeBin) {
mCFContext->tpcMaxTimeBin = timeBin + hdr->nTimeBins;
}
for (unsigned int f = firstPossibleFragment; f < mCFContext->nFragments; f++) {
if (timeBin < (unsigned int)fragments[f].first.last()) {
if ((unsigned int)fragments[f].first.first() <= timeBin + hdr->nTimeBins) {
fragments[f].second[2] = k + 1;
fragments[f].second[3] = l + 1;
if (!fragments[f].second[4]) {
fragments[f].second[4] = 1;
fragments[f].second[0] = k;
fragments[f].second[1] = l;
} else if (emptyPages) {
mCFContext->fragmentData[f].nPages[iSlice][j] += emptyPages;
for (unsigned int m = 0; m < emptyPages; m++) {
mCFContext->fragmentData[f].pageDigits[iSlice][j].emplace_back(0);
}
}
mCFContext->fragmentData[f].nPages[iSlice][j]++;
mCFContext->fragmentData[f].nDigits[iSlice][j] += hdr->nADCsamples;
if (doGPU) {
mCFContext->fragmentData[f].pageDigits[iSlice][j].emplace_back(hdr->nADCsamples);
}
}
} else {
firstPossibleFragment = f + 1;
}
}
emptyPages = 0;
}
}
for (unsigned int f = 0; f < mCFContext->nFragments; f++) {
mCFContext->fragmentData[f].minMaxCN[iSlice][j].maxC = fragments[f].second[2];
mCFContext->fragmentData[f].minMaxCN[iSlice][j].minC = fragments[f].second[0];
mCFContext->fragmentData[f].minMaxCN[iSlice][j].maxN = fragments[f].second[3];
mCFContext->fragmentData[f].minMaxCN[iSlice][j].minN = fragments[f].second[1];
}
}
mCFContext->nPagesTotal += nPages;
mCFContext->nPagesSector[iSlice] = nPages;
mCFContext->nPagesSectorMax = std::max(mCFContext->nPagesSectorMax, nPages);
unsigned int digitsFragment = 0;
for (unsigned int i = 0; i < mCFContext->nFragments; i++) {
unsigned int pages = 0;
unsigned int digits = 0;
for (unsigned short j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
pages += mCFContext->fragmentData[i].nPages[iSlice][j];
digits += mCFContext->fragmentData[i].nDigits[iSlice][j];
}
mCFContext->nPagesFragmentMax = std::max(mCFContext->nPagesSectorMax, pages);
digitsFragment = std::max(digitsFragment, digits);
}
mRec->getGeneralStepTimer(GeneralStep::Prepare).Stop();
return {nDigits, digitsFragment};
}
void GPUChainTracking::RunTPCClusterizer_compactPeaks(GPUTPCClusterFinder& clusterer, GPUTPCClusterFinder& clustererShadow, int stage, bool doGPU, int lane)
{
auto& in = stage ? clustererShadow.mPpeakPositions : clustererShadow.mPpositions;
auto& out = stage ? clustererShadow.mPfilteredPeakPositions : clustererShadow.mPpeakPositions;
if (doGPU) {
const unsigned int iSlice = clusterer.mISlice;
auto& count = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
std::vector<size_t> counts;
unsigned int nSteps = clusterer.getNSteps(count);
if (nSteps > clusterer.mNBufs) {
GPUError("Clusterer buffers exceeded (%u > %u)", nSteps, (int)clusterer.mNBufs);
exit(1);
}
size_t tmpCount = count;
if (nSteps > 1) {
for (unsigned int i = 1; i < nSteps; i++) {
counts.push_back(tmpCount);
if (i == 1) {
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanStart>(GetGrid(tmpCount, clusterer.mScanWorkGroupSize, lane), {iSlice}, {}, i, stage);
} else {
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanUp>(GetGrid(tmpCount, clusterer.mScanWorkGroupSize, lane), {iSlice}, {}, i, tmpCount);
}
tmpCount = (tmpCount + clusterer.mScanWorkGroupSize - 1) / clusterer.mScanWorkGroupSize;
}
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanTop>(GetGrid(tmpCount, clusterer.mScanWorkGroupSize, lane), {iSlice}, {}, nSteps, tmpCount);
for (unsigned int i = nSteps - 1; i > 1; i--) {
tmpCount = counts[i - 1];
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanDown>(GetGrid(tmpCount - clusterer.mScanWorkGroupSize, clusterer.mScanWorkGroupSize, lane), {iSlice}, {}, i, clusterer.mScanWorkGroupSize, tmpCount);
}
}
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::compactDigits>(GetGrid(count, clusterer.mScanWorkGroupSize, lane), {iSlice}, {}, 1, stage, in, out);
} else {
auto& nOut = stage ? clusterer.mPmemory->counters.nClusters : clusterer.mPmemory->counters.nPeaks;
auto& nIn = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
size_t count = 0;
for (size_t i = 0; i < nIn; i++) {
if (clusterer.mPisPeak[i]) {
out[count++] = in[i];
}
}
nOut = count;
}
}
std::pair<unsigned int, unsigned int> GPUChainTracking::RunTPCClusterizer_transferZS(int iSlice, const CfFragment& fragment, int lane)
{
bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
const auto& retVal = TPCClusterizerDecodeZSCountUpdate(iSlice, fragment);
if (doGPU) {
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
unsigned int nPagesSector = 0;
for (unsigned int j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
unsigned int nPages = 0;
mInputsHost->mPzsMeta->slice[iSlice].zsPtr[j] = &mInputsShadow->mPzsPtrs[iSlice * GPUTrackingInOutZS::NENDPOINTS + j];
mInputsHost->mPzsPtrs[iSlice * GPUTrackingInOutZS::NENDPOINTS + j] = clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE;
for (unsigned int k = clusterer.mMinMaxCN[j].minC; k < clusterer.mMinMaxCN[j].maxC; k++) {
const unsigned int min = (k == clusterer.mMinMaxCN[j].minC) ? clusterer.mMinMaxCN[j].minN : 0;
const unsigned int max = (k + 1 == clusterer.mMinMaxCN[j].maxC) ? clusterer.mMinMaxCN[j].maxN : mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k];
if (max > min) {
char* src = (char*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[j][k] + min * TPCZSHDR::TPC_ZS_PAGE_SIZE;
size_t size = o2::raw::RDHUtils::getMemorySize(*(const RAWDataHeaderGPU*)src);
size = (max - min - 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + (size ? TPCZSHDR::TPC_ZS_PAGE_SIZE : size);
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE, src, size, lane, true);
}
nPages += max - min;
}
mInputsHost->mPzsMeta->slice[iSlice].nZSPtr[j] = &mInputsShadow->mPzsSizes[iSlice * GPUTrackingInOutZS::NENDPOINTS + j];
mInputsHost->mPzsSizes[iSlice * GPUTrackingInOutZS::NENDPOINTS + j] = nPages;
mInputsHost->mPzsMeta->slice[iSlice].count[j] = 1;
nPagesSector += nPages;
}
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzsOffsets, clusterer.mPzsOffsets, clusterer.mNMaxPages * sizeof(*clusterer.mPzsOffsets), lane, true);
}
return retVal;
}
int GPUChainTracking::RunTPCClusterizer_prepare(bool restorePointers)
{
if (restorePointers) {
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
processors()->tpcClusterer[iSlice].mPzsOffsets = mCFContext->ptrSave[iSlice].zsOffsetHost;
processorsShadow()->tpcClusterer[iSlice].mPzsOffsets = mCFContext->ptrSave[iSlice].zsOffsetDevice;
processorsShadow()->tpcClusterer[iSlice].mPzs = mCFContext->ptrSave[iSlice].zsDevice;
}
processorsShadow()->ioPtrs.clustersNative = mCFContext->ptrClusterNativeSave;
return 0;
}
const auto& threadContext = GetThreadContext();
mRec->MemoryScalers()->nTPCdigits = 0;
if (mCFContext == nullptr) {
mCFContext.reset(new GPUTPCCFChainContext);
}
mCFContext->tpcMaxTimeBin = param().par.ContinuousTracking ? std::max<int>(param().par.continuousMaxTimeBin, TPC_MAX_FRAGMENT_LEN) : TPC_MAX_TIME_BIN_TRIGGERED;
const CfFragment fragmentMax{(tpccf::TPCTime)mCFContext->tpcMaxTimeBin + 1, TPC_MAX_FRAGMENT_LEN};
mCFContext->prepare(mIOPtrs.tpcZS, fragmentMax);
if (mIOPtrs.tpcZS) {
unsigned int nDigitsFragment[NSLICES];
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
if (mIOPtrs.tpcZS->slice[iSlice].count[0]) {
const void* rdh = mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0];
if (rdh && o2::raw::RDHUtils::getVersion<o2::gpu::RAWDataHeaderGPU>() != o2::raw::RDHUtils::getVersion(rdh)) {
GPUError("Data has invalid RDH version %d, %d required\n", o2::raw::RDHUtils::getVersion(rdh), o2::raw::RDHUtils::getVersion<o2::gpu::RAWDataHeaderGPU>());
return 1;
}
}
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 1 && iSlice < NSLICES - 1) {
for (unsigned int j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
for (unsigned int k = 0; k < mIOPtrs.tpcZS->slice[iSlice].count[j]; k++) {
for (unsigned int l = 0; l < mIOPtrs.tpcZS->slice[iSlice].nZSPtr[j][k]; l++) {
Vc::Common::prefetchFar(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchFar(((const unsigned char*)mIOPtrs.tpcZS->slice[iSlice + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(RAWDataHeaderGPU));
}
}
}
}
#endif
const auto& x = TPCClusterizerDecodeZSCount(iSlice, fragmentMax);
nDigitsFragment[iSlice] = x.second;
processors()->tpcClusterer[iSlice].mPmemory->counters.nDigits = x.first;
mRec->MemoryScalers()->nTPCdigits += x.first;
}
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
processors()->tpcClusterer[iSlice].SetNMaxDigits(processors()->tpcClusterer[iSlice].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsFragment[iSlice]);
if (mRec->IsGPU()) {
processorsShadow()->tpcClusterer[iSlice].SetNMaxDigits(processors()->tpcClusterer[iSlice].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsFragment[iSlice]);
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSlice].mZSOffsetId, mRec);
mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSlice].mZSId, mRec);
} else {
AllocateRegisteredMemory(processors()->tpcClusterer[iSlice].mZSOffsetId);
AllocateRegisteredMemory(processors()->tpcClusterer[iSlice].mZSId);
}
}
} else {
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
unsigned int nDigits = mIOPtrs.tpcPackedDigits->nTPCDigits[iSlice];
mRec->MemoryScalers()->nTPCdigits += nDigits;
processors()->tpcClusterer[iSlice].SetNMaxDigits(nDigits, mCFContext->nPagesFragmentMax, nDigits);
}
}
if (mIOPtrs.tpcZS) {
GPUInfo("Event has %u 8kb TPC ZS pages, %lld digits", mCFContext->nPagesTotal, (long long int)mRec->MemoryScalers()->nTPCdigits);
} else {
GPUInfo("Event has %lld TPC Digits", (long long int)mRec->MemoryScalers()->nTPCdigits);
}
mCFContext->fragmentFirst = CfFragment{std::max<int>(mCFContext->tpcMaxTimeBin + 1, TPC_MAX_FRAGMENT_LEN), TPC_MAX_FRAGMENT_LEN};
for (int iSlice = 0; iSlice < GetProcessingSettings().nTPCClustererLanes && iSlice < NSLICES; iSlice++) {
if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSlice]) {
mCFContext->nextPos[iSlice] = RunTPCClusterizer_transferZS(iSlice, mCFContext->fragmentFirst, GetProcessingSettings().nTPCClustererLanes + iSlice);
}
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
mCFContext->ptrSave[iSlice].zsOffsetHost = processors()->tpcClusterer[iSlice].mPzsOffsets;
mCFContext->ptrSave[iSlice].zsOffsetDevice = processorsShadow()->tpcClusterer[iSlice].mPzsOffsets;
mCFContext->ptrSave[iSlice].zsDevice = processorsShadow()->tpcClusterer[iSlice].mPzs;
}
}
return 0;
}
#endif
int GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput)
{
if (param().rec.fwdTPCDigitsAsClusters) {
return ForwardTPCDigits();
}
#ifdef GPUCA_TPC_GEOMETRY_O2
mRec->PushNonPersistentMemory(qStr2Tag("TPCCLUST"));
const auto& threadContext = GetThreadContext();
bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
if (RunTPCClusterizer_prepare(mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer)) {
return 1;
}
if (GetProcessingSettings().ompAutoNThreads && !mRec->IsGPU()) {
mRec->SetNOMPThreads(mRec->MemoryScalers()->nTPCdigits / 20000);
}
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
processors()->tpcClusterer[iSlice].SetMaxData(mIOPtrs); // First iteration to set data sizes
}
mRec->ComputeReuseMax(nullptr); // Resolve maximums for shared buffers
for (unsigned int iSlice = 0; iSlice < NSLICES; iSlice++) {
SetupGPUProcessor(&processors()->tpcClusterer[iSlice], true); // Now we allocate
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
RunTPCClusterizer_prepare(true); // Restore some pointers, allocated by the other pipeline, and set to 0 by SetupGPUProcessor (since not allocated in this pipeline)
}
if (doGPU && mIOPtrs.tpcZS) {
processorsShadow()->ioPtrs.tpcZS = mInputsShadow->mPzsMeta;
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), mRec->NStreams() - 1);
}
if (doGPU) {
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)processors()->tpcClusterer - (char*)processors(), processorsShadow()->tpcClusterer, sizeof(GPUTPCClusterFinder) * NSLICES, mRec->NStreams() - 1, &mEvents->init);
}
size_t nClsTotal = 0;
ClusterNativeAccess* tmpNative = mClusterNativeAccess.get();
// setup MC Labels
bool propagateMCLabels = GetProcessingSettings().runMC && processors()->ioPtrs.tpcPackedDigits && processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC;
auto* digitsMC = propagateMCLabels ? processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC : nullptr;
if (param().par.continuousMaxTimeBin > 0 && mCFContext->tpcMaxTimeBin >= (unsigned int)std::max(param().par.continuousMaxTimeBin + 1, TPC_MAX_FRAGMENT_LEN)) {
GPUError("Input data has invalid time bin %u > %d\n", mCFContext->tpcMaxTimeBin, std::max(param().par.continuousMaxTimeBin + 1, TPC_MAX_FRAGMENT_LEN));
return 1;
}
bool buildNativeGPU = (mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCConversion) || (mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCSliceTracking) || (mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCMerging) || (mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCCompression);
bool buildNativeHost = mRec->GetRecoStepsOutputs() & GPUDataTypes::InOutType::TPCClusters; // TODO: Should do this also when clusters are needed for later steps on the host but not requested as output
mRec->MemoryScalers()->nTPCHits = mRec->MemoryScalers()->NTPCClusters(mRec->MemoryScalers()->nTPCdigits);
mInputsHost->mNClusterNative = mInputsShadow->mNClusterNative = mRec->MemoryScalers()->nTPCHits;
if (buildNativeGPU) {
AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeBuffer);
}
if (buildNativeHost && !(buildNativeGPU && GetProcessingSettings().delayedOutput)) {
AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeOutput, mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
}
GPUTPCLinearLabels mcLinearLabels;
if (propagateMCLabels) {
// No need to overallocate here, nTPCHits is anyway an upper bound used for the GPU cluster buffer, and we can always enlarge the buffer anyway
mcLinearLabels.header.reserve(mRec->MemoryScalers()->nTPCHits / 2);
mcLinearLabels.data.reserve(mRec->MemoryScalers()->nTPCHits);
}
char transferRunning[NSLICES] = {0};
unsigned int outputQueueStart = mOutputQueue.size();
for (unsigned int iSliceBase = 0; iSliceBase < NSLICES; iSliceBase += GetProcessingSettings().nTPCClustererLanes) {
std::vector<bool> laneHasData(GetProcessingSettings().nTPCClustererLanes, false);
for (CfFragment fragment = mCFContext->fragmentFirst; !fragment.isEnd(); fragment = fragment.next()) {
if (GetProcessingSettings().debugLevel >= 3) {
GPUInfo("Processing time bins [%d, %d) for sectors %d to %d", fragment.start, fragment.last(), iSliceBase, iSliceBase + GetProcessingSettings().nTPCClustererLanes - 1);
}
for (int lane = 0; lane < GetProcessingSettings().nTPCClustererLanes && iSliceBase + lane < NSLICES; lane++) {
if (fragment.index != 0) {
SynchronizeStream(lane); // Don't overwrite charge map from previous iteration until cluster computation is finished
}
unsigned int iSlice = iSliceBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
clusterer.mPmemory->counters.nPeaks = clusterer.mPmemory->counters.nClusters = 0;
clusterer.mPmemory->fragment = fragment;
if (propagateMCLabels && fragment.index == 0) {
clusterer.PrepareMC();
clusterer.mPinputLabels = digitsMC->v[iSlice];
// TODO: Why is the number of header entries in truth container
// sometimes larger than the number of digits?
assert(clusterer.mPinputLabels->getIndexedSize() >= mIOPtrs.tpcPackedDigits->nTPCDigits[iSlice]);
}
if (mIOPtrs.tpcPackedDigits) {
bool setDigitsOnGPU = doGPU && not mIOPtrs.tpcZS;
bool setDigitsOnHost = (not doGPU && not mIOPtrs.tpcZS) || propagateMCLabels;
auto* inDigits = mIOPtrs.tpcPackedDigits;
size_t numDigits = inDigits->nTPCDigits[iSlice];
if (setDigitsOnGPU) {
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPdigits, inDigits->tpcDigits[iSlice], sizeof(clustererShadow.mPdigits[0]) * numDigits, lane, true);
clusterer.mPmemory->counters.nDigits = numDigits;
} else if (setDigitsOnHost) {
clusterer.mPdigits = const_cast<o2::tpc::Digit*>(inDigits->tpcDigits[iSlice]); // TODO: Needs fixing (invalid const cast)
clusterer.mPmemory->counters.nDigits = numDigits;
}
}
if (mIOPtrs.tpcZS) {
if (mCFContext->nPagesSector[iSlice]) {
clusterer.mPmemory->counters.nPositions = mCFContext->nextPos[iSlice].first;
clusterer.mPmemory->counters.nPagesSubslice = mCFContext->nextPos[iSlice].second;
} else {
clusterer.mPmemory->counters.nPositions = clusterer.mPmemory->counters.nPagesSubslice = 0;
}
}
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
using ChargeMapType = decltype(*clustererShadow.mPchargeMap);
using PeakMapType = decltype(*clustererShadow.mPpeakMap);
runKernel<GPUMemClean16>(GetGridAutoStep(lane, RecoStep::TPCClusterFinding), krnlRunRangeNone, {}, clustererShadow.mPchargeMap, TPCMapMemoryLayout<ChargeMapType>::items() * sizeof(ChargeMapType));
runKernel<GPUMemClean16>(GetGridAutoStep(lane, RecoStep::TPCClusterFinding), krnlRunRangeNone, {}, clustererShadow.mPpeakMap, TPCMapMemoryLayout<PeakMapType>::items() * sizeof(PeakMapType));
if (fragment.index == 0) {
using HasLostBaselineType = decltype(*clustererShadow.mPpadHasLostBaseline);
runKernel<GPUMemClean16>(GetGridAutoStep(lane, RecoStep::TPCClusterFinding), krnlRunRangeNone, {}, clustererShadow.mPpadHasLostBaseline, TPC_PADS_IN_SECTOR * sizeof(HasLostBaselineType));
}
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Zeroed Charges");
if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSlice]) {
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, mInputsHost->mResourceZS, lane);
SynchronizeStream(GetProcessingSettings().nTPCClustererLanes + lane);
}
SynchronizeStream(mRec->NStreams() - 1); // Wait for copying to constant memory
if (mIOPtrs.tpcZS && !mCFContext->nPagesSector[iSlice]) {
continue;
}
if (not mIOPtrs.tpcZS) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>(GetGrid(1, lane), {iSlice}, {}, mIOPtrs.tpcZS == nullptr);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
} else if (propagateMCLabels) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>(GetGrid(1, lane, GPUReconstruction::krnlDeviceType::CPU), {iSlice}, {}, mIOPtrs.tpcZS == nullptr);
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
}
if (mIOPtrs.tpcZS) {
int firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : (mIOPtrs.tpcZS->slice[iSlice].count[0] && mIOPtrs.tpcZS->slice[iSlice].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const RAWDataHeaderGPU*)mIOPtrs.tpcZS->slice[iSlice].zsPtr[0][0]) : 0;
runKernel<GPUTPCCFDecodeZS, GPUTPCCFDecodeZS::decodeZS>(GetGridBlk(doGPU ? clusterer.mPmemory->counters.nPagesSubslice : GPUTrackingInOutZS::NENDPOINTS, lane), {iSlice}, {}, firstHBF);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
}
}
for (int lane = 0; lane < GetProcessingSettings().nTPCClustererLanes && iSliceBase + lane < NSLICES; lane++) {
unsigned int iSlice = iSliceBase + lane;
SynchronizeStream(lane);
if (mIOPtrs.tpcZS) {
CfFragment f = fragment.next();
int nextSlice = iSlice;
if (f.isEnd()) {
nextSlice += GetProcessingSettings().nTPCClustererLanes;
f = mCFContext->fragmentFirst;
}
if (nextSlice < NSLICES && mIOPtrs.tpcZS && mCFContext->nPagesSector[nextSlice]) {
mCFContext->nextPos[nextSlice] = RunTPCClusterizer_transferZS(nextSlice, f, GetProcessingSettings().nTPCClustererLanes + lane);
}
}
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
if (clusterer.mPmemory->counters.nPositions == 0) {
continue;
}
if (!mIOPtrs.tpcZS) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillFromDigits>(GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSlice}, {});
}
if (DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpDigits, *mDebugFile)) {
clusterer.DumpChargeMap(*mDebugFile, "Charges");
}
if (propagateMCLabels) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillIndexMap>(GetGrid(clusterer.mPmemory->counters.nDigitsInFragment, lane, GPUReconstruction::krnlDeviceType::CPU), {iSlice}, {});
}
bool checkForNoisyPads = (rec()->GetParam().rec.maxTimeBinAboveThresholdIn1000Bin > 0) || (rec()->GetParam().rec.maxConsecTimeBinAboveThreshold > 0);
checkForNoisyPads &= (rec()->GetParam().rec.noisyPadsQuickCheck ? fragment.index == 0 : true);
if (checkForNoisyPads) {
int nBlocks = TPC_PADS_IN_SECTOR / GPUTPCCFCheckPadBaseline::PadsPerCacheline;
runKernel<GPUTPCCFCheckPadBaseline>(GetGridBlk(nBlocks, lane), {iSlice}, {});
}
runKernel<GPUTPCCFPeakFinder>(GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSlice}, {});
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpPeaks, *mDebugFile);
RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 0, doGPU, lane);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpPeaksCompacted, *mDebugFile);
}
for (int lane = 0; lane < GetProcessingSettings().nTPCClustererLanes && iSliceBase + lane < NSLICES; lane++) {
unsigned int iSlice = iSliceBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
SynchronizeStream(lane);
if (clusterer.mPmemory->counters.nPeaks == 0) {
continue;
}
runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::noiseSuppression>(GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSlice}, {});
runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::updatePeaks>(GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSlice}, {});
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpSuppressedPeaks, *mDebugFile);
RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 1, doGPU, lane);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpSuppressedPeaksCompacted, *mDebugFile);
}
for (int lane = 0; lane < GetProcessingSettings().nTPCClustererLanes && iSliceBase + lane < NSLICES; lane++) {
unsigned int iSlice = iSliceBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
SynchronizeStream(lane);
if (fragment.index == 0) {
runKernel<GPUMemClean16>(GetGridAutoStep(lane, RecoStep::TPCClusterFinding), krnlRunRangeNone, {nullptr, transferRunning[lane] == 1 ? &mEvents->stream[lane] : nullptr}, clustererShadow.mPclusterInRow, GPUCA_ROW_COUNT * sizeof(*clustererShadow.mPclusterInRow));
transferRunning[lane] = 2;
}
if (clusterer.mPmemory->counters.nClusters == 0) {
continue;
}
runKernel<GPUTPCCFDeconvolution>(GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSlice}, {});
DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Split Charges");
runKernel<GPUTPCCFClusterizer>(GetGrid(clusterer.mPmemory->counters.nClusters, lane), {iSlice}, {}, 0);
if (doGPU && propagateMCLabels) {
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mScratchId, lane);
SynchronizeStream(lane);
runKernel<GPUTPCCFClusterizer>(GetGrid(clusterer.mPmemory->counters.nClusters, lane, GPUReconstruction::krnlDeviceType::CPU), {iSlice}, {}, 1);
}
if (GetProcessingSettings().debugLevel >= 3) {
GPUInfo("Lane %d: Found clusters: digits %u peaks %u clusters %u", lane, (int)clusterer.mPmemory->counters.nPositions, (int)clusterer.mPmemory->counters.nPeaks, (int)clusterer.mPmemory->counters.nClusters);
}
TransferMemoryResourcesToHost(RecoStep::TPCClusterFinding, &clusterer, lane);
laneHasData[lane] = true;
if (DoDebugAndDump(RecoStep::TPCClusterFinding, 0, clusterer, &GPUTPCClusterFinder::DumpCountedPeaks, *mDebugFile)) {
clusterer.DumpClusters(*mDebugFile);
}
}
}
size_t nClsFirst = nClsTotal;
bool anyLaneHasData = false;
for (int lane = 0; lane < GetProcessingSettings().nTPCClustererLanes && iSliceBase + lane < NSLICES; lane++) {
unsigned int iSlice = iSliceBase + lane;
std::fill(&tmpNative->nClusters[iSlice][0], &tmpNative->nClusters[iSlice][0] + MAXGLOBALPADROW, 0);
SynchronizeStream(lane);
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSlice];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSlice] : clusterer;
if (laneHasData[lane]) {
anyLaneHasData = true;
if (buildNativeGPU && GetProcessingSettings().tpccfGatherKernel) {
runKernel<GPUTPCCFGather>(GetGridBlk(GPUCA_ROW_COUNT, mRec->NStreams() - 1), {iSlice}, {}, &mInputsShadow->mPclusterNativeBuffer[nClsTotal]);
}
for (unsigned int j = 0; j < GPUCA_ROW_COUNT; j++) {
if (buildNativeGPU) {
if (!GetProcessingSettings().tpccfGatherKernel) {
GPUMemCpyAlways(RecoStep::TPCClusterFinding, (void*)&mInputsShadow->mPclusterNativeBuffer[nClsTotal], (const void*)&clustererShadow.mPclusterByRow[j * clusterer.mNMaxClusterPerRow], sizeof(mIOPtrs.clustersNative->clustersLinear[0]) * clusterer.mPclusterInRow[j], mRec->NStreams() - 1, -2);
}
} else if (buildNativeHost) {
GPUMemCpyAlways(RecoStep::TPCClusterFinding, (void*)&mInputsHost->mPclusterNativeOutput[nClsTotal], (const void*)&clustererShadow.mPclusterByRow[j * clusterer.mNMaxClusterPerRow], sizeof(mIOPtrs.clustersNative->clustersLinear[0]) * clusterer.mPclusterInRow[j], mRec->NStreams() - 1, false);
}
tmpNative->nClusters[iSlice][j] += clusterer.mPclusterInRow[j];
nClsTotal += clusterer.mPclusterInRow[j];
}
if (transferRunning[lane]) {
ReleaseEvent(&mEvents->stream[lane]);
}
RecordMarker(&mEvents->stream[lane], mRec->NStreams() - 1);
transferRunning[lane] = 1;
}
if (not propagateMCLabels || not laneHasData[lane]) {
assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
continue;
}
runKernel<GPUTPCCFMCLabelFlattener, GPUTPCCFMCLabelFlattener::setRowOffsets>(GetGrid(GPUCA_ROW_COUNT, lane, GPUReconstruction::krnlDeviceType::CPU), {iSlice}, {});
GPUTPCCFMCLabelFlattener::setGlobalOffsetsAndAllocate(clusterer, mcLinearLabels);
runKernel<GPUTPCCFMCLabelFlattener, GPUTPCCFMCLabelFlattener::flatten>(GetGrid(GPUCA_ROW_COUNT, lane, GPUReconstruction::krnlDeviceType::CPU), {iSlice}, {}, &mcLinearLabels);
clusterer.clearMCMemory();
assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
}
if (buildNativeHost && buildNativeGPU && anyLaneHasData) {
if (GetProcessingSettings().delayedOutput) {
mOutputQueue.emplace_back(outputQueueEntry{(void*)((char*)&mInputsHost->mPclusterNativeOutput[nClsFirst] - (char*)&mInputsHost->mPclusterNativeOutput[0]), &mInputsShadow->mPclusterNativeBuffer[nClsFirst], (nClsTotal - nClsFirst) * sizeof(mInputsHost->mPclusterNativeOutput[nClsFirst]), RecoStep::TPCClusterFinding});
} else {
GPUMemCpy(RecoStep::TPCClusterFinding, (void*)&mInputsHost->mPclusterNativeOutput[nClsFirst], (void*)&mInputsShadow->mPclusterNativeBuffer[nClsFirst], (nClsTotal - nClsFirst) * sizeof(mInputsHost->mPclusterNativeOutput[nClsFirst]), mRec->NStreams() - 1, false);
}
}
}
for (int i = 0; i < GetProcessingSettings().nTPCClustererLanes; i++) {
if (transferRunning[i]) {
ReleaseEvent(&mEvents->stream[i]);
}
}
ClusterNativeAccess::ConstMCLabelContainerView* mcLabelsConstView = nullptr;
if (propagateMCLabels) {
// TODO: write to buffer directly
o2::dataformats::MCTruthContainer<o2::MCCompLabel> mcLabels;
std::pair<ConstMCLabelContainer*, ConstMCLabelContainerView*> buffer;
if (mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clusterLabels)] && mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clusterLabels)]->useExternal()) {
if (!mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clusterLabels)]->allocator) {
throw std::runtime_error("Cluster MC Label buffer missing");
}
ClusterNativeAccess::ConstMCLabelContainerViewWithBuffer* container = reinterpret_cast<ClusterNativeAccess::ConstMCLabelContainerViewWithBuffer*>(mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clusterLabels)]->allocator(0));
buffer = {&container->first, &container->second};
} else {
mIOMem.clusterNativeMCView = std::make_unique<ConstMCLabelContainerView>();
mIOMem.clusterNativeMCBuffer = std::make_unique<ConstMCLabelContainer>();
buffer.first = mIOMem.clusterNativeMCBuffer.get();
buffer.second = mIOMem.clusterNativeMCView.get();
}
assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
assert(propagateMCLabels ? mcLinearLabels.data.size() >= nClsTotal : true);
mcLabels.setFrom(mcLinearLabels.header, mcLinearLabels.data);
mcLabels.flatten_to(*buffer.first);
*buffer.second = *buffer.first;
mcLabelsConstView = buffer.second;
}
if (buildNativeHost && buildNativeGPU && GetProcessingSettings().delayedOutput) {
mInputsHost->mNClusterNative = mInputsShadow->mNClusterNative = nClsTotal;
AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeOutput, mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
for (unsigned int i = outputQueueStart; i < mOutputQueue.size(); i++) {
mOutputQueue[i].dst = (char*)mInputsHost->mPclusterNativeOutput + (size_t)mOutputQueue[i].dst;
}
}
if (buildNativeHost) {
tmpNative->clustersLinear = mInputsHost->mPclusterNativeOutput;
tmpNative->clustersMCTruth = mcLabelsConstView;
tmpNative->setOffsetPtrs();
mIOPtrs.clustersNative = tmpNative;
}
if (mPipelineNotifyCtx) {
SynchronizeStream(mRec->NStreams() - 2); // Must finish before updating ioPtrs in (global) constant memory
std::lock_guard<std::mutex> lock(mPipelineNotifyCtx->mutex);
mPipelineNotifyCtx->ready = true;
mPipelineNotifyCtx->cond.notify_one();
}
if (buildNativeGPU) {
processorsShadow()->ioPtrs.clustersNative = mInputsShadow->mPclusterNativeAccess;
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), 0);
*mInputsHost->mPclusterNativeAccess = *mIOPtrs.clustersNative;
mInputsHost->mPclusterNativeAccess->clustersLinear = mInputsShadow->mPclusterNativeBuffer;
mInputsHost->mPclusterNativeAccess->setOffsetPtrs();
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, mInputsHost->mResourceClusterNativeAccess, 0);
}
if (synchronizeOutput) {
SynchronizeStream(mRec->NStreams() - 1);
}
if (buildNativeHost && GetProcessingSettings().debugLevel >= 4) {
for (unsigned int i = 0; i < NSLICES; i++) {
for (unsigned int j = 0; j < GPUCA_ROW_COUNT; j++) {
std::sort(&mInputsHost->mPclusterNativeOutput[tmpNative->clusterOffset[i][j]], &mInputsHost->mPclusterNativeOutput[tmpNative->clusterOffset[i][j] + tmpNative->nClusters[i][j]]);
}
}
}
mRec->MemoryScalers()->nTPCHits = nClsTotal;
mRec->PopNonPersistentMemory(RecoStep::TPCClusterFinding, qStr2Tag("TPCCLUST"));
if (mPipelineNotifyCtx) {
mRec->UnblockStackedMemory();
mPipelineNotifyCtx = nullptr;
}
#endif
return 0;
}
| 56.99867
| 324
| 0.692812
|
chengtt0406
|
4d7f93f0016f329758d5450b3ab9c7024a88d65b
| 1,035
|
cpp
|
C++
|
src/State.cpp
|
Speedy-code13/Shawarma.is-SFML-2022
|
904359317eef4fb90df32db961dfcb3819287bbb
|
[
"Apache-2.0"
] | null | null | null |
src/State.cpp
|
Speedy-code13/Shawarma.is-SFML-2022
|
904359317eef4fb90df32db961dfcb3819287bbb
|
[
"Apache-2.0"
] | null | null | null |
src/State.cpp
|
Speedy-code13/Shawarma.is-SFML-2022
|
904359317eef4fb90df32db961dfcb3819287bbb
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "State.h"
State::State(StateData* stateData)
: resolution(stateData->gfx->resolution), stateData(stateData)
{
this->window = this->stateData->window;
this->dt = this->stateData->dt;
this->states = this->stateData->states;
this->quit = false;
this->updatedRes = false;
this->keytimeMax = 10.f;
this->keytime = keytimeMax;
}
void State::updateKeytime()
{
if (this->keytime <= keytimeMax)
this->keytime += 50.f * (*dt);
}
const bool State::getQuit() const
{
return this->quit;
}
const bool State::getUpdatedRes() const
{
return this->updatedRes;
}
void State::endState()
{
this->quit = true;
}
const bool State::getKeytime()
{
if (this->keytime >= this->keytimeMax)
{
this->keytime = 0.f;
return true;
}
return false;
}
void State::updateMousePositions()
{
this->mousePosScreen = sf::Mouse::getPosition();
this->mousePosWindow = sf::Mouse::getPosition(*this->window);
this->mousePosView = this->window->mapPixelToCoords(sf::Mouse::getPosition(*this->window));
}
| 16.693548
| 92
| 0.675362
|
Speedy-code13
|
4d8034c64400950d7b8e6b00e08fd4214d510e6b
| 4,576
|
cxx
|
C++
|
minisw/minisw.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
minisw/minisw.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
minisw/minisw.cxx
|
trotill/11parts_CPP
|
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
|
[
"MIT"
] | null | null | null |
#include "engine/minisw/minisw.h"
#include "engine/lib/11p_string.h"
eErrorTp MiniSW_Run(int argc,char *argv[],string SWname)
{
//printf("run %s\n",SWname.c_str());
if (SWname.compare(USB_RESET_SW)==0)
{
usb_reset_main(argc,argv);
}
if (SWname.compare(IMAGE_CHECK)==0)
{
imcheck_main(argc,argv);
}
if (SWname.compare(CNODA_PROCESS_NAME)==0)
{
EventSender(argc,argv,SWname);
}
if (SWname.compare(WDT_PROCESS_NAME)==0)
{
EventSender(argc,argv,SWname);
}
if (SWname.compare(NODE_PROCESS_NAME)==0)
{
EventSender(argc,argv,SWname);
}
#ifdef _SNMP
if (SWname.compare(SNMP_AGENT)==0)
{
snmp_main(argc,argv);
}
#endif
if (SWname.compare(LOAD_SETTINGS_PROCESS_NAME)==0)
{
load_settings(argc,argv);
}
if (SWname.compare(SAVE_SETTINGS_PROCESS_NAME)==0)
{
save_settings(argc,argv);
}
if (SWname.compare(SETTINGS_CLEAN_PROCESS_NAME)==0)
{
settings_clean_main(argc,argv);
}
if (SWname.compare(SETTINGS_GET_PRIVATE)==0)
{
settings_private(argc,argv);
}
if (SWname.compare(TO_FACTORY)==0)
{
to_factory(argc,argv);
}
//
//zr();
#ifdef _SAFE_LOGGER
if (SWname.compare(SAFE_LOGGER_FW)==0)
{
//zr();
safe_logger(argc,argv);
}
#endif
return NO_ERROR;
}
EvSender::EvSender(string & ToProcess,char * event, char * args,int method,int packtype)
{
debug_level=NO_USE;
u16 ToPort=0;
if (ToProcess.compare(WDT_PROCESS_NAME)==0)
{
ToPort=CnT->WDT_PORT_NODEJS;
}
else
{
if (ToProcess.compare(NODE_PROCESS_NAME)==0)
{
ToPort=CnT->NODE_PORT_NODEJS;
}
else
{
if (ToProcess.compare(CNODA_PROCESS_NAME)==0)
{
ToPort=CnT->NODE_PORT_CPP;
}
else
{
GPRINT(NORMAL_LEVEL,"Incorrect port, Error send Event %s(%s)\n",event,args);
exit(1);
}
}
}
GPRINT(NORMAL_LEVEL,"Send from port %d to port %d\n",htons(CnT->WDT_PORT_CPP),htons(ToPort));
if (InitLHBus(CnT->WDT_PORT_CPP,ToPort,(char*)CnT->NODE_GROUP_IP.c_str())==NO_ERROR)
{
stringstream SendBuf;
if (strlen(args)!=0){
if (method==EV_SENDER_METHOD_EVENT)
{
SendBuf<< "{\"t\":["<< packtype <<","<< JSON_PACK_HEADER_VERSION << "],\"d\":{\"" << event << "\":" << args << "}}";
}
if (method==EV_SENDER_METHOD_RAW)
{
SendBuf<< "{\"t\":["<< packtype <<","<< JSON_PACK_HEADER_VERSION << "],\"d\":" << event << args <<"}";
}
}
else{
SendBuf<< event;
}
SockSendToLH_Bus((char*)SendBuf.str().c_str(), SendBuf.str().length());
GPRINT(NORMAL_LEVEL,"Send Event %s(%s) %s\n",event,args,SendBuf.str().c_str());
}
else
{
GPRINT(NORMAL_LEVEL,"Error send Event %s(%s)\n",event,args);
}
exit(1);
}
eErrorTp SendDataFromCnodaToUI_base(string dMessage,u32 json_pack_type,u32 json_pack_version, string user ,char * action)
{
string data="{}";
string sid="";
if (user.length()!=0){
sid=string_format(",\"sid\":\"%s\"",(char*)user.c_str());
}
string evnative="{}";
if (dMessage[0]=='{'){
evnative=string_format("%s/evwdt '{\"t\":[%d,%d],\"d\":' '{\"action\":\"%s\",\"%s\":%s}%s}' %d\n",
(char*)CnT->CNODA_PATH.c_str(),
json_pack_type,
json_pack_version,
action,
action,
dMessage.c_str(),
sid.c_str(),
JSON_PACK_TYPE_TO_UI);
//(char*)user.c_str());
}
else{
evnative=string_format("%s/evwdt '{\"t\":[%d,%d],\"d\":' '{\"action\":\"%s\",\"%s\":\"%s\"}%s}' %d\n",
(char*)CnT->CNODA_PATH.c_str(),
json_pack_type,
json_pack_version,
action,
action,
dMessage.c_str(),
sid.c_str(),
JSON_PACK_TYPE_TO_UI);
//(char*)user.c_str());
}
printf("%s\n",evnative.c_str());
system(evnative.c_str());
return NO_ERROR;
//GPRINT(MEDIUM_LEVEL,"SendEventFromCnoda\n");
//return SendSharedFifoMessage(srvmSendToLH,"wead", (u8*)container.c_str(),container.size());
}
eErrorTp SendSystemFromCnodaToUI(string dMessageJson)
{
return SendDataFromCnodaToUI_base(dMessageJson,JSON_PACK_TYPE_SET_SYSTEM,JSON_PACK_VERSION,"","cnoda");
}
eErrorTp SendSystemFromCnodaToUI(string dMessageJson,string user)
{
return SendDataFromCnodaToUI_base(dMessageJson,JSON_PACK_TYPE_SET_SYSTEM,JSON_PACK_VERSION,user,"cnoda");
}
eErrorTp SendEventFromCnodaToUI(string dMessageJson)
{
return SendDataFromCnodaToUI_base(dMessageJson,JSON_PACK_TYPE_SEND_EVENT,JSON_PACK_VERSION,"","cnoda");
}
eErrorTp SendEventFromCnodaToUI(string dMessageJson,string user)
{
return SendDataFromCnodaToUI_base(dMessageJson,JSON_PACK_TYPE_SEND_EVENT,JSON_PACK_VERSION,user,"cnoda");
}
| 22.653465
| 122
| 0.646416
|
trotill
|
4d81bc7e0d9fbcccbeb19e2375f19e83c1b5ab8e
| 2,478
|
hh
|
C++
|
hoo/emitter/EmitterContext.hh
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | null | null | null |
hoo/emitter/EmitterContext.hh
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | 14
|
2020-07-24T10:25:59.000Z
|
2020-08-02T13:27:09.000Z
|
hoo/emitter/EmitterContext.hh
|
benoybose/hoolang
|
4e280a03caec837be35c8aac948923e1bea96b85
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2020 Benoy Bose
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EMITTER_CONTEXT_HH
#define EMITTER_CONTEXT_HH
#include <hoo/emitter/BlockContext.hh>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Function.h>
#include <string>
#include <memory>
#include <stack>
namespace hoo
{
namespace emitter
{
class EmitterContext
{
private:
std::shared_ptr<llvm::LLVMContext> _context;
std::shared_ptr<llvm::Module> _module;
std::shared_ptr<llvm::IRBuilder<>> _builder;
std::string _unit_name;
Function* _function;
std::shared_ptr<std::stack<BlockContext*>> _block_stack;
public:
EmitterContext(const std::string &unit_name);
public:
llvm::LLVMContext *GetContext() { return _context.get(); }
llvm::Module *GetModule() { return _module.get(); }
llvm::IRBuilder<> *GetBuilder() { return _builder.get(); };
std::string &GetUnitName() { return _unit_name; }
BlockContext *BeginBlock(const std::string &name = "");
void EndBlock();
BlockContext *GetCurrentBlockContext();
void SetFunction(Function* function) { _function = function; }
Function* GetFunction() { return _function; }
};
}
}
#endif // EMITTER_CONTEXT_HH
| 38.71875
| 100
| 0.679177
|
benoybose
|
4d85d955ffae4b0f070bcee9a900a806bb3195d0
| 11,945
|
cpp
|
C++
|
olp-cpp-sdk-dataservice-write/src/generated/PublishApi.cpp
|
matthiaskunter/here-data-sdk-cpp
|
30b0cdce39dc7218416e820cc3f928f2f2e15675
|
[
"Apache-2.0"
] | null | null | null |
olp-cpp-sdk-dataservice-write/src/generated/PublishApi.cpp
|
matthiaskunter/here-data-sdk-cpp
|
30b0cdce39dc7218416e820cc3f928f2f2e15675
|
[
"Apache-2.0"
] | null | null | null |
olp-cpp-sdk-dataservice-write/src/generated/PublishApi.cpp
|
matthiaskunter/here-data-sdk-cpp
|
30b0cdce39dc7218416e820cc3f928f2f2e15675
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include "PublishApi.h"
#include <memory>
#include <sstream>
#include <olp/core/client/HttpResponse.h>
// clang-format off
// Ordering Required - Parser template specializations before #include "JsonResultParser.h"
#include <generated/parser/PublicationParser.h>
#include <generated/parser/PublishPartitionsParser.h>
#include "JsonResultParser.h"
#include <generated/serializer/PublicationSerializer.h>
#include <generated/serializer/PublishPartitionsSerializer.h>
#include <generated/serializer/JsonSerializer.h>
// clang-format on
namespace client = olp::client;
namespace {
const std::string kQueryParamBillingTag = "billingTag";
} // namespace
namespace olp {
namespace dataservice {
namespace write {
client::CancellationToken PublishApi::InitPublication(
const client::OlpClient& client, const model::Publication& publication,
const boost::optional<std::string>& billing_tag,
InitPublicationCallback callback) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string init_publication_uri = "/publications";
auto serialized_publication = serializer::serialize(publication);
auto data = std::make_shared<std::vector<unsigned char>>(
serialized_publication.begin(), serialized_publication.end());
auto cancel_token = client.CallApi(
init_publication_uri, "POST", query_params, header_params, form_params,
data, "application/json", [callback](client::HttpResponse http_response) {
if (http_response.status != http::HttpStatusCode::OK) {
callback(InitPublicationResponse{client::ApiError(
http_response.status, http_response.response.str())});
return;
}
callback(parser::parse_result<InitPublicationResponse>(
http_response.response));
});
return cancel_token;
}
InitPublicationResponse PublishApi::InitPublication(
const client::OlpClient& client, const model::Publication& publication,
const boost::optional<std::string>& billing_tag,
client::CancellationContext cancellation_context) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string init_publication_uri = "/publications";
auto serialized_publication = serializer::serialize(publication);
auto data = std::make_shared<std::vector<unsigned char>>(
serialized_publication.begin(), serialized_publication.end());
auto http_response = client.CallApi(
std::move(init_publication_uri), "POST", std::move(query_params),
std::move(header_params), std::move(form_params), std::move(data),
"application/json", cancellation_context);
if (http_response.status != olp::http::HttpStatusCode::OK) {
return InitPublicationResponse(
client::ApiError(http_response.status, http_response.response.str()));
}
return parser::parse_result<InitPublicationResponse>(http_response.response);
}
client::CancellationToken PublishApi::UploadPartitions(
const client::OlpClient& client,
const model::PublishPartitions& publish_partitions,
const std::string& publication_id, const std::string& layer_id,
const boost::optional<std::string>& billing_tag,
UploadPartitionsCallback callback) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string upload_partitions_uri =
"/layers/" + layer_id + "/publications/" + publication_id + "/partitions";
auto serialized_publish_partitions =
serializer::serialize(publish_partitions);
auto data = std::make_shared<std::vector<unsigned char>>(
serialized_publish_partitions.begin(),
serialized_publish_partitions.end());
auto cancel_token = client.CallApi(
upload_partitions_uri, "POST", query_params, header_params, form_params,
data, "application/json", [callback](client::HttpResponse http_response) {
if (http_response.status != olp::http::HttpStatusCode::NO_CONTENT) {
callback(UploadPartitionsResponse{client::ApiError(
http_response.status, http_response.response.str())});
return;
}
callback(UploadPartitionsResponse(client::ApiNoResult()));
});
return cancel_token;
}
UploadPartitionsResponse PublishApi::UploadPartitions(
const client::OlpClient& client,
const model::PublishPartitions& publish_partitions,
const std::string& publication_id, const std::string& layer_id,
const boost::optional<std::string>& billing_tag,
client::CancellationContext cancellation_context) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string upload_partitions_uri =
"/layers/" + layer_id + "/publications/" + publication_id + "/partitions";
auto serialized_publish_partitions =
serializer::serialize(publish_partitions);
auto data = std::make_shared<std::vector<unsigned char>>(
serialized_publish_partitions.begin(),
serialized_publish_partitions.end());
auto http_response = client.CallApi(
std::move(upload_partitions_uri), "POST", std::move(query_params),
std::move(header_params), std::move(form_params), std::move(data),
"application/json", cancellation_context);
if (http_response.status != olp::http::HttpStatusCode::NO_CONTENT) {
return UploadPartitionsResponse(
client::ApiError(http_response.status, http_response.response.str()));
}
return UploadPartitionsResponse(client::ApiNoResult());
}
client::CancellationToken PublishApi::SubmitPublication(
const client::OlpClient& client, const std::string& publication_id,
const boost::optional<std::string>& billing_tag,
SubmitPublicationCallback callback) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string submit_publication_uri = "/publications/" + publication_id;
auto cancel_token = client.CallApi(
submit_publication_uri, "PUT", query_params, header_params, form_params,
nullptr, "application/json",
[callback](client::HttpResponse http_response) {
if (http_response.status != olp::http::HttpStatusCode::NO_CONTENT) {
callback(SubmitPublicationResponse{client::ApiError(
http_response.status, http_response.response.str())});
return;
}
callback(SubmitPublicationResponse(client::ApiNoResult()));
});
return cancel_token;
}
SubmitPublicationResponse PublishApi::SubmitPublication(
const client::OlpClient& client, const std::string& publication_id,
const boost::optional<std::string>& billing_tag,
client::CancellationContext cancellation_context) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string submit_publication_uri = "/publications/" + publication_id;
auto http_response = client.CallApi(
std::move(submit_publication_uri), "PUT", std::move(query_params),
std::move(header_params), std::move(form_params), nullptr,
"application/json", cancellation_context);
if (http_response.status != olp::http::HttpStatusCode::NO_CONTENT) {
return SubmitPublicationResponse(
client::ApiError(http_response.status, http_response.response.str()));
}
return SubmitPublicationResponse(client::ApiNoResult());
}
client::CancellationToken PublishApi::GetPublication(
const client::OlpClient& client, const std::string& publication_id,
const boost::optional<std::string>& billing_tag,
GetPublicationCallback callback) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string get_publication_uri = "/publications/" + publication_id;
auto cancel_token = client.CallApi(
get_publication_uri, "GET", query_params, header_params, form_params,
nullptr, "application/json",
[callback](client::HttpResponse http_response) {
if (http_response.status != http::HttpStatusCode::OK) {
callback(GetPublicationResponse{client::ApiError(
http_response.status, http_response.response.str())});
return;
}
callback(parser::parse_result<GetPublicationResponse>(
http_response.response));
});
return cancel_token;
}
SubmitPublicationResponse PublishApi::CancelPublication(
const client::OlpClient& client, const std::string& publication_id,
const boost::optional<std::string>& billing_tag,
client::CancellationContext context) {
std::multimap<std::string, std::string> header_params;
std::multimap<std::string, std::string> query_params;
std::multimap<std::string, std::string> form_params;
header_params.insert(std::make_pair("Accept", "application/json"));
if (billing_tag) {
query_params.insert(
std::make_pair(kQueryParamBillingTag, billing_tag.get()));
}
std::string submit_publication_uri = "/publications/" + publication_id;
auto http_response = client.CallApi(submit_publication_uri, "DELETE",
query_params, header_params, form_params,
nullptr, "application/json", context);
if (http_response.status != olp::http::HttpStatusCode::NO_CONTENT) {
return client::ApiError(http_response.status, http_response.response.str());
}
return client::ApiNoResult();
}
} // namespace write
} // namespace dataservice
} // namespace olp
| 37.211838
| 91
| 0.721139
|
matthiaskunter
|
4d8cc39ad118c3961952f65f6821862138fa2485
| 371
|
cpp
|
C++
|
mazeLocation.cpp
|
bolym/C-Escape
|
fe448c1bcbfcda8090c6642fa1417e08581cdf8e
|
[
"MIT"
] | null | null | null |
mazeLocation.cpp
|
bolym/C-Escape
|
fe448c1bcbfcda8090c6642fa1417e08581cdf8e
|
[
"MIT"
] | null | null | null |
mazeLocation.cpp
|
bolym/C-Escape
|
fe448c1bcbfcda8090c6642fa1417e08581cdf8e
|
[
"MIT"
] | null | null | null |
#include "mazeLocation.hpp"
/******************************************************************
* Function: mazeLocation()
* Description: Default empty MazeLocation constructor
* Parameters: None
* Pre-Conditions: None
* Post-Conditions: None
******************************************************************/
MazeLocation::MazeLocation(){
//empty
}
| 28.538462
| 68
| 0.447439
|
bolym
|
4d8d565fa9d9a5ef5f1918204e8c55481a02c65c
| 7,246
|
cxx
|
C++
|
examples/cmdline.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | null | null | null |
examples/cmdline.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | null | null | null |
examples/cmdline.cxx
|
elcuco/mimetic
|
00c46f7e25235ea6de9ddefc0b63c3249eb1d1da
|
[
"MIT"
] | 1
|
2022-02-24T19:24:28.000Z
|
2022-02-24T19:24:28.000Z
|
#include <getopt.h>
#include <iostream>
#include <cstring>
#include "mm.h"
#include "cmdline.h"
using namespace std;
command_line::command_line()
{
for(int i = 0; i < p_last_item; ++i)
m_is_opt_set[i] = 0;
}
command_line::iterator command_line::begin(const string& key)
{
if(key.length())
return m_map.lower_bound(key);
else
return m_map.begin();
}
command_line::iterator command_line::end(const string& key)
{
if(key.length())
return m_map.upper_bound(key);
else
return m_map.end();
}
command_line::const_iterator command_line::begin(const string& key) const
{
if(key.length())
return m_map.lower_bound(key);
else
return m_map.begin();
}
command_line::const_iterator command_line::end(const string& key) const
{
if(key.length())
return m_map.upper_bound(key);
else
return m_map.end();
}
string& command_line::operator[](const string& key)
{
iterator it = m_map.find(key);
if(it == m_map.end())
it = m_map.insert(command_line_switch(key,""));
return it->second;
}
bool command_line::is_set(int i) const
{
return m_is_opt_set[i];
}
bool command_line::is_set(const string& switch_name) const
{
return m_map.find(switch_name) != m_map.end();
}
void command_line::die_if_not_valid() const
{
die_if(is_set(p_match_shell) && is_set(p_match_regex),
"just one of --match-shell and --match-regex can be specified");
die_if(is_set(p_match_shell) && is_set(p_perl_regex),
"--match-shell and --perl-regex are not compatible");
die_if(is_set(p_print_msg) && is_set(p_print_part),
"just one of --print-message and --print-part can be specified");
die_if(is_set(p_delete_msg) && is_set(p_delete_part),
"just one of --delete-msg and --delete-part can be specified");
}
void command_line::add_switch(const string& name, const string& arg)
{
m_map.insert(command_line_switch(name,arg));
}
bool command_line::parse_cmd_line(int argc, char **argv)
{
#define CMDLINE_ARG( name, desc, arg ) { name "\000" desc, arg, 0, 0 }
#define CMDLINE_ARG_VAL( name, desc, arg, val ) { name "\000" desc, arg, 0, val }
enum { NO_ARG, REQ_ARG, OPT_ARG };
int opt_idx = 0;
static struct option long_options[] = {
// "name", has-arg, flag, val
CMDLINE_ARG_VAL("attachment-filename",
"filename of the attachment",
REQ_ARG, p_attachment_filename),
CMDLINE_ARG_VAL("has-binary-attach",
"match if the message has attachments",
NO_ARG,p_has_binary_attach),
CMDLINE_ARG_VAL("has-field","",OPT_ARG,p_has_field),
CMDLINE_ARG_VAL("field", "",OPT_ARG,p_field),
CMDLINE_ARG_VAL("ifield","",OPT_ARG,p_ifield),
CMDLINE_ARG_VAL("from", "",OPT_ARG, p_std_field),
CMDLINE_ARG_VAL("sender", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("to", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("subject", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("cc", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("bcc", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("user-agent", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("date", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("content-type", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("content-transfer-encoding","",OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("content-disposition", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("content-description", "", OPT_ARG,p_std_field),
CMDLINE_ARG_VAL("add-header", "", REQ_ARG, p_add_header),
CMDLINE_ARG_VAL("del-header", "", REQ_ARG, p_del_header),
CMDLINE_ARG_VAL("mod-header", "", REQ_ARG, p_mod_header),
CMDLINE_ARG_VAL("add-part-header", "", REQ_ARG, p_add_part_header),
CMDLINE_ARG_VAL("del-part-header", "", REQ_ARG, p_del_part_header),
CMDLINE_ARG_VAL("mod-part-header", "", REQ_ARG, p_mod_part_header),
CMDLINE_ARG_VAL("attach", "", REQ_ARG, p_attach),
CMDLINE_ARG_VAL("detach", "", NO_ARG, p_detach),
CMDLINE_ARG_VAL("delete-part", "", NO_ARG, p_delete_part),
CMDLINE_ARG_VAL("delete-message", "", NO_ARG, p_delete_msg),
CMDLINE_ARG_VAL("print-part", "", NO_ARG,p_print_part),
CMDLINE_ARG_VAL("print-message", "", NO_ARG,p_print_msg),
CMDLINE_ARG_VAL("pipe-to", "", REQ_ARG, p_pipe_to),
CMDLINE_ARG_VAL("recursive", "", NO_ARG, p_recursive),
CMDLINE_ARG_VAL("invert-selection", "", NO_ARG, p_invert_selection),
CMDLINE_ARG_VAL("match-shell", "", NO_ARG, p_match_shell),
CMDLINE_ARG_VAL("match-regex", "", NO_ARG, p_match_regex),
CMDLINE_ARG_VAL("perl-regex", "", NO_ARG, p_perl_regex),
CMDLINE_ARG_VAL("case-insensitive", "", NO_ARG, p_case_insensitive),
CMDLINE_ARG_VAL("encoding", "", REQ_ARG, p_encoding),
CMDLINE_ARG_VAL("in", "", REQ_ARG, p_in),
CMDLINE_ARG_VAL("out", "", REQ_ARG, p_out),
CMDLINE_ARG_VAL("help", "", NO_ARG, p_help),
CMDLINE_ARG_VAL("version", "", NO_ARG, p_version),
{0, 0, 0, 0}
};
int ret;
while((ret = getopt_long(argc,argv, "hv", long_options, &opt_idx))!= -1)
{
switch(ret)
{
case ':':
die("missing parameter");
case '?':
die("unknown option");
case 'v':
cerr << MM_VERSION << endl;
exit(1);
break;
case 'h':
//usage_if(1);
for(int i = 0; long_options[i].name; ++i)
{
const char *name= long_options[i].name;
cerr << "--" << name;
switch(long_options[i].has_arg)
{
case NO_ARG:
break;
case REQ_ARG:
cerr << " ARG";
break;
case OPT_ARG:
cerr << " [ARG]";
break;
default:
die("unknown has_arg");
}
// past the end of name
const char *desc = 1 + name + strlen(name);
cerr << "\t" << desc << endl;
}
exit(0);
break;
default:
m_is_opt_set[ret]++;
for(int i = 0; long_options[i].name; ++i)
{
struct option *opt = &long_options[i];
if(ret == opt->val)
{
if(opt->has_arg == NO_ARG || !optarg)
add_switch(opt->name,"");
else
add_switch(opt->name, optarg);
}
}
}
}
/*
switch(argc - optind)
{
case 0:
// read from stdin write to stdout
break;
case 1:
//stdin provided in argv[optind]
pCl->args.push_back(argv[optind]);
break;
case 2:
//stdin & stdout provided in argv[optind] && argv[++optind]
pCl->args.push_back(argv[optind]);
pCl->args.push_back(argv[++optind]);
break;
default:
usage();
}
cerr << endl;
*/
return true;
}
| 33.238532
| 85
| 0.571488
|
elcuco
|
4d8e6016b10a02398941365fb9b5e4a78b8011fb
| 5,083
|
cpp
|
C++
|
src/xray/animation/sources/test_mixing_animation_group.cpp
|
ixray-team/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 3
|
2021-10-30T09:36:14.000Z
|
2022-03-26T17:00:06.000Z
|
src/xray/animation/sources/test_mixing_animation_group.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | null | null | null |
src/xray/animation/sources/test_mixing_animation_group.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:08.000Z
|
2022-03-26T17:00:08.000Z
|
////////////////////////////////////////////////////////////////////////////
// Created : 15.04.2010
// Author : Konstantin Slipchenko
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "test_mixing_animation_group.h"
#include "fermi_dirac_interpolator.h"
#include "linear_interpolator.h"
#include "instant_interpolator.h"
#include "mixing_animation_lexeme.h"
#include "mixing_weight_lexeme.h"
#include "mixing_addition_lexeme.h"
#include "mixing_multiplication_lexeme.h"
#include "mixing_expression.h"
#include "skeleton_animation_data.h"
#include "mixer.h"
#include "skeleton_animation.h"
#include "mixing_animation_clip.h"
using xray::animation::test_mixing_animation_group;
using xray::configs::lua_config_ptr;
using xray::configs::lua_config_value;
using xray::configs::lua_config_iterator;
void test_mixing_animation_group::add_animation( lua_config_value const &config, xray::resources::query_result_for_user const &anim, xray::animation::skeleton const* skel )
{
lua_config_value cfg = config["animation"];
base_interpolator* interpolator = 0;
pcstr const interpolator_type = cfg["interpolator_type"];
if ( !strings::compare(interpolator_type,"fermi") ) {
interpolator = NEW(fermi_dirac_interpolator)(cfg["interpolation_time"], cfg["interpolation_epsilon"] );
} else if ( !strings::compare(interpolator_type,"linear") ) {
interpolator = NEW(linear_interpolator)( cfg["interpolation_time"] );
} else if ( !strings::compare(interpolator_type,"instant") ) {
interpolator = NEW(instant_interpolator);
} else if ( !strings::compare(interpolator_type,"instant") ) {
UNREACHABLE_CODE( );
}
skeleton_animation_data* const animation_data =
static_cast_checked<skeleton_animation_data*>( anim.get_unmanaged_resource().c_ptr() );
animation_data->set_skeleton( skel );
skeleton_animation* const skeleton_animation = NEW( animation::skeleton_animation )( *animation_data ) ;
m_p_animations.push_back( skeleton_animation );
ASSERT ( interpolator );
mixing::animation_clip* const animation =
NEW (mixing::animation_clip) (
cfg["animation"],
interpolator,
skeleton_animation,
!strings::compare( "full", cfg["animation_type"]) ? mixing::animation_clip::full : mixing::animation_clip::additive
);
m_max_time = math::min( m_max_time, animation->time() );
m_max_mix_time = math::max( m_max_mix_time, interpolator->transition_time() );
m_clips.push_back (std::make_pair( animation, config["weight"] ) );
}
test_mixing_animation_group::test_mixing_animation_group( lua_config_value cfg, xray::animation::skeleton const* skel ):
m_max_mix_time( 0 ),
m_max_time( math::infinity ),
m_config( cfg ),
m_skeleton( skel ),
m_loaded( false )
{
u32 const size = cfg["group"].size();
resources::request* const resources = static_cast<resources::request*>( ALLOCA( size*sizeof(resources::request) ) );
lua_config_iterator i = cfg["group"].begin( );
lua_config_iterator const e = cfg["group"].end( );
for (resources::request* j = resources; i != e; ++i, ++j ) {
j->path = (*i)["animation"]["animation"];
j->id = resources::animation_data_class;
}
xray::resources::query_resources(
resources,
size,
boost::bind( &test_mixing_animation_group::on_animations_loaded, this, _1 ),
g_allocator
);
}
float test_mixing_animation_group::play_time() const
{
ASSERT( m_max_time != math::infinity );
return m_max_time - m_max_mix_time ;
}
test_mixing_animation_group::~test_mixing_animation_group( )
{
{
vector< animation_pair >::iterator i = m_clips.begin() , e = m_clips.end();
for ( ; i != e; ++i )
DELETE( (*i).first );
}
{
vector< skeleton_animation* >::iterator i = m_p_animations.begin() , e = m_p_animations.end();
for ( ; i != e; ++i )
DELETE( (*i) );
}
}
void test_mixing_animation_group::on_animations_loaded ( xray::resources::queries_result& resource )
{
u32 const size =resource.size();
for (u32 i=0; i < size; ++i ) {
add_animation( m_config["group"][i], resource[i], m_skeleton );
}
m_loaded = true;
}
void test_mixing_animation_group::set_target( xray::animation::mixer& mxr, const u32 time )const
{
mutable_buffer buffer( ALLOCA(mixer::stack_buffer_size), mixer::stack_buffer_size );
mixing::animation_lexeme lx_animation( buffer, m_clips.front().first );
mixing::weight_lexeme lx_weight( buffer, m_clips.front().second, &m_clips.front().first->interpolator() );
mixing::expression expression = lx_weight * lx_animation;
const u32 count = m_clips.size();
for( u32 i = 1; i < count; ++i )
{
mixing::animation_lexeme animation( buffer, m_clips[i].first );
mixing::weight_lexeme weight( buffer, m_clips[i].second, & m_clips[i].first->interpolator() );
expression = animation*weight + expression;
}
mxr.set_target ( expression, time );
}
| 31.968553
| 173
| 0.677159
|
ixray-team
|
4da11d3b7e98ea2242567634b3cae0a956d67928
| 4,412
|
cpp
|
C++
|
lib/heif/Srcs/common/samplegroupdescriptionbox.cpp
|
anzksdk/tifig-by
|
17a306b27e6e2dd2992e1c0896312047541f4be0
|
[
"Apache-2.0"
] | null | null | null |
lib/heif/Srcs/common/samplegroupdescriptionbox.cpp
|
anzksdk/tifig-by
|
17a306b27e6e2dd2992e1c0896312047541f4be0
|
[
"Apache-2.0"
] | null | null | null |
lib/heif/Srcs/common/samplegroupdescriptionbox.cpp
|
anzksdk/tifig-by
|
17a306b27e6e2dd2992e1c0896312047541f4be0
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2015, Nokia Technologies Ltd.
* All rights reserved.
*
* Licensed under the Nokia High-Efficiency Image File Format (HEIF) License (the "License").
*
* You may not use the High-Efficiency Image File Format except in compliance with the License.
* The License accompanies the software and can be found in the file "LICENSE.TXT".
*
* You may also obtain the License at:
* https://nokiatech.github.io/heif/license.txt
*/
#include "samplegroupdescriptionbox.hpp"
#include "bitstream.hpp"
#include "log.hpp"
#include <memory>
#include <stdexcept>
SampleGroupDescriptionBox::SampleGroupDescriptionBox() :
FullBox("sgpd", 0, 0),
mGroupingType(),
mDefaultLength(0),
mSampleGroupEntry()
{
}
void SampleGroupDescriptionBox::setDefaultLength(std::uint32_t defaultLength)
{
mDefaultLength = defaultLength;
}
std::uint32_t SampleGroupDescriptionBox::getDefaultLength() const
{
return mDefaultLength;
}
void SampleGroupDescriptionBox::addEntry(std::unique_ptr<SampleGroupEntry> sampleGroupEntry)
{
mSampleGroupEntry.push_back(std::move(sampleGroupEntry));
}
const SampleGroupEntry* SampleGroupDescriptionBox::getEntry(std::uint32_t index) const
{
return mSampleGroupEntry.at(index - 1).get();
}
void SampleGroupDescriptionBox::setGroupingType(const std::string& groupingType)
{
if (groupingType.length() != 4)
{
throw std::runtime_error("SampleGroupDescriptionBox::setGroupingType: invalid grouping type length, must be 4 characters");
}
mGroupingType = groupingType;
}
const std::string& SampleGroupDescriptionBox::getGroupingType() const
{
return mGroupingType;
}
std::uint32_t SampleGroupDescriptionBox::getEntryIndexOfSampleId(const std::uint32_t sampleId) const
{
uint32_t index = 1;
for (const auto& entry : mSampleGroupEntry)
{
DirectReferenceSampleListEntry* drsle = dynamic_cast<DirectReferenceSampleListEntry*>(entry.get());
if ((drsle != nullptr) && (drsle->getSampleId() == sampleId))
{
return index;
}
++index;
}
throw std::runtime_error("SampleGroupDescriptionBox::getEntryIndexOfSampleId: no entry for sampleId found.");
}
void SampleGroupDescriptionBox::writeBox(BitStream& bitstr)
{
if (mSampleGroupEntry.size() == 0)
{
throw std::runtime_error("SampleGroupDescriptionBox::writeBox: not writing an invalid box without entries");
}
// Write box headers
writeFullBoxHeader(bitstr);
if (mGroupingType.length() != 4)
{
throw std::runtime_error("SampleGroupDescriptionBox::writeBox: Invalid grouping_type length");
}
bitstr.writeString(mGroupingType);
if (getVersion() == 1)
{
bitstr.write32Bits(mDefaultLength);
}
bitstr.write32Bits(mSampleGroupEntry.size());
for (auto& entry : mSampleGroupEntry)
{
if (getVersion() == 1 && mDefaultLength == 0)
{
bitstr.write32Bits(entry->getSize());
}
entry->writeEntry(bitstr);
}
// Update the size of the movie box
updateSize(bitstr);
}
void SampleGroupDescriptionBox::parseBox(BitStream& bitstr)
{
// First parse the box header
parseFullBoxHeader(bitstr);
bitstr.readStringWithLen(mGroupingType, 4);
if (getVersion() == 1)
{
mDefaultLength = bitstr.read32Bits();
}
const uint32_t entryCount = bitstr.read32Bits();
for (unsigned int i = 0; i < entryCount; ++i)
{
uint32_t descriptionLength = mDefaultLength;
if (getVersion() == 1 && mDefaultLength == 0)
{
descriptionLength = bitstr.read32Bits();
}
BitStream subBitstr;
bitstr.extract(bitstr.getPos(), bitstr.getPos() + descriptionLength, subBitstr); // extract "sub-bitstream" for entry
bitstr.skipBytes(descriptionLength);
if (mGroupingType == "refs")
{
std::unique_ptr<SampleGroupEntry> directReferenceSampleListEntry(new DirectReferenceSampleListEntry);
directReferenceSampleListEntry->parseEntry(subBitstr);
mSampleGroupEntry.push_back(std::move(directReferenceSampleListEntry));
}
else
{
/** @todo Add support for other entry types here. **/
logWarning() << "Skipping an entry of SampleGroupDescriptionBox of an unknown grouping type '" << mGroupingType << "'.";
}
}
}
| 28.649351
| 132
| 0.682457
|
anzksdk
|
4da4220cb0d259307ff95cd134a724b843b45219
| 16,191
|
cpp
|
C++
|
src/yyy_main.cpp
|
FlyingJester/kashyyyk2
|
b7de62d6db6d3740f49ff72e5dd94b2f412aa143
|
[
"Linux-OpenIB"
] | null | null | null |
src/yyy_main.cpp
|
FlyingJester/kashyyyk2
|
b7de62d6db6d3740f49ff72e5dd94b2f412aa143
|
[
"Linux-OpenIB"
] | null | null | null |
src/yyy_main.cpp
|
FlyingJester/kashyyyk2
|
b7de62d6db6d3740f49ff72e5dd94b2f412aa143
|
[
"Linux-OpenIB"
] | null | null | null |
/*
* Copyright (c) 2014-2017 Martin McDonough. 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.
*
* - Products derived from this software may not be called "Kashyyyk", nor may
* "YYY" appear in their name, without prior written permission of
* the copyright holders.
*
* 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 "yyy_main.h"
#include "yyy_assert.h"
#include "yyy_connect_thread.h"
// Vector must be included before Fl_Window or else Watcom literally crashes.
// The issue seems related with FL_x.H including Windows.h, which redefines
// 'max' in a way that seriously confuses Watcom. To the point of crashing.
// Somehow that redefine messes up how the std::numeric_limits<>::max() is
// understood by the compiler.
#include <vector>
// Included early to fix warnings about unary & operators.
#include <FL/fl_ask.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Tree.H>
#include <FL/Fl_Tree_Item.H>
#include "kashyyyk2.hpp"
#include "ui/yyy_server_tree.hpp"
#include "yyy_server_controller.hpp"
#include "yyy_server_core.hpp"
#include "yyy_server_ui.hpp"
#include "yyy_server_thread.hpp"
#include "yyy_theme.h"
#include "yyy_maintainer.hpp"
#include "yyy_alloca.h"
#include "monitor/yyy_monitor.hpp"
#include "thread/yyy_thread.h"
#include <FL/Fl.H>
#include "utils/yyy_fl_locker.hpp"
#include <string>
#include <stdlib.h>
#include <assert.h>
#ifdef YYY_ENABLE_IRC
#include "irc/yyy_irc.hpp"
#endif
#ifdef YYY_ENABLE_SPARK
#include "irc/yyy_spark.hpp"
#endif
#ifdef YYY_ENABLE_DISCORD
#include "irc/yyy_discord.hpp"
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include "Windows.h"
#include "TCHAR.h"
#ifdef __WATCOMC__
#ifndef _TRUNCATE
#define _TRUNCATE 0
#endif
static inline int _sntprintf_s(TCHAR *dest, size_t size, size_t count, const TCHAR *fmt, ...){
assert(count == _TRUNCATE || count <= size);
va_list args;
va_start(args, fmt);
const int r = _sntprintf(dest, size - 1, fmt, args);
va_end(args);
dest[size-1] = *TEXT("");
return r;
}
#endif
#endif
const char help_string[] = "Kashyyyk2\n"\
" -v, --version Display version information\n"\
" -h, --help Display this help information\n";
namespace YYY {
/*---------------------------------------------------------------------------*/
struct Window {
Fl_Double_Window *m_window;
ServerTree *m_server_tree;
ServerThread *m_server_thread;
} yyy_main_window;
/*---------------------------------------------------------------------------*/
#ifdef YYY_ENABLE_IRC
static ChatProtocol *irc_protocol;
#endif
/*---------------------------------------------------------------------------*/
#ifdef YYY_ENABLE_SPARK
ChatProtocol *spark_protocol;
#endif
/*---------------------------------------------------------------------------*/
#ifdef YYY_ENABLE_DISCORD
ChatProtocol *discord_protocol;
#endif
/*---------------------------------------------------------------------------*/
static inline const char *yyy_determine_server_name(const char *url,
unsigned short &name_len){
const char *name;
unsigned short dot_indices[2] = {0, 0};
// Sort out the probable name of the server. This mostly depends on
// where the domain separators (aka, a dot) appear. If there is only
// one, everything before the separator is used. If there are two or
// more, the name is everything after the first but before the last.
unsigned short len = 0;
for(unsigned short dot = 0; url[len] != '\0'; len++){
if(url[len] == '.'){
dot_indices[dot] = len;
dot = 1;
}
}
YYY_Assert(dot_indices[0] != 0 || dot_indices[1] != 0, "Invalid URI");
if(dot_indices[0] == 0 && dot_indices[1] == 0){
// What the actual fart?
name = url;
name_len = len;
}
else if(dot_indices[1] == 0){
name = url;
name_len = dot_indices[0];
}
else{
name = url + dot_indices[0] + 1;
name_len = dot_indices[1] - (dot_indices[0] + 1);
}
return name;
}
/*---------------------------------------------------------------------------*/
static inline Window &yyy_connection_args(const char *uri, void *arg,
const char *&out_name, unsigned short &out_name_len){
assert(uri != NULL);
assert(*uri != '\0');
out_name = yyy_determine_server_name(uri, out_name_len);
return (arg == NULL) ? yyy_main_window : *static_cast<Window*>(arg);
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_FASTCALL YYY_AttemptingConnection(const char *uri, void *arg){
unsigned short name_len;
const char *name;
Window &window = yyy_connection_args(uri, arg, name, name_len);
{
YYY::FlLocker locker;
window.m_server_tree->addConnectingServer(uri, name, name_len);
window.m_server_tree->redraw();
}
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_FASTCALL YYY_FailedConnection(const char *uri, void *arg){
unsigned short name_len;
const char *name;
Window &window = yyy_connection_args(uri, arg, name, name_len);
{
YYY::FlLocker locker;
window.m_server_tree->connectionFailed(name, name_len);
window.m_server_tree->redraw();
}
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_FASTCALL YYY_AddConnection(struct YYY_NetworkSocket *socket, const char *uri,
void *arg){
unsigned short name_len;
const char *name;
Window &window = yyy_connection_args(uri, arg, name, name_len);
// TEST: Assume IRC for now.
ServerController *const server = new ServerController(*irc_protocol);
server->setup(name, name_len, socket);
window.m_server_thread->addServer(*server);
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_FASTCALL YYY_TryJoin(const char *channel){
ServerTree::ServerData *const server_data =
yyy_main_window.m_server_tree->getSelectedServer();
YYY_Assert(server_data != NULL, "No server data found when trying to connect");
if(server_data){
Message join_msg;
const size_t where_len = strlen(channel);
assert(where_len < ~((unsigned short)0));
join_msg.type = eYYYChatJoin;
join_msg.m.join.from = NULL;
join_msg.m.join.from_len = 0;
join_msg.m.join.where = channel;
join_msg.m.join.where_len = (unsigned short)where_len;
server_data->arg->send(join_msg);
}
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_FASTCALL YYY_SendPrivateMessage(const char *msg,
unsigned short lens,
const char *channel){
YYY_SendPrivateMessageV(&msg, &lens, 1, channel);
}
/*---------------------------------------------------------------------------*/
extern "C"
void YYY_SendPrivateMessageV(const char **msgs,
unsigned short *lens,
unsigned short num_msgs,
const char *channel){
assert(msgs);
assert(lens);
if(num_msgs == 0)
return;
Message priv_msg;
priv_msg.type = eYYYChatMessage;
priv_msg.m.message.from = NULL;
priv_msg.m.message.from_len = 0;
ServerTree::ServerData *server_data = NULL;
// This is used to echo the message in our own buffer if applicable.
ChannelController *channel_controller = NULL;
if(channel == NULL){
if(const ServerTree::ChannelData *const channel_data =
yyy_main_window.m_server_tree->getSelectedChannel(&server_data)){
assert(server_data != NULL);
assert(channel_data->arg != NULL);
channel_controller = channel_data->arg;
const std::string &channel_name = channel_controller->name();
priv_msg.m.message.to = channel_name.c_str();
assert(channel_name.length() < ~((unsigned short)0));
priv_msg.m.message.to_len = (unsigned short)channel_name.length();
}
else{
// Send an error message otherwise?
return;
}
}
else{
server_data = yyy_main_window.m_server_tree->getSelectedServer();
priv_msg.m.message.to = channel;
const size_t channel_len = strlen(channel);
assert(channel_len < ~((unsigned short)0));
priv_msg.m.message.to_len = (unsigned short)channel_len;
}
if(server_data == NULL)
return;
assert(server_data->arg != NULL);
ServerController &server = *server_data->arg;
for(unsigned short i = 0; i < num_msgs; i++){
if(const unsigned short len = lens[i]){
priv_msg.m.message.message = msgs[i];
priv_msg.m.message.message_len = len;
assert(msgs[i] != NULL);
server.send(priv_msg);
if(channel_controller)
channel_controller->handleMessage(priv_msg, false, false);
}
}
}
/*---------------------------------------------------------------------------*/
static void yyy_server_tree_callback(Fl_Widget *w, void *arg){
assert(w != NULL);
assert(arg != NULL);
Window &window = *static_cast<Window*>(arg);
ServerTree &tree = *static_cast<ServerTree*>(w);
(void)window;
if(tree.callback_reason() != FL_TREE_REASON_SELECTED)
return;
Fl_Tree_Item *const item = tree.callback_item();
const char *l = item->label();
assert(l != NULL);
if(item == tree.root()){}
else if(item->parent() == tree.root()){ // Is a server
ServerTree::ServerData *const data =
(ServerTree::ServerData*)(item->user_data());
assert(data != NULL);
ServerController *const server = data->arg;
if(ServerTree::IsConnected(data)){
assert(server != NULL);
server->select(NULL, 0);
}
else if(server != NULL){
// Since we only put a server/arg into the server data when a
// connection succeeds, this means we were previously connected,
// and then got disconnected.
}
}
else{ // Is a channel
ServerTree::ChannelData *const data =
(ServerTree::ChannelData*)(item->user_data());
ChannelController *controller = data->arg;
controller->select();
}
}
/*---------------------------------------------------------------------------*/
// args must be free-able by YYY_ALLOCA_FREE.
static bool Main(unsigned num_args, const std::string *args){
#ifndef NDEBUG
#if defined __GNUC__
Fl::scheme("plastic");
#elif defined __WATCOMC__
Fl::scheme("gleam");
#else
Fl::scheme("gtk+");
#endif
#else
Fl::scheme("gtk+");
#endif
#ifdef YYY_ENABLE_IRC
irc_protocol = new IRCProtocol();
#endif
#ifdef YYY_ENABLE_SPARK
ChatProtocol *spark_protocol;
#endif
#ifdef YYY_ENABLE_DISCORD
ChatProtocol *discord_protocol;
#endif
YYY_InitThemes();
YYY_StartConnectThread();
yyy_main_window.m_window = YYY_MakeWindow();
#ifdef _WIN32
// Get the application icon, and set the FLTK window to this icon.
{
const HINSTANCE instance = GetModuleHandle(NULL);
HICON icon = LoadIcon(instance, MAKEINTRESOURCE(101));
if(icon != NULL){
yyy_main_window.m_window->icon(icon);
DestroyIcon(icon);
}
else{
TCHAR buffer[100];
_sntprintf_s(buffer,
sizeof(buffer) / sizeof(TCHAR),
_TRUNCATE,
TEXT("Could not load icon: %i\n"),
GetLastError());
OutputDebugString(buffer);
}
}
#endif
yyy_main_window.m_server_tree = server_tree;
yyy_main_window.m_window->show();
yyy_main_window.m_server_thread = new ServerThread();
yyy_main_window.m_server_thread->start();
chat_scroll->callback(ChannelController::ChatScrollCallback, NULL);
chat_scroll->step(1);
chat_scroll->step(1.0);
chat_scroll->range(0.0, 1.0);
chat_scroll->value(0);
server_tree->callback(yyy_server_tree_callback, &yyy_main_window);
YYY_SetTheme(eYYY_DefaultTheme);
{
YYY::FlLocker locker;
Fl::run();
}
YYY_StopConnectThread();
delete yyy_main_window.m_server_thread;
delete yyy_main_window.m_window;
YYY_ALLOCA_FREE(args);
return EXIT_SUCCESS;
}
} // namespace YYY
/*---------------------------------------------------------------------------*/
// Returns false if the option means we should quit.
static bool yyy_handle_arg(const char *arg){
if(arg[0] != '-')
return true;
if((arg[1] == 'h' && (arg[2] == '\0' || strcmp(arg+2, "elp") == 0)) ||
strcmp(arg+1, "-help") == 0){
fwrite(help_string, sizeof(help_string)-1, 1, stdout);
fflush(stdout);
return false;
}
if((arg[1] == 'v' && (arg[2] == '\0' || strcmp(arg+2, "ersion") == 0)) ||
strcmp(arg+1, "-version") == 0){
printf("Kashyyyk 2\nCompiled %s using %s and FLTK %f\n"\
"Copyright Martin McDonough (C) 2017, released under the Mozilla Public License 1.1\n",
__DATE__,
#if (defined __clang__) || (defined __CLANG__)
"Clang",
#elif defined __GNUC__
"GNU gcc/g++ Compiler",
#elif defined _MSC_VER
"Microsoft Visual C/C++ Compiler",
#elif defined __WATCOMC__
"Open Watcom C/C++ Compiler",
#else
"Unknown C/C++ Compiler",
#endif
Fl::version());
fflush(stdout);
return false;
}
return true;
}
/*---------------------------------------------------------------------------*/
#if (defined _MSC_VER) || (((defined WIN32) || (defined _WIN32)) && (defined __GNUC__))
#include <Windows.h>
extern "C"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int){
LPWSTR raw_args = GetCommandLineW();
int argc = 0;
LPWSTR *const argv = CommandLineToArgvW(raw_args, &argc);
std::string *const args = (std::string*)YYY_ALLOCA(argc*sizeof(std::string));
for(int i = 0; i < argc; i++){
const unsigned len = wcslen(argv[i]);
new (args + i) std::string(len + sizeof(TEXT("")), ' ');
size_t resize_len;
#ifdef __WATCOMC__
resize_len = wcstombs(&(args[i][0]), argv[i], args[i].length());
#else
wcstombs_s(&resize_len, &(args[i][0]), args[i].length(), argv[i], len);
#endif
args[i].resize(resize_len);
if(!yyy_handle_arg(args[i].c_str()))
return EXIT_SUCCESS;
}
return YYY::Main(argc, args) ? EXIT_SUCCESS : EXIT_FAILURE;
}
#else
int main(int argc, char **argv){
std::string *const args = (std::string*)YYY_ALLOCA(argc*sizeof(std::string));
for(unsigned i = 0; i < static_cast<unsigned>(argc); i++){
if(!yyy_handle_arg(argv[i])){
return EXIT_SUCCESS;
}
else{
new (args + i) std::string(argv[i]);
}
}
return YYY::Main(argc, args) ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif
| 29.708257
| 99
| 0.584955
|
FlyingJester
|
4dabc83776b871de31d9a018c3b16d6d078091ae
| 298
|
cpp
|
C++
|
Crack_Practice/Xor_Decode_Shellcode.cpp
|
TuringGu/RELearning
|
a44813d6ae0416631bf5b345a7606cdf3d1a3ffe
|
[
"MIT"
] | null | null | null |
Crack_Practice/Xor_Decode_Shellcode.cpp
|
TuringGu/RELearning
|
a44813d6ae0416631bf5b345a7606cdf3d1a3ffe
|
[
"MIT"
] | null | null | null |
Crack_Practice/Xor_Decode_Shellcode.cpp
|
TuringGu/RELearning
|
a44813d6ae0416631bf5b345a7606cdf3d1a3ffe
|
[
"MIT"
] | null | null | null |
void main()
{
__asm int 3 // break
__asm
{
nop
nop
nop
nop
nop
nop
pop eax
add eax, 0x14
xor ecx,ecx
decode_loop:
mov bl,[eax+ecx]
xor bl, 0x44
mov [eax+ecx],bl
inc ecx
cmp bl,0x90 // Ende
jne decode_loop
nop
nop
nop
nop
nop
}
}
| 9.933333
| 22
| 0.536913
|
TuringGu
|
4dac4be4eb05e68464363041ed58d3aacfcb99c3
| 6,057
|
cpp
|
C++
|
skse/GameEvents.cpp
|
Schwarz-Hexe/YAMMS
|
2a64c482a3813ec2450f025e97854f5671c1851e
|
[
"MIT"
] | null | null | null |
skse/GameEvents.cpp
|
Schwarz-Hexe/YAMMS
|
2a64c482a3813ec2450f025e97854f5671c1851e
|
[
"MIT"
] | null | null | null |
skse/GameEvents.cpp
|
Schwarz-Hexe/YAMMS
|
2a64c482a3813ec2450f025e97854f5671c1851e
|
[
"MIT"
] | null | null | null |
#include "GameEvents.h"
// For testing
// TESActivateEvent 0x012E3E60
// TESActiveEffectApplyRemoveEvent 0x012E3E90
// TESActorLocationChangeEvent 0x012E3EC0
// TESBookReadEvent 0x012E3EF0
// TESCellAttachDetachEvent 0x012E3F20
// TESCellFullyLoadedEvent 0x012E3F50
EventDispatcher<TESCombatEvent>* g_combatEventDispatcher = (EventDispatcher<TESCombatEvent>*) 0x012E4DB0;
// TESContainerChangedEvent 0x012E3FE0
EventDispatcher<TESDeathEvent>* g_deathEventDispatcher = (EventDispatcher<TESDeathEvent>*) 0x012E4E10;
// TESDestructionStageChangedEvent 0x012E4E40
// TESEnterBleedoutEvent 0x012E4E70
// TESEquipEvent 0x012E4EA0
// TESFormDeleteEvent 0x012E4ED0
// TESFurnitureEvent 0x012E4F00
// TESGrabReleaseEvent 0x012E4F30
EventDispatcher<TESHitEvent>* g_hitEventDispatcher = (EventDispatcher<TESHitEvent>*) 0x012E4F60;
// TESLoadGameEvent 0x012E4FC0
// TESLockChangedEvent 0x012E4FF0
// TESMagicEffectApplyEvent 0x012E5020
// TESMagicWardHitEvent 0x012E5050
// TESMoveAttachDetachEvent 0x012E5080
// TESObjectLoadedEvent 0x012E50B0
// TESObjectREFRTranslationEvent 0x012E50E0
// TESOpenCloseEvent 0x012E5110
// TESPackageEvent 0x012E5140
// TESPerkEntryRunEvent 0x012E5170
// TESQuestInitEvent 0x012E51A0
EventDispatcher<TESQuestStageEvent>* g_questStageEventDispatcher = (EventDispatcher<TESQuestStageEvent>*) 0x012E51D0;
// TESResetEvent 0x012E5260
// TESResolveNPCTemplatesEvent 0x012E5290
// TESSceneEvent 0x012E52C0
// TESSceneActionEvent 0x012E52F0
// TESScenePhaseEvent 0x012E5320
// TESSellEvent 0x012E5350
//EventDispatcher<TESSleepStartEvent>* g_sleepStartEventDispatcher = (EventDispatcher<TESSleepStartEvent>*) 0x012E4580;
// TESSleepStopEvent 0x012E53B0
// TESSpellCastEvent 0x012E53E0
// TESTopicInfoEvent 0x012E5440
// TESTrackedStatsEvent 0x012E5470
// TESTrapHitEvent 0x012E54A0
// TESTriggerEvent 0x012E54D0
// TESTriggerEnterEvent 0x012E5500
// TESTriggerLeaveEvent 0x012E5530
// TESUniqueIDChangeEvent 0x012E5560
// TESSwitchRaceCompleteEvent 0x012E55F0
// TESPlayerBowShotEvent 0x012E5410
EventDispatcher<BGSFootstepEvent>* g_footstepEventDispatcher = (EventDispatcher<BGSFootstepEvent>*) 0x01B2E9C0;
// Story based events
EventDispatcher<TESHarvestEvent::ItemHarvested>* g_harvestEventDispatcher = (EventDispatcher<TESHarvestEvent::ItemHarvested>*) 0x012E5A74;
// Event ActorKill 0xDEADBEEF
// Event ActorItemEquipped 0xDEADBEEF
// Event Pickpocket 0xDEADBEEF
// Event BooksRead 0xDEADBEEF
EventDispatcher<LevelIncrease::Event>* g_levelIncreaseEventDispatcher = (EventDispatcher<LevelIncrease::Event>*) 0x01B39804;
// Event SkillIncrease 0xDEADBEEF
// Event WordLearned 0xDEADBEEF
// Event WordUnlocked 0xDEADBEEF
// Event Inventory 0xDEADBEEF
// Event Bounty 0xDEADBEEF
// Event QuestStatus 0xDEADBEEF
// Event ObjectiveState 0xDEADBEEF
// Event Trespass 0xDEADBEEF
// Event FinePaid 0xDEADBEEF
// Event HoursPassed 0xDEADBEEF
// Event DaysPassed 0xDEADBEEF
// Event DaysJailed 0xDEADBEEF
// Event CriticalHitEvent 0xDEADBEEF
// Event DisarmedEvent 0xDEADBEEF
// Event ItemsPickpocketed 0xDEADBEEF
// Event ItemSteal 0xDEADBEEF
// Event ItemCrafted 0xDEADBEEF
// Event LocationDiscovery 0xDEADBEEF
// Event Jailing 0xDEADBEEF
// Event ChestsLooted 0xDEADBEEF
// Event TimesTrained 0xDEADBEEF
// Event TimesBartered 0xDEADBEEF
// Event ContractedDisease 0xDEADBEEF
// Event SpellsLearned 0xDEADBEEF
// Event DragonSoulGained 0xDEADBEEF
// Event SoulGemsUsed 0xDEADBEEF
// Event SoulsTrapped 0xDEADBEEF
// Event PoisonedWeapon 0xDEADBEEF
// Event ShoutAttack 0xDEADBEEF
// Event JailEscape 0xDEADBEEF
// Event GrandTheftHorse 0xDEADBEEF
// Event AssaultCrime 0xDEADBEEF
// Event MurderCrime 0xDEADBEEF
// Event LocksPicked 0xDEADBEEF
// Event LocationCleared 0xDEADBEEF
// Event ShoutMastered 0xDEADBEEF
| 62.443299
| 139
| 0.517418
|
Schwarz-Hexe
|
4db2c93e2f3756702fca4065eb04355580b84e38
| 1,844
|
cpp
|
C++
|
POJ/10 - 13/poj1001.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | 1
|
2017-08-19T16:02:15.000Z
|
2017-08-19T16:02:15.000Z
|
POJ/10 - 13/poj1001.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | null | null | null |
POJ/10 - 13/poj1001.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | 1
|
2018-01-05T23:37:23.000Z
|
2018-01-05T23:37:23.000Z
|
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
const int MaxL = 1000;
int n, point, index; // n次幂。point代表小数点后有几位。
int si[MaxL], res[MaxL], tmp[MaxL], l; // si[MaxL]存s变成的整数,一位一位存
string s;
void _toInt() // 让s变成一个整数串,并且记录下小数点后有几位
{
point = 0; // 初始化point;
index = 0; // si的下标变量
int l = s.length();
int i = l - 1, flag = 0;
for (int j = 0; j <= i; j++)
{
if (s[j] == '0' && !index && !flag)
/*除去前导0,前导0满足3个要求 1.为0 2.在.前面 3.在数前面*/
continue;
if (s[j]=='.')
{
for (i = l - 1; s[i] == '0'; i--); // 除去后导0
flag = 1;
continue;
}
if (flag) { si[index++] = s[j] - 48; point++; }
else si[index++] = s[j] - 48;
}
}
void print()
{
int k = point * n;
if (l + 1 > k)
{
for (int i = 1; i <= l + 1; i++)
{
if (i == l + 1 - k + 1) cout << ".";
cout << res[i - 1];
}
}
else{
cout << ".";
for (int i = 0; i < k - l - 1; i++)
cout << "0";
for (int i = 0; i <= l; i++)
cout << res[i];
}
cout << endl;
}
int main()
{
while (cin >> s >> n)
{
_toInt();
memcpy(res, si, sizeof(res));
l = index - 1; // 记录res的长度
int tsz; // 记录中间过程的下标
for (int tt = 0; tt < n - 1; tt++) // 进行n - 1次迭代
{
memset(tmp, 0, sizeof(tmp)); // 把中间变量置为0
for (int i = index - 1; i >= 0; i--) // 对于si的每一位
{
tsz = index - i - 2; // 要把这位的结果从这里开始放。模拟竖式乘法
for (int j = l; j >= 0; j--) // 乘以res中的每一位
{
tsz++;
tmp[tsz] += si[i] * res[j];
if (tmp[tsz] >= 10)
{
int k = tmp[tsz] / 10;
tmp[tsz] %= 10;
tmp[tsz + 1] += k;
}
}
}
tsz++;
while (tmp[tsz] != 0)
{
if (tmp[tsz] >= 10)
{
int k = tmp[tsz] / 10;
tmp[tsz] %= 10;
tmp[tsz + 1] += k;
}
tsz++;
}
tsz--;
if (tsz > l) l = tsz;
for (int i = 0; i <= l; i++) res[i] = tmp[l - i];
}
print();
}
return 0;
}
| 19.410526
| 63
| 0.453362
|
bilibiliShen
|
4dbaef671c5ae9df84c6bc67b713e514c099acb9
| 5,061
|
cpp
|
C++
|
lib/AST/Stmt.cpp
|
jamboree/Sora
|
a75c96452857109e90ff61771991415d880b5b37
|
[
"MIT"
] | null | null | null |
lib/AST/Stmt.cpp
|
jamboree/Sora
|
a75c96452857109e90ff61771991415d880b5b37
|
[
"MIT"
] | null | null | null |
lib/AST/Stmt.cpp
|
jamboree/Sora
|
a75c96452857109e90ff61771991415d880b5b37
|
[
"MIT"
] | null | null | null |
//===--- Stmt.cpp -----------------------------------------------*- C++ -*-===//
// Part of the Sora project, licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
//
// Copyright (c) 2019 Pierre van Houtryve
//===----------------------------------------------------------------------===//
#include "Sora/AST/Stmt.hpp"
#include "ASTNodeLoc.hpp"
#include "Sora/AST/ASTContext.hpp"
#include "Sora/AST/Decl.hpp"
#include "Sora/AST/Expr.hpp"
#include "llvm/ADT/ArrayRef.h"
using namespace sora;
/// Check that all statements are trivially destructible. This is needed
/// because, as they are allocated in the ASTContext's arenas, their destructors
/// are never called.
#define STMT(ID, PARENT) \
static_assert(std::is_trivially_destructible<ID##Stmt>::value, \
#ID "Stmt is not trivially destructible.");
#include "Sora/AST/StmtNodes.def"
void *Stmt::operator new(size_t size, ASTContext &ctxt, unsigned align) {
return ctxt.allocate(size, align, ArenaKind::Permanent);
}
SourceLoc Stmt::getBegLoc() const {
switch (getKind()) {
#define STMT(ID, PARENT) \
case StmtKind::ID: \
return ASTNodeLoc<Stmt, ID##Stmt>::getBegLoc(cast<ID##Stmt>(this));
#include "Sora/AST/StmtNodes.def"
}
llvm_unreachable("unknown StmtKind");
}
SourceLoc Stmt::getEndLoc() const {
switch (getKind()) {
#define STMT(ID, PARENT) \
case StmtKind::ID: \
return ASTNodeLoc<Stmt, ID##Stmt>::getEndLoc(cast<ID##Stmt>(this));
#include "Sora/AST/StmtNodes.def"
}
llvm_unreachable("unknown StmtKind");
}
SourceLoc Stmt::getLoc() const {
switch (getKind()) {
#define STMT(ID, PARENT) \
case StmtKind::ID: \
return ASTNodeLoc<Stmt, ID##Stmt>::getLoc(cast<ID##Stmt>(this));
#include "Sora/AST/StmtNodes.def"
}
llvm_unreachable("unknown StmtKind");
}
SourceRange Stmt::getSourceRange() const {
switch (getKind()) {
#define STMT(ID, PARENT) \
case StmtKind::ID: \
return ASTNodeLoc<Stmt, ID##Stmt>::getSourceRange(cast<ID##Stmt>(this));
#include "Sora/AST/StmtNodes.def"
}
llvm_unreachable("unknown StmtKind");
}
SourceLoc ReturnStmt::getBegLoc() const { return returnLoc; }
SourceLoc ReturnStmt::getEndLoc() const {
return result ? result->getEndLoc() : returnLoc;
}
SourceRange BlockStmtElement::getSourceRange() const {
if (is<Expr *>())
return get<Expr *>()->getSourceRange();
if (is<Decl *>())
return get<Decl *>()->getSourceRange();
if (is<Stmt *>())
return get<Stmt *>()->getSourceRange();
llvm_unreachable("unknown node");
}
SourceLoc BlockStmtElement::getBegLoc() const {
if (is<Expr *>())
return get<Expr *>()->getBegLoc();
if (is<Decl *>())
return get<Decl *>()->getBegLoc();
if (is<Stmt *>())
return get<Stmt *>()->getBegLoc();
llvm_unreachable("unknown node");
}
SourceLoc BlockStmtElement::getEndLoc() const {
if (is<Expr *>())
return get<Expr *>()->getEndLoc();
if (is<Decl *>())
return get<Decl *>()->getEndLoc();
if (is<Stmt *>())
return get<Stmt *>()->getEndLoc();
llvm_unreachable("unknown node");
}
BlockStmt::BlockStmt(SourceLoc lCurlyLoc, ArrayRef<BlockStmtElement> elts,
SourceLoc rCurlyLoc)
: Stmt(StmtKind::Block), lCurlyLoc(lCurlyLoc), rCurlyLoc(rCurlyLoc) {
bits.BlockStmt.numElements = elts.size();
assert(getNumElements() == elts.size() && "Bits dropped");
std::uninitialized_copy(elts.begin(), elts.end(),
getTrailingObjects<BlockStmtElement>());
}
BlockStmt *BlockStmt::create(ASTContext &ctxt, SourceLoc lCurlyLoc,
ArrayRef<BlockStmtElement> elts,
SourceLoc rCurlyLoc) {
auto size = totalSizeToAlloc<BlockStmtElement>(elts.size());
void *mem = ctxt.allocate(size, alignof(BlockStmt));
return new (mem) BlockStmt(lCurlyLoc, elts, rCurlyLoc);
}
BlockStmt *BlockStmt::createEmpty(ASTContext &ctxt, SourceLoc lCurlyLoc,
SourceLoc rCurlyLoc) {
return create(ctxt, lCurlyLoc, {}, rCurlyLoc);
}
SourceLoc StmtCondition::getBegLoc() const {
switch (getKind()) {
case StmtConditionKind::Expr:
return getExpr()->getBegLoc();
case StmtConditionKind::LetDecl:
return getLetDecl()->getBegLoc();
}
llvm_unreachable("unknown condition kind");
}
SourceLoc StmtCondition::getEndLoc() const {
switch (getKind()) {
case StmtConditionKind::Expr:
return getExpr()->getEndLoc();
case StmtConditionKind::LetDecl:
return getLetDecl()->getEndLoc();
}
llvm_unreachable("unknown condition kind");
}
| 34.903448
| 80
| 0.586248
|
jamboree
|
4dbc7e2c54ee15fdcc13bd611c177fae31bcc842
| 931
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_SpiderL_Character_BP_Medium_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_SpiderL_Character_BP_Medium_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_SpiderL_Character_BP_Medium_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_SpiderL_Character_BP_Medium_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function SpiderL_Character_BP_Medium.SpiderL_Character_BP_Medium_C.UserConstructionScript
struct ASpiderL_Character_BP_Medium_C_UserConstructionScript_Params
{
};
// Function SpiderL_Character_BP_Medium.SpiderL_Character_BP_Medium_C.ExecuteUbergraph_SpiderL_Character_BP_Medium
struct ASpiderL_Character_BP_Medium_C_ExecuteUbergraph_SpiderL_Character_BP_Medium_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 28.212121
| 152
| 0.62406
|
2bite
|
4dc0bf2ad998aef2dc265069a24a59052750f211
| 1,279
|
cpp
|
C++
|
test/doc/math/geommean.cpp
|
the-moisrex/eve
|
80b52663eefee11460abb0aedf4158a5067cf7dc
|
[
"MIT"
] | 340
|
2020-09-16T21:12:48.000Z
|
2022-03-28T15:40:33.000Z
|
test/doc/math/geommean.cpp
|
the-moisrex/eve
|
80b52663eefee11460abb0aedf4158a5067cf7dc
|
[
"MIT"
] | 383
|
2020-09-17T06:56:35.000Z
|
2022-03-13T15:58:53.000Z
|
test/doc/math/geommean.cpp
|
the-moisrex/eve
|
80b52663eefee11460abb0aedf4158a5067cf7dc
|
[
"MIT"
] | 28
|
2021-02-27T23:11:23.000Z
|
2022-03-25T12:31:29.000Z
|
//#include <eve/function/geommean.hpp>
#include <eve/module/math.hpp>
#include <eve/literals.hpp>
#include <eve/wide.hpp>
#include <vector>
#include <iostream>
int main()
{
using w_t = eve::wide<double, eve::fixed<4>>;
w_t pi = {3, 2, 3, -3}, qi = {4, 2, 1, -100};
std::cout << "---- simd" << '\n'
<< " <- pi = " << pi << '\n'
<< " <- qi = " << qi << '\n'
<< " -> geommean(pi, qi) = " << eve::geommean(pi, qi) << '\n';
float xi = 3, yi = 4;
std::cout << "---- scalar" << '\n'
<< " xi = " << xi << '\n'
<< " yi = " << yi << '\n'
<< " -> geommean(xi, yi) = " << eve::geommean(xi, yi) << '\n';
w_t pf = {3, 1, -3, -10}, qf = {4, 1, 1, 15};;
std::cout << "---- multi" << '\n'
<< " <- pf = " << pf << '\n'
<< " <- qf = " << qf << '\n'
<< " -> geommean(1.0f, qf, pf, 32.0f) = " << eve::geommean(1.0f, qf, pf, 32.0f) << '\n'
<< " -> geommean(1.0f, qf, pf, 32.0f) = " << eve::geommean(1.0f, qf, pf, 32.0f) << '\n'
<< " -> geommean(-1.0f, qf, pf) = " << eve::geommean(-1.0f, qf, pf) << '\n';
return 0;
}
| 36.542857
| 101
| 0.351837
|
the-moisrex
|
4dc15a0f79e0439877e50c88b073d29b408d3ebb
| 2,458
|
cpp
|
C++
|
src/RcppExports.cpp
|
rdinnager/rbff
|
899e4f32558c82e180ecd79df247f1c8e5e92308
|
[
"MIT"
] | 4
|
2021-08-18T04:33:42.000Z
|
2021-12-30T02:06:07.000Z
|
src/RcppExports.cpp
|
rdinnager/rbff
|
899e4f32558c82e180ecd79df247f1c8e5e92308
|
[
"MIT"
] | 7
|
2021-09-21T17:38:21.000Z
|
2022-01-11T14:54:54.000Z
|
src/RcppExports.cpp
|
rdinnager/rbff
|
899e4f32558c82e180ecd79df247f1c8e5e92308
|
[
"MIT"
] | 3
|
2021-09-09T20:43:55.000Z
|
2021-12-29T23:17:04.000Z
|
// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// auto_flatten
void auto_flatten(const std::string& inputPath, int nCones, bool flattenToDisk, bool mapToSphere, bool normalizeUVs, const std::string& outputPath);
RcppExport SEXP _rbff_auto_flatten(SEXP inputPathSEXP, SEXP nConesSEXP, SEXP flattenToDiskSEXP, SEXP mapToSphereSEXP, SEXP normalizeUVsSEXP, SEXP outputPathSEXP) {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::string& >::type inputPath(inputPathSEXP);
Rcpp::traits::input_parameter< int >::type nCones(nConesSEXP);
Rcpp::traits::input_parameter< bool >::type flattenToDisk(flattenToDiskSEXP);
Rcpp::traits::input_parameter< bool >::type mapToSphere(mapToSphereSEXP);
Rcpp::traits::input_parameter< bool >::type normalizeUVs(normalizeUVsSEXP);
Rcpp::traits::input_parameter< const std::string& >::type outputPath(outputPathSEXP);
auto_flatten(inputPath, nCones, flattenToDisk, mapToSphere, normalizeUVs, outputPath);
return R_NilValue;
END_RCPP
}
// flatten_to_shape
void flatten_to_shape(const std::string& inputPath, NumericMatrix boundary_shape, bool normalizeUVs, const std::string& outputPath);
RcppExport SEXP _rbff_flatten_to_shape(SEXP inputPathSEXP, SEXP boundary_shapeSEXP, SEXP normalizeUVsSEXP, SEXP outputPathSEXP) {
BEGIN_RCPP
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const std::string& >::type inputPath(inputPathSEXP);
Rcpp::traits::input_parameter< NumericMatrix >::type boundary_shape(boundary_shapeSEXP);
Rcpp::traits::input_parameter< bool >::type normalizeUVs(normalizeUVsSEXP);
Rcpp::traits::input_parameter< const std::string& >::type outputPath(outputPathSEXP);
flatten_to_shape(inputPath, boundary_shape, normalizeUVs, outputPath);
return R_NilValue;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_rbff_auto_flatten", (DL_FUNC) &_rbff_auto_flatten, 6},
{"_rbff_flatten_to_shape", (DL_FUNC) &_rbff_flatten_to_shape, 4},
{NULL, NULL, 0}
};
RcppExport void R_init_rbff(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| 47.269231
| 163
| 0.771766
|
rdinnager
|
4dc3e113d59467dae5f14e3acbd211f36d0677d0
| 634
|
hpp
|
C++
|
services/interactive_python/jupyter/display_publisher.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 9
|
2020-07-20T15:32:07.000Z
|
2021-06-04T13:02:58.000Z
|
services/interactive_python/jupyter/display_publisher.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 26
|
2019-10-27T12:58:42.000Z
|
2020-05-30T16:43:48.000Z
|
services/interactive_python/jupyter/display_publisher.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 3
|
2020-08-29T07:07:49.000Z
|
2021-06-04T13:02:59.000Z
|
#pragma once
#include <pybind11/embed.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace services { namespace interactive_python { namespace jupyter {
namespace py = pybind11;
class display_publisher final {
public:
static auto set_parent(py::object self, py::dict parent) -> void;
static auto publish(py::object self, py::dict data, py::dict metadata,
py::str source, py::dict trasistent, py::bool_ update)
-> void;
static auto clear_output(py::object self, py::bool_ wait = false) -> void;
};
}}}
| 26.416667
| 82
| 0.648265
|
jinntechio
|
4dca20639345e2fb09e2ae2ac76726892aa651ab
| 5,493
|
cpp
|
C++
|
src/lib/foundations/geometry/decomposition.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-10-27T15:18:28.000Z
|
2022-02-09T11:13:07.000Z
|
src/lib/foundations/geometry/decomposition.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 4
|
2019-12-09T11:49:11.000Z
|
2020-07-30T17:34:45.000Z
|
src/lib/foundations/geometry/decomposition.cpp
|
abetten/orbiter
|
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
|
[
"RSA-MD"
] | 15
|
2016-06-10T20:05:30.000Z
|
2020-12-18T04:59:19.000Z
|
// decomposition.cpp
//
// Anton Betten
//
// December 1, 2012
#include "foundations.h"
using namespace std;
namespace orbiter {
namespace foundations {
decomposition::decomposition()
{
null();
}
decomposition::~decomposition()
{
freeself();
}
void decomposition::null()
{
Inc = 0;
I = 0;
Stack = NULL;
f_has_decomposition = FALSE;
f_has_row_scheme = FALSE;
f_has_col_scheme = FALSE;
}
void decomposition::freeself()
{
if (Inc) {
FREE_int(Inc);
}
if (I) {
FREE_OBJECT(I);
}
if (Stack) {
FREE_OBJECT(Stack);
}
if (f_has_decomposition) {
FREE_int(row_classes);
FREE_int(row_class_inv);
FREE_int(col_classes);
FREE_int(col_class_inv);
}
if (f_has_row_scheme) {
FREE_int(row_scheme);
}
if (f_has_col_scheme) {
FREE_int(col_scheme);
}
null();
}
void decomposition::init_inc_and_stack(
incidence_structure *Inc,
partitionstack *Stack,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::init_inc_and_stack" << endl;
}
nb_points = Inc->nb_rows;
nb_blocks = Inc->nb_cols;
I = Inc;
decomposition::Stack = Stack;
if (f_v) {
cout << "decomposition::init_inc_and_stack done" << endl;
}
}
void decomposition::init_incidence_matrix(
int m, int n, int *M, int verbose_level)
// copies the incidence matrix
{
int f_v = (verbose_level >= 1);
int i;
if (f_v) {
cout << "decomposition::init_incidence_matrix" << endl;
}
nb_points = m;
nb_blocks = n;
Inc = NEW_int(nb_points * nb_blocks);
for (i = 0; i < nb_points * nb_blocks; i++) {
Inc[i] = M[i];
}
}
void decomposition::setup_default_partition(int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::setup_default_partition" << endl;
}
I = NEW_OBJECT(incidence_structure);
if (f_v) {
cout << "decomposition::setup_default_partition "
"before I->init_by_matrix" << endl;
}
I->init_by_matrix(nb_points, nb_blocks,
Inc, 0 /* verbose_level */);
if (f_v) {
cout << "decomposition::setup_default_partition "
"after I->init_by_matrix" << endl;
}
Stack = NEW_OBJECT(partitionstack);
Stack->allocate(nb_points + nb_blocks,
0 /* verbose_level */);
Stack->subset_continguous(nb_points, nb_blocks);
Stack->split_cell(0 /* verbose_level */);
Stack->sort_cells();
if (f_v) {
cout << "decomposition::setup_default_partition done" << endl;
}
}
void decomposition::compute_TDO(int max_depth, int verbose_level)
// put max_depth = INT_MAX if you want full depth
{
int f_v = (verbose_level >= 1);
//int depth = INT_MAX;
if (f_v) {
cout << "decomposition::compute_TDO" << endl;
}
if (f_v) {
cout << "decomposition::compute_TDO "
"before I->compute_TDO_safe" << endl;
}
I->compute_TDO_safe(*Stack, max_depth, verbose_level /*- 2 */);
if (f_v) {
cout << "decomposition::compute_TDO "
"after I->compute_TDO_safe" << endl;
}
Stack->allocate_and_get_decomposition(
row_classes, row_class_inv, nb_row_classes,
col_classes, col_class_inv, nb_col_classes,
0);
f_has_decomposition = TRUE;
if (f_v) {
cout << "decomposition::compute_TDO done" << endl;
}
}
void decomposition::get_row_scheme(int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::get_row_scheme" << endl;
}
if (!f_has_decomposition) {
cout << "decomposition::get_row_scheme "
"!f_has_decomposition" << endl;
exit(1);
}
f_has_row_scheme = TRUE;
row_scheme = NEW_int(nb_row_classes * nb_col_classes);
I->get_row_decomposition_scheme(*Stack,
row_classes, row_class_inv, nb_row_classes,
col_classes, col_class_inv, nb_col_classes,
row_scheme, 0);
if (f_v) {
cout << "decomposition::get_row_scheme done" << endl;
}
}
void decomposition::get_col_scheme(int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::get_col_scheme" << endl;
}
if (!f_has_decomposition) {
cout << "decomposition::get_col_scheme "
"!f_has_decomposition" << endl;
exit(1);
}
f_has_col_scheme = TRUE;
col_scheme = NEW_int(nb_row_classes * nb_col_classes);
I->get_col_decomposition_scheme(*Stack,
row_classes, row_class_inv, nb_row_classes,
col_classes, col_class_inv, nb_col_classes,
col_scheme, 0);
if (f_v) {
cout << "decomposition::get_col_scheme done" << endl;
}
}
void decomposition::print_row_decomposition_tex(
ostream &ost,
int f_enter_math, int f_print_subscripts,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::print_row_decomposition_tex" << endl;
}
if (!f_has_row_scheme) {
cout << "decomposition::print_row_decomposition_tex "
"!f_has_row_scheme" << endl;
exit(1);
}
//I->get_and_print_row_tactical_decomposition_scheme_tex(
// file, FALSE /* f_enter_math */, *Stack);
Stack->print_row_tactical_decomposition_scheme_tex(
ost, f_enter_math,
row_classes, nb_row_classes,
col_classes, nb_col_classes,
row_scheme, f_print_subscripts);
}
void decomposition::print_column_decomposition_tex(
ostream &ost,
int f_enter_math, int f_print_subscripts,
int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "decomposition::print_column_decomposition_tex" << endl;
}
//I->get_and_print_column_tactical_decomposition_scheme_tex(
// file, FALSE /* f_enter_math */, *Stack);
Stack->print_column_tactical_decomposition_scheme_tex(
ost, f_enter_math,
row_classes, nb_row_classes,
col_classes, nb_col_classes,
col_scheme, f_print_subscripts);
}
}
}
| 21.373541
| 66
| 0.697797
|
abetten
|
4dca932f6db3b9a3dabc5d7c95e9075d7f91d709
| 617
|
cpp
|
C++
|
Websites/Codeforces/339A.cpp
|
justaname94/Algorithms
|
4c9ec4119b0d92d5889f85b89fcb24f885a82373
|
[
"MIT"
] | null | null | null |
Websites/Codeforces/339A.cpp
|
justaname94/Algorithms
|
4c9ec4119b0d92d5889f85b89fcb24f885a82373
|
[
"MIT"
] | null | null | null |
Websites/Codeforces/339A.cpp
|
justaname94/Algorithms
|
4c9ec4119b0d92d5889f85b89fcb24f885a82373
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string operation;
cin >> operation;
string result;
int arrSize = (operation.length()/2) + 1;
int digits[arrSize];
int digitIndex = 0;
for (int i = 0; i < operation.length(); i++) {
if (operation[i] != '+')
digits[digitIndex++] = operation[i] - '0';
}
sort(digits, digits+arrSize);
for (int i = 0; i < arrSize; i++) {
result += (digits[i] + '0');
result += "+";
}
result = result.substr(0, result.length()-1);
cout << result << endl;
return 0;
}
| 21.275862
| 54
| 0.531605
|
justaname94
|
4dcaff8952eddbe7a377bcbff443daebfb3f60a7
| 173
|
cpp
|
C++
|
cpp_composition_over_inheritance_code/src/i_movable.cpp
|
kedingp/sandbox
|
b9a814c6578dfabe2463b3c83982c3fdfeda7f21
|
[
"MIT"
] | null | null | null |
cpp_composition_over_inheritance_code/src/i_movable.cpp
|
kedingp/sandbox
|
b9a814c6578dfabe2463b3c83982c3fdfeda7f21
|
[
"MIT"
] | 4
|
2019-02-24T07:59:05.000Z
|
2019-03-17T22:51:23.000Z
|
cpp_composition_over_inheritance_code/src/i_movable.cpp
|
kedingp/sandbox
|
b9a814c6578dfabe2463b3c83982c3fdfeda7f21
|
[
"MIT"
] | null | null | null |
#include <cpp_composition_over_inheritance_code/i_movable.h>
namespace table_tennis {
I_Movable::I_Movable()
{
}
I_Movable::~I_Movable()
{
}
}
| 10.8125
| 60
| 0.641618
|
kedingp
|
4dccdbec58853d23d5d1490cdc0bedf6d57efc12
| 184
|
cpp
|
C++
|
source/tests.cpp
|
Looo911/programmiersprachen-aufgabenblatt-3
|
7ac3e5f0a37e889e03ceae3b62ebd5da2370b91f
|
[
"MIT"
] | null | null | null |
source/tests.cpp
|
Looo911/programmiersprachen-aufgabenblatt-3
|
7ac3e5f0a37e889e03ceae3b62ebd5da2370b91f
|
[
"MIT"
] | null | null | null |
source/tests.cpp
|
Looo911/programmiersprachen-aufgabenblatt-3
|
7ac3e5f0a37e889e03ceae3b62ebd5da2370b91f
|
[
"MIT"
] | null | null | null |
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
TEST_CASE("Circle&Rectangle", "[operator]")
{
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
| 12.266667
| 43
| 0.668478
|
Looo911
|
4dd0653c57f4ce46eb0910682235f37dab678229
| 721
|
cpp
|
C++
|
samples/round_robin.cpp
|
alarouche/cppao
|
5519c8014286c60200bc7123b445b57848168584
|
[
"MIT",
"Unlicense"
] | null | null | null |
samples/round_robin.cpp
|
alarouche/cppao
|
5519c8014286c60200bc7123b445b57848168584
|
[
"MIT",
"Unlicense"
] | null | null | null |
samples/round_robin.cpp
|
alarouche/cppao
|
5519c8014286c60200bc7123b445b57848168584
|
[
"MIT",
"Unlicense"
] | null | null | null |
#include <active/object.hpp>
#include <cstdio>
/* A slightly more sophisticated example.
* In this case, each node punts a message to its next node in a loop.
* To make things interesting, we add lots of messages concurrently.
*/
struct RoundRobin : public active::object<RoundRobin>
{
RoundRobin * next;
void active_method( int packet )
{
printf( "Received packed %d\n", packet );
if( packet>0 ) (*next)(packet-1);
}
};
int main()
{
// Create 1000 nodes.
const int Count=1000;
RoundRobin nodes[Count];
// Link them together
for(int i=0; i<Count-1; ++i) nodes[i].next = nodes+i+1;
nodes[Count-1].next=nodes;
// Send each node a packet.
for(int i=0; i<Count; ++i) nodes[i](10);
active::run();
}
| 20.6
| 70
| 0.67129
|
alarouche
|
4dddccd6861c9ebff6d530023c4981974fbe7aed
| 5,947
|
hpp
|
C++
|
src/autonomy/script_commands.hpp
|
medlefsen/autonomy
|
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
|
[
"Artistic-2.0"
] | 2
|
2015-05-31T20:26:51.000Z
|
2022-02-19T16:11:14.000Z
|
src/autonomy/script_commands.hpp
|
medlefsen/autonomy
|
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
|
[
"Artistic-2.0"
] | null | null | null |
src/autonomy/script_commands.hpp
|
medlefsen/autonomy
|
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
|
[
"Artistic-2.0"
] | null | null | null |
#ifndef AUTONOMY_SCRIPT_COMMANDS_HPP
#define AUTONOMY_SCRIPT_COMMANDS_HPP
#include <boost/random.hpp>
#include <autonomy/script_instruction.hpp>
#include <autonomy/entity/scripted_drone.hpp>
namespace autonomy {
//! \brief Move command.
//! Takes 2 "directions", up and right.
//! A direction is either positive, 0 or negative
struct move : public script_instruction_base<move>
{
friend class boost::serialization::access;
static std::string name() { return "move"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<move>);
}
};
struct get_x : public script_instruction_base<get_x>
{
friend class boost::serialization::access;
static std::string name() { return "get_x"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<get_x>);
}
};
struct get_y : public script_instruction_base<get_y>
{
friend class boost::serialization::access;
static std::string name() { return "get_y"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<get_y>);
}
};
//! \brief scan command
//! Takes an x and a y and returns an "object type"
struct scan : public script_instruction_base<scan>
{
friend class boost::serialization::access;
static std::string name() { return "scan"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<scan>);
}
};
struct is_drone : public script_instruction_base<is_drone>
{
friend class boost::serialization::access;
static std::string name() { return "is_drone"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_drone>);
}
};
struct is_asteroid : public script_instruction_base<is_asteroid>
{
friend class boost::serialization::access;
static std::string name() { return "is_asteroid"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_asteroid>);
}
};
struct is_base : public script_instruction_base<is_base>
{
friend class boost::serialization::access;
static std::string name() { return "is_base"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone );
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<is_base>);
}
};
//! \brief Random direction command
//! Returns a random "direction" which is either -1, 0, or 1
struct rand_dir : public script_instruction_base<rand_dir>
{
friend class boost::serialization::access;
rand_dir()
{}
static std::string name() { return "rand_dir"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
static boost::mt19937 rng;
static boost::uniform_int<> dir;
static boost::variate_generator<boost::mt19937&, boost::uniform_int<> > _rand_dir;
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<rand_dir>);
}
};
//! \brief Mine command
//! Takes an x, and a y and mines an asteroid some set amount if there is one there
struct mine : public script_instruction_base<mine>
{
friend class boost::serialization::access;
static std::string name() { return "mine"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<mine>);
}
};
//! \brief Unload command
//! Takes an x, and a y and unloads some set amount to a basestation
struct unload : public script_instruction_base<unload>
{
friend class boost::serialization::access;
static std::string name() { return "unload"; }
unsigned int execute(size_t which_queue, entity::scripted_drone & drone);
private:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(script_instruction_base<unload>);
}
};
}
#endif
| 38.121795
| 95
| 0.633092
|
medlefsen
|
4ddf249e6bd0d57ada52921e5a19a88b411a1ba6
| 748
|
cpp
|
C++
|
local_addons/ofxCv/example-gesture/src/ofApp.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 446
|
2015-01-08T00:14:06.000Z
|
2022-03-16T13:08:03.000Z
|
local_addons/ofxCv/example-gesture/src/ofApp.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 139
|
2015-01-02T19:20:53.000Z
|
2021-05-03T16:54:45.000Z
|
local_addons/ofxCv/example-gesture/src/ofApp.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 195
|
2015-01-18T05:13:39.000Z
|
2022-03-21T08:24:37.000Z
|
#include "ofApp.h"
using namespace ofxCv;
using namespace cv;
void ofApp::setup() {
ofSetVerticalSync(true);
ofEnableSmoothing();
ofEnableAlphaBlending();
ofSetLineWidth(3);
ofSetFrameRate(120);
}
void ofApp::update() {
}
void ofApp::draw() {
ofBackground(0);
ofSetColor(255, 64);
polyline.draw();
switch(recognizer.getGestureType()) {
case Recognizer::GESTURE_LINE: ofSetColor(magentaPrint); break;
case Recognizer::GESTURE_ARC: ofSetColor(cyanPrint); break;
}
if(recognizer.getFitError() < .5) {
recognizer.getPolyline().draw();
}
}
void ofApp::mousePressed(int x, int y, int button) {
polyline.clear();
}
void ofApp::mouseDragged(int x, int y, int button) {
polyline.addVertex(x, y);
recognizer.update(polyline);
}
| 18.7
| 65
| 0.713904
|
yxcde
|
4de02a6730eedb7fe2158b32483e9c1f5c3e26ce
| 177
|
cpp
|
C++
|
non-iOS/antlr4_generated_src/init_parser/InitFileParserListener.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
non-iOS/antlr4_generated_src/init_parser/InitFileParserListener.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
non-iOS/antlr4_generated_src/init_parser/InitFileParserListener.cpp
|
opendragon/IF
|
11e9132b896a67115b8fc9fc9cddcd592b838bfa
|
[
"BSD-3-Clause"
] | null | null | null |
// Generated from /Volumes/Shejidan/git.repositories/IF/non-iOS/../InitFile/InitFileParser.g4 by ANTLR 4.8
#include "InitFileParserListener.h"
using namespace InitParser;
| 17.7
| 106
| 0.779661
|
opendragon
|
4de37c1987a34efbda06b44fed249896d9a9865b
| 15,204
|
cpp
|
C++
|
src/sprite.cpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | null | null | null |
src/sprite.cpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | null | null | null |
src/sprite.cpp
|
GhostInABottle/octopus_engine
|
50429e889493527bdc0e78b307937002e0f2c510
|
[
"BSD-2-Clause"
] | null | null | null |
#include "../include/sprite.hpp"
#include "../include/sprite_data.hpp"
#include "../include/map_object.hpp"
#include "../include/canvas.hpp"
#include "../include/object_layer.hpp"
#include "../include/object_layer_renderer.hpp"
#include "../include/image_layer.hpp"
#include "../include/game.hpp"
#include "../include/configurations.hpp"
#include "../include/utility/math.hpp"
#include "../include/utility/string.hpp"
#include "../include/utility/direction.hpp"
#include "../include/xd/audio.hpp"
#include "../include/xd/graphics.hpp"
#include <algorithm>
#include <iostream>
#include <optional>
#include <unordered_map>
#include <vector>
namespace detail {
xd::vec4 default_color(1, 1, 1, 1);
}
struct Sprite::Impl {
// Game instance
Game& game;
// Sprite data (poses, frames, etc.)
std::unique_ptr<Sprite_Data> data;
// Current pose name
std::string current_pose_name;
// Current pose state
std::string current_pose_state;
// Current direction
Direction current_pose_direction;
// Cache of tag combination to poses
std::unordered_map<std::string, int> tag_map;
// Currently active pose
Pose* pose;
// Source rectangle of current frame
xd::rect src;
// Current frame index
int frame_index;
// Used to check if enough time has passed since last frame
long old_time;
// Number of times the animation repeated so far
int repeat_count;
// Total number of frames
int frame_count;
// Is animation in a tween frame
bool tweening;
// Default color
const static xd::vec4 default_color;
// Is the pose finished
bool finished;
// Is the sprite paused
bool paused;
// Time when sprite got paused
long pause_start;
// Last frame where sound was played
int last_sound_frame;
// Animation speed modifier (based on object speed)
float speed;
// Maximum possible speed modifier
const static float max_speed;
// Volume of the sprite's sound effects
float sfx_volume;
// How fast sound volume falls off
float sound_attenuation_factor;
Impl(Game& game, std::unique_ptr<Sprite_Data> data) :
game(game),
data(std::move(data)),
current_pose_direction(Direction::NONE),
frame_index(0),
old_time(game.ticks()),
repeat_count(0),
frame_count(0),
tweening(false),
finished(false),
paused(false),
pause_start(-1),
last_sound_frame(-1),
speed(1.0f),
sfx_volume(1.0f),
sound_attenuation_factor(Configurations::get<float>("audio.sound-attenuation-factor"))
{
set_default_pose();
}
void render(xd::sprite_batch& batch, xd::vec2 pos, float opacity = 1.0f,
xd::vec2 mag = xd::vec2(1.0f), xd::vec4 color = xd::vec4(1.0f),
std::optional<float> angle = std::nullopt, std::optional<xd::vec2> origin = std::nullopt,
bool repeat = false, xd::vec2 repeat_pos = xd::vec2()) {
auto& frame = pose->frames[frame_index];
auto& image = frame.image ? frame.image :
(pose->image ? pose->image : data->image);
if (!image)
return;
xd::rect src = frame.rectangle;
if (repeat) {
// Sprite's src rectangle position is ignored
src.x = -repeat_pos.x;
src.y = -repeat_pos.y;
}
color.a *= opacity * frame.opacity;
batch.add(image, src,
pos.x, pos.y,
xd::radians(angle.value_or(static_cast<float>(frame.angle))),
frame.magnification * mag,
color,
origin.value_or(pose->origin));
}
void update() {
if (frame_count == 0 || finished)
return;
auto current_frame = &pose->frames[frame_index];
int frame_time = get_frame_time(*current_frame);
auto audio = game.get_audio();
auto sound_file = current_frame->sound_file.get();
auto play_sfx = audio && sound_file
&& (last_sound_frame != frame_index || sound_file->stopped());
if (play_sfx) {
sound_file->set_volume(current_frame->sound_volume * sfx_volume);
sound_file->play();
last_sound_frame = frame_index;
}
if (passed_time() > frame_time) {
old_time = game.ticks();
if (tweening) tweening = false;
if (frame_index + 1 >= frame_count) {
repeat_count++;
last_sound_frame = -1;
if (finished_repeating()) {
finished = true;
return;
}
}
frame_index = (frame_index + 1) % frame_count;
}
current_frame = &pose->frames[frame_index];
if (!tweening && current_frame->tween_frame) {
Frame& prev_frame = pose->frames[frame_index - 1];
current_frame->rectangle.x = prev_frame.rectangle.x;
current_frame->rectangle.y = prev_frame.rectangle.y;
current_frame->rectangle.w = prev_frame.rectangle.w;
current_frame->rectangle.h = prev_frame.rectangle.h;
old_time = game.ticks();
tweening = true;
}
if (tweening) {
Frame& prev_frame = pose->frames[frame_index - 1];
Frame& next_frame = pose->frames[frame_index + 1];
const float time_diff = static_cast<float>(passed_time());
float alpha = time_diff / frame_time;
alpha = std::min(std::max(alpha, 0.0f), 1.0f);
current_frame->magnification = lerp(prev_frame.magnification,
next_frame.magnification, alpha);
current_frame->angle= static_cast<int>(
lerp(static_cast<float>(prev_frame.angle),
static_cast<float>(next_frame.angle), alpha));
current_frame->opacity=
lerp(prev_frame.opacity, next_frame.opacity, alpha);
}
}
void reset() {
frame_index = 0;
old_time = game.ticks();
repeat_count = 0;
last_sound_frame = -1;
if (pose)
frame_count = pose->frames.size();
finished = false;
tweening = false;
}
int get_frame_time(const Frame& frame) const {
const int frame_time = frame.duration == -1 ? pose->duration : frame.duration;
return static_cast<int>(frame_time * speed);
}
std::string get_filename() const {
return data->filename;
}
bool finished_repeating() const {
return pose->repeats != -1 && repeat_count >= pose->repeats;
}
void pause() {
paused = true;
pause_start = game.ticks();
}
void resume() {
paused = false;
pause_start = -1;
}
long paused_time() const {
if (pause_start == -1) return 0;
return game.ticks() - pause_start;
}
long passed_time() const {
return game.ticks() - old_time - paused_time();
}
bool is_completed() const {
return frame_count > 0
&& frame_index == frame_count - 1
&& passed_time() >= get_frame_time(pose->frames[frame_index]);
}
void set_pose(const std::string& pose_name, const std::string& state_name, Direction dir) {
// Update current pose tags
current_pose_name = string_utilities::capitalize(pose_name);
current_pose_state = string_utilities::capitalize(state_name);
current_pose_direction = dir;
// Lookup pose in cache
std::string tag_string;
tag_string = "P:" + current_pose_name + "|S:" + current_pose_state + "|D:" + direction_to_string(dir);
int matched_pose = -1;
bool default_name_matched = false;
if (tag_map.find(tag_string) != tag_map.end()) {
matched_pose = tag_map[tag_string];
} else {
// Map of pose IDs to their tag match count
std::unordered_map<int, unsigned int> matches;
int matches_needed = (pose_name.empty() ? 0 : 1) + (state_name.empty() ? 0 : 1) + (dir == Direction::NONE ? 0 : 1);
int default_pose = -1;
bool is_default = data->default_pose != "" && current_pose_name == data->default_pose;
// Loop over poses incrementing poses that match
for (unsigned int i = 0; i < data->poses.size(); ++i) {
auto& pose = data->poses[i];
auto name_matched = current_pose_name == pose.name;
if (!current_pose_name.empty() && name_matched) {
matches[i]++;
// Update best default pose
if (is_default && compare_matches(i, default_pose, matches) > 0) {
default_pose = i;
default_name_matched = true;
}
}
if (!current_pose_state.empty() && current_pose_state == pose.state) {
matches[i]++;
}
if (dir != Direction::NONE && dir == pose.direction) {
matches[i]++;
}
// Update best match
auto comparison = compare_matches(i, matched_pose, matches);
if (comparison > 0 || (comparison == 0 && name_matched)) {
matched_pose = i;
}
if (matches[i] == matches_needed) {
break;
}
}
// Prefer default pose to other poses with same matches
if (matched_pose == -1 || (default_name_matched && compare_matches(matched_pose, default_pose, matches) == 0)) {
matched_pose = default_pose == -1 ? 0 : default_pose;
}
// Update pose cache
tag_map[tag_string] = matched_pose;
}
// Set matched pose and reset the sprite
if (pose != &data->poses[matched_pose] || finished) {
pose = &data->poses[matched_pose];
reset();
}
}
// A pose is better than current best if there's no best yet or if it matches more tags
int compare_matches(int candidate_index, int best_index,
std::unordered_map<int, unsigned int>& matches) {
auto candidate = matches[candidate_index];
auto best = best_index > -1 ? matches[best_index] : 0;
if (candidate > best) return 1;
if (best > candidate) return -1;
return 0;
}
void set_default_pose() {
if (data->default_pose.empty()) {
pose = &data->poses[0];
return;
}
for (auto& p : data->poses) {
if (p.name == data->default_pose) {
pose = &p;
return;
}
}
}
void update_sound_attenuation(Map_Object& object) {
auto player_position{game.get_player()->get_centered_position()};
auto distance = xd::length(object.get_centered_position() - player_position);
// Sound is 1 within [factor] pixels, then falls off based on distance
sfx_volume = std::min(1.0f, sound_attenuation_factor / (1.0f + distance));
auto current_frame = &pose->frames[frame_index];
if (current_frame->sound_file && current_frame->sound_file->playing()) {
current_frame->sound_file->set_volume(sfx_volume);
}
}
};
const xd::vec4 Sprite::Impl::default_color(1, 1, 1, 1);
const float Sprite::Impl::max_speed = 10.0f;
Sprite::Sprite(Game& game, std::unique_ptr<Sprite_Data> data)
: pimpl(std::make_unique<Impl>(game, std::move(data))) {
pimpl->reset();
}
Sprite::~Sprite() {}
void Sprite::render(Map_Object& object) {
if (!object.is_visible()) return;
auto layer = object.get_layer();
auto& batch = layer->renderer->get_batch();
auto color = object.uses_layer_color()
? object.get_color() * layer->tint_color
: object.get_color();
pimpl->render(batch, object.get_position(),
layer->opacity * object.get_opacity(),
object.get_magnification(),
color);
}
void Sprite::render(xd::sprite_batch& batch, const Canvas& canvas, const xd::vec2 pos) {
if (!canvas.is_visible()) return;
pimpl->render(batch,
pos,
canvas.get_opacity(),
canvas.get_magnification(),
canvas.get_color(),
canvas.get_angle(),
canvas.get_origin());
}
void Sprite::render(xd::sprite_batch& batch, const Image_Layer& image_layer, const xd::vec2 pos) {
if (!image_layer.visible) return;
pimpl->render(batch,
pos,
image_layer.opacity,
xd::vec2(1.0f), // magnification
xd::vec4(1.0f), // Color
std::nullopt, // angle
std::nullopt, // origin
image_layer.repeat,
image_layer.position);
}
void Sprite::update(Map_Object& object) {
if (object.is_sound_attenuation_enabled()) {
pimpl->update_sound_attenuation(object);
}
pimpl->update();
}
void Sprite::update() {
pimpl->update();
}
void Sprite::reset() {
pimpl->reset();
}
std::string Sprite::get_filename() const {
return pimpl->get_filename();
}
void Sprite::set_pose(const std::string& pose_name, const std::string& state_name, Direction dir) {
pimpl->set_pose(pose_name, state_name, dir);
}
Pose& Sprite::get_pose() {
return *pimpl->pose;
}
xd::rect Sprite::get_bounding_box() const {
return pimpl->pose->bounding_box;
}
std::string Sprite::get_default_pose() const {
return pimpl->data->default_pose;
}
xd::vec2 Sprite::get_size() const {
xd::vec2 size;
auto& pose = *pimpl->pose;
if (pose.frames.size() > 0) {
auto& frame = pose.frames.front();
size = xd::vec2(frame.rectangle.w, frame.rectangle.h);
}
return size;
}
Frame& Sprite::get_frame() {
return pimpl->pose->frames[pimpl->frame_index];
}
const Frame& Sprite::get_frame() const {
return pimpl->pose->frames[pimpl->frame_index];
}
bool Sprite::is_stopped() const {
return pimpl->finished;
}
void Sprite::stop() {
pimpl->finished = true;
}
bool Sprite::is_paused() const {
return pimpl->paused;
}
void Sprite::pause() {
pimpl->pause();
}
void Sprite::resume() {
pimpl->resume();
}
bool Sprite::is_completed() const {
return pimpl->is_completed();
}
float Sprite::get_speed() const {
return pimpl->speed;
}
void Sprite::set_speed(float speed) {
// Scale sprite speed in the opposite direction of object speed,
// between 0.5 for max speed (10) and 2 for min speed (0)
// but also make sure object speed 1 maps to sprite speed 1
// s-speed = s-min + (s-max - s-min) * (o-speed - o-min) / (o-max - o-min)
speed = std::max(0.0f, std::min(pimpl->max_speed, speed));
if (speed <= 1)
pimpl->speed = 2.0f - speed;
else
pimpl->speed = 1.0f - 0.5f * (speed - 1.0f) / (pimpl->max_speed - 1.0f);
}
bool Sprite::is_eight_directional() const {
return pimpl->data->has_diagonal_directions;
}
float Sprite::get_sfx_volume() const {
return pimpl->sfx_volume;
}
void Sprite::set_sfx_volume(float volume) {
pimpl->sfx_volume = volume;
}
| 32.143763
| 127
| 0.587872
|
GhostInABottle
|
4de479230edb288dc4c57ca2b364fcc1ab9474bc
| 195
|
cpp
|
C++
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/AliasTarget/targetgenerator.cpp
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 107
|
2021-08-28T20:08:42.000Z
|
2022-03-22T08:02:16.000Z
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/AliasTarget/targetgenerator.cpp
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 3
|
2021-09-08T02:18:00.000Z
|
2022-03-12T00:39:44.000Z
|
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/AliasTarget/targetgenerator.cpp
|
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
|
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
|
[
"MIT"
] | 16
|
2021-08-30T06:57:36.000Z
|
2022-03-22T08:05:52.000Z
|
#include <fstream>
int main(int argc, char** argv)
{
std::ofstream fout("targetoutput.h");
if (!fout)
return 1;
fout << "#define TARGETOUTPUT_DEFINE\n";
fout.close();
return 0;
}
| 15
| 42
| 0.630769
|
duonglvtnaist
|
4e2896425937add552d5ce4aedf077c28aac0cee
| 5,027
|
hpp
|
C++
|
include/nodamushi/svd/svd_reader.hpp
|
nodamushi/nsvd-reader
|
cf3a840aaac78d5791df1cf045596ec20dc03257
|
[
"CC0-1.0"
] | null | null | null |
include/nodamushi/svd/svd_reader.hpp
|
nodamushi/nsvd-reader
|
cf3a840aaac78d5791df1cf045596ec20dc03257
|
[
"CC0-1.0"
] | null | null | null |
include/nodamushi/svd/svd_reader.hpp
|
nodamushi/nsvd-reader
|
cf3a840aaac78d5791df1cf045596ec20dc03257
|
[
"CC0-1.0"
] | null | null | null |
/*!
@brief svd_reader
@file nodamushi/svd/svd_reader.hpp
*/
/*
* These codes are licensed under CC0.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
#ifndef NODAMUSHI_SVD_SVD_READER_HPP
#define NODAMUSHI_SVD_SVD_READER_HPP
# include "nodamushi/const_string.hpp"
# include "nodamushi/boxvec.hpp"
# include <cassert>
# include <type_traits>
# include <utility>
# include <stdexcept>
# include <fstream>
namespace nodamushi{
namespace svd{
enum class svd_error
{
//! unknown element
UNKNOWN_ELEMENT,
//! illegal value
ILLEGAL_VALUE
};
/**
* @brief Indicates which element caused an error in processing.
*/
enum class svd_element
{
//! @brief nodamushi::svd::Device
Device,
//! @brief nodamushi::svd::Peripheral
Peripheral,
//! @brief nodamushi::svd::Register
Register,
//! @brief nodamushi::svd::Registers
Registers,
//! @brief nodamushi::svd::Cluster
Cluster,
//! @brief nodamushi::svd::Field
Field,
//! @brief nodamushi::svd::Fields
Fields,
//! @brief nodamushi::svd::EnumeratedValue
EnumeratedValue,
//! @brief nodamushi::svd::DimArrayIndex
DimArrayIndex,
//! @brief nodamushi::svd::WriteConstraintRange
WriteConstraintRange,
//! @brief nodamushi::svd::WriteConstraint
WriteConstraint,
//! @brief nodamushi::svd::Enumeration
Enumeration,
//! @brief nodamushi::svd::Interrupt
Interrupt,
//! @brief nodamushi::svd::AddressBlock
AddressBlock,
//! @brief nodamushi::svd::SAURegionsConfig
SAURegionsConfig,
//! @brief nodamushi::svd::SAURegionsConfigRegion
SAURegionsConfigRegion,
//! @brief nodamushi::svd::Cpu
Cpu,
};
/*!
svd read marker interface.
implements interface
@code
struct svd_reader
{
//! if this element is svd attribute group,return true.
bool is_attribute()const;
//! get this element name
string_ref get_name()const;
//! get trimed value
string_ref get_value();
//! get next child element
svd_reader next_child();
//! @return has next child
operator bool();
// error handler
void unknown_element(svd_element e);
void illegal_value(svd_element e);
};
@endcode
*/
struct svd_reader{};
/**
* @brief file open ,read error
*/
struct file_read_exception:public std::invalid_argument
{
static bool check(const std::string& file_name,bool throw_exception)
{
using namespace std;
ifstream ifs(file_name);
if(!ifs.good()){
if(throw_exception){
string m = "File read error : "s + file_name;
throw file_read_exception(file_name,m);
}
return false;
}
return true;
}
file_read_exception(const std::string& file,const std::string& message):
invalid_argument(message),
file_name(file){}
std::string file_name;
};
/**
* @brief xml parse error
*/
struct xml_parse_exception:public std::runtime_error
{
static constexpr size_t UNKNOWN_FILE_LINE= ~(size_t)0;
static xml_parse_exception make(
const std::string& file,size_t file_line = UNKNOWN_FILE_LINE)
{
using namespace std;
string m = "XML parse error occured: "s + file;
return {file,m,file_line};
}
xml_parse_exception(const std::string& file,
const std::string& message,
size_t file_line):
runtime_error(message),
file_name(file),
line_number(file_line){}
std::string file_name;
size_t line_number;
};
struct svd_reader_util
{
template<typename T>
static std::pair<size_t,size_t> _trim(T& str)
{
size_t b = 0;
const size_t len = str.length();
size_t e = len;
while(b!=e){
char c = str[b];
if(c == ' ' || c == '\t' || c =='\r' || c == '\n')
b++;
else
break;
}
while(b!=e){
char c = str[e-1];
if(c == ' ' || c == '\t' || c =='\r' || c == '\n')
e--;
else
break;
}
return {b,e};
}
//! @brief remove white spaces
static void trim(std::string& str)
{
auto v = _trim(str);
size_t b = v.first,e=v.second;
if(e != str.length())
str.erase(e);
if(b)
str.erase(0,b);
}
# if __cplusplus >= 201703
//! @brief remove white spaces
static void trim(std::string_view& str)
{
auto v = _trim(str);
size_t b = v.first,e=v.second,len = e-b;
std::string_view n(str.data()+b,len);
str = n;
}
//! @brief remove white spaces
static std::string_view trimc(const std::string_view& str)
{
auto v = _trim(str);
size_t b = v.first,e=v.second,len = e-b;
return {str.data()+b,len};
}
//! @brief remove white spaces
static std::string_view trimc(const std::string& str)
{
auto v = _trim(str);
size_t b = v.first,e=v.second,len = e-b;
return {str.data()+b,len};
}
# else
//! @brief remove white spaces
static std::string trimc(const std::string& str)
{
auto v = _trim(str);
size_t b = v.first,e=v.second,len = e-b;
return std::string(str,b,len);
}
# endif
};
}}// end namespace nodamushi::svd
#endif // NODAMUSHI_SVD_SVD_READER_HPP
| 22.048246
| 74
| 0.636364
|
nodamushi
|
4e3543d791d949534f562cd11bd3278e14a298d5
| 2,771
|
inl
|
C++
|
dist/include/Fuji/MFHashList.inl
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 35
|
2015-01-19T22:07:48.000Z
|
2022-02-21T22:17:53.000Z
|
dist/include/Fuji/MFHashList.inl
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 1
|
2022-02-23T09:34:15.000Z
|
2022-02-23T09:34:15.000Z
|
dist/include/Fuji/MFHashList.inl
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 4
|
2015-05-11T03:31:35.000Z
|
2018-09-27T04:55:57.000Z
|
template<class T>
const T* MFHashList<T>::operator[](const char *pHashString) const
{
uint32 crc = MFUtil_CrcString(pHashBuffer);
uint32 id = crc%listSize;
//.....
}
template<class T>
T* MFHashList<T>::operator[](const char *pHashString)
{
uint32 crc = MFUtil_CrcString(pHashBuffer);
uint32 id = crc%listSize;
//.....
}
template<class T>
void MFHashList<T>::Init(const char *pGroupName, uint32 maxElements)
{
pList = (MFHashListItem*)MFHeap_Alloc(sizeof(T)*maxElements);
MFZeroMemory(pList, sizeof(T)*maxElements);
}
template<class T>
void MFHashList<T>::Deinit()
{
MFHeap_Free(pList);
pList = NULL;
}
template<class T>
T* MFHashList<T>::Create(T* pItem, const char *pHashBuffer, int len = -1)
{
uint32 crc = len == -1 ? MFUtil_CrcString(pHashBuffer) : MFUtil_Crc(pHashBuffer, len);
uint32 id = crc%listSize;
//.....
}
template<class T>
void MFHashList<T>::Destroy(const char *pHashBuffer, int len = -1)
{
uint32 crc = len == -1 ? MFUtil_CrcString(pHashBuffer) : MFUtil_Crc(pHashBuffer, len);
uint32 id = crc%listSize;
//.....
// NOTE: destroying an item may make following items that were meant for this key inaccessable.. following items should be shuffled back into this space..
}
template<class T>
void MFHashList<T>::Destroy(uint32 hash)
{
uint32 id = hash%listSize;
//.....
// NOTE: destroying an item may make following items that were meant for this key inaccessable.. following items should be shuffled back into this space..
}
template<class T>
void MFHashList<T>::DestroyItem(T* pItem)
{
for(int a=0; a<listSize; a++)
{
if(pList[a].pItem == pItem)
{
pList[a].pItem = NULL;
pList[a].hash = 0;
break;
}
}
// NOTE: destroying an item may make following items that were meant for this key inaccessable.. following items should be shuffled back into this space..
}
template<class T>
T* MFHashList<T>::Find(const char *pHashBuffer, int len = -1)
{
uint32 crc = len == -1 ? MFUtil_CrcString(pHashBuffer) : MFUtil_Crc(pHashBuffer, len);
uint32 id = crc%listSize;
uint32 i = id;
while(pList[i].pItem)
{
if(crc == pList[id].hash)
return pList[id].pItem;
++i;
if(i == numItems) i==0;
if(i == id) return NULL;
}
return NULL;
}
template<class T>
void MFHashList<T>::Clear()
{
for(int a=0; a<listSize; a++)
{
pList[a].pItem = NULL;
}
numItems = 0;
}
template<class T>
int MFHashList<T>::GetNumItems()
{
return numItems;
}
template<class T>
int MFHashList<T>::GetMaxItems()
{
return listSize;
}
template<class T>
bool MFHashList<T>::IsFull()
{
return numItems == listSize;
}
template<class T>
bool MFHashList<T>::IsEmpty()
{
return numItems == 0;
}
| 20.679104
| 156
| 0.653555
|
TurkeyMan
|
4e3939b19ea82d41e8b79c1b4eef53ade4cc59ed
| 1,266
|
cpp
|
C++
|
draw_rr_robot.cpp
|
HebiRobotics/RobotDiagrams
|
722040e919bd3ecf89fc5df65233aff9ce6ad6c8
|
[
"MIT"
] | 5
|
2018-02-13T02:40:45.000Z
|
2021-04-02T01:23:12.000Z
|
draw_rr_robot.cpp
|
HebiRobotics/RobotDiagrams
|
722040e919bd3ecf89fc5df65233aff9ce6ad6c8
|
[
"MIT"
] | null | null | null |
draw_rr_robot.cpp
|
HebiRobotics/RobotDiagrams
|
722040e919bd3ecf89fc5df65233aff9ce6ad6c8
|
[
"MIT"
] | 1
|
2019-03-16T07:45:20.000Z
|
2019-03-16T07:45:20.000Z
|
#include "robot_diagrams_0.0.hpp"
int main()
{
// TODO: messy! figure out the C++03 way to do this right...
// NOTE: in C++11, these could be unique_ptrs...
// Build robot:
// Link 1:
// l = 100
// theta = pi/4
// Line 2:
// l = 50
// theta = pi/8
// End effector:
rob_diag::Robot robot;
rob_diag::Base e0(10);
rob_diag::RJoint e1;
rob_diag::Link e2(100, M_PI / 4);
rob_diag::RJoint e3;
rob_diag::Link e4(50, M_PI / 8);
robot.elements_.push_back((rob_diag::RobotElement*)&e0);
robot.elements_.push_back((rob_diag::RobotElement*)&e1);
robot.elements_.push_back((rob_diag::RobotElement*)&e2);
robot.elements_.push_back((rob_diag::RobotElement*)&e3);
robot.elements_.push_back((rob_diag::RobotElement*)&e4);
// Compute dimensions
rob_diag::Rect bounds = robot.compute_dimensions();
double width = bounds.right_ - bounds.left_;
double height = bounds.top_ - bounds.bottom_;
double margin = 10;
svg::Dimensions dimensions(width + margin * 2.0, height + margin * 2.0);
// Draw to file:
Document doc("robot.svg", svg::Layout(dimensions, svg::Layout::BottomLeft));
rob_diag::Pose origin(-bounds.left_ + margin, -bounds.bottom_ + margin, 0);
robot.draw_at(doc, origin);
// Save and quit
doc.save();
}
| 30.142857
| 78
| 0.668246
|
HebiRobotics
|
4e40271d3c05cc41522e8de3a7c1b09c9e60bfde
| 946
|
cpp
|
C++
|
04 April Leetcode Challenge 2021/17 removeAdjString2.cpp
|
FazeelUsmani/Leetcode
|
aff4c119178f132c28a39506ffaa75606e0a861b
|
[
"MIT"
] | 7
|
2020-12-01T14:27:57.000Z
|
2022-02-12T09:17:22.000Z
|
04 April Leetcode Challenge 2021/17 removeAdjString2.cpp
|
FazeelUsmani/Leetcode
|
aff4c119178f132c28a39506ffaa75606e0a861b
|
[
"MIT"
] | 4
|
2020-11-12T17:49:22.000Z
|
2021-09-06T07:46:37.000Z
|
04 April Leetcode Challenge 2021/17 removeAdjString2.cpp
|
FazeelUsmani/Leetcode
|
aff4c119178f132c28a39506ffaa75606e0a861b
|
[
"MIT"
] | 6
|
2021-05-21T03:49:22.000Z
|
2022-01-20T20:36:53.000Z
|
class Solution {
public:
string removeDuplicates(string s, int k) {
// support variables
string res;
int counter, tot = s.size(), pos = 0, prevPos;
pair<char, int> stack[tot];
// parsing s
for (char c: s) {
prevPos = pos - 1;
// case 1: new insertion for empty stack or different char
if (!pos || stack[prevPos].first != c) {
stack[pos++] = {c, 2};
}
// case 2: same character found
else {
counter = stack[prevPos].second;
if (counter == k) tot -= k, pos--;
else stack[prevPos].second++;
}
}
// properly sizing res
res.resize(tot);
// building res
for (int i = 0, j = 0; i < pos; i++) {
auto [c, freq] = stack[i];
while (--freq) res[j++] = c;
}
return res;
}
};
| 29.5625
| 70
| 0.438689
|
FazeelUsmani
|
4e42b370cefd6081554867c536f6fdf68f1140fb
| 7,037
|
cc
|
C++
|
tests/checkers/checker.cc
|
numairmansur/crab
|
316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7
|
[
"Apache-2.0"
] | 4
|
2021-05-19T17:35:30.000Z
|
2021-08-17T04:03:21.000Z
|
tests/checkers/checker.cc
|
numairmansur/crab
|
316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7
|
[
"Apache-2.0"
] | null | null | null |
tests/checkers/checker.cc
|
numairmansur/crab
|
316e3946d3a4d92db638c54fbfa8fb7bee1ebbc7
|
[
"Apache-2.0"
] | 1
|
2022-01-15T11:20:30.000Z
|
2022-01-15T11:20:30.000Z
|
#include "../program_options.hpp"
#include "../common.hpp"
#include <crab/checkers/base_property.hpp>
#include <crab/checkers/null.hpp>
#include <crab/checkers/div_zero.hpp>
#include <crab/checkers/assertion.hpp>
#include <crab/checkers/checker.hpp>
#include <crab/analysis/dataflow/assertion_crawler.hpp>
#include <crab/analysis/dataflow/assumptions.hpp>
using namespace std;
using namespace crab::analyzer;
using namespace crab::cfg;
using namespace crab::cfg_impl;
using namespace crab::domain_impl;
using namespace crab::checker;
z_cfg_t* cfg1 (variable_factory_t &vfac)
{
// entry and exit block
z_cfg_t* cfg = new z_cfg_t("b0","b3",PTR);
// adding blocks
z_basic_block_t& b0 = cfg->insert ("b0");
z_basic_block_t& b1 = cfg->insert ("b1");
z_basic_block_t& b2 = cfg->insert ("b2");
z_basic_block_t& b3 = cfg->insert ("b3");
// adding control flow
b0 >> b1; b0 >> b2; b1 >> b3; b2 >> b3;
// definining program variables
z_var p(vfac ["p"], crab::PTR_TYPE);
z_var q1(vfac ["q1"], crab::PTR_TYPE);
z_var q2(vfac ["q2"], crab::PTR_TYPE);
z_var r(vfac ["r"], crab::PTR_TYPE);
z_var nd(vfac ["nd"], crab::INT_TYPE, 32);
// adding statements
b0.ptr_new_object (p , 1); // p = malloc (...);
b0.ptr_new_object (q1, 2); // q1 = malloc (...);
b0.ptr_new_object (q2, 3); // q2 = malloc (...);
b0.havoc (nd);
b1.assume (nd >= 1);
b2.assume (nd <= 0);
b1.ptr_store (p, q1); // *p = q1
b2.ptr_store (p, q2); // *p = q2
b3.ptr_load (r, p); // r = *p
return cfg;
}
z_cfg_t* cfg2 (variable_factory_t &vfac) {
// Definining program variables
z_var i (vfac ["i"], crab::INT_TYPE, 32);
z_var x (vfac ["x"], crab::INT_TYPE, 32);
z_var y (vfac ["y"], crab::INT_TYPE, 32);
z_var p (vfac ["p"], crab::PTR_TYPE);
z_var q (vfac ["q"], crab::PTR_TYPE);
// entry and exit block
z_cfg_t* cfg = new z_cfg_t("entry","ret",PTR);
// adding blocks
z_basic_block_t& entry = cfg->insert ("entry");
z_basic_block_t& bb1 = cfg->insert ("bb1");
z_basic_block_t& bb1_t = cfg->insert ("bb1_t");
z_basic_block_t& bb1_f = cfg->insert ("bb1_f");
z_basic_block_t& bb2 = cfg->insert ("bb2");
z_basic_block_t& ret = cfg->insert ("ret");
// adding control flow
entry >> bb1;
bb1 >> bb1_t; bb1 >> bb1_f;
bb1_t >> bb2; bb2 >> bb1; bb1_f >> ret;
// adding statements
entry.assign (i, 0);
entry.assign (x, 1);
entry.assign (y, 0);
entry.ptr_null (p);
bb1_t.assume (i <= 99);
bb1_f.assume (i >= 100);
bb2.add(x,x,y);
bb2.add(y,y,1);
bb2.ptr_new_object (q, 1);
bb2.ptr_assign (p, q, z_number(4));
bb2.add(i, i, 1);
ret.assume (x <= y);
ret.assertion (i == 100);
ret.assertion (i >= 200);
ret.assertion (x >= y);
ret.assertion (x >= 200);
return cfg;
}
// Print invariants by traversing the cfg in dfs.
template<typename Analyzer>
static void print_invariants(z_cfg_ref_t cfg, Analyzer& analyser) {
std::set<crab::cfg_impl::basic_block_label_t> visited;
std::vector<crab::cfg_impl::basic_block_label_t> worklist;
worklist.push_back(cfg.entry());
visited.insert(cfg.entry());
while (!worklist.empty()) {
auto cur_label = worklist.back();
worklist.pop_back();
auto pre = analyser.get_pre (cur_label);
auto post = analyser.get_post (cur_label);
crab::outs() << get_label_str (cur_label) << "="
<< pre
<< " ==> "
<< post << "\n";
auto const &cur_node = cfg.get_node (cur_label);
for (auto const kid_label : boost::make_iterator_range(cur_node.next_blocks())) {
if (visited.insert(kid_label).second) {
worklist.push_back(kid_label);
}
}
}
}
void check (z_cfg_ref_t cfg, variable_factory_t& vfac) {
// Each checker is associated to one analyzer
typedef intra_fwd_analyzer<z_cfg_ref_t, z_num_null_domain_t> null_analyzer_t;
typedef intra_checker<null_analyzer_t> null_checker_t;
typedef intra_fwd_analyzer<z_cfg_ref_t, z_sdbm_domain_t> num_analyzer_t;
typedef intra_checker<num_analyzer_t> num_checker_t;
// We can have multiple properties per analyzer
typedef null_property_checker<null_analyzer_t> null_prop_null_checker_t;
typedef div_zero_property_checker<num_analyzer_t> div_zero_prop_num_checker_t;
typedef assert_property_checker<num_analyzer_t> assert_prop_num_checker_t;
// Run liveness (optionally) and print cfg
liveness<z_cfg_ref_t> live (cfg);
crab::outs() << cfg << "\n";
// Run nullity analysis
null_analyzer_t null_a (cfg, z_num_null_domain_t::top (), &live);
null_a.run ();
crab::outs() << "Analysis using " << z_num_null_domain_t::getDomainName () << "\n";
print_invariants(cfg, null_a);
// for (auto &b : cfg) {
// auto pre = null_a.get_pre (b.label ());
// auto post = null_a.get_post (b.label ());
// crab::outs() << get_label_str (b.label ()) << "="
// << pre
// << " ==> "
// << post << "\n";
// }
// Run numerical analysis
num_analyzer_t num_a (cfg, z_sdbm_domain_t::top (), &live);
num_a.run ();
crab::outs() << "Analysis using " << z_sdbm_domain_t::getDomainName () << "\n";
print_invariants(cfg, num_a);
// for (auto &b : cfg) {
// auto pre = num_a.get_pre (b.label ());
// auto post = num_a.get_post (b.label ());
// crab::outs() << get_label_str (b.label ()) << "="
// << pre
// << " ==> "
// << post << "\n";
// }
// Run the checkers with several properties
// A checker can take any property checker associated to same
// analyzer.
const int verbose = 3;
{
typename null_checker_t::prop_checker_ptr prop1 (new null_prop_null_checker_t (verbose));
null_checker_t checker (null_a, {prop1});
checker.run ();
checker.show (crab::outs());
}
{
typename num_checker_t::prop_checker_ptr prop1 (new div_zero_prop_num_checker_t (verbose));
typename num_checker_t::prop_checker_ptr prop2 (new assert_prop_num_checker_t (verbose));
num_checker_t checker (num_a, {prop1, prop2});
checker.run ();
checker.show (crab::outs());
}
}
int main (int argc, char**argv) {
bool stats_enabled = false;
if (!crab_tests::parse_user_options(argc,argv,stats_enabled)) {
return 0;
}
variable_factory_t vfac;
z_cfg_t* p1 = cfg1 (vfac);
check (*p1, vfac);
z_cfg_t* p2 = cfg2 (vfac);
// To test the assertion crawler analysis
crab::analyzer::assertion_crawler<z_cfg_ref_t> assert_crawler(*p2);
assert_crawler.exec();
crab::outs() << "\n" << assert_crawler << "\n";
// To test the assumption analyses
crab::analyzer::assumption_naive_analysis<z_cfg_ref_t> assumption_naive_analyzer(*p2);
assumption_naive_analyzer.exec();
crab::outs() << "\n" << assumption_naive_analyzer << "\n";
crab::analyzer::assumption_dataflow_analysis<z_cfg_ref_t> assumption_dataflow_analyzer(*p2);
assumption_dataflow_analyzer.exec();
crab::outs() << "\n" << assumption_dataflow_analyzer << "\n";
check (*p2, vfac);
delete p1;
delete p2;
return 0;
}
| 31.137168
| 95
| 0.647293
|
numairmansur
|
4e49a7fefdd9e99a662c62d628dc49a1394a442a
| 34,868
|
cpp
|
C++
|
src/libs/viface/viface.cpp
|
francescomessina/polycube
|
38f2fb4ffa13cf51313b3cab9994be738ba367be
|
[
"ECL-2.0",
"Apache-2.0"
] | 337
|
2018-12-12T11:50:15.000Z
|
2022-03-15T00:24:35.000Z
|
src/libs/viface/viface.cpp
|
l1b0k/polycube
|
7af919245c131fa9fe24c5d39d10039cbb81e825
|
[
"ECL-2.0",
"Apache-2.0"
] | 253
|
2018-12-17T21:36:15.000Z
|
2022-01-17T09:30:42.000Z
|
src/libs/viface/viface.cpp
|
l1b0k/polycube
|
7af919245c131fa9fe24c5d39d10039cbb81e825
|
[
"ECL-2.0",
"Apache-2.0"
] | 90
|
2018-12-19T15:49:38.000Z
|
2022-03-27T03:56:07.000Z
|
/**
* Copyright (C) 2015 Hewlett Packard Enterprise Development LP
*
* 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 "viface/private/viface.hpp"
namespace viface
{
/*= Utilities ================================================================*/
namespace utils
{
vector<uint8_t> parse_mac(string const& mac)
{
unsigned int bytes[6];
int scans = sscanf(
mac.c_str(),
"%02x:%02x:%02x:%02x:%02x:%02x",
&bytes[0], &bytes[1], &bytes[2], &bytes[3], &bytes[4], &bytes[5]
);
if (scans != 6) {
ostringstream what;
what << "--- Invalid MAC address " << mac << endl;
throw invalid_argument(what.str());
}
vector<uint8_t> parsed(6);
parsed.assign(&bytes[0], &bytes[6]);
return parsed;
}
string hexdump(vector<uint8_t> const& bytes)
{
ostringstream buff;
int buflen = bytes.size();
int i;
int j;
char c;
for (i = 0, j = 0; i < buflen; i += 16) {
// Print offset
buff << right << setfill('0') << setw(4) << i << " ";
// Print bytes in hexadecimal
buff << hex;
for (j = 0; j < 16; j++) {
if (i + j < buflen) {
c = bytes[i + j];
buff << setfill('0') << setw(2) << (int(c) & 0xFF);
buff << " ";
} else {
buff << " ";
}
}
buff << dec;
buff << " ";
// Print printable characters
for (j = 0; j < 16; j++) {
if (i + j < buflen) {
c = bytes[i + j];
if (isprint(c)) {
buff << c;
} else {
buff << ".";
}
}
}
buff << endl;
}
return buff.str();
}
uint32_t crc32(vector<uint8_t> const& bytes)
{
static uint32_t crc_table[] = {
0x4DBDF21C, 0x500AE278, 0x76D3D2D4, 0x6B64C2B0,
0x3B61B38C, 0x26D6A3E8, 0x000F9344, 0x1DB88320,
0xA005713C, 0xBDB26158, 0x9B6B51F4, 0x86DC4190,
0xD6D930AC, 0xCB6E20C8, 0xEDB71064, 0xF0000000
};
uint32_t crc = 0;
const uint8_t* data = &bytes[0];
for (uint32_t i = 0; i < bytes.size(); ++i) {
crc = (crc >> 4) ^ crc_table[(crc ^ data[i]) & 0x0F];
crc = (crc >> 4) ^ crc_table[(crc ^ (data[i] >> 4)) & 0x0F];
}
return crc;
}
}
/*= Helpers ==================================================================*/
static void read_flags(int sockfd, string name, struct ifreq& ifr)
{
ostringstream what;
// Prepare communication structure
memset(&ifr, 0, sizeof(struct ifreq));
// Set interface name
(void) strncpy(ifr.ifr_name, name.c_str(), IFNAMSIZ - 1);
// Read interface flags
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) != 0) {
what << "--- Unable to read " << name << " flags." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
static uint read_mtu(string name, size_t size_bytes)
{
int fd = -1;
int nread = -1;
ostringstream what;
char buffer[size_bytes + 1];
// Opens MTU file
fd = open(("/sys/class/net/" + name + "/mtu").c_str(),
O_RDONLY | O_NONBLOCK);
if (fd < 0) {
what << "--- Unable to open MTU file for '";
what << name << "' network interface." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
// Reads MTU value
nread = read(fd, &buffer, size_bytes);
buffer[size_bytes] = '\0';
// Handles errors
if (nread == -1) {
what << "--- Unable to read MTU for '";
what << name << "' network interface." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
if (close(fd) < 0) {
what << "--- Unable to close MTU file for '";
what << name << "' network interface." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
return stoul(buffer, nullptr, 10);
err:
// Rollback close file descriptor
close(fd);
throw runtime_error(what.str());
}
static string alloc_viface(string name, bool tap, struct viface_queues* queues)
{
int i = 0;
int fd = -1;
ostringstream what;
/* Create structure for ioctl call
*
* Flags: IFF_TAP - TAP device (layer 2, ethernet frame)
* IFF_TUN - TUN device (layer 3, IP packet)
* IFF_NO_PI - Do not provide packet information
* IFF_MULTI_QUEUE - Create a queue of multiqueue device
*/
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_NO_PI | IFF_MULTI_QUEUE;
if (tap) {
ifr.ifr_flags |= IFF_TAP;
} else {
ifr.ifr_flags |= IFF_TUN;
}
(void) strncpy(ifr.ifr_name, name.c_str(), IFNAMSIZ - 1);
// Allocate queues
for (i = 0; i < 2; i++) {
// Open TUN/TAP device
fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
if (fd < 0) {
what << "--- Unable to open TUN/TAP device." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
// Register a network device with the kernel
if (ioctl(fd, TUNSETIFF, (void *)&ifr) != 0) {
what << "--- Unable to register a TUN/TAP device." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
if (close(fd) < 0) {
what << "--- Unable to close a TUN/TAP device." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
}
goto err;
}
((int *)queues)[i] = fd;
}
return string(ifr.ifr_name);
err:
// Rollback close file descriptors
for (--i; i >= 0; i--) {
if (close(((int *)queues)[i]) < 0) {
what << "--- Unable to close a TUN/TAP device." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
}
}
throw runtime_error(what.str());
}
static void hook_viface(string name, struct viface_queues* queues)
{
int i = 0;
int fd = -1;
ostringstream what;
// Creates Tx/Rx sockets and allocates queues
for (i = 0; i < 2; i++) {
// Creates the socket
fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (fd < 0) {
what << "--- Unable to create the Tx/Rx socket channel." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
(void) strncpy(ifr.ifr_name, name.c_str(), IFNAMSIZ - 1);
// Obtains the network index number
if (ioctl(fd, SIOCGIFINDEX, &ifr) != 0) {
what << "--- Unable to get network index number.";
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
struct sockaddr_ll socket_addr;
memset(&socket_addr, 0, sizeof(struct sockaddr_ll));
socket_addr.sll_family = AF_PACKET;
socket_addr.sll_protocol = htons(ETH_P_ALL);
socket_addr.sll_ifindex = ifr.ifr_ifindex;
// Binds the socket to the 'socket_addr' address
if (bind(fd, (struct sockaddr*) &socket_addr,
sizeof(socket_addr)) != 0) {
what << "--- Unable to bind the Tx/Rx socket channel to the '";
what << name << "' network interface." << endl;
what << " Queue: " << i << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
goto err;
}
((int *)queues)[i] = fd;
}
return;
err:
// Rollback close file descriptors
for (--i; i >= 0; i--) {
if (close(((int *)queues)[i]) < 0) {
what << "--- Unable to close a Rx/Tx socket." << endl;
what << " Name: " << name << " Queue: " << i << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
}
}
throw runtime_error(what.str());
}
/*= Virtual Interface Implementation =========================================*/
uint VIfaceImpl::idseq = 0;
VIfaceImpl::VIfaceImpl(string name, bool tap, int id)
{
// Check name length
if (name.length() >= IFNAMSIZ) {
throw invalid_argument("--- Virtual interface name too long.");
}
// Create queues
struct viface_queues queues;
memset(&queues, 0, sizeof(struct viface_queues));
/* Checks if the path name can be accessed. If so,
* it means that the network interface is already defined.
*/
if (access(("/sys/class/net/" + name).c_str(), F_OK) == 0) {
hook_viface(name, &queues);
this->name = name;
// Read MTU value and resize buffer
this->mtu = read_mtu(name, sizeof(this->mtu));
this->pktbuff.resize(this->mtu);
} else {
this->name = alloc_viface(name, tap, &queues);
// Other defaults
this->mtu = 1500;
}
this->queues = queues;
// Create socket channels to the NET kernel for later ioctl
this->kernel_socket = -1;
this->kernel_socket = socket(AF_INET, SOCK_STREAM, 0);
if (this->kernel_socket < 0) {
ostringstream what;
what << "--- Unable to create IPv4 socket channel to the NET kernel.";
what << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
this->kernel_socket_ipv6 = -1;
this->kernel_socket_ipv6 = socket(AF_INET6, SOCK_STREAM, 0);
if (this->kernel_socket_ipv6 < 0) {
ostringstream what;
what << "--- Unable to create IPv6 socket channel to the NET kernel.";
what << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Set id
if (id < 0) {
this->id = this->idseq;
} else {
this->id = id;
}
this->idseq++;
}
VIfaceImpl::~VIfaceImpl()
{
if (close(this->queues.rx) ||
close(this->queues.tx) ||
close(this->kernel_socket) ||
close(this->kernel_socket_ipv6)) {
ostringstream what;
what << "--- Unable to close file descriptors for interface ";
what << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
void VIfaceImpl::setMAC(string mac)
{
vector<uint8_t> mac_bin = utils::parse_mac(mac);
this->mac = mac;
return;
}
string VIfaceImpl::getMAC() const
{
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
if (ioctl(this->kernel_socket, SIOCGIFHWADDR, &ifr) != 0) {
ostringstream what;
what << "--- Unable to get MAC addr for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Convert binary MAC address to string
ostringstream addr;
addr << hex << std::setfill('0');
for (int i = 0; i < 6; i++) {
addr << setw(2) << (unsigned int) (0xFF & ifr.ifr_hwaddr.sa_data[i]);
if (i != 5) {
addr << ":";
}
}
return addr.str();
}
void VIfaceImpl::setIPv4(string ipv4)
{
// Validate format
struct in_addr addr;
if (!inet_pton(AF_INET, ipv4.c_str(), &addr)) {
ostringstream what;
what << "--- Invalid IPv4 address (" << ipv4 << ") for ";
what << this->name << "." << endl;
throw invalid_argument(what.str());
}
this->ipv4 = ipv4;
return;
}
string VIfaceImpl::ioctlGetIPv4(unsigned long request) const
{
ostringstream what;
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
if (ioctl(this->kernel_socket, request, &ifr) != 0) {
what << "--- Unable to get IPv4 for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Convert binary IP address to string
char addr[INET_ADDRSTRLEN];
memset(&addr, 0, sizeof(addr));
struct sockaddr_in* ipaddr = (struct sockaddr_in*) &ifr.ifr_addr;
if (inet_ntop(AF_INET, &(ipaddr->sin_addr), addr, sizeof(addr)) == NULL) {
what << "--- Unable to convert IPv4 for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
return string(addr);
}
string VIfaceImpl::getIPv4() const
{
return this->ioctlGetIPv4(SIOCGIFADDR);
}
void VIfaceImpl::setIPv4Netmask(string netmask)
{
// Validate format
struct in_addr addr;
if (!inet_pton(AF_INET, netmask.c_str(), &addr)) {
ostringstream what;
what << "--- Invalid IPv4 netmask (" << netmask << ") for ";
what << this->name << "." << endl;
throw invalid_argument(what.str());
}
this->netmask = netmask;
return;
}
string VIfaceImpl::getIPv4Netmask() const
{
return this->ioctlGetIPv4(SIOCGIFNETMASK);
}
void VIfaceImpl::setIPv4Broadcast(string broadcast)
{
// Validate format
struct in_addr addr;
if (!inet_pton(AF_INET, broadcast.c_str(), &addr)) {
ostringstream what;
what << "--- Invalid IPv4 address (" << broadcast << ") for ";
what << this->name << "." << endl;
throw invalid_argument(what.str());
}
this->broadcast = broadcast;
return;
}
string VIfaceImpl::getIPv4Broadcast() const
{
return this->ioctlGetIPv4(SIOCGIFBRDADDR);
}
void VIfaceImpl::setMTU(uint mtu)
{
ostringstream what;
if (mtu < ETH_HLEN) {
what << "--- MTU " << mtu << " too small (< " << ETH_HLEN << ").";
what << endl;
throw invalid_argument(what.str());
}
// Are we sure about this upper validation?
// lo interface reports this number for its MTU
if (mtu > 65536) {
what << "--- MTU " << mtu << " too large (> 65536)." << endl;
throw invalid_argument(what.str());
}
this->mtu = mtu;
return;
}
void VIfaceImpl::setIPv6(set<string> const& ipv6s)
{
// Validate format
struct in6_addr addr6;
for (auto & ipv6 : ipv6s) {
if (!inet_pton(AF_INET6, ipv6.c_str(), &addr6)) {
ostringstream what;
what << "--- Invalid IPv6 address (" << ipv6 << ") for ";
what << this->name << "." << endl;
throw invalid_argument(what.str());
}
}
this->ipv6s = ipv6s;
return;
}
set<string> VIfaceImpl::getIPv6() const
{
// Return set
set<string> result;
// Buffer to store string representation of the address
char buff[INET6_ADDRSTRLEN];
memset(&buff, 0, sizeof(buff));
// Cast pointer to ipv6 address
struct sockaddr_in6* addr;
// Pointers to list head and current node
struct ifaddrs *head;
struct ifaddrs *node;
// Get list of interfaces
if (getifaddrs(&head) == -1) {
ostringstream what;
what << "--- Failed to get list of interface addresses." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Iterate list
for (node = head; node != NULL; node = node->ifa_next) {
if (node->ifa_addr == NULL) {
continue;
}
if (node->ifa_addr->sa_family != AF_INET6) {
continue;
}
if (string(node->ifa_name) != this->name) {
continue;
}
// Convert IPv6 address to string representation
addr = (struct sockaddr_in6*) node->ifa_addr;
if (inet_ntop(AF_INET6, &(addr->sin6_addr), buff,
sizeof(buff)) == NULL) {
ostringstream what;
what << "--- Unable to convert IPv6 for " << this->name;
what << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
result.insert(string(buff));
}
freeifaddrs(head);
return result;
}
uint VIfaceImpl::getMTU() const
{
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
if (ioctl(this->kernel_socket, SIOCGIFMTU, &ifr) != 0) {
ostringstream what;
what << "--- Unable to get MTU for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
return ifr.ifr_mtu;
}
void VIfaceImpl::up()
{
ostringstream what;
if (this->isUp()) {
what << "--- Virtual interface " << this->name;
what << " is already up." << endl;
what << " up() Operation not permitted." << endl;
throw runtime_error(what.str());
}
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
// Set MAC address
if (!this->mac.empty()) {
vector<uint8_t> mac_bin = utils::parse_mac(this->mac);
ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
for (int i = 0; i < 6; i++) {
ifr.ifr_hwaddr.sa_data[i] = mac_bin[i];
}
if (ioctl(this->kernel_socket, SIOCSIFHWADDR, &ifr) != 0) {
what << "--- Unable to set MAC Address (" << this->mac;
what << ") for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
// Set IPv4 related
// FIXME: Refactor this, it's ugly :/
struct sockaddr_in* addr = (struct sockaddr_in*) &ifr.ifr_addr;
addr->sin_family = AF_INET;
// Address
if (!this->ipv4.empty()) {
if (!inet_pton(AF_INET, this->ipv4.c_str(), &addr->sin_addr)) {
what << "--- Invalid cached IPv4 address (" << this->ipv4;
what << ") for " << this->name << "." << endl;
what << " Something really bad happened :/" << endl;
throw runtime_error(what.str());
}
if (ioctl(this->kernel_socket, SIOCSIFADDR, &ifr) != 0) {
what << "--- Unable to set IPv4 (" << this->ipv4;
what << ") for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
// Netmask
if (!this->netmask.empty()) {
if (!inet_pton(AF_INET, this->netmask.c_str(), &addr->sin_addr)) {
what << "--- Invalid cached IPv4 netmask (" << this->netmask;
what << ") for " << this->name << "." << endl;
what << " Something really bad happened :/" << endl;
throw runtime_error(what.str());
}
if (ioctl(this->kernel_socket, SIOCSIFNETMASK, &ifr) != 0) {
what << "--- Unable to set IPv4 netmask (" << this->netmask;
what << ") for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
// Broadcast
if (!this->broadcast.empty()) {
if (!inet_pton(AF_INET, this->broadcast.c_str(), &addr->sin_addr)) {
what << "--- Invalid cached IPv4 broadcast (" << this->broadcast;
what << ") for " << this->name << "." << endl;
what << " Something really bad happened :/" << endl;
throw runtime_error(what.str());
}
if (ioctl(this->kernel_socket, SIOCSIFBRDADDR, &ifr) != 0) {
what << "--- Unable to set IPv4 broadcast (" << this->broadcast;
what << ") for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
// Set IPv6 related
// FIXME: Refactor this, it's ugly :/
if (!this->ipv6s.empty()) {
struct in6_ifreq ifr6;
memset(&ifr6, 0, sizeof(struct in6_ifreq));
// Get interface index
if (ioctl(this->kernel_socket, SIOGIFINDEX, &ifr) < 0) {
what << "--- Unable to get interface index for (";
what << this->name << "." << endl;
what << " Something really bad happened :/" << endl;
throw runtime_error(what.str());
}
ifr6.ifr6_ifindex = ifr.ifr_ifindex;
ifr6.ifr6_prefixlen = 64;
for (auto & ipv6 : this->ipv6s) {
// Parse IPv6 address into IPv6 address structure
if (!inet_pton(AF_INET6, ipv6.c_str(), &ifr6.ifr6_addr)) {
what << "--- Invalid cached IPv6 address (" << ipv6;
what << ") for " << this->name << "." << endl;
what << " Something really bad happened :/" << endl;
throw runtime_error(what.str());
}
// Set IPv6 address
if (ioctl(this->kernel_socket_ipv6, SIOCSIFADDR, &ifr6) < 0) {
what << "--- Unable to set IPv6 address (" << ipv6;
what << ") for " << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
}
}
// Set MTU
ifr.ifr_mtu = this->mtu;
if (ioctl(this->kernel_socket, SIOCSIFMTU, &ifr) != 0) {
what << "--- Unable to set MTU (" << this->mtu << ") for ";
what << this->name << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
this->pktbuff.resize(this->mtu);
// Bring-up interface
ifr.ifr_flags |= IFF_UP;
if (ioctl(this->kernel_socket, SIOCSIFFLAGS, &ifr) != 0) {
what << "--- Unable to bring-up interface " << this->name;
what << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
return;
}
void VIfaceImpl::down() const
{
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
// Bring-down interface
ifr.ifr_flags &= ~IFF_UP;
if (ioctl(this->kernel_socket, SIOCSIFFLAGS, &ifr) != 0) {
ostringstream what;
what << "--- Unable to bring-down interface " << this->name;
what << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
return;
}
bool VIfaceImpl::isUp() const
{
// Read interface flags
struct ifreq ifr;
read_flags(this->kernel_socket, this->name, ifr);
return (ifr.ifr_flags & IFF_UP) != 0;
}
vector<uint8_t> VIfaceImpl::receive()
{
// Read packet into our buffer
int nread = read(this->queues.rx, &(this->pktbuff[0]), this->mtu);
// Handle errors
if (nread == -1) {
// Nothing was read for this fd (non-blocking).
// This could happen, as http://linux.die.net/man/2/select states:
//
// Under Linux, select() may report a socket file descriptor as
// "ready for reading", while nevertheless a subsequent read
// blocks. This could for example happen when data has arrived
// but upon examination has wrong checksum and is discarded.
// There may be other circumstances in which a file descriptor
// is spuriously reported as ready. Thus it may be safer to
// use O_NONBLOCK on sockets that should not block.
//
// I know this is not a socket, but the "There may be other
// circumstances in which a file descriptor is spuriously reported
// as ready" warns it, and so, it better to do this that to have
// an application that frozes for no apparent reason.
//
if (errno == EAGAIN) {
return vector<uint8_t>(0);
}
// Something bad happened
ostringstream what;
what << "--- IO error while reading from " << this->name;
what << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Copy packet from buffer and return
vector<uint8_t> packet(nread);
packet.assign(&(this->pktbuff[0]), &(this->pktbuff[nread]));
return packet;
}
void VIfaceImpl::send(vector<uint8_t>& packet) const
{
ostringstream what;
int size = packet.size();
if (size < ETH_HLEN) {
what << "--- Packet too small (" << size << ") ";
what << "too small (< " << ETH_HLEN << ")." << endl;
throw invalid_argument(what.str());
}
if (size > this->mtu) {
what << "--- Packet too large (" << size << ") ";
what << "for current MTU (> " << this->mtu << ")." << endl;
throw invalid_argument(what.str());
}
// Write packet to TX queue
int written = write(this->queues.tx, &packet[0], size);
if (written != size) {
what << "--- IO error while writting to " << this->name;
what << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
return;
}
std::set<std::string> VIfaceImpl::listStats()
{
set<string> result;
DIR* dir;
struct dirent* ent;
ostringstream what;
string path = "/sys/class/net/" + this->name + "/statistics/";
// Open directory
if ((dir = opendir(path.c_str())) == NULL) {
what << "--- Unable to open statistics folder for interface ";
what << this->name << ":" << endl;
what << " " << path << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// List files
while ((ent = readdir(dir)) != NULL) {
string entry(ent->d_name);
// Ignore current, parent and hidden files
if (entry[0] != '.') {
result.insert(entry);
}
}
// Close directory
if (closedir(dir) != 0) {
what << "--- Unable to close statistics folder for interface ";
what << this->name << ":" << endl;
what << " " << path << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Update cache
this->stats_keys_cache = result;
return result;
}
uint64_t VIfaceImpl::readStatFile(string const& stat)
{
ostringstream what;
// If no cache exists, create it.
if (this->stats_keys_cache.empty()) {
this->listStats();
}
// Check if stat is valid
if (stats_keys_cache.find(stat) == stats_keys_cache.end()) {
what << "--- Unknown statistic " << stat;
what << " for interface " << this->name << endl;
throw runtime_error(what.str());
}
// Open file
string path = "/sys/class/net/" + this->name + "/statistics/" + stat;
ifstream statf(path);
uint64_t value;
// Check file open
if (!statf.is_open()) {
what << "--- Unable to open statistics file " << path;
what << " for interface " << this->name << endl;
throw runtime_error(what.str());
}
// Read content into value
statf >> value;
// close file
statf.close();
// Create entry if this stat wasn't cached
if (this->stats_cache.find(stat) == this->stats_cache.end()) {
this->stats_cache[stat] = 0;
}
return value;
}
uint64_t VIfaceImpl::readStat(std::string const& stat)
{
uint64_t value = this->readStatFile(stat);
// Return value minus the cached value
return value - this->stats_cache[stat];
}
void VIfaceImpl::clearStat(std::string const& stat)
{
uint64_t value = this->readStatFile(stat);
// Set current value as cache
this->stats_cache[stat] = value;
return;
}
void dispatch(set<VIface*>& ifaces, dispatcher_cb callback, int millis)
{
int fd = -1;
int fdsread = -1;
int nfds = -1;
struct timeval tv;
struct timeval* tvp = NULL;
// Check non-empty set
if (ifaces.empty()) {
ostringstream what;
what << "--- Empty virtual interfaces set" << endl;
throw invalid_argument(what.str());
}
// Setup timeout
if (millis >= 0) {
tvp = &tv;
}
// Store mapping between file descriptors and interface it belongs
map<int,VIface*> reverse_id;
// Create and clear set of file descriptors
fd_set rfds;
// Create map of file descriptors and get maximum file descriptor for
// select call
for (auto iface : ifaces) {
// Store identity
fd = iface->pimpl->getRX();
reverse_id[fd] = iface;
// Get maximum file descriptor
if (fd > nfds) {
nfds = fd;
}
}
nfds++;
// Perform select system call
while (true) {
// Re-create set
FD_ZERO(&rfds);
for (auto iface : ifaces) {
fd = iface->pimpl->getRX();
FD_SET(fd, &rfds);
}
// Re-set timeout
if (tvp != NULL) {
tv.tv_sec = millis / 1000;
tv.tv_usec = (millis % 1000) * 1000;
}
fdsread = select(nfds, &rfds, NULL, NULL, tvp);
// Check if select error
if (fdsread == -1) {
// A signal was caught. Return.
if (errno == EINTR) {
return;
}
// Something bad happened
ostringstream what;
what << "--- Unknown error in select() system call: ";
what << fdsread << "." << endl;
what << " Error: " << strerror(errno);
what << " (" << errno << ")." << endl;
throw runtime_error(what.str());
}
// Check if timeout
if (tvp != NULL && fdsread == 0) {
return;
}
// Iterate all active file descriptors for reading
for (auto &pair : reverse_id) {
// Check if fd wasn't marked in select as available
if (!FD_ISSET(pair.first, &rfds)) {
continue;
}
// File descriptor is ready, perform read and dispatch
vector<uint8_t> packet = pair.second->receive();
if (packet.size() == 0) {
// Even if this is very unlikely, supposedly it can happen.
// See receive() comments about this.
continue;
}
// Dispatch packet
if (!callback(
pair.second->getName(),
pair.second->getID(),
packet)) {
return;
}
}
}
}
/*============================================================================
= PIMPL IDIOM BUREAUCRACY
=
= Starting this point there is not much relevant things...
= Stop scrolling...
*============================================================================*/
VIface::VIface(string name, bool tap, int id) :
pimpl(new VIfaceImpl(name, tap, id))
{}
VIface::~VIface() = default;
string VIface::getName() const {
return this->pimpl->getName();
}
uint VIface::getID() const {
return this->pimpl->getID();
}
void VIface::setMAC(string mac)
{
return this->pimpl->setMAC(mac);
}
string VIface::getMAC() const
{
return this->pimpl->getMAC();
}
void VIface::setIPv4(string ipv4)
{
return this->pimpl->setIPv4(ipv4);
}
string VIface::getIPv4() const
{
return this->pimpl->getIPv4();
}
void VIface::setIPv4Netmask(string netmask)
{
return this->pimpl->setIPv4Netmask(netmask);
}
string VIface::getIPv4Netmask() const
{
return this->pimpl->getIPv4Netmask();
}
void VIface::setIPv4Broadcast(string broadcast)
{
return this->pimpl->setIPv4Broadcast(broadcast);
}
string VIface::getIPv4Broadcast() const
{
return this->pimpl->getIPv4Broadcast();
}
void VIface::setIPv6(set<string> const& ipv6s)
{
return this->pimpl->setIPv6(ipv6s);
}
set<string> VIface::getIPv6() const
{
return this->pimpl->getIPv6();
}
void VIface::setMTU(uint mtu)
{
return this->pimpl->setMTU(mtu);
}
uint VIface::getMTU() const
{
return this->pimpl->getMTU();
}
void VIface::up()
{
return this->pimpl->up();
}
void VIface::down() const
{
return this->pimpl->down();
}
bool VIface::isUp() const
{
return this->pimpl->isUp();
}
vector<uint8_t> VIface::receive()
{
return this->pimpl->receive();
}
void VIface::send(vector<uint8_t>& packet) const
{
return this->pimpl->send(packet);
}
std::set<std::string> VIface::listStats()
{
return this->pimpl->listStats();
}
uint64_t VIface::readStat(std::string const& stat)
{
return this->pimpl->readStat(stat);
}
void VIface::clearStat(std::string const& stat)
{
return this->pimpl->clearStat(stat);
}
}
| 28.347967
| 80
| 0.52085
|
francescomessina
|
4e4d01653ccd5b2005f830cb05245bc5eb02fd1f
| 2,082
|
hpp
|
C++
|
zen/tuple.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | null | null | null |
zen/tuple.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | 2
|
2020-02-06T17:01:39.000Z
|
2020-02-12T17:50:14.000Z
|
zen/tuple.hpp
|
ZenLibraries/ZenLibraries
|
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
|
[
"Apache-2.0"
] | null | null | null |
#ifndef ZEN_TUPLE_HPP
#define ZEN_TUPLE_HPP
#include "zen/config.h"
#include "zen/meta.hpp"
ZEN_NAMESPACE_START
template<typename T>
struct IsEmpty;
template<size_t I, typename ValueT, bool IsEmpty = IsEmpty<ValueT>::value>
class _TupleLeaf {
ValueT value;
};
template<size_t ...I>
struct _TupleIndices {};
template<typename Indices, typename ...Ts>
struct _TupleImpl;
template<size_t ...Indices, typename ...Ts>
struct _TupleImpl<_TupleIndices<Indices...>, Ts...>
: public _TupleLeaf<Indices, Ts>... {};
template<size_t N, typename T>
auto get(T value);
/**
* @brief An indexed list of types that can be populated at run-time.
*
* The implementation was inspired by [this article][1] and [this article][2].
*
* [1]: https://ldionne.com/2015/11/29/efficient-parameter-pack-indexing/
* [2]: https://mitchnull.blogspot.com/2012/06/c11-tuple-implementation-details-part-1.html
*/
template<typename ...Ts>
class Tuple {
template<size_t N, typename T>
friend auto get(T value);
using Impl = _TupleImpl<Ascending<size_t, sizeof...(Ts)>, Ts...>;
Impl _elements;
public:
template<typename T>
constexpr auto append(T element) {
return Tuple<Ts..., T>(get<Ascending<size_t, sizeof...(Ts)>>(), element);
}
};
template<size_t N, typename ...Ts>
auto get(Tuple<Ts...> tuple) {
return static_cast<_TupleLeaf<N, TypePackElement<N, Ts...>>&>(tuple._elements).value;
}
ZEN_NAMESPACE_END
#if ZEN_STL
#include <tuple>
#else
namespace std {
// Structural binding declarations require std::tuple_size<T> and
// std::tuple_element<N, T> to be present. The compiler will use these
// templates to automatically extract elements from a given type.
template <typename T>
struct tuple_size;
template<size_t N, typename T>
struct tuple_element;
}
#endif
#if ZEN_STL
#include <tuple>
namespace std {
template <typename ...Ts>
struct tuple_size< ::zen::Tuple<Ts...> > {
static const size_t value = sizeof...(Ts);
};
}
#endif // of #if ZEN_STL
#endif // of #ifndef ZEN_TUPLE_HPP
| 20.82
| 91
| 0.685879
|
ZenLibraries
|
4e4dfa73660b3973982c98467dfb425e9c4efb25
| 255
|
cpp
|
C++
|
src/fft_x86_sse41.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | 3
|
2019-10-30T11:17:32.000Z
|
2019-11-04T16:38:37.000Z
|
src/fft_x86_sse41.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | null | null | null |
src/fft_x86_sse41.cpp
|
mzient/genFFT
|
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
|
[
"BSD-2-Clause"
] | null | null | null |
#include <cassert>
#include <smmintrin.h>
#include <genFFT/FFTLevel.h>
#include <genFFT/generic/fft_impl_generic.h>
#include "dispatch_helper.h"
namespace genfft {
namespace impl_SSE41 {
#include <genFFT/x86/fft_impl_x86.inl>
DISPATCH_ALL()
}
}
| 18.214286
| 44
| 0.745098
|
mzient
|
4e4f4236e4e4e37a73a068f75f77abf5d1ba4e7a
| 2,125
|
cpp
|
C++
|
ares/ngp/kge/sprite.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 153
|
2020-07-25T17:55:29.000Z
|
2021-10-01T23:45:01.000Z
|
ares/ngp/kge/sprite.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 245
|
2021-10-08T09:14:46.000Z
|
2022-03-31T08:53:13.000Z
|
ares/ngp/kge/sprite.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 44
|
2020-07-25T08:51:55.000Z
|
2021-09-25T16:09:01.000Z
|
//technically, the Neo Geo Pocket attempts to buffer a line of sprites in advance.
//so long as the user program does not write to VRAM during display, it can render
//all 64 sprites on the same line. currently, the "character over" condition when
//writing to VRAM during active display is not emulated, nor is the exact timing
//of the caching used by real hardware, as this information is not currently known.
auto KGE::Sprite::begin(n8 y) -> void {
for(auto& tile : tiles) tile.priority = 0;
n8 count;
n8 px;
n8 py;
for(auto& object : objects) {
n8 ox = object.hoffset;
n8 oy = object.voffset;
if(object.hchain) ox += px;
if(object.vchain) oy += py;
px = ox;
py = oy;
if(!object.priority) continue; //invisible
ox = (ox + hscroll);
oy = y - (oy + vscroll);
if(oy >= 8) continue; //out of range
if(object.vflip) oy ^= 7;
auto& tile = tiles[count++];
tile.x = ox;
tile.y = oy;
tile.character = object.character;
tile.priority = object.priority;
tile.palette = object.palette;
tile.hflip = object.hflip;
tile.code = object.code;
}
}
auto KGE::Sprite::render(n8 x, n8 y) -> maybe<Output&> {
for(auto& tile : tiles) {
if(!tile.priority) continue; //invisible
n8 tx = x - tile.x;
n3 ty = tile.y;
if(tx >= 8) continue; //out of range
if(tile.hflip) tx ^= 7;
if(n2 index = self.characters[tile.character][ty][tx]) {
output.priority = tile.priority;
if(Model::NeoGeoPocket()) {
output.color = palette[tile.palette][index];
}
if(Model::NeoGeoPocketColor()) {
switch(self.dac.colorMode) {
case 0: output.color = tile.code * 4 + index; break;
case 1: output.color = tile.palette * 8 + palette[tile.palette][index]; break;
}
}
return output;
}
}
return {};
}
auto KGE::Sprite::power() -> void {
output = {};
for(auto& object : objects) object = {};
for(auto& tile : tiles) tile = {};
hscroll = 0;
vscroll = 0;
memory::assign(palette[0], 0, 0, 0, 0);
memory::assign(palette[1], 0, 0, 0, 0);
}
| 27.960526
| 86
| 0.603765
|
CasualPokePlayer
|
4e51aed902d19268ced31e4b9cddd7a9870820a5
| 1,381
|
cpp
|
C++
|
firmware/lib/LCDMenu/LCDMenu.cpp
|
nowtechnologies/open_ozone_controller
|
38999144a71794eb44ba3ed1d4227068e6253085
|
[
"Unlicense"
] | null | null | null |
firmware/lib/LCDMenu/LCDMenu.cpp
|
nowtechnologies/open_ozone_controller
|
38999144a71794eb44ba3ed1d4227068e6253085
|
[
"Unlicense"
] | null | null | null |
firmware/lib/LCDMenu/LCDMenu.cpp
|
nowtechnologies/open_ozone_controller
|
38999144a71794eb44ba3ed1d4227068e6253085
|
[
"Unlicense"
] | null | null | null |
#include <LiquidCrystal.h>
#include <Arduino.h>
#include "LCDMenu.h"
LCDMenu::LCDMenu(String newName, LiquidCrystal* newLCD, LCDMenu* parentMenu)
{
setName(newName);
setLCD(newLCD);
menuFirst = NULL;
menuLast = NULL;
parent = parentMenu;
}
void LCDMenu::setName(String newName)
{
Name = newName;
}
LCDMenuItem* LCDMenu::next()
{
menuCurrent=menuCurrent->getNext();
return menuCurrent;
}
LCDMenuItem* LCDMenu::prev()
{
menuCurrent=menuCurrent->getPrev();
return menuCurrent;
}
void LCDMenu::addMenuItem(LCDMenuItem* item)
{
if (item != NULL)
{
if (menuFirst == NULL)
{
menuFirst = menuLast = menuCurrent = item;
menuFirst->setPrev(item);
menuFirst->setNext(item);
}
else
{
menuLast->setNext(item);
item->setPrev(menuLast);
item->setNext(menuFirst);
menuFirst->setPrev(item);
menuLast=item;
}
}
}
void LCDMenu::setLCD(LiquidCrystal* newLCD)
{
LCD=newLCD;
}
LiquidCrystal* LCDMenu::getLCD()
{
return LCD;
}
void LCDMenu::selectOption()
{
menuCurrent->executeAction();
}
void LCDMenu::display()
{
LCD->clear();
LCD->setCursor(0,0);
LCD->print(">" + menuCurrent->getName());
if (menuCurrent->getNext() != menuCurrent)
{
LCD->setCursor(1,1);
LCD->print(menuCurrent->getNext()->getName());
}
}
bool LCDMenu::hasParentMenu() {
return (parent != NULL);
}
LCDMenu* LCDMenu::getParentMenu() {
return parent;
}
| 16.247059
| 76
| 0.678494
|
nowtechnologies
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.